CORS in Express — Configuring Cross-Origin Requests in Node.js
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
- What npm package handles CORS in Express?
- How do you restrict CORS to multiple specific origins?
- Why must CORS middleware handle OPTIONS requests?
- What happens if you don't configure
originoption? - How do you allow credentials with cors()?
Answers:
cors(npm install cors).- Use a function callback that checks the origin against a whitelist.
- The browser sends OPTIONS preflight requests that must be responded to.
origindefaults to*(all origins).- Set
credentials: truein 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
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