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
- Add
"type": "module"topackage.json, or rename the file to.mjs. - Running TypeScript? Use
npx tsx file.tsor compile first, instead ofnode file.ts. - In a browser
<script>, addtype="module". - 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
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.
Did this fix it?
(Placeholder: feedback isn't recorded yet.)