prisma: `__dirname is not defined` in ES module scope, Error Only In `hooks.server.ts` in SvelteKit

Bug description

I’m getting a ReferenceError: __dirname is not defined in ES module scope when building a barebones Prisma + Sveltekit app to node, preventing deployment - narrowed it down to importing prisma in hooks.server.ts, builds and runs fine when I remove the import!

full error:

;console.warn(`${ye("warn(prisma)")} ${u}`);}}}}function so(e){return zl(e)?(bn(`Environment variables loaded from ${e}`),{dotenvResult:oo(wn.default.config({path:e,debug:process.env.DOTENV_CONFIG_DEBUG?!0:void 0})),message:Oe(`Environment variables loaded from ${it.default.relative(process.cwd(),e)}`),path:e}):(bn(`Environment variables not found at ${e}`),null)}function ao(e,t){return e&&t&&it.default.resolve(e)===it.default.resolve(t)}function zl(e){return Boolean(e&&pr.default.existsSync(e))}var lo="library";function Pn(e){let t=Yl();return t||(e?.config.engineType==="library"?"library":e?.config.engineType==="binary"?"binary":lo)}function Yl(){let e=process.env.PRISMA_CLIENT_ENGINE_TYPE;return e==="library"?"library":e==="binary"?"binary":void 0}A(En());var k=A(require$$4);A(En());N("prisma:engines");function go(){return k.default.join(__dirname,"../")}k.default.join(__dirname,"../query-engine-darwin");k.default.join(__dirname,"../query-engine-darwin-arm64");k.default.join(__dirname,"../query-engine-debian-openssl-1.0.x");k.default.join(__dirname,"../query-engine-debian-openssl-1.1.x");k.default.join(__dirname,"../query-engine-debian-openssl-3.0.x");k.default.join(__dirname,"../query-engine-linux-static-x64");k.default.join(__dirname,"../query-engine-linux-static-arm64");k.default.join(__dirname,"../query-engine-rhel-openssl-1.0.x");k.default.join(__dirname,"../query-engine-rhel-openssl-1.1.x");k.default.join(__dirname,"../query-engine-rhel-openssl-3.0.x");k.default.join(__dirname,"../libquery_engine-darwin.dylib.node");k.default.join(__dirname,"../libquery_engine-darwin-arm64.dylib.node");k.default.join(__dirname,"../libquery_engine-debian-openssl-1.0.x.so.node");k.default.join(__dirname,"../libquery_engine-debian-openssl-1.1.x.so.node");k.default.join(__dirname,"../libquery_engine-debian-openssl-3.0.x.so.node");k.default.join(__dirname,"../libquery_engine-linux-arm64-openssl-1.0.x.so.node");k.default.join(__dirname,"../libquery_engine-linux-arm64-openssl-1.1.x.so.node");k.default.join(__dirname,"../libquery_engine-linux-arm64-openssl-3.0.x.so.node");k.default.join(__dirname,"../libquery_engine-linux-musl.so.node");k.default.join(__dirname,"../libquery_engine-linux-musl-openssl-3.0.x.so.node");k.default.join(__dirname,"../libquery_engine-rhel-openssl-1.0.x.so.node");k.default.join(__dirname,"../libquery_engine-rhel-openssl-1.1.x.so.node");k.default.join(__dirname,"../libquery_engine-rhel-openssl-3.0.x.so.node");k.default.join(__dirname,"../query_engine-windows.dll.node");var Tn=A(require$$3),yo=N("chmodPlusX");function vn(e){if(process.platform==="win32")return;let t=Tn.default.statSync(e),r=t.mode|64|8|1;if(t.mode===r){yo(`Execution permissions of ${e} are fine`);return}let n=r.toString(8).slice(-3);yo(`Have to call chmodPlusX on ${e}`),Tn.default.chmodSync(e,n);}function Cn(e){let t=e.e,r=a=>`Prisma cannot find the required \`${a}\` system library in your system`,n=t.message.includes("cannot open shared object file"),i=`Please refer to the documentation about Prisma's system requirements: ${Tt("https://pris.ly/d/system-requirements")}`,o=`Unable to require(\`${Oe(e.id)}\`).`,s=et({message:t.message,code:t.code}).with({code:"ENOENT"},()=>"File does not exist.").when(({message:a})=>n&&a.includes("libz"),()=>`${r("libz")}. Please install it and try again.`).when(({message:a})=>n&&a.includes("libgcc_s"),()=>`${r("libgcc_s")}. Please install it and try again.`).when(({message:a})=>n&&a.includes("libssl"),()=>{let a=e.platformInfo.libssl?`openssl-${e.platformInfo.libssl}`:"openssl";return `${r("libssl")}. Please install ${a} and try again.`}).when(({message:a})=>a.includes("GLIBC"),()=>`Prisma has detected an incompatible version of the \`glibc\` C standard library installed in your system. This probably means your system may be too old to run Prisma. ${i}`).when(({message:a})=>e.platformInfo.platform==="linux"&&a.includes("symbol not found"),()=>`The Prisma engines are not compatible with your system ${e.platformInfo.originalDistro} on (${e.platformInfo.archFromUname}) which uses the \`${e.platformInfo.binaryTarget}\` binaryTarget by default. ${i}`).otherwise(()=>`The Prisma engines do not seem to be compatible with your system. ${i}`);return `${o}

How to reproduce

I’m running a minimal example, fairly easy to repro

Expected behavior

No response

Prisma information

model User {
  id           String    @id @unique

  auth_session Session[]
  key          Key[]
}

model Session {
  id             String @id @unique
  user_id        String
  active_expires BigInt
  idle_expires   BigInt
  user           User   @relation(references: [id], fields: [user_id], onDelete: Cascade)

  @@index([user_id])
}

model Key {
  id              String  @id @unique
  hashed_password String?
  user_id         String
  user            User    @relation(references: [id], fields: [user_id], onDelete: Cascade)

  @@index([user_id])
}

Environment & setup

  • OS:Macos
  • Database: Neon
  • Node.js version:18

Prisma Version

5.0.0
### Tasks

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 4
  • Comments: 23 (1 by maintainers)

Most upvoted comments

In case someone finds it useful, this is the trick I’ve been using for a while Source: https://github.com/liloryan/iru_belongings/commit/3044d732133df397e324eaef19b8905b31a6f442

Just define a single prisma instance in the project and use it everywhere: import type { PrismaClient as Prisma } from ‘@prisma/client’; import { createRequire } from ‘module’; const require = createRequire(import.meta.url); const { PrismaClient } = require(‘@prisma/client’); const prisma: Prisma = new PrismaClient(); export default prisma;

@Mateleo is correct with their solution.

@manuel-84 @JoeskiG - Make sure you’ve changed your provider from prisma-client-js to prisma-client, or the solution will not work.

This is my generator block. Note - I work exclusively in typescript, but you can swap out configs where you see fit.

generator client {
  provider               = "prisma-client"
  output                 = "../src/generated/prisma"
  runtime                = "nodejs"
  moduleFormat           = "esm"
  generatedFileExtension = "ts"
  importFileExtension    = "ts" 
}

~Same issue for Nuxt~

Ok, I’ve found a solution for the “__dirname is not defined in ES module scope” error.

The issue arises when using ES modules (ESM) in the generated Prisma Client. The __dirname variable is not automatically available in ESM.

Solution:

Explicitly set moduleFormat = "esm" in the generator block of your schema.prisma file. This ensures that the Prisma Client is generated with the correct module format and uses import.meta.url instead of __dirname for resolving file paths.

generator client {
  provider = "prisma-client"
  output   = "../src/generated/prisma"
  moduleFormat = "esm" // Explicitly set module format to ESM
}

ref : https://www.prisma.io/docs/orm/prisma-schema/overview/generators#field-reference-1

I also have this problem and it is a pain. I haven’t found a fix. I am working with Lucia, so it is not a direct import into the hook. But now I am really stuck on my project. I might have to switch to Drizzle unless I find a fix.

@SevInf After using create-svelte-app:

/src/lib/server/db.ts:

import { PrismaClient } from '@prisma/client';
export default new PrismaClient();

/src/hooks.server.ts:

import type { Handle } from "@sveltejs/kit";
import db from '$lib/server/db'

export const handle: Handle = async ({ event, resolve }) => {
	return await resolve(event);
};

If I remove the import from hooks.server.ts, everything works, I can even add it to page server paths and it works - but this is a breaking issue for all sveltekit users! Confirming it works as expected on prisma versions <= 4.16.0.

@Mateleo is correct with their solution.

@manuel-84 @JoeskiG - Make sure you’ve changed your provider from prisma-client-js to prisma-client, or the solution will not work.

This is my generator block. Note - I work exclusively in typescript, but you can swap out configs where you see fit.

generator client {
  provider               = "prisma-client"
  output                 = "../src/generated/prisma"
  runtime                = "nodejs"
  moduleFormat           = "esm"
  generatedFileExtension = "ts"
  importFileExtension    = "ts" 
}

This is not working with nuxt did anyone solved the issue?

@benpoulson Thank you. this solved my issue

I run into the same problem importing prisma to catch the PrismaClientKnownRequestError. I couldnt figure out a way for a workaround for that.

Same error with node build, only when hooks.server.ts is there and using PrismaClient somewhere (in my case with Lucia Auth)

ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/home/sample-user/code/my-app/apps/userapp/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at requireLibrary (file:///home/sample-user/code/my-app/apps/userapp/build/server/chunks/default-BtqcaNrT.js:38:908)
    at file:///home/sample-user/code/my-app/apps/userapp/build/server/chunks/default-BtqcaNrT.js:194:7
    at requireClient (file:///home/sample-user/code/my-app/apps/userapp/build/server/chunks/default-BtqcaNrT.js:435:4)
    at require_default$1 (file:///home/sample-user/code/my-app/apps/userapp/build/server/chunks/default-BtqcaNrT.js:445:20)
    at require_default (file:///home/sample-user/code/my-app/apps/userapp/build/server/chunks/default-BtqcaNrT.js:456:7)
    at file:///home/sample-user/code/my-app/apps/userapp/build/server/chunks/default-BtqcaNrT.js:461:23
    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)
    at async get_hooks (file:///home/sample-user/code/my-app/apps/userapp/build/server/index.js:239:8)
    at async Server.init (file:///home/sample-user/code/my-app/apps/userapp/build/server/index.js:3894:24)

Node.js v20.12.2

Using Prisma 5.13.0 with TS bundled in a Turborepo package called “database”, imported as a dependency.

(Edit : This hack made my build runs well : https://github.com/prisma/prisma/issues/5030#issuecomment-1398076317 The only thing to do with turbo repo, is to remove the default export * from '@prisma/client'; in the index.js/ts and replace it by that :

import type { PrismaClient as PrismaClientType } from '@prisma/client';
import { createRequire } from 'module';

const require = createRequire(import.meta.url ?? __filename);

const { PrismaClient: PrismaClientImpl } = require('@prisma/client');

export class PrismaClient extends (PrismaClientImpl as typeof PrismaClientType) {}

And then import it like that in your /server/* or *.server.ts/js files

import { PrismaClient } from 'your-turbo-repo-database-package';)

Issue is that prisma is a cjs pkg, not esm, but the app runs as esm, so it will fail

What you can do is externalize the dependency

  1. Build prisma client as package in monorepo
  2. Add prisma client cjs package as (runtime) dependency not devDependency to sveltekit project package.json
  3. Mark as external in vite.config.ts: ssr.external

Very helpful: https://discord.com/channels/457912077277855764/1059917031295680562/1219880147193298944