Error: Cannot find module 'express'
What causes this
Node.js canβt find a package youβre trying to import. This is one of the most common Node errors and usually means the package isnβt installed, or Node is looking in the wrong place.
Common causes:
- The package isnβt installed (
npm installwas never run) node_modulesis corrupted or incomplete- Youβre running the script from the wrong directory
- The package is installed globally but youβre importing it locally
- A typo in the module name
- The packageβs
mainfield inpackage.jsonpoints to a missing file
Fix 1: Install the missing package
# Check if it's in package.json
cat package.json | grep express
# If it's listed, install all dependencies
npm install
# If it's not listed, add it
npm install express
Fix 2: Delete node_modules and reinstall
Corrupted node_modules is surprisingly common:
rm -rf node_modules package-lock.json
npm install
If youβre using other package managers:
# yarn
rm -rf node_modules yarn.lock && yarn install
# pnpm
rm -rf node_modules pnpm-lock.yaml && pnpm install
Fix 3: Check youβre in the right directory
# Where am I?
pwd
# Is there a package.json here?
ls package.json
# Is the module in node_modules?
ls node_modules/express
If youβre in a monorepo, make sure youβre in the right workspace directory.
Fix 4: Fix the import path
// β Typo in module name
const express = require('expresss');
// β Wrong relative path
const utils = require('./util'); // file is actually ./utils.js
// β
Correct
const express = require('express');
const utils = require('./utils');
For local files, check the exact filename and path. Node.js is case-sensitive on Linux even if your Mac doesnβt care.
Fix 5: Check for global vs local confusion
# β Installed globally but importing locally
npm install -g some-cli-tool
# Then in code: require('some-cli-tool') β won't work
# β
Install locally for code imports
npm install some-cli-tool
# Global installs are only for CLI commands, not code imports
Fix 6: Clear npm cache
npm cache clean --force
rm -rf node_modules package-lock.json
npm install
Related resources
How to prevent it
- Always run
npm installafter cloning a repo or pulling changes - Use exact versions in
package.jsonto avoid resolution issues - Commit
package-lock.jsonto ensure consistent installs across machines - Use a
.nvmrcfile to pin the Node.js version for your project
Related: npm ERR! ERESOLVE β Could Not Resolve Dependency Conflict