← Back to Error Lab

SyntaxError: Cannot use import statement outside a module

Published 2026-04-13

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

Node.js traditionally uses CommonJS (`require()` and `module.exports`) for module resolution. This error occurs when you try to use ECMAScript module syntax (`import` and `export`) in a Node.js script without explicitly telling Node that the file should be treated as an ES module. By default, Node.js treats `.js` files as CommonJS. The JavaScript engine encounters the `import` keyword, doesn't recognize it in the current context, and throws a syntax error.

Fix / Solution

There are two primary ways to fix this. You can change the file extension from `.js` to `.mjs` to explicitly mark it as an ES module. Alternatively, and more commonly for larger projects, you can add `"type": "module"` to your `package.json` file. This tells Node.js to treat all `.js` files in the project as ES modules.

Code Snippet

// ❌ Throws error in a standard Node.js environment
import { myFunc } from './myFile.js';

// ✅ Fix 1: Update package.json
{
  "name": "my-project",
  "type": "module",
  "main": "index.js"
}

// ✅ Fix 2: Use CommonJS instead
const { myFunc } = require('./myFile.js');