How to configure CORS in Node.js with Express

Enable Cross-Origin Resource Sharing (CORS) in a Node.js Express application using the cors npm package or manual response headers.

Configure Cross-Origin Resource Sharing (CORS) in a Node.js application using Express to allow cross-origin requests from specific domains or all origins.

Prerequisites

  • Node.js 16 or later installed.
  • An Express application.
  • npm or yarn for package management.

Step-by-Step: Enable CORS in Node.js with Express

  1. Install the cors npm package in the Node.js project. This package provides Express middleware that sets Cross-Origin Resource Sharing (CORS) headers automatically:

    npm install cors
  2. Import the cors middleware and apply it to the Express application.

    Option A: Allow all origins-- Call app.use(cors()) with no arguments to permit requests from any origin:

    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    app.use(cors());
    
    app.get('/api/data', (req, res) => {
      res.json({ message: 'CORS enabled for all origins' });
    });
    
    app.listen(3000);

    Option B: Allow a specific origin-- Pass an options object with the origin property to restrict CORS access to a single domain:

    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    const corsOptions = {
      origin: 'https://app.example.com',
      methods: ['GET', 'POST', 'PUT', 'DELETE'],
      allowedHeaders: ['Content-Type', 'Authorization'],
      credentials: true,
      maxAge: 86400
    };
    
    app.use(cors(corsOptions));
    
    app.listen(3000);

    Option C: Allow multiple origins-- Pass an array of origins or a function that validates the Origin header:

    const allowedOrigins = [
      'https://app.example.com',
      'https://admin.example.com'
    ];
    
    const corsOptions = {
      origin: (origin, callback) => {
        if (!origin || allowedOrigins.includes(origin)) {
          callback(null, true);
        } else {
          callback(new Error('Not allowed by CORS'));
        }
      },
      credentials: true
    };
    
    app.use(cors(corsOptions));

    Option D: Set CORS headers manually-- Set the response headers without the cors package for full control over the Cross-Origin Resource Sharing behavior:

    app.use((req, res, next) => {
      res.setHeader('Access-Control-Allow-Origin', 'https://app.example.com');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.setHeader('Access-Control-Allow-Credentials', 'true');
    
      if (req.method === 'OPTIONS') {
        res.sendStatus(204);
        return;
      }
    
      next();
    });

How to Verify CORS Is Working in Node.js

Send a test request with curl to confirm the Node.js application returns Cross-Origin Resource Sharing (CORS) headers:

curl -I -H "Origin: https://app.example.com" http://localhost:3000/api/data

The response should include:

Access-Control-Allow-Origin: https://app.example.com

Common Issues When Configuring CORS in Node.js

  • cors middleware applied after route handlers.Express processes middleware in order. Place app.use(cors()) before all route definitions.
  • Credentials rejected with wildcard origin.The cors package sets Access-Control-Allow-Origin: * by default. Set a specific origin value when credentials: true is enabled.
  • Preflight requests return 404.The Express router does not handle OPTIONS requests by default. The cors middleware handles preflight automatically. Verify the middleware is loaded before the router.

For a detailed explanation of the CORS mechanism, see CORS tutorial: How Cross-Origin Resource Sharing works.