ReferenceError: __dirname is not defined in ES module scope: how to fix it
Node.js runs the file as an ES module, because package.json says "type": "module", the file ends in .mjs, or it uses import syntax, and ES modules have no __dirname, __filename or require. Use import.meta.dirname and import.meta.filename (Node.js 20.11 and 21.2 and later), path.dirname(fileURLToPath(import.meta.url)) on older versions, createRequire for require, or rename the file to .cjs to keep it CommonJS.
By Livops team, the people who build and run LivopsUpdated
As Node.js 24 prints it, when a .js file uses __dirname in a package whose package.json has "type": "module" (stack trimmed, paths shortened):
file:///app/index.js:1
console.log(__dirname)
^
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 '/app/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///app/index.js:1:13
__filename gives the same message with its own name. The sibling for require adds a hint[6]:
ReferenceError: require is not defined in ES module scope, you can use import instead
The second line, about "type": "module", appears only for a .js file under such a package.json[6]; a .mjs file gets the first line alone. This page explains why the names are missing, gives the four fixes, and covers why the error often shows up only after a deploy. It is a Node.js error, not one specific to any host.
What does the error mean?
In CommonJS, Node.js wraps each file in a function before running it, (function(exports, require, module, __filename, __dirname) { … }), and that is where __dirname, __filename and require come from[3]. ES modules are not wrapped. Node’s docs list it among the differences: no require, exports or module.exports, and no __filename or __dirname[1]. So in an ES module these are plain undefined names, and the first line that uses one throws.
Node.js runs a file as an ES module when[2]:
- it ends in
.mjs; - it ends in
.jsand the nearest parentpackage.jsonhas"type": "module"; - it ends in
.jswith notypefield to say otherwise, and contains ES module syntax —importorexportstatements,import.meta, or top-levelawait. This syntax detection is on by default since Node.js 22.7.0 and 20.19.0[2].
A .cjs file is always CommonJS, whatever package.json says[2].
Fix 1: import.meta.dirname and import.meta.filename
The direct replacements[1]:
import path from 'node:path'
const configPath = path.join(import.meta.dirname, 'config.json')
console.log(import.meta.filename) // was __filename
import.meta.dirname is the directory of the current module and import.meta.filename its full path, with symlinks resolved[1]. Both were added in Node.js 21.2.0 and 20.11.0, and are no longer experimental since 24.0.0 and 22.16.0[1]. They exist only for modules loaded from file: URLs[1], which is every file on disk.
On an older Node.js they are undefined, and the error moves: path.join(undefined, …) throws a TypeError about the "path" argument instead. If you must support those versions, use fix 2.
Fix 2: fileURLToPath(import.meta.url), for older Node.js
Works on every Node.js that runs ES modules. import.meta.filename is the same as url.fileURLToPath() of import.meta.url[1], and import.meta.dirname is its path.dirname()[1]:
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
fileURLToPath decodes percent-encoded characters and returns a valid absolute path for the platform[5], so do not slice the URL string by hand: a path with spaces breaks that way.
Fix 3: createRequire, when you need require
import covers most uses: it can load CommonJS packages too[1]. Where you really need require, build one for the current file with module.createRequire()[1][4]:
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const legacy = require('./legacy-config.cjs')
For a JSON file you do not need it: import attributes load JSON in an ES module, and the JSON comes back as the default export[1]:
import packageConfig from './package.json' with { type: 'json' }
JSON modules stopped being experimental in Node.js 23.1.0, 22.12.0, 20.18.3 and 18.20.5[1].
Fix 4: keep the file CommonJS
If the code is CommonJS, and only one file or the package’s setting makes it an ES module, change that instead:
- One file: rename it to
.cjs, as the error message itself suggests[6]. A.cjsfile is CommonJS even in a"type": "module"package[2]. - The whole package: set
"type": "commonjs", or remove the field. Then.jsfiles run as CommonJS[2]. Rename the files that useimportto.mjs: without atypefield Node.js would detect them, but its docs say that costs performance and ask packages to be explicit[2].
Mixing the two in one file does not work. A file with no type that uses both __dirname and top-level await stops with a different message, because Node.js cannot tell which format was meant[6]:
ReferenceError: Cannot determine intended module format because both '__dirname' and top-level await are present. If the code is intended to be CommonJS, wrap await in an async function. If the code is intended to be an ES module, use import.meta.dirname instead.
code: 'ERR_AMBIGUOUS_MODULE_SYNTAX'
Why it appears only after a deploy
The code that runs on the server is often not the code you run locally. The usual reasons:
- The build output changed format. With
--module nodenext, TypeScript emits each.tsfile as an ES module if the nearestpackage.jsonhas"type": "module", and as CommonJS otherwise;.mtsalways becomes ESM and.ctsCommonJS[7]. Adding"type": "module"turns the same source into ES module output, and a__dirnamein it now throws. - A bundler emits ESM.
__dirnameexists only in CommonJS; tsup, for example, fills it in for its ESM output only when itsshimsoption is on, aspath.dirname(fileURLToPath(import.meta.url))[8]. "type": "module"was added topackage.json, often to use a package that ships only as an ES module (see ERR_REQUIRE_ESM). Every.jsfile in the package becomes an ES module at once[2], including scripts nobody touched.- A newer Node.js on the server. A
.jsfile with notypefield that usesimportruns as an ES module on Node.js 22.7.0 and 20.19.0 or later[2]; an older Node.js stopped at theimportwith Cannot use import statement outside a module. The new Node.js gets further, to the first__dirname. - An older Node.js on the server, the reverse case: code that uses
import.meta.dirnameruns on your Node.js 22 and getsundefinedon a server older than 20.11.0[1].
How to confirm the fix
Run the file the way the server runs it — the built output, with the server’s Node.js version:
node --version
node dist/index.js
To see which format Node.js uses for a file, check its extension and the type field of the nearest package.json above it[2]. In that package.json’s folder:
node -p "require('./package.json').type"
module means .js files there are ES modules; undefined means CommonJS unless the file contains ES module syntax[2].
On Livops
- Where it shows. The build passes, the app stops right after it starts, and the deploy fails as
start_failed. The Logs page shows the app’s last words, theReferenceErroramong them, often with a Tip: line under it. A web app’s previous version keeps running; a bot’s previous version is stopped first, so the bot is down until a deploy succeeds. See The app did not start. - Node.js versions. Livops has Node.js 22 and 24. It reads
.nvmrcand.node-version, anddevEngines.runtime.versioninpackage.jsoncan ask for 22 or 24. Both versions haveimport.meta.dirnameandimport.meta.filename, so fix 1 works without a fallback. - The start command decides which file runs. Set it in Settings → Start. Without one, Livops looks for the
startscript inpackage.json, then themainfield, thenindex.js,server.js,app.js,main.js. In a TypeScript project, build first and start the built file, for examplenode dist/main.js— that built file is the one to test locally. See No start command.
A Node.js web app costs 39 credits a month; a bot or worker 19. Running a Node.js server in production is covered in Node.js hosting.
Questions
Why is __dirname not defined in ES module scope?
In CommonJS, Node.js wraps every file in a function that passes in __dirname, __filename, require, module and exports. ES modules are not wrapped that way, so those names do not exist there. Node's docs list them under the differences between ES modules and CommonJS.
What replaces __dirname in an ES module?
import.meta.dirname, and import.meta.filename for __filename. They were added in Node.js 21.2.0 and 20.11.0 and are no longer experimental since 24.0.0 and 22.16.0. On older versions use path.dirname(fileURLToPath(import.meta.url)).
Why does my file count as an ES module?
Node.js treats a file as an ES module if it ends in .mjs, if it ends in .js and the nearest package.json has "type": "module", or, with no type field at all, if it contains import, export, import.meta or top-level await. The error message says which one when it is the type field.
How do I use require in an ES module?
Prefer import. Where you need require, for example for a JSON file or a package that only works with require, build one: import { createRequire } from 'node:module' and const require = createRequire(import.meta.url).
Why does it work on my machine but fail after deploy?
The server runs different code or a different Node.js. Usually the build output changed format: TypeScript emits ES modules once package.json has "type": "module", and a bundler can emit ESM. A newer Node.js also detects ES module syntax by default, from 22.7.0 and 20.19.0.
Can I just remove "type": "module" from package.json?
Only if your code is CommonJS. Without it, .js files run as CommonJS, and files that use import should be renamed to .mjs; Node.js can detect them, but at a performance cost. To keep one file CommonJS inside a type module package, rename it to .cjs instead.
Which Node.js version does Livops run?
Node.js 22 or 24, chosen with .nvmrc, .node-version or devEngines.runtime.version in package.json. Both have import.meta.dirname and import.meta.filename.
Sources
- Node.js Docs — Modules: ECMAScript modules (nodejs.org). Checked .
- Node.js Docs — Modules: Packages (nodejs.org). Checked .
- Node.js Docs — Modules: CommonJS modules (nodejs.org). Checked .
- Node.js Docs — Modules: node:module API (nodejs.org). Checked .
- Node.js Docs — URL (nodejs.org). Checked .
- Node.js v24.16.0 source — lib/internal/modules/esm/module_job.js (raw.githubusercontent.com). Checked .
- TypeScript Handbook — Modules: Reference (typescriptlang.org). Checked .
- tsup — documentation (raw.githubusercontent.com). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your Node appRelated
- Error [ERR_REQUIRE_ESM]: require() of ES Module not supported: how to fix itError [ERR_REQUIRE_ESM]: require() of ES Module not supported means CommonJS code called require() on a package that ships only as an ES module, as node-fetch 3, chalk 5 and nanoid 4 do. Node.js 22.12.0 and 20.19.0 and later can require() such a module unless it uses top-level await, which throws ERR_REQUIRE_ASYNC_MODULE instead. Otherwise switch the project to ES modules, load the package with import(), or pin the last CommonJS major.
- SyntaxError: Cannot use import statement outside a module: how to fix it in Node.jsSyntaxError: Cannot use import statement outside a module means Node.js loaded a file as CommonJS and found an ES module import in it. The reverse, ReferenceError: require is not defined in ES module scope, means it loaded the file as an ES module and found require. Node.js decides by the file extension and the type field in package.json: set "type": "module", rename the file to .mjs or .cjs, or compile TypeScript with module nodenext and start the built file.
- Error: Cannot find module (MODULE_NOT_FOUND) in Node.js: how to fix itError: Cannot find module 'x' with code MODULE_NOT_FOUND, or ERR_MODULE_NOT_FOUND with import, means Node.js looked for a package or file and it was not there. On a server the usual causes are a package missing from package.json, a devDependency the install skipped, a path whose case differs from the file, a start command pointing at a file that was never built, or an ES module import without its .js extension.
- error TS2307: Cannot find module 'x' or its corresponding type declarations: how to fix iterror TS2307: Cannot find module 'x' or its corresponding type declarations means the TypeScript compiler could not find a file or type declarations for an import. The usual causes: the package is not installed, an @/ path alias missing from paths in tsconfig.json, a moduleResolution setting that does not match how the package or your imports are written, and .css, .svg or image imports with no declaration. It is a compile-time error from tsc, not Node.js's runtime Cannot find module or a bundler's Can't resolve.
- Module not found: Can't resolve './components/Header' in webpack and Next.js: how to fix itModule not found: Can't resolve './components/Header' means the bundler followed an import and found no file or package there. The usual causes: the file name's case differs from the import (fine on macOS and Windows, fatal on a Linux build server), a wrong relative path or a missing extension, a package that is not in package.json, an @/ alias the bundler does not know, and, for Can't resolve 'fs', Node-only code pulled into the browser bundle.
- Node.js hosting in 2026: how to deploy an Express appA Node.js server in production needs one long-running process that listens on the port it is given, restarts when it crashes and exits cleanly on SIGTERM. On Livops you push a repository with package.json and it runs as a web app for 39 credits a month (39,000 so'm). Here is what Node needs, and how a VPS, Render, Railway, Fly.io, DigitalOcean and Heroku compare.
- Express.js hosting in 2026: the options comparedAn Express app in production needs one long-running Node process that listens on process.env.PORT on every interface, trusts exactly the proxy in front of it, exits cleanly on SIGTERM, and keeps sessions and data in a database rather than in memory. On Livops an Express repository deploys from a push for 39 credits a month (39,000 so'm). Here is how Render, Railway, Fly.io, Vercel and a VPS with pm2 compare.