SyntaxError: Cannot use import statement outside a module
A .js file is CommonJS unless package.json says module. The three valid configurations, the __dirname cascade, JSON import attributes and the browser version of the same error.

Introduction & Quick Summary
Symptom. Node reads a file and stops on its first import line:
file:///app/src/index.js:1
import { readFile } from "node:fs/promises";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:77:18)The same text appears in a browser console as Uncaught SyntaxError: Cannot use import statement outside a module when a <script> tag loads a file containing import without type="module". Both are the same mistake in different parsers: ESM syntax handed to a CommonJS (or classic script) parser.
Cause. In Node, the module format of a .js file is decided by the nearest package.json: "type": "module" makes .js files ESM, anything else makes them CommonJS. A .mjs file is always ESM and a .cjs file is always CommonJS. When no type field exists, import/export at the top level of a .js file is a syntax error, because CommonJS has no such statement.
Fix. Choose the format deliberately: add "type": "module" to the package and keep .cjs for the files that must stay CommonJS, or leave the package CommonJS and rename ESM files to .mjs. Converting usually exposes follow-ups — __dirname disappears, relative imports need an extension, require() of a JSON file becomes an import attribute — and those are section 4.
Core Mechanics, Signatures & Reproducible Setup
Node decides in this order: extension (.mjs → ESM, .cjs → CommonJS), then the nearest package.json type field, then the default CommonJS. Nothing else — not file contents, not import usage — changes the decision.
mkdir esm-demo && cd esm-demo
cat > index.js <<'JS'
import os from "node:os";
console.log(os.platform());
JS
node index.js
# SyntaxError: Cannot use import statement outside a module
node --input-type=module index.js # still fails: --input-type applies to stdin/-e only
node --check index.js # same syntax error, without executingConfirm what Node believes about the file instead of guessing:
node -p "require('./package.json').type ?? '(absent -> commonjs)'"
node -p "require('module').findPackageJSON ? 'has findPackageJSON (node 22.12+)' : 'older'"
node --versionnode --check and node -p are read-only and worth running before any edit, because the error can also come from a dependency's file loaded through a dynamic import(), where the terminal line number points at code you did not write.
The three valid configurations, with the resulting behaviour:
# package.json: { "type": "module" }
index.js -> ESM index.cjs -> CommonJS
# package.json: { "type": "commonjs" } or absent
index.js -> CommonJS index.mjs -> ESMKey Comparison Table
| Setting | .js | .mjs | .cjs | require() of ESM |
|---|---|---|---|---|
"type": "module" | ESM | ESM | CommonJS | Fails before Node 22.12 with ERR_REQUIRE_ESM |
"type": "commonjs" | CommonJS | ESM | CommonJS | ERR_REQUIRE_ESM |
No type field | CommonJS | ESM | CommonJS | ERR_REQUIRE_ESM |
--experimental-default-type=module | ESM | ESM | CommonJS | — |
What changes after switching a package to ESM:
| In CommonJS | In ESM |
|---|---|
require("./util") | import "./util.js" — extension required |
require("./dir") resolves dir/index.js | Directory imports are not resolved; import "./dir/index.js" |
__dirname, __filename | import.meta.dirname, import.meta.filename (Node 20.11+) |
require("./data.json") | import data from "./data.json" with { type: "json" } (Node 22+) |
module.exports = fn | export default fn |
Free top-level await is illegal | Allowed at module top level |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Adding "type": "module" and hitting __dirname is not defined
The classic cascade. Every CommonJS global written as a bare identifier now throws ReferenceError: __dirname is not defined in ES module scope. The replacement is import.meta:
// before (CommonJS)
const path = require("node:path");
const dataFile = path.join(__dirname, "data.json");
// after (ESM)
import path from "node:path";
// Node 20.11+ and 21.2+ only:
const dataFile = path.join(import.meta.dirname, "data.json");
// portable fallback for older Node
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const port = path.join(here, "data.json");import.meta.dirname is undefined before Node 20.11, which turns a working file into TypeError: The "path" argument must be of type string on an older runtime — check engines before using it.
2. Relative imports that worked before and now fail
ESM has no extension guessing. import { x } from "./lib/util" throws ERR_MODULE_NOT_FOUND, and a directory import fails too. TypeScript users see this twice, because the compiler accepts ./util under "module": "commonjs" and rejects or misemits it under NodeNext:
// tsconfig.json
{ "compilerOptions": { "module": "nodenext", "moduleResolution": "nodenext",
"target": "es2022", "verbatimModuleSyntax": true } }// source: write .js, even though the file on disk is .ts
import { slugify } from "./lib/slugify.js";
import type { Post } from "./types/post.js";Under nodenext the emitted import keeps the extension, so .js is correct in the source. Writing ./lib/slugify.ts compiles with allowImportingTsExtensions and then fails at runtime.
3. One package, two formats: the .cjs escape hatch
The cleanest migration path for a codebase with one stubborn CommonJS dependency is a per-file override rather than a per-package flag. Set "type": "module", keep the odd file as .cjs, and reference it with createRequire where you must call into CommonJS:
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const legacy = require("./legacy/old-tool.cjs"); // CommonJS, from an ESM file
const pkg = require("./package.json"); // JSON without import attributescreateRequire is also the pragmatic way to read JSON below Node 22, where with { type: "json" } is not yet available for import.
4. Test runners keep their own opinion
Jest's default transform runs files through Babel's CommonJS transform, so a repo that works with node fails under jest with the same message. Vitest reads the package type and is usually fine. For Jest, either keep the test files in CommonJS (.cjs, .test.cjs) or point Jest at the ESM path:
// jest.config.mjs
export default {
testEnvironment: "node",
transform: {},
extensionsToTreatAsEsm: [".ts"],
moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1" },
};Run it with NODE_OPTIONS=--experimental-vm-modules npx jest. The alternative — ts-jest plus a tsconfig with "module": "commonjs" — is simpler and reintroduces none of this; pick one and keep the test toolchain in the same format as production.
5. require() of an ESM-only dependency
An ESM-only package has no CommonJS entry, so require("chalk") in a CommonJS file throws ERR_REQUIRE_ESM (or Cannot use import statement outside a module if the package ships one .js flagged as ESM). Node 22.12 and 23 enable require(esm) for modules without top-level await; older runtimes need the dynamic form:
// works on every Node 14+
const chalk = (await import("chalk")).default; // inside an async functionNowhere is this sharper than in a CLI: the top-level await is legal only in an ESM file, so a CommonJS entry point has to wrap the dynamic import in an async main().
6. The browser version of the error
<script src="/app.js"> parsing import fails because classic scripts are not modules. The fix is one attribute, plus the CORS and MIME rules that come with modules:
<script type="module" src="/app.js"></script>Modules are deferred, always strict, and fetched with CORS semantics, so opening index.html from file:// fails with an opaque CORS error and a server returning Content-Type: text/html for a .js file fails with Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html".
Common Compilation/Runtime Mistakes & Version Gotchas
- Setting
"type": "module"without checking every.jsfile. CommonJS syntax (require,module.exports,__dirname) is then aReferenceErrorat runtime, not a build error. - Forgetting the lockfile and
node_modules. Some tooling caches the resolution; after changingtype, reinstall before concluding the change did nothing. --experimental-specifier-resolution=node. Removed in Node 19; the flag no longer restores extensionless imports, and code relying on it breaks silently on new Node majors.- Bare
import "./config"in TypeScript withmoduleResolution: bundler. It compiles, then fails under Node withERR_MODULE_NOT_FOUND;nodenextis what catches it. - JSON imports without attributes.
import pkg from "./package.json"needswith { type: "json" }on Node 22+ andassert { type: "json" }on 18 and 20. Missing attributes produceERR_IMPORT_ATTRIBUTE_MISSING, not the original message. __dirnamein a.mjsfile copied from documentation. Older guides suggestimport.meta.urlplusfileURLToPath; keep the fallback ifengines.nodeallows below 20.11.node --input-type=module file.js. The flag applies only to--evaland stdin, so it changes nothing for a file and wastes an afternoon.- Dual-package hazard. A package that ships both CJS and ESM builds can be loaded twice, producing two copies of a singleton. Use an
exportsmap withimport/requireconditions and test both entry points.
Related tools. When a package.json change is in play, format both the before and after manifests with the JSON formatter and diff them with the text diff tool — a missing "type" key or a stray "exports" block is invisible in a one-line terminal output — and keep the exact node --version in the issue, since the same file behaves differently on 18, 20 and 22.
Official references
primary documentationThe Node.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesnpm ERESOLVE: unable to resolve dependency tree
Since npm 7 a peer conflict is a hard error. How to read the tree dump, and when to upgrade, override, use --legacy-peer-deps, or reach for --force.
ERR_OSSL_EVP_UNSUPPORTED: digital envelope routines on OpenSSL 3
Node 17+ ships OpenSSL 3, where md4 lives in a legacy provider webpack 4 asks for by default. Upgrade, change hashFunction, or bridge with the legacy provider.
Node.js JWT invalid signature: JWKS Rotation and Clock Skew
One message covers three bugs: the wrong key type for RS256 or ES256, a JWKS cache that never refreshes after a kid rotation, and a clock that drifted.
ERR_REQUIRE_ESM and __dirname Is Not Defined in ESM Projects
require of an ESM-only package has nothing to load, and ESM creates none of the CommonJS wrapper globals. Dynamic import, createRequire, and the path replacements.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.