prisma: Prisma Postgres Adapter with Turborepo does not work

Bug description

if I have a turborepo monorepo with a packages/db folder containing my prisma schema, and a apps/web application (Next.JS) and I use the updated prisma with previewFeatures = ["queryCompiler", "driverAdapters"]

I get an error:

web:dev: Error: ENOENT: no such file or directory, open '/MYPATH/MONOREPO/apps/web/generated/prisma/query_compiler_bg.wasm'
web:dev:     at Object.getQueryCompilerWasmModule (../../packages/db/generated/prisma/index.js:2534:70)
web:dev:     at eval (../../packages/db/generated/prisma/runtime/client.js:74:23092)
web:dev:   2532 |       getQueryCompilerWasmModule: async () => {
web:dev:   2533 |         const queryCompilerWasmFilePath = require('path').join(config.dirname, 'query_compiler_bg.wasm')
web:dev: > 2534 |         const queryCompilerWasmFileBytes = require('fs').readFileSync(queryCompilerWasmFilePath)
web:dev:        |                                                                      ^
web:dev:   2535 |
web:dev:   2536 |         return new WebAssembly.Module(queryCompilerWasmFileBytes)
web:dev:   2537 |       } {
web:dev:   errno: -2,
web:dev:   code: 'ENOENT',
web:dev:   syscall: 'open',
web:dev:   path: '/MYPATH/MONOREPO/apps/web/generated/prisma/query_compiler_bg.wasm'
web:dev: }

it is looking for query_compiler_bg.wasm at the web application but it should look for the same in the db package

before you ask if I am creating a new PrismaClient inside the web application, I’m not, I’m only creating one prisma client in db package and exporting it, which is getting used in all other apps

Severity

🚨 Critical: Data loss, app crash, security issue

Reproduction

Follow your guide to use prisma with turborepo and update the index.ts file to use the “Rust-free” version of Prisma ORM (using the queryCompiler and adapters), something you guys have mentioned here

Expected vs. Actual Behavior

let’s call prisma with previewFeatures = ["queryCompiler", "driverAdapters"] to be p1 and prisma without previewFeatures = ["queryCompiler", "driverAdapters"] to be p2

I expect p1 and p2 to behave the same when I’m using them in a monorepo/turborepo

Frequency

Consistently reproducible

Does this occur in development or production?

Both development and production

Is this a regression?

if I directly use prisma without the previewFeatures = ["queryCompiler", "driverAdapters"], it works

Workaround

as I said

if I directly use prisma without the previewFeatures = ["queryCompiler", "driverAdapters"], it works

Prisma Schema & Queries

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["queryCompiler", "driverAdapters", "views"]
  output          = "../generated/prisma"
}

generator kysely {
  provider     = "prisma-kysely"
  output       = "../src/db"
  fileName     = "types.ts"
  enumFileName = "enums.ts"
}

model AuthSession {
  id        String   @id @unique
  userId    String
  expiresAt DateTime @map("expiresAt")
 
  @@map("auth_session")
}
// and rest of the models
import { PrismaPg } from "@prisma/adapter-pg";
import * as dotenv from "dotenv";
import { Kysely, PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler } from "kysely";
import kyselyExtension from "prisma-extension-kysely";
import { PrismaClient as prismaClient } from "../generated/prisma";
import type { DB } from "./db/types";

import type { z } from "zod";
dotenv.config();

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
const prismaBase = new prismaClient({ adapter });

const p = prismaBase.$extends(
	kyselyExtension({
		kysely: (driver) =>
			new Kysely<DB>({
				dialect: {
					createDriver: () => driver,
					createAdapter: () => new PostgresAdapter(),
					createIntrospector: (db) => new PostgresIntrospector(db),
					createQueryCompiler: () => new PostgresQueryCompiler(),
				},
				plugins: [],
			}),
	})
);

const globalForPrisma = global as unknown as { prisma: typeof p };

const prisma = globalForPrisma.prisma || p;

