How to Configure CORS in Node.js

Cross-Origin Resource Sharing (CORS) is an essential browser security feature that controls how web applications running at one origin can access resources from a different origin. This article provides a quick, practical guide on how to configure CORS in a Node.js backend, demonstrating how to allow all origins, restrict access to specific domains, and set up manual CORS headers.

The easiest and most common way to handle CORS in a Node.js application using the Express framework is by using the official cors package.

First, install the package in your project:

npm install cors

Enable CORS for All Requests

To allow any website to access your API, import the middleware and apply it globally to your Express application.

const express = require('express');
const cors = require('cors');

const app = express();

// Enable CORS for all origins
app.use(cors());

app.get('/api/data', (req, res) => {
    res.json({ message: 'This is CORS-enabled for all origins!' });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Enable CORS for Specific Origins

For production environments, you should restrict access to trusted domains only. Pass a configuration object to the cors middleware to define these limits.

const express = require('express');
const cors = require('cors');

const app = express();

const corsOptions = {
    origin: 'https://yourfrontenddomain.com', // Allow only this origin
    methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allowed HTTP methods
    allowedHeaders: ['Content-Type', 'Authorization'], // Allowed headers
    optionsSuccessStatus: 200 // Some legacy browsers choke on 204
};

app.use(cors(corsOptions));

Enable CORS for a Single Route

If you only need CORS enabled on a specific endpoint, you can apply the middleware directly to that route.

app.get('/api/public-data', cors(), (req, res) => {
    res.json({ message: 'This route has CORS enabled.' });
});

Method 2: Manual Configuration via Custom Middleware

If you are not using Express, or if you prefer not to install external packages, you can configure CORS manually by setting the appropriate HTTP response headers.

Add this custom middleware function before your route definitions:

app.use((req, res, next) => {
    // Allow access from a specific origin
    res.setHeader('Access-Control-Allow-Origin', 'https://yourfrontenddomain.com');
    
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization');
    
    // Set to true if you need the website to include cookies in the requests sent
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Handle preflight OPTIONS requests
    if (req.method === 'OPTIONS') {
        return res.sendStatus(200);
    }

    next();
});

Summary of Key CORS Headers