How do I fix Cannot use import statement outside a module in Node.js?
Node.js is treating your file as CommonJS, where import is not allowed. Tell Node the file is an ES module: add "type": "module" to the nearest package.json, or rename the file to .mjs. Or keep CommonJS and replace each import with require(). Pick one style for the whole project.
Cite
CoursesWeb Forum, "How do I fix Cannot use import statement outside a module in Node.js?", https://coursesweb.net/forum/t/how-do-i-fix-cannot-use-import-statement-outside-a-module-in-nodejs/, accessed 2026-11-21.- Callum IwuStaffModerator: PHP, MySQL, Node.js and AI coding tools ·
The error and the smallest fix
You write modern syntax, run
node app.js, and get:SyntaxError: Cannot use import statement outside a moduleHere is a file that triggers it in a project without any marker:
// app.js import { readFile } from 'node:fs/promises'; const text = await readFile('./notes.txt', 'utf8'); console.log(text.length);The fix that keeps your
importlines is a package.json next to the file:{ "name": "my-project", "version": "1.0.0", "type": "module" }Create it with
npm init -yif you do not have one, then add the"type"line. Runnode app.jsagain.Why it happens
Node.js has two module systems, CommonJS (
requireandmodule.exports) and ECMAScript modules (importandexport). The Node.js ES modules documentation says authors can tell Node to read a file as an ES module with the.mjsextension, with"type": "module"in package.json, or with the--input-type=moduleflag. It also saysimportstatements are permitted only in ES modules. In the other direction,.cjsor"type": "commonjs"marks CommonJS.The same page says that when there is no explicit marker, Node inspects the source for ES module syntax and runs the file as an ES module if it finds some, otherwise as CommonJS. Detection depends on your Node version and on the file, so do not rely on it. An explicit marker works the same everywhere.
Your options compared
Option What you change Good for "type": "module"One line in package.json Whole projects written with import.mjsextensionRename one file A single script in an older CommonJS project --input-type=moduleA flag on the command line Rare one-off command line use, not for normal files Stay on CommonJS Use require()Following an older tutorial without changes What changes once you are in module mode
The ES modules page lists differences that catch beginners:
- File extensions are required. For relative paths,
import './helper'fails andimport './helper.js'works. Folders need the full path too, like./utils/index.js. require,module.exportsand__dirnameare not there. Useimportandexport. For the folder of the current file, the docs listimport.meta.dirname(added in v21.2.0 and v20.11.0) andimport.meta.filename.- Mixing styles in one file.
importstatements are allowed only in ES modules, but a dynamicimport()expression works in CommonJS too, which is how you load an ES module from old code.
Our CoursesWeb page on moving and copying files in Node.js is a good small project to try after the switch.
If you would rather stay on CommonJS
Sometimes the tutorial you follow is written with
require(), and you want it to run as is. Then change the code instead of the project. Replace the import line with arequirecall, and do not add"type": "module":// app.js, CommonJS version const { readFile } = require('node:fs/promises'); readFile('./notes.txt', 'utf8').then((text) => console.log(text.length));Top level
awaitis not available in this style, which is why the example usesthen. Whichever style you pick, use it consistently, because a project that mixes the two produces confusing errors.Check this in order
- Open package.json. Is there a
"type"field? Does its value match the syntax in your file? - Is there more than one package.json? Node reads the nearest one above the file, so a package.json in a subfolder can override the one at the top.
- Do your relative imports end in a file extension?
- Are you running the file you think you are? Check the path you typed after
node. - Does a tool in front of Node (a test runner, a bundler, a TypeScript setup) read its own config for the module type? Each has its own setting.
The Node.js packages documentation has the full rules, including a section on how Node determines the module system.
- File extensions are required. For relative paths,
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.