0%
September 3, 2023

Restrict CORS to Limited Origins

express

import express from "express";
import cors from 'cors';

const allowlist = ['http://localhost:3000']

const corsOptionsDelegate = (req, callback) => {
  var corsOptions;

  if (allowlist.indexOf(req.header('Origin')) > -1) {
    // reflect (enable) the requested origin in the CORS response
    corsOptions = { origin: true };
  } else {
    // disable CORS for this request
    corsOptions = { origin: false }; 
  }
  // callback expects two parameters: (error, options)
  callback(null, corsOptions) 
}

app.use(cors(corsOptionsDelegate));