if (process.env.NODE_ENV !== "production") {
	globalForPrisma.prisma = prisma;
}

export { prisma };
type PrismaClient = typeof prisma;
export type { PrismaClient };

Prisma Config

I tried with and without it, the results were same

import "dotenv/config";
import path from "node:path";
import type { PrismaConfig } from "prisma";

export default {
	earlyAccess: true,
	schema: path.join("prisma", "schema.prisma"),
} satisfies PrismaConfig;

Logs & Debug Info

I was not able to run any database queries as it was throwing the following error everytime, so I have attached this only, let me know if you need anything else

web:dev: Error: ENOENT: no such file or directory, open '/MYPATH/MONOREPO/apps/web/generated/prisma/query_compiler_bg.wasm'
web:dev:     at Object.getQueryCompilerWasmModule (../../packages/db/generated/prisma/index.js:2534:70)
web:dev:     at eval (../../packages/db/generated/prisma/runtime/client.js:74:23092)
web:dev:   2532 |       getQueryCompilerWasmModule: async () => {
web:dev:   2533 |         const queryCompilerWasmFilePath = require('path').join(config.dirname, 'query_compiler_bg.wasm')
web:dev: > 2534 |         const queryCompilerWasmFileBytes = require('fs').readFileSync(queryCompilerWasmFilePath)
web:dev:        |                                                                      ^
web:dev:   2535 |
web:dev:   2536 |         return new WebAssembly.Module(queryCompilerWasmFileBytes)
web:dev:   2537 |       } {
web:dev:   errno: -2,
web:dev:   code: 'ENOENT',
web:dev:   syscall: 'open',
web:dev:   path: '/MYPATH/MONOREPO/apps/web/generated/prisma/query_compiler_bg.wasm'
web:dev: }

Environment & Setup

  • OS: macOS
  • Database: PostgreSQL
  • Node.js version: 20.11.1

Prisma Version

6.7.0
"@prisma/client": "^6.7.0",
"@prisma/adapter-pg": "^6.7.0"

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 16
  • Comments: 30 (4 by maintainers)

Most upvoted comments

