Node.jsExpressError Fix2026 Updated

CORS Error in Node.js— Fixed [Complete Guide 2026]

Also covers: CORS policy blocked request · Access-Control-Allow-Origin missing · Preflight OPTIONS errors

January 20267 min readNode.js · Express · All OS

⚡ Quickest Fix

Install cors and add it before your routes:

terminal
npm install cors
server.js
const cors = require('cors')
app.use(cors({ origin: 'http://localhost:3000' }))  // before routes

For development only — allow all origins: app.use(cors())

What Is a CORS Error?

Browser / Terminal 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 containsFix
No 'Access-Control-Allow-Origin' headerAdd cors middleware (#fix-1)
Response to preflight doesn't passHandle OPTIONS requests (#fix-4)
Wildcard '*' not working with credentialsUse exact origin with credentials (#fix-3)
CORS error only in browser, not PostmanPostman doesn't enforce CORS — add middleware (#fix-1)
1

Install and Configure cors Middleware

Complete working setup
2 min
terminal
npm install cors
server.js
const 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.

2

Allow Specific Origins

Production config — multiple origins
2 min
server.js
// 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.

3

CORS with Credentials (Cookies / Auth Headers)

For cookie-based sessions or Authorization headers
2 min

When your frontend sends cookies, session tokens, or Authorization headers cross-origin, you need credentials: true on both sides.

server.js
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'],
}))
Frontend — fetch
fetch('http://localhost:5000/api/profile', {
  credentials: 'include',   // send cookies with request
  headers: { 'Authorization': 'Bearer ' + token }
})
Frontend — Axios
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.

4

Handle Preflight OPTIONS Requests

CORS error on POST, PUT, DELETE, or custom headers
2 min

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

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

5

CORS in Next.js API Routes

Next.js backend — App Router and Pages Router
2 min

App Router (Next.js 13+)

app/api/data/route.js
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)

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' },
        ],
      },
    ]
  },
}
6

Use a Dev Proxy (Development Only)

React / Vite — avoid CORS in development
3 min

In 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

package.json
{ "proxy": "http://localhost:5000" }
// Now: fetch('/api/data') proxies to http://localhost:5000/api/data

Vite

vite.config.js
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.

7

nginx CORS Headers

Production nginx config
5 min
nginx.conf
server {
    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.

ClientEnforces 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

Frequently Asked Questions

What is a CORS error in Node.js?+
CORS (Cross-Origin Resource Sharing) errors happen when your frontend (on one origin/port) calls your API (on another origin/port) without the server sending the correct Access-Control-Allow-Origin header. Browsers block the response for security. It is always a server-side fix.
How do I fix CORS error in Express?+
Install cors: npm install cors. Then: const cors = require('cors'); app.use(cors({ origin: 'http://localhost:3000' })) before your routes.
CORS error with credentials — how to fix?+
Set credentials: true in cors config AND specify an exact origin: app.use(cors({ origin: 'http://localhost:3000', credentials: true })). In frontend add credentials: 'include' to fetch.
CORS works in Postman but not browser — why?+
Postman does not enforce CORS — only browsers do. If it works in Postman but not browser, your server is missing the Access-Control-Allow-Origin header. Add the cors middleware to Express.
How to allow all origins in Express?+
app.use(cors()) allows all origins. Only use this in development. In production always specify exact origins to prevent unauthorized access.
Can I fix CORS from the frontend?+
No. CORS is enforced by the browser based on headers from the server. The server must send the correct Access-Control-Allow-Origin header. You can use a dev proxy but the production server must be properly configured.

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