Error: Cannot find module 'cors'— Fixed [Complete Guide 2026]
⚡ Quickest Fix — Complete Solution
Install cors and add it to your Express app before routes:
npm install corsconst express = require('express')
const cors = require('cors')
const app = express()
// Add BEFORE all routes
app.use(cors({ origin: 'http://localhost:3000' }))
app.get('/api/data', (req, res) => {
res.json({ message: 'CORS working!' })
})
app.listen(5000)What Causes Cannot find module 'cors'?
Error: Cannot find module 'cors'
Require stack:
- /Users/you/projects/api/server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object.<anonymous> (/Users/you/projects/api/server.js:2:14)cors is an npm package — it is not built into Node.js or Express. This error means the cors package has not been installed in your project. The fix is straightforward: install it and configure it correctly in your Express app.
Installing cors fixes the module error. But you also need to configure it correctly to actually allow cross-origin requests. Fixes 4, 5, and 6 cover the configuration after installation.
Install and Configure cors
Complete fix — install + basic setupStep 1 — Install
npm install corsStep 2 — Add to Express app (before routes)
const express = require('express')
const cors = require('cors')
const app = express()
// ✅ Allow all origins (development only)
app.use(cors())
// ✅ Allow specific origin (recommended)
app.use(cors({ origin: 'http://localhost:3000' }))
// ✅ Allow multiple origins
app.use(cors({
origin: ['http://localhost:3000', 'https://yourapp.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
}))
// Routes AFTER cors middleware
app.get('/api/users', (req, res) => {
res.json({ users: [] })
})
app.listen(5000)cors() middleware must go BEFORE your route definitions. If you place it after a route, that route will not have CORS headers applied.
Wrong Directory or Missing node_modules
After git clone or wrong folderIf you just cloned a repository or are in the wrong folder, node_modules may not exist at all — meaning no packages are available, not just cors.
# Check you are in the right place
pwd
ls package.json
# Check node_modules exists
ls node_modules
# If missing — recreate from package.json
npm install
# Verify cors installed
ls node_modules | grep corsReinstall All Dependencies
Corrupted node_modulesIf cors is in package.json but still not found, node_modules may be corrupted. A clean reinstall fixes this.
rm -rf node_modules package-lock.json
npm installRemove-Item -Recurse -Force node_modules
Remove-Item package-lock.json
npm installConfigure cors Correctly for Production
After installing — production setupFor production, never allow all origins. Always specify the exact frontend URL to prevent unauthorized access to your API.
const allowedOrigins = [
'https://yourapp.com',
'https://www.yourapp.com',
]
// Development also allows localhost
if (process.env.NODE_ENV !== 'production') {
allowedOrigins.push('http://localhost:3000')
allowedOrigins.push('http://localhost:5173')
}
app.use(cors({
origin: function(origin, callback) {
// Allow requests with no origin (mobile apps, Postman)
if (!origin) return callback(null, true)
if (allowedOrigins.includes(origin)) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
}))Store allowed origins in environment variables: process.env.CORS_ORIGIN — never hardcode production URLs in your source code.
cors with Credentials (Cookies & Auth)
For cookie-based auth sessionsIf you are using cookies, sessions, or Authorization headers in cross-origin requests, you need to enable credentials in both your backend and frontend.
app.use(cors({
origin: 'http://localhost:3000', // must be exact URL — not '*'
credentials: true, // allow cookies
}))// Must include credentials: 'include' in every request
fetch('http://localhost:5000/api/data', {
method: 'GET',
credentials: 'include', // send cookies cross-origin
})
// Axios — set globally
import axios from 'axios'
axios.defaults.withCredentials = trueWhen credentials: true is set, you CANNOT use origin: '*'. You must specify an exact URL. Using '*' with credentials: true will cause the browser to reject the response.
Handle Preflight OPTIONS Requests
CORS error on POST/PUT/DELETE or with custom headersBrowsers send a preflight OPTIONS request before cross-origin POST, PUT, DELETE, or requests with custom headers. Your server must respond correctly to these preflight checks.
// Allow preflight for all routes
app.options('*', cors())
// Then apply cors to all routes
app.use(cors({
origin: 'http://localhost:3000',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}))
// Your routes
app.post('/api/data', (req, res) => {
res.json({ success: true })
})app.options('*', cors()) must come BEFORE app.use(cors()) to handle preflight requests for all routes.
cors Installed But Still Getting CORS Error in Browser?
If you installed cors and the module error is gone but you still see CORS policy errors in the browser console, the issue is configuration — not installation. Check these:
| Problem | Fix |
|---|---|
| cors() placed after routes | Move app.use(cors()) before all routes |
| Wrong origin URL — http vs https | Match exactly: http://localhost:3000 not https://localhost:3000 |
| Port mismatch | Frontend on :3000, backend on :5000 — specify origin: 'http://localhost:3000' |
| credentials: true with origin: '*' | Must use exact URL with credentials — not wildcard |
| Preflight OPTIONS failing | Add app.options('*', cors()) before app.use(cors()) |
How to Prevent This Error
- Add cors to package.json with npm install cors
- Apply cors middleware before all route definitions
- Always specify exact origins in production — never use wildcard '*' with credentials
- Store allowed origins in environment variables
- Add app.options('*', cors()) to handle preflight requests
- Commit package.json so npm install recreates cors for teammates
Quick Reference — cors Configuration Patterns
app.use(cors())app.use(cors({ origin: 'http://localhost:3000' }))app.use(cors({ origin: ['http://localhost:3000', 'https://app.com'] }))app.use(cors({ origin: 'http://localhost:3000', credentials: true }))app.options('*', cors()); app.use(cors({...}))Frequently Asked Questions
How do I install and use cors in Express?+−
Why is cors module not found after npm install?+−
How do I allow only specific origins with cors?+−
cors is installed but CORS error still appears in browser?+−
Can I use cors with credentials (cookies)?+−
How do I fix CORS without the cors package?+−
Need Expert Help?
We Build Production-Grade Node.js & Express APIs
Softplix is a full-stack development agency. Struggling with CORS or API configuration in production? We can help.
Talk to an Engineer