CORS Error in Node.js— Fixed [Complete Guide 2026]
Also covers: CORS policy blocked request · Access-Control-Allow-Origin missing · Preflight OPTIONS errors
⚡ Quickest Fix
Install cors and add it before your routes:
npm install corsconst cors = require('cors')
app.use(cors({ origin: 'http://localhost:3000' })) // before routesFor development only — allow all origins: app.use(cors())
What Is a CORS Error?
Access to fetch at 'http://localhost:5000/api/data'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.CORS (Cross-Origin Resource Sharing) is a browser security feature. When your frontend (running at one origin) makes a request to your API (running at another origin), the browser checks whether the server explicitly allows it. If the server does not respond with the correct Access-Control-Allow-Origin header, the browser blocks the response.
CORS is always a server-side fix. The server must send the correct headers. You cannot fix it from the frontend — you can only use a dev proxy as a workaround.
| Error contains | Fix |
|---|---|
| No 'Access-Control-Allow-Origin' header | Add cors middleware (#fix-1) |
| Response to preflight doesn't pass | Handle OPTIONS requests (#fix-4) |
| Wildcard '*' not working with credentials | Use exact origin with credentials (#fix-3) |
| CORS error only in browser, not Postman | Postman doesn't enforce CORS — add middleware (#fix-1) |
Install and Configure cors Middleware
Complete working setupnpm install corsconst express = require('express')
const cors = require('cors')
const app = express()
// Development — allow all origins
app.use(cors())
// Or — allow specific origin (recommended)
app.use(cors({ origin: 'http://localhost:3000' }))
// MUST be before all routes
app.get('/api/data', (req, res) => {
res.json({ message: 'CORS working' })
})
app.listen(5000)cors() middleware must go BEFORE your route definitions. If placed after, routes defined above will not have CORS headers.
Allow Specific Origins
Production config — multiple origins// Single origin
app.use(cors({ origin: 'https://yourapp.com' }))
// Multiple origins
app.use(cors({
origin: ['https://yourapp.com', 'https://www.yourapp.com', 'http://localhost:3000'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
}))
// Dynamic origin from environment variable
const allowedOrigins = process.env.CORS_ORIGIN?.split(',') || ['http://localhost:3000']
app.use(cors({
origin: function(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}))Never use origin: '*' in production — it allows any website to call your API. Always specify exact allowed origins.
CORS with Credentials (Cookies / Auth Headers)
For cookie-based sessions or Authorization headersWhen your frontend sends cookies, session tokens, or Authorization headers cross-origin, you need credentials: true on both sides.
app.use(cors({
origin: 'http://localhost:3000', // MUST be exact — not '*'
credentials: true, // allow cookies and auth headers
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
}))fetch('http://localhost:5000/api/profile', {
credentials: 'include', // send cookies with request
headers: { 'Authorization': 'Bearer ' + token }
})axios.defaults.withCredentials = true
// or per-request:
axios.get('/api/profile', { withCredentials: true })credentials: true + origin: '*' is invalid. Browsers reject it. You must specify an exact URL.
Handle Preflight OPTIONS Requests
CORS error on POST, PUT, DELETE, or custom headersBefore sending a POST/PUT/DELETE or a request with custom headers, browsers send an OPTIONS 'preflight' request to check if the server allows it. Your server must handle OPTIONS.
// Handle all OPTIONS preflight requests
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,
}))
// OR — manual headers if not using cors package
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000')
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
res.header('Access-Control-Allow-Credentials', 'true')
if (req.method === 'OPTIONS') return res.status(200).end()
next()
})app.options('*', cors()) must come BEFORE app.use(cors()) to handle preflight for all routes.
CORS in Next.js API Routes
Next.js backend — App Router and Pages RouterApp Router (Next.js 13+)
export async function GET(request) {
return new Response(JSON.stringify({ data: 'hello' }), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
},
})
}
export async function OPTIONS() {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
})
}Pages Router (next.config.js)
module.exports = {
async headers() {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Origin', value: 'https://yourfrontend.com' },
{ key: 'Access-Control-Allow-Methods', value: 'GET,POST,PUT,DELETE,OPTIONS' },
{ key: 'Access-Control-Allow-Headers', value: 'Content-Type, Authorization' },
],
},
]
},
}Use a Dev Proxy (Development Only)
React / Vite — avoid CORS in developmentIn development, you can proxy API requests through your frontend dev server so they appear same-origin — eliminating CORS entirely for local development.
Create React App
{ "proxy": "http://localhost:5000" }
// Now: fetch('/api/data') proxies to http://localhost:5000/api/dataVite
export default {
server: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true,
}
}
}
}Dev proxies only work in development. Your production server must have proper CORS headers configured.
nginx CORS Headers
Production nginx configserver {
listen 80;
server_name api.yourdomain.com;
location / {
# CORS headers
add_header 'Access-Control-Allow-Origin' 'https://yourfrontend.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
# Handle preflight
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 86400;
return 204;
}
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
}
}CORS Error in Browser but Works in Postman — Why?
Postman does not enforce CORS — it sends requests directly without a browser's security checks. CORS is a browser-only restriction. If your API works in Postman but fails in the browser, the fix is always adding CORS headers to your Express server.
| Client | Enforces CORS? |
|---|---|
| Browser (Chrome, Firefox, Safari) | ✅ Yes — blocks responses without CORS headers |
| Postman | ❌ No — bypasses CORS checks |
| curl | ❌ No — command line, no browser security |
| Server-to-server (Node fetch) | ❌ No — CORS is browser-only |
| Mobile app (React Native) | Depends on WebView usage |
How to Prevent CORS Errors
- Always add cors middleware before routes in Express
- Use environment variables for allowed origins
- Add app.options('*', cors()) to handle preflight
- Never use origin: '*' with credentials: true
- Test CORS config from actual browser — not just Postman
- In development, use a proxy (Vite, CRA) to avoid CORS entirely
Frequently Asked Questions
What is a CORS error in Node.js?+−
How do I fix CORS error in Express?+−
CORS error with credentials — how to fix?+−
CORS works in Postman but not browser — why?+−
How to allow all origins in Express?+−
Can I fix CORS from the frontend?+−
Need Expert Help?
We Build Production-Grade Node.js APIs
Softplix builds full-stack Node.js applications. Dealing with CORS, API security, or backend architecture? We can help.
Talk to an Engineer