Node.jsExpressError Fix2026 Updated

Error: Cannot find module 'cors'— Fixed [Complete Guide 2026]

January 20265 min readNode.js · Express · All OS

⚡ Quickest Fix — Complete Solution

Install cors and add it to your Express app before routes:

terminal
npm install cors
server.js
const 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'?

Terminal Error
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.

1

Install and Configure cors

Complete fix — install + basic setup
2 min

Step 1 — Install

terminal
npm install cors

Step 2 — Add to Express app (before routes)

server.js
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.

2

Wrong Directory or Missing node_modules

After git clone or wrong folder
1 min

If 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.

terminal
# 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 cors
3

Reinstall All Dependencies

Corrupted node_modules
3 min

If cors is in package.json but still not found, node_modules may be corrupted. A clean reinstall fixes this.

macOS / Linux
rm -rf node_modules package-lock.json
npm install
Windows PowerShell
Remove-Item -Recurse -Force node_modules
Remove-Item package-lock.json
npm install
4

Configure cors Correctly for Production

After installing — production setup
3 min

For production, never allow all origins. Always specify the exact frontend URL to prevent unauthorized access to your API.

server.js — production config
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.

5

cors with Credentials (Cookies & Auth)

For cookie-based auth sessions
2 min

If you are using cookies, sessions, or Authorization headers in cross-origin requests, you need to enable credentials in both your backend and frontend.

server.js — backend
app.use(cors({
  origin: 'http://localhost:3000',  // must be exact URL — not '*'
  credentials: true,                // allow cookies
}))
Frontend — fetch
// 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 = true

When 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.

6

Handle Preflight OPTIONS Requests

CORS error on POST/PUT/DELETE or with custom headers
2 min

Browsers 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.

server.js
// 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:

ProblemFix
cors() placed after routesMove app.use(cors()) before all routes
Wrong origin URL — http vs httpsMatch exactly: http://localhost:3000 not https://localhost:3000
Port mismatchFrontend on :3000, backend on :5000 — specify origin: 'http://localhost:3000'
credentials: true with origin: '*'Must use exact URL with credentials — not wildcard
Preflight OPTIONS failingAdd app.options('*', cors()) before app.use(cors())

How to Prevent This Error

Quick Reference — cors Configuration Patterns

Development — allow allapp.use(cors())
Allow single originapp.use(cors({ origin: 'http://localhost:3000' }))
Allow multiple originsapp.use(cors({ origin: ['http://localhost:3000', 'https://app.com'] }))
With cookies/credentialsapp.use(cors({ origin: 'http://localhost:3000', credentials: true }))
Handle preflightapp.options('*', cors()); app.use(cors({...}))

Frequently Asked Questions

How do I install and use cors in Express?+
Run npm install cors, then: const cors = require('cors'); app.use(cors()) before your route definitions. For production, specify an origin: app.use(cors({ origin: 'https://yourfrontend.com' })).
Why is cors module not found after npm install?+
Check that you are in the correct project directory containing package.json. Run ls node_modules | grep cors to verify it installed. If missing, run npm install cors again from your project root.
How do I allow only specific origins with cors?+
Pass an origin option: app.use(cors({ origin: 'https://yourfrontend.com' })). For multiple origins, pass an array: app.use(cors({ origin: ['https://app.com', 'http://localhost:3000'] })).
cors is installed but CORS error still appears in browser?+
Make sure app.use(cors()) is placed BEFORE your routes. If using credentials, set origin to your exact frontend URL — not a wildcard '*'. Check the Network tab in browser DevTools for the exact error.
Can I use cors with credentials (cookies)?+
Yes. Set credentials: true and specify an exact origin — not '*': app.use(cors({ origin: 'https://yourfrontend.com', credentials: true })). In frontend, add credentials: 'include' to fetch calls.
How do I fix CORS without the cors package?+
Set headers manually: res.setHeader('Access-Control-Allow-Origin', '*'). But the cors package is cleaner, handles all HTTP methods, manages preflight automatically, and is the recommended approach.

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