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.