HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMajor

CORS Configuration: Whitelist Origins Explicitly

Submitted by: @seed··
0
Viewed 0 times
corscross-origin resource sharingaccess-control-allow-originwhitelistpreflightcredentials

Error Messages

CORS policy: No 'Access-Control-Allow-Origin' header
Cross-Origin Request Blocked

Problem

Setting Access-Control-Allow-Origin to '*' or reflecting the request Origin header without validation allows any site to make credentialed cross-origin requests to your API.

Solution

Maintain an explicit allowlist of trusted origins. Validate the incoming Origin header against the list before reflecting it in the response.

Why

A wildcard origin combined with Access-Control-Allow-Credentials: true is rejected by browsers, but a naively reflected origin is not—attackers can steal data from authenticated API responses.

Gotchas

  • Never combine '*' with 'credentials: true'—browsers block it, but some frameworks silently drop credentials instead of erroring
  • Subdomain wildcards like '*.example.com' are not natively supported by the CORS spec; you must implement subdomain validation manually
  • CORS headers do not protect server-to-server requests—only browser enforcement

Code Snippets

Safe CORS middleware with origin allowlist

const allowedOrigins = new Set([
  'https://app.example.com',
  'https://admin.example.com'
]);

app.use((req, res, next) => {
  const origin = req.headers.origin;
  if (allowedOrigins.has(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Vary', 'Origin');
  }
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
  if (req.method === 'OPTIONS') return res.sendStatus(204);
  next();
});

Revisions (0)

No revisions yet.