NodeModules

SyntaxError: Cannot use import statement outside a module

SyntaxError: Cannot use import statement outside a module

In short: Node is treating your file as CommonJS, but it uses import/export syntax.

Why it happens

Node decides module type from package.json "type" and the file extension. A .js file without "type": "module" is CommonJS. Running TypeScript files directly with node causes this too.

How to fix it

  1. Add "type": "module" to package.json, or rename the file to .mjs.
  2. Running TypeScript? Use npx tsx file.ts or compile first, instead of node file.ts.
  3. In a browser <script>, add type="module".
  4. In test runners (Jest), configure ESM/TypeScript transforms or switch to Vitest, which handles ESM natively.
Don't: Don't mix require and import in the same file.

Copy-paste fix prompt

3 · The fix promptPaste into Cursor, Claude Code, Codex, Lovable, Bolt, Replit or v0
I'm getting this error in my app:

SyntaxError: Cannot use import statement outside a module

[Paste the full error, stack trace, and the file it points to here]

Likely cause: Node is treating your file as CommonJS, but it uses import/export syntax.

Task: Determine how this file is being run (node, tsx, a test runner, a browser) and fix the module configuration so import/export works, without converting the whole project unless needed.

Rules:
- First explain the root cause in 2 sentences and list the files you'll change.
- Make the smallest change that fixes it. Don't refactor unrelated code.
- Don't disable security or checks (RLS, auth, signature verification, type checking, CORS allow-all) to make the error disappear.
- Never print or hard-code secret keys.
- Finish by telling me exactly how to verify the fix.

Common with: Cursor, Claude Code, Replit. Last reviewed 2026-11-13.

Related fixes

← All fixes · Still stuck? Use the diagnose-first prompt