Skip to content
CoursesWeb Forum

How do I fix Cannot use import statement outside a module in Node.js?

Staff answerWritten by Callum Iwu · Node.js and Server Side JavaScript0 replies

Short answer

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.

Written by Callum Iwu · Moderator: PHP, MySQL, Node.js and AI coding tools ·
CiteCoursesWeb 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.
  1. Moderator: 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 module
    

    Here 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 import lines is a package.json next to the file:

    {
      "name": "my-project",
      "version": "1.0.0",
      "type": "module"
    }
    

    Create it with npm init -y if you do not have one, then add the "type" line. Run node app.js again.

    Why it happens

    Node.js has two module systems, CommonJS (require and module.exports) and ECMAScript modules (import and export). The Node.js ES modules documentation says authors can tell Node to read a file as an ES module with the .mjs extension, with "type": "module" in package.json, or with the --input-type=module flag. It also says import statements are permitted only in ES modules. In the other direction, .cjs or "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
    .mjs extension Rename one file A single script in an older CommonJS project
    --input-type=module A 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:

    1. File extensions are required. For relative paths, import './helper' fails and import './helper.js' works. Folders need the full path too, like ./utils/index.js.
    2. require, module.exports and __dirname are not there. Use import and export. For the folder of the current file, the docs list import.meta.dirname (added in v21.2.0 and v20.11.0) and import.meta.filename.
    3. Mixing styles in one file. import statements are allowed only in ES modules, but a dynamic import() 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 a require call, 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 await is not available in this style, which is why the example uses then. Whichever style you pick, use it consistently, because a project that mixes the two produces confusing errors.

    Check this in order

    1. Open package.json. Is there a "type" field? Does its value match the syntax in your file?
    2. 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.
    3. Do your relative imports end in a file extension?
    4. Are you running the file you think you are? Check the path you typed after node.
    5. 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.

    2
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

CoursesWeb Forum. Questions and answers on learning web development: HTML, CSS, JavaScript, PHP, MySQL, Node.js and AI coding help.