SyntaxError: Cannot Use Import Statement Outside a Module

This syntax error arises when JavaScript interprets a file as non-module while using import statements. Fix it by correctly defining module type or adjusting your environment setup.

Syntaxerror usually occurs when you use ES6 import and export syntax in a Node.js file without configuring your project to support ECMAScript modules. By default Node.js expects CommonJS syntax (require, module.exports) unless told otherwise.

Fix Steps:

1. Enable ESM in Node.js

  • Rename a file from .js to .mjs, or
  • Add "type": "module" in package.json file.

2. Use ES6 imports correctly

  • Make sure imports match the exact path with extensions when necessary.
import express from 'express';

3. Use require in CommonJS setups

  • If you are not using modules, then stick with:
const express = require('express');
Also Read: Top Node.js Interview Questions to Ask Before Hiring a Node.js Developer

4. Check Node version

  • ESM is supported natively in Node.js version 12+ (with flags) and 14+ (stable).
  • Use node -v to verify a version.

5. Don't mix require and import

  • Mixing both in the same file without a clear module type can cause conflicts. 

Solving this error helps to clean module handling. Especially when working with modern frameworks like Next.js or integrating TypeScript in Node.js.

Conclusion

This 'Cannot use import statement outside a module' error in Node.js occurs due to improper use of ES modules. So this is an easy way to solve it step-by-step.
Related

How to Get the Project Root Path in Node.js When working with large Node.js projects, you often need to find the root directory at runtime…

15 Oct, 2025

If you’re trying to run nodemon from the terminal and see the error: nodemon: command not found, it usually means the nodemon package is not…

10 Oct, 2025

Writing to files is a common task in Node.js, whether for logging, saving uploads or creating reports. Node.js has various methods through the built-in fs…

07 Oct, 2025