Deviopath › Node.js

CORS Headers

Medium · Security

Browsers block cross-origin requests unless the server answers with CORS headers (the cors middleware adds them for you; here we use a simplified set of rules). Write corsHeaders(request, config) that returns the headers object to add.

request is { method, headers } with lower-case header names. config is { origins, methods, headers, credentials, maxAge? } where origins is "*" or a list of allowed origins.

- No origin header, or an origin not in the list → {} (no CORS headers).

- Access-Control-Allow-Origin: "*" when origins is "*" and credentials is false. Otherwise reflect the request origin and also add Vary: "Origin" (so caches keep one copy per origin). Browsers reject * together with credentials.

- credentials: true → Access-Control-Allow-Credentials: "true".

A preflight is an OPTIONS request that has an access-control-request-method header. For a preflight:

- If the requested method is not in methods → {}.

- Also add Access-Control-Allow-Methods (methods joined with ", "), Access-Control-Allow-Headers (headers joined with ", ", only if the list is not empty) and Access-Control-Max-Age (as a string, only if maxAge is set).

Next: Fixed-Window Rate Limiter