AZ.dev

Fix "Cannot find module" with ES modules in Node.js

| node: 16+
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/path/to/file' imported from /path/to/other/file

Node.js ES modules require explicit file extensions in import paths. Unlike CommonJS (require), the module resolver does not try .js, .ts, or /index.js automatically.

The Fix

Add the file extension to your import:

// Wrong
import { handler } from "./routes/auth";

// Correct
import { handler } from "./routes/auth.js";

Yes, use .js even if your source file is .ts. TypeScript compiles .ts to .js, and Node resolves imports at runtime against the compiled output.

Root cause

When "type": "module" is set in package.json, Node uses the ESM resolver. The ESM spec requires explicit extensions, unlike CommonJS which probes multiple extensions.

Also check

  1. package.json has "type": "module" if you’re using import/export syntax
  2. tsconfig.json has "moduleResolution": "nodenext" or "bundler" for proper TypeScript ESM support
  3. Directory imports need /index.js: import { foo } from "./utils/index.js", not "./utils"

If you’re using a bundler

Bundlers (Vite, esbuild, webpack) resolve imports themselves and don’t need file extensions. This error only happens when Node.js resolves imports directly (server-side code, scripts, tests without a bundler).

esm modules import extensions

Was this helpful?

Related Entries

Reproduce Railway's npm ci locally with the exact npm versionSerialize per-user check-then-write flows with pg_advisory_xact_lock(hashtext(id))Content-hash dedup that restores a soft-deleted row must re-run quota and limit checksA storage URL builder and its static file handler must share one prefix constant