Writing CORS Configuration With LLMs in November 2026: List Exact Origins, Never Reflect the Origin With Credentials, and Test the Preflight With curl

CORS errors are one of the most common reasons developers paste a stack trace into a chat window and ask an LLM to "just make it work." The model will happily oblige, and the fastest fix it knows is usually the worst one: allow every origin, reflect whatever the browser sends, and turn on credentials. The red error in the console goes away, and your API is now readable by any website a logged-in user happens to visit.

This post walks through how to get an LLM to write CORS configuration that is actually correct: what to tell it up front, which patterns to reject on sight, and how to test the result from the command line before you deploy.

Passport page covered in entry stamps from several countries

Each stamp is an explicit, per-origin permission. Your CORS allowlist should work the same way. Image: Brazil, Iceland, UK, US passport stamps by Jon Evans, CC BY 2.0, via Wikimedia Commons.

What CORS actually does (and what it does not)

Before prompting anything, it helps to have the model's job straight in your own head, because a lot of bad generated code comes from a wrong mental model.

  • Browsers enforce it, servers do not. The same-origin policy stops JavaScript on https://a.example from reading responses from https://b.example. CORS headers are how b.example tells the browser "this origin is allowed to read my response." curl, Postman, and server-to-server calls ignore CORS entirely.
  • CORS is not access control. It does not stop anyone from calling your API. Authentication and authorization still have to happen on every request.
  • CORS is not CSRF protection. For "simple" requests (a GET, or a POST with a form-style content type), the browser sends the request and only blocks JavaScript from reading the response. The side effect on your server has already happened. Use SameSite cookies and CSRF tokens for that problem.
  • The risk is reading. A loose CORS policy lets a hostile page make requests with the user's cookies and read the answers: profile data, tokens, internal records.

If the model's explanation of your fix ever says something like "this secures the API," that is a sign it is confused about what CORS is for.

Step 1: Write down your real origins before you prompt

The single most useful thing you can give the model is an explicit list of the origins that need access, per environment. An origin is scheme plus host plus port, with no path and no trailing slash:

production:  https://app.example.com
             https://admin.example.com
staging:     https://staging-app.example.com
local dev:   http://localhost:5173

Also answer three questions, because they change the configuration:

  1. Does the browser send cookies or HTTP auth to this API? If yes, you need credentials mode, and wildcards are off the table.
  2. Which methods and request headers does the frontend actually use? For example GET, POST, PATCH, DELETE and Content-Type, Authorization.
  3. Does the frontend need to read any custom response headers? Things like X-Request-Id or a pagination header are hidden from JavaScript unless you expose them.

A prompt that works well looks like this:

Write CORS configuration for an Express API.
Allowed origins come from the CORS_ORIGINS env var (comma-separated,
exact matches only). Production value:
https://app.example.com,https://admin.example.com
The frontend sends cookies (credentials: 'include').
Methods used: GET, POST, PATCH, DELETE.
Request headers used: Content-Type, X-CSRF-Token.
The frontend must read the X-Request-Id response header.
Requirements:
- Exact string match on Origin; no regex, no substring checks.
- Never send Access-Control-Allow-Origin: * or reflect an unlisted origin.
- Requests from unlisted origins get no CORS headers (not an error page).
- Add Vary: Origin.
- CORS headers must also be present on 4xx/5xx responses.

Being this specific removes most of the room the model has to improvise.

Step 2: Reject these patterns on sight

When you review generated CORS code, these are the ones to look for. Each one shows up regularly in tutorials, which is exactly why models reproduce them.

Reflecting the Origin header

// Do not ship this
res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
res.setHeader("Access-Control-Allow-Credentials", "true");

This tells the browser that every origin on the internet may read authenticated responses. It is functionally worse than *, because browsers refuse to combine * with credentials but will accept a reflected origin. Some framework options produce the same effect quietly (for example, setting an origin option to true in some middleware means "reflect the request origin"), so check what each option does in the library's docs rather than trusting the variable name.

Substring and sloppy regex checks

// All of these are bypassable
if (origin.endsWith("example.com")) ...        // matches https://evilexample.com
if (origin.includes("example.com")) ...        // matches https://example.com.attacker.net
if (/^https:\/\/.*example.com$/.test(origin)) // unescaped dot, and .* matches anything

Use a set of exact strings. If you genuinely need many subdomains, anchor the pattern and escape the dots, for example /^https:\/\/[a-z0-9-]+\.example\.com$/, and ask whether every subdomain really deserves to read your API. A forgotten marketing subdomain with an XSS bug then becomes a way into your data.

Allowing the "null" origin

Sandboxed iframes, some redirects, and local file:// pages send Origin: null. An attacker can produce that value on purpose with a sandboxed iframe. Never put null in the allowlist, even if it makes local testing easier.

Wildcard everything

Access-Control-Allow-Origin: * is fine for a truly public, unauthenticated resource such as a public font, a public JSON dataset, or open map tiles. It is wrong for anything that depends on who the user is. Pair it with credentials and the browser will block the request anyway, which is why the model then "fixes" it by reflecting the origin.

Step 3: Get the details right

A correct minimal implementation in Express, without a library, looks like this:

const allowed = new Set(
  (process.env.CORS_ORIGINS || "")
    .split(",")
    .map(s => s.trim())
    .filter(Boolean)
);

app.use((req, res, next) => {
  const origin = req.headers.origin;
  res.append("Vary", "Origin");

  if (origin && allowed.has(origin)) {
    res.setHeader("Access-Control-Allow-Origin", origin);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Expose-Headers", "X-Request-Id");
  }

  if (req.method === "OPTIONS" && req.headers["access-control-request-method"]) {
    if (origin && allowed.has(origin)) {
      res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE");
      res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token");
      res.setHeader("Access-Control-Max-Age", "600");
    }
    return res.status(204).end();
  }
  next();
});

Points worth checking in whatever the model gives you:

  • Vary: Origin. When the response header depends on the request's Origin, caches and CDNs must know that. Without it, a CDN can cache a response with one origin's header and serve it to another, which shows up as intermittent CORS failures that are hard to reproduce.
  • Preflight handling. Browsers send an OPTIONS preflight before requests that use methods like PUT, PATCH, or DELETE, custom headers, or a Content-Type such as application/json. The preflight must succeed without authentication, because browsers do not send credentials on it. If your auth middleware runs first and returns 401 to the OPTIONS request, every non-simple call will fail.
  • Error responses. If CORS headers are only added on the success path, a 500 or 403 reaches the browser without them, and the console shows a CORS error instead of the real status. Developers then "fix CORS" when the actual problem is a server error. Put the CORS middleware before routes and error handlers.
  • Access-Control-Max-Age. This caches the preflight result. Browsers cap the value (Chromium-based browsers at two hours), so huge numbers do nothing. A few minutes is a reasonable starting point while you are still changing things.
  • Configuration in one place. If CORS headers are set both in the app and at a reverse proxy or API gateway, you can end up with duplicate Access-Control-Allow-Origin headers, which browsers reject. Tell the model where CORS lives in your stack.
Passport control booths at Budapest Airport

A preflight is the passport check before the real trip. It has to work before anything else can. Image: Budapest Airport Passport Control T2 by Luis9595, CC BY-SA 4.0, via Wikimedia Commons.

Step 4: Test the preflight with curl

You do not need a browser to check the behavior. Ask the model to generate these commands for your endpoints, then run them yourself against staging.

Preflight from an allowed origin should return 204 with the allow headers:

curl -i -X OPTIONS https://api.example.com/items/42 \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: PATCH" \
  -H "Access-Control-Request-Headers: content-type,x-csrf-token"

Preflight from an unlisted origin should return no Access-Control-Allow-Origin header at all:

curl -i -X OPTIONS https://api.example.com/items/42 \
  -H "Origin: https://evil.example" \
  -H "Access-Control-Request-Method: PATCH"

Lookalike origins should also be refused. Try each of these as the Origin value and confirm no allow header comes back:

  • https://evilexample.com
  • https://app.example.com.attacker.net
  • http://app.example.com (wrong scheme)
  • null

An error path should still carry CORS headers for an allowed origin. Hit a route you know returns 404 or 401 with -H "Origin: https://app.example.com" and check the response.

These checks are easy to turn into a small automated test. With a framework test client (supertest for Express, the test client in Flask or FastAPI), assert on the presence or absence of Access-Control-Allow-Origin for each origin in a table of allowed and disallowed values. Once that test exists, a future "quick CORS fix" that loosens the policy will fail in CI instead of reaching production.

Step 5: Debug with the right evidence

When something still fails in the browser, give the model the actual evidence instead of the console's summary line:

  1. Open the browser's network panel, find the failing request, and check whether there is a separate OPTIONS request before it.
  2. Copy the request headers (especially Origin, Access-Control-Request-Method, and Access-Control-Request-Headers) and the full response headers and status of both requests.
  3. Paste those, plus your current CORS config, and ask the model which header is missing or mismatched. Tell it explicitly that widening the allowed origins is not an acceptable answer.

Most real-world failures turn out to be one of a short list: the preflight is hitting auth middleware, a request header the frontend sends is not in Access-Control-Allow-Headers, the origin in config has a trailing slash or the wrong port, the server is returning a 500 without CORS headers, or two layers are both setting the header.

A short checklist

  • Allowed origins are an explicit list per environment, loaded from config.
  • Exact string match; no reflection, no substring checks, no null.
  • No * on anything that uses cookies or user-specific data.
  • Vary: Origin is set.
  • Preflight succeeds without auth, and lists only the methods and headers you use.
  • CORS headers appear on error responses too.
  • CORS is configured in exactly one layer.
  • curl or test-client checks cover allowed, disallowed, and lookalike origins.
  • CSRF is handled separately with SameSite cookies and tokens.

LLMs are good at producing CORS boilerplate for any framework you name. The part you have to supply is the policy: who is allowed to read your responses. Write that down first, forbid the shortcuts, and test it from the command line, and the generated code becomes something you can actually trust.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Tencent Hy4 Preview: Open 770B MoE Built for Real Work

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)