Skip to content

CORS in Express — Configuring Cross-Origin Requests in Node.js

DodaTech Updated 2026-06-28 2 min read

In this tutorial, you will learn about CORS in Express. We cover key concepts, practical examples, and best practices to help you master this topic.

Configuring CORS in Express.js is straightforward with the cors middleware package, which handles preflight requests, origin validation, and header configuration.

What You'll Learn

  • How to install and configure the cors package
  • Writing custom CORS middleware for advanced scenarios
  • Testing CORS configuration with real requests

Why It Matters

Express is one of the most popular Node.js frameworks. Proper CORS configuration ensures your Express API works with frontend applications on different domains.

Code Examples

// Basic CORS with express
const express = require('express');
const cors = require('cors');
const app = express();

// Allow all origins
app.use(cors());

// Restrict to specific origin
app.use(cors({
  origin: 'https://myapp.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  maxAge: 86400
}));

// Dynamic origin based on whitelist
const whitelist = ['https://app1.com', 'https://app2.com'];
app.use(cors({
  origin: (origin, callback) => {
    if (!origin || whitelist.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
}));
// Custom CORS middleware (no package)
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'https://myapp.com');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.setHeader('Access-Control-Max-Age', '86400');
  if (req.method === 'OPTIONS') return res.sendStatus(200);
  next();
});
# Test Express CORS configuration
curl -X OPTIONS http://localhost:3000/api/data \
  -H "Origin: https://myapp.com" \
  -H "Access-Control-Request-Method: POST" \
  -v

Common Mistakes

1. Installing Without Configuring

app.use(cors()) with defaults allows all origins, which may be too permissive.

2. Forgetting Express JSON Middleware

CORS middleware should be before express.json() in the middleware chain.

3. Not Handling OPTIONS for All Routes

Preflight requests must be handled on every route, not just a few.

4. CORS Errors Appearing as Network Errors

CORS failures look like network errors in the browser. Enable detailed error logging.

5. Missing Vary: Origin on Dynamic Origins

Without Vary: Origin, CDN caches may serve wrong CORS headers.

Practice Questions

  1. What npm package handles CORS in Express?
  2. How do you restrict CORS to multiple specific origins?
  3. Why must CORS middleware handle OPTIONS requests?
  4. What happens if you don't configure origin option?
  5. How do you allow credentials with cors()?

Answers:

  1. cors (npm install cors).
  2. Use a function callback that checks the origin against a whitelist.
  3. The browser sends OPTIONS preflight requests that must be responded to.
  4. origin defaults to * (all origins).
  5. Set credentials: true in the cors options.

Challenge: Build an Express API with three CORS configurations: open (all origins), restricted (specific origins), and custom (origin validation function). Write tests for each.

FAQ

Can I use Express cors() for subdomain access?

: Yes. Use a function to check if the origin matches your subdomain pattern.

Does Express cors() handle preflight automatically?

: Yes. It detects OPTIONS requests and sends appropriate responses.

Is it safe to use `cors()` in production?

: Yes, as long as you configure it with specific origins, not the wildcard default.

What's Next

Learn CORS in Django for Python backends, then explore CORS Security best practices.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro