Generate correct CORS config for your stack
Cross-Origin Resource Sharing (CORS) is the browser security mechanism that
controls whether JavaScript running on one origin may read responses from a
different origin. Getting the headers slightly wrong leads to the familiar
“blocked by CORS policy” error. This builder takes your allowed origins,
methods, headers, credentials mode, and preflight cache, then emits a tested
configuration for Express (cors middleware), Fastify (@fastify/cors), or
plain Nginx add_header directives.
How it works
CORS is enforced entirely by the browser using a set of Access-Control-*
response headers. For a “simple” request the browser sends the call directly and
checks the Access-Control-Allow-Origin header on the response. For anything
else — custom headers, PUT/DELETE, JSON bodies — it first issues a preflight
OPTIONS request, and your server must answer with the allowed methods and
headers:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
The key rule the builder enforces: when credentials are enabled you cannot use
the * wildcard origin. Instead the server must compare the incoming Origin
header against an allow-list and echo back the exact match, which is why the
generated Express and Fastify snippets use an origin callback function rather
than a static string.
Tips and notes
- Match origins exactly —
https://example.comandhttps://www.example.comare different origins, and the port matters too (:3000vs:8080). - The Nginx snippet includes a dedicated
if ($request_method = OPTIONS)block that returns204for preflight, because Nginx will not run your application forOPTIONSunless you handle it. - Keep the allowed-headers list tight; only list headers your client actually
sends, such as
Content-TypeandAuthorization. - CORS protects browser reads only — never rely on it for access control on server-to-server or mobile API traffic.