We now have a working example of @prisma/adapter-pg + Next.js + Turborepo here (it should get merged in main next Monday, see https://github.com/prisma/prisma-examples/pull/8243).

We expect Turborepo to work out of the box in Prisma 6.12.0 (expected to be released on July 15th).

Hey folks, there are two possible workarounds for you right now, choose whichever you prefer:

  1. You can remove the output path in you generator config and import the generated client from @prisma/client.
  2. You can try using the new prisma-client generator instead of prisma-client-js. It’s currently in Early Access and we are working on bringing it to Preview.

Method 1 will cause the dev server to work, the build to succeed, but it will fail in production (just like in OP’s case).

Unhandled Rejection: [Error: ENOENT: no such file or directory, open '/var/task/node_modules/.prisma/client/query_compiler_bg.wasm'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/var/task/node_modules/.prisma/client/query_compiler_bg.wasm'
}

Method 2 will work in development, but will fail to build due to a webpack bug.

next:build:    Collecting page data ...
next:build: TypeError: t is not a function
next:build:     at Object.getQueryCompilerWasmModule (.next/server/chunks/7443.js:1:218820)
next:build: TypeError: t is not a function
next:build:     at Object.getQueryCompilerWasmModule (.next/server/chunks/7443.js:1:218820)
next:build: TypeError: t is not a function
next:build:     at Object.getQueryCompilerWasmModule (.next/server/chunks/7443.js:1:218820)
next:build: prisma:error t is not a function
next:build: TypeError: t is not a function
next:build:     at Object.getQueryCompilerWasmModule (.next/server/chunks/7443.js:1:218820) {
next:build:   clientVersion: '6.10.1'
next:build: }

Hey folks, there are two possible workarounds for you right now, choose whichever you prefer:

  1. You can remove the output path in you generator config and import the generated client from @prisma/client.
  2. You can try using the new prisma-client generator instead of prisma-client-js. It’s currently in Early Access and we are working on bringing it to Preview.

Issue still present on 6.8.0-dev.46.

I am experiencing this exact issue with an identical setup (repo/database, turborepo, queryCompiler, generated output in src/generated/prisma).

ENOENT: no such file or directory, open '/path/apps/web/src/generated/prisma/query_compiler_bg.wasm'
at Jn.handleRequestError (../../packages/database/src/generated/prisma/runtime/client.js:84:7458)

The directory it’s looking at is an app in the monorepo outside of the database package.

Just curious, since it’s wasm, why not embed the binary into the js file instead of writing a separate file to disk and then expecting to find it in a different location?

I can confirm this is still not working with the latest release

Same issue, unfortunately a blocker!

Hello everyone,

I found a solution that feels VERY HACKY but, in my case, worked.

I needed to edit the generated internal/class.ts file thats generated, and update the content of the getQueryCompilerWasmModule

getQueryCompilerWasmModule: async () => {
    const dynamicRequireFn = async <const T extends string>(name: T) =>
      typeof globalThis.__non_webpack_require__ === 'function'
        ? Promise.resolve(globalThis.__non_webpack_require__(name))
        : await import(/* webpackIgnore: true */ /* @vite-ignore */ name)

    // Note: we must use dynamic imports here to avoid bundling errors like `Module parse failed: Unexpected character '' (1:0)`.
    const { readFile } = await dynamicRequireFn('node:fs/promises')
    const { join } = await dynamicRequireFn('node:path')
    const { createRequire } = await dynamicRequireFn('node:module')
    const _require = createRequire(import.meta.url)

    // THE MAGIC HAPPENS HERE
    const wasmModulePath = _require.resolve(join(process.cwd(), "node_modules/@prisma/client/runtime/query_compiler_bg.postgresql.wasm"))
    const wasmModuleBytes = await readFile(wasmModulePath)

    return new globalThis.WebAssembly.Module(wasmModuleBytes)

This made the error gone, but again, feels very hacky

Hello everyone,

I encountered this issue aswell, and spent the day without being able to fix the issue. However, I managed to be able to see the wasm binaries in the vercel source, which wasnt the case before. What I needed to do was to add the following in the next config :

outputFileTracingIncludes: {
    "**": [
      path
        .join(prismaClientRequire, "runtime/*.postgresql.wasm")
        .replace("../", ""),
    ],
  },

where prismaClientRequire is

const _require = createRequire(import.meta.url);
const prismaClientRequire = path.relative(
  fileURLToPath(import.meta.url),
  path.dirname(_require.resolve("@prisma/client"))
);

After this, I’m able to see the WASM binaries in the correct path in the source of my deployment. But yeah I still get the error saying that the binary is not found, which is weird.

I don’t know if that can help things moving in the right direction, but I’ll keep digging. Hope this can help

I am able to reproduce this issue with Prisma 6.9.0

Image

The error doesn’t occur if we remove the previewFeatures - ["queryCompiler", "driverAdapters"]

Same issue on my side tested it in 6.9.0 the wasm file is not included in the build output for some reason.

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["relationJoins", "queryCompiler", "driverAdapters"]
  output          = "../src/@db-client"
}

const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL,
});

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    log: ['info', 'warn', 'error'],
    adapter,
  });
ENOENT: no such file or directory, open '/var/task/frontend/next-app/src/@db-client/query_compiler_bg.wasm'

This works locally but not on Vercel, I have no idea why

had this issue when switching from normal client to driverAdapter.

fixed by

bun r @prisma/client
bun i @prisma/client -f

bunx prisma generate
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma

✔ Generated Prisma Client (v6.8.2) to ./node_modules/@prisma/client in 31ms

