#ReferenceError: __dirname is not defined in ES module scope

1 messages · Page 1 of 1 (latest)

plush stratusBOT
#

You've gone full bot mode! Let me fetch that AI answer for you ASAP.

plush stratusBOT
# plush stratus You've gone full bot mode! Let me fetch that AI answer for you ASAP.

This error occurs when using Prisma in an ES module environment (indicated by .js files in a project with "type": "module" in package.json). The issue is that Prisma's client uses __dirname which isn't available in ES modules.

Solutions:

1. Use moduleFormat = "esm" with prisma-client provider

generator client {
  provider     = "prisma-client"
  output       = "../src/generated/prisma"
  moduleFormat = "esm"
}

This ensures Prisma Client uses import.meta.url instead of __dirname for file path resolution.

2. Create a CommonJS wrapper

import type { PrismaClient as ImportedPrismaClient } from "@prisma/client";
import { createRequire } from "module";

const require = createRequire(import.meta.url);
const { PrismaClient: RequiredPrismaClient } = require("@prisma/client");

const _PrismaClient = RequiredPrismaClient;

export class PrismaClient extends _PrismaClient {}

3. Add a global definition

For build scripts, you can add a global definition of __dirname:

sed -i '1i\globalThis.__dirname = "/";' "node_modules/.../library.js"

4. For Nuxt/SvelteKit projects

In Nuxt, you can add to your config:

build: {
  transpile: ['~/prisma/client'],
}

For SvelteKit, a post-build script can fix the issue:

sed -i '/await server.init/i \
globalThis.__filename = fileURLToPath(import.meta.url); \
globalThis.__dirname = path.dirname(__filename);' build/handler.js

This issue is particularly common in SvelteKit, Nuxt, and other modern frameworks that use ES modules by default.

GitHub Issue #15614
GitHub Issue #20702

plush stratusBOT