SyntaxError: Cannot use import statement outside a module: how to fix it in Node.js
SyntaxError: 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.
By Livops team, the people who build and run LivopsUpdated
As Node.js 24 prints it (shortened; paths vary):
(node:41) Warning: Failed to load the ES module: /app/src/index.js. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.
/app/src/index.js:1
import express from "express";
^^^^^^
SyntaxError: Cannot use import statement outside a module
And the reverse:
file:///app/src/index.js:1
const express = require("express");
^
ReferenceError: require is not defined in ES module scope, you can use import instead
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.
This page explains the two module systems in Node.js, how Node.js decides which one a file belongs to, the reasons the error appears only after a deploy, and the fix for each. The last section shows where it surfaces on Livops.
What does the error mean?
Node.js has two module systems: CommonJS, with require() and module.exports, and ECMAScript modules (ES modules), with import and export[2]. Each file is loaded by one of them, and the syntax of the other is an error there.
Cannot use import statement outside a module: Node.js loaded the file as CommonJS, and it contains animportstatement.require is not defined in ES module scope: Node.js loaded the file as an ES module, which has norequire,exportsormodule.exports, and no__filenameor__dirname[2]. Node.js addsyou can use import instead, and when the reason is"type": "module"inpackage.json, it names that file and suggests the.cjsextension[6]. The same happens forexports:ReferenceError: exports is not defined in ES module scope.
The fix is rarely in the line the error points at. It is in how Node.js classified the file.
How does Node.js decide which kind a file is?
In this order[1]:
| File | Nearest package.json |
Loaded as |
|---|---|---|
.mjs |
anything | ES module |
.cjs |
anything | CommonJS |
.js |
"type": "module" |
ES module |
.js |
"type": "commonjs" |
CommonJS |
.js |
no type field, or no package.json at all |
CommonJS, unless it contains ES module syntax |
The extension wins: .mjs is always an ES module and .cjs always CommonJS, whatever type says[1]. The type field applies to every .js file that has that package.json as its nearest parent[1].
The last row is syntax detection. For a .js file with no type to go by, Node.js tries CommonJS first and, if the parser finds ES module syntax (import, export, import.meta, a top-level await), runs the file again as an ES module[1]. Detection has been on by default since Node.js 22.7.0 and 20.19.0[1]; before that, such a file failed with this error. It works, but it costs time, and Node.js asks package authors to always set type[1]. It prints a MODULE_TYPELESS_PACKAGE_JSON warning that says the same.
So on a current Node.js, Cannot use import statement outside a module means the file was explicitly CommonJS: a .cjs file, or "type": "commonjs" in package.json.
Causes, most common first
1. package.json says “type”: “commonjs”
You may never have typed it: npm init writes the type field, and its default value is "commonjs"[8]. With that line, every .js file in the package is CommonJS and syntax detection does not apply[1].
Fix, if the project uses import throughout: say so in package.json.
{
"type": "module",
"scripts": {
"start": "node src/index.js"
}
}
Then every .js file under it is an ES module[1], including config files that use require or module.exports. Those now fail with the reverse error. Rename each of them to .cjs, which stays CommonJS whatever type says[1].
Fix, if only one file is different: rename that file to .mjs (an ES module) or .cjs (CommonJS), and leave type alone.
2. One file mixes import and require
A file with both import at the top and require() below it is treated as an ES module, either by "type": "module" or by syntax detection, and then require does not exist. Convert the require calls to import. Where you cannot, build a require function[4]:
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const legacy = require("./legacy.cjs");
__dirname and __filename have replacements too: import.meta.dirname and import.meta.filename[2], added in Node.js 21.2.0 and 20.11.0[2].
import path from "node:path";
const dataDir = path.join(import.meta.dirname, "data"); // was path.join(__dirname, "data")
Relative imports in an ES module also need the file extension, ./utils.js and not ./utils[2]. Missing it is a different error, covered in Cannot find module.
3. TypeScript is compiled to the wrong module format
tsc decides whether the .js it writes uses import or require, from the module option in tsconfig.json. Two mismatches are common:
"module": "commonjs"with"type": "module". The output usesrequireandexports, and Node.js loads it as an ES module:ReferenceError: exports is not defined in ES module scope. The handbook says ofcommonjsfor Node.js: you probably should not use it[7]."module": "esnext"for a server. The output usesimport. The handbook says not to useesnextfor Node.js; it is meant for bundlers[7].
Fix: use nodenext (or node16, node18, node20), which the handbook calls the only correct module options for code that runs in Node.js[7]. With it, each file’s format follows the same rules Node.js uses: .mts is an ES module, .cts is CommonJS, and .ts is an ES module if the nearest package.json has "type": "module", otherwise CommonJS[7]. The emitted JavaScript gets the same format[7], so tsc and Node.js agree by construction. module: nodenext also sets moduleResolution: nodenext[7].
{
"compilerOptions": {
"module": "nodenext",
"outDir": "dist"
}
}
Under nodenext, a relative import without an extension is not supported[7]: write import { db } from "./db.js" in the .ts source.
4. The start command runs the source, not the build
The code is fine after the build, but the server starts something else: node src/index.js when src/ is written for a bundler or Babel, or a .ts file. Point the start command at what the build writes:
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
About running .ts directly: Node.js strips TypeScript types by default since 23.6.0 and 22.18.0[5]. A .ts file gets its module system the same way as a .js file, so to use import it needs "type": "module"; .mts is always an ES module and .cts always CommonJS[5]. Node.js does not read tsconfig.json[5], and it refuses TypeScript files inside node_modules[5]. Older versions do not run .ts files by default. A build step is the predictable choice for a server.
5. The server runs a different Node.js version
Three behaviours in this area depend on the version:
- syntax detection for
.jsfiles withouttype: on by default from 22.7.0 and 20.19.0[1]; - running
.tsfiles: by default from 23.6.0 and 22.18.0[5]; require()of an ES module from CommonJS: no flag needed from 22.12.0 and 20.19.0[3]. It loads only modules without top-levelawait; for those it throwsERR_REQUIRE_ASYNC_MODULE, and you load them withimport()instead[3].
A project that works on your Node.js 24 can fail on an older Node.js on the server. Check node --version in both places, and pin the version in the project.
In Jest tests
If the error comes from Jest rather than from your server: Jest’s support for ES modules is experimental[9]. To use it, turn off code transforms with transform: {} (or make your transformer emit ES modules) and run Jest under node --experimental-vm-modules[9]:
NODE_OPTIONS="$NODE_OPTIONS --experimental-vm-modules" npx jest
How to confirm the fix locally
Run what the server runs, from a fresh clone, with the server’s Node.js version:
git clone <your repo> /tmp/check && cd /tmp/check
node --version
node -p "require('./package.json').type" # module, commonjs, or undefined
npm ci && npm run build
npm start
To try another Node.js version without installing it:
docker run --rm -v "$PWD":/app -w /app node:22 sh -c "npm ci && npm run build && npm start"
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, theSyntaxErroramong 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. -
The start command. Set it in Settings → Start. In
livops.json,startis applied when the project is created; after that it is changed in the project’s settings. AProcfileat the project root works too:web:for a site or an API,worker:for a bot.{ "build": "npm run build", "start": "node dist/index.js" } -
Without a start command, Livops looks for the
startscript inpackage.json, then themainfield, thenindex.js,server.js,app.js,main.js. For TypeScript, its docs say what cause 4 says: build first and start the built file, for examplenode dist/main.js. See No start command. -
Node.js versions. Livops has Node.js 22 and 24. It reads
.nvmrcand.node-version, anddevEngines.runtime.versioninpackage.jsoncan ask for 22 or 24. See Install failed.
A start that fails with Cannot find module instead is in Error: Cannot find module, and running a Node.js server in production in Node.js hosting.
Questions
Should I add "type": "module" or rename the file to .mjs?
Add "type": "module" when the whole project uses import and export: every .js file under that package.json becomes an ES module. Rename one file to .mjs, or to .cjs, when only that file is different. The extension wins over the type field.
Why does it work on my machine but not on the server?
Usually the Node.js version or the start command differs. Node.js 22.7 and later, and 20.19 and later, detect ES module syntax in a .js file when package.json has no type field; older versions do not. And the server may start a source file your machine never runs directly, such as src/index.js instead of the built dist/index.js.
What does ReferenceError require is not defined in ES module scope mean?
The reverse problem. Node.js loaded the file as an ES module, where require, exports, module.exports, __filename and __dirname do not exist. Replace require with import, rename the file to .cjs to keep it CommonJS, or build a require function with createRequire from node:module.
How do I get __dirname in an ES module?
Use import.meta.dirname and import.meta.filename. They were added in Node.js 21.2 and 20.11, so Node.js 22 and 24 have them, and they work only for modules loaded from files.
Which tsconfig module setting should a Node.js app use?
nodenext, or node16, node18 or node20. The TypeScript handbook calls them the only correct module options for code that runs in Node.js. Each .ts file is then emitted as an ES module when package.json says "type": "module", and as CommonJS otherwise. esnext is meant for bundlers, not for Node.js.
Can I start a .ts file with node directly?
In Node.js 22.18 and later, and 23.6 and later, type stripping is on by default, so node src/index.ts runs. The module format is decided as for a .js file, tsconfig.json is ignored, and import paths need their .ts extension. A build with tsc and a start command that runs the built file is the safer choice for a server.
Where do I set the start command on Livops?
In the project's Settings, under Start, or in a Procfile at the project root. The start field of livops.json is applied only when the project is created; after that, change it in the settings.
Sources
- Node.js Docs — Modules: Packages (nodejs.org). Checked .
- Node.js Docs — Modules: ECMAScript modules (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 — Modules: TypeScript (nodejs.org). Checked .
- Node.js source — lib/internal/modules/esm/module_job.js (github.com). Checked .
- TypeScript Handbook — Modules: Reference (typescriptlang.org). Checked .
- npm Docs — config (docs.npmjs.com). Checked .
- Jest Docs — ECMAScript Modules (jestjs.io). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your Node appRelated
- 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.
- 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.
- npm failed with return code 1 (npm ERR! code 1): how to fix the buildnpm failed with return code 1, or npm install exited with 1, is npm ERR! code 1 in newer npm: it only says that a script npm ran exited with code 1. The real error is printed above it: usually a compile or type error, a lockfile out of sync with package.json, or a dependency whose install script failed. Find the first error line above code 1, fix that, and the build passes.
- 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.
- Telegraf bot hosting: deploying a Telegraf 4 bot on Node.jsA Telegraf bot is one Node.js process: bot.launch() for polling, or bot.webhookCallback() behind an HTTP server for a webhook, with bot.stop() on SIGTERM. On Livops a repository with telegraf in package.json is run as a bot from every push, for 19 credits a month (19,000 so'm).
- ReferenceError: __dirname is not defined in ES module scope: how to fix itNode.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.
- 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.