Start by importing your Prisma Client (See: https://pris.ly/d/importing-client)

Tip: Want to turn off tips and other hints? https://pris.ly/tip-4-nohints``

Hmm, these don’t seem to work for me 😦

Heres a copy of my current project: https://github.com/IHIutch/gtm-prisma-6.9.0-repro

I’m using

 '@prisma/adapter-pg': ^6.9.0
 '@prisma/client': ^6.9.0
 '@tanstack/react-start': ^1.121.0-alpha.26
  prisma: ^6.9.0
  turbo: ^2.5.4
  typescript: ^5.7.2
  vite: ^6.3.5

@prisma/client

Here’s what I get if I use @prisma/client:

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["relationJoins"]
}

The build succeeds, but I get this error at runtime

TypeError [ERR_INVALID_MODULE_SPECIFIER]: Invalid module ".prisma/client/default" is not a valid package name imported from /var/task/chunks/_/ssr.mjs
    at parsePackageName (node:internal/modules/package_json_reader:222:11)
    ... 8 lines matching cause stack trace ...
    at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:305:38) {

prisma-client with output

If I try prisma-client, I get

generator client {
  provider        = "prisma-client"
  output          = "../generated/prisma"
  previewFeatures = ["relationJoins"]
}

The build succeeds, not immediate errors, but when I execute a Prisma query I get this error:

Unhandled Rejection: PrismaClientInitializationError: Prisma Client could not locate the Query Engine for runtime "rhel-openssl-3.0.x".

This is likely caused by a bundler that has not copied "libquery_engine-rhel-openssl-3.0.x.so.node" next to the resulting bundle.

PG Adapter with linked dependency

Since I’m not using Next.js, I’m not using [@prisma/nextjs-monorepo-workaround-plugin] (https://www.npmjs.com/package/@prisma/nextjs-monorepo-workaround-plugin). Instead, I tried the Postgres Adapter.

That brings me back to the Postgres Adapter.

I actually hadn’t seen this guidance until just now:

What you should not do is reference that path relatively: // what not to do! import { PrismaClient } from './src/generated/client'; const client = new PrismaClient()

But that led to this build error:

gtm-start:build: error during build:
gtm-start:build: [vite]: Rollup failed to resolve import "db" from "/vercel/path0/packages/database/src/index.ts".
gtm-start:build: This is most likely unintended because it can break your application at runtime.
gtm-start:build: If you do want to externalize this module explicitly add it to
gtm-start:build: `build.rollupOptions.external`

PG Adapter with relative import

Prior to that, I was using a relative path, which again, did allow the build to succeed, when when executing Prisma cause this error (perhaps expectedly?):

Unhandled Rejection: Error: Cannot find module '@prisma/client/runtime/query_compiler_bg.postgresql.wasm'

For what its worth, for me anyway, trying to follow several of the guides has been tricky because there are different approaches for each. It’s not clear if its me who set my project up incorrectly or if/where there’s an issue with Prisma. I know there are a lot of changes currently in progress (very much looking forward to the updates) but that’s made following the guidance a bit difficult. Here are a few pages I’ve been bouncing between:


Some updates:

I’m using turborepo with pnpm, someone in discord suggested creating .npmrc and adding public-hoist-pattern[]=*prisma*.

That seemed to work if I’m not using the PG Adapter. However, after updating Prisma to 6.10.1, I started getting the rhel-openssl-3.0.x issue again. Tried downgrading and continued to get the same issue.

Then I switched from prisma-client to prisma-client-js and importing PrismaClient from ./generated/prisma to @prisma/client. That is now working. Then, as an experiment, I switched back to prisma-client and everything is still working. 🤷 Anyway, I’m leaving it for now.

One thing to note: v6.10 appears to remove the index.ts from generated, which adds another difference from the guides above. If you’re using output = './generate/prisma' you’ll need to import PrismaClient from './generated/prisma/client'.

The problem is, for me anyway, that I’ve been trying to use queryCompiler as a workaround for this issue https://github.com/prisma/prisma/discussions/19498

Any updates on this issue now that 6.9.0 is released? I’ve tested it and it’s still a blocker