CORS configuration per server: Workers, Nginx, Express and Apache
In one line: The same allowlist implemented safely on four platforms, with the pitfall each one hides — and a deployment checklist.
CORS is a matter of response headers, not of the application. So the same four principles apply at the edge (Workers), in a reverse proxy (Nginx), in the application (Express) or in the web server (Apache).
- Echo only origins that are on your allowlist.
- List only the methods and headers you actually use.
- Answer
OPTIONSquickly with a 2xx status. - Add
Vary: Originto every response.
1. Cloudflare Workers
const ALLOWED = new Set(["https://app.example.com"]);
export default {
async fetch(request) {
const origin = request.headers.get("Origin") || "";
const h = new Headers({ "Vary": "Origin" });
if (ALLOWED.has(origin)) {
h.set("Access-Control-Allow-Origin", origin);
h.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
h.set("Access-Control-Allow-Headers", "content-type, authorization");
h.set("Access-Control-Max-Age", "600");
}
if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: h });
return new Response(JSON.stringify({ ok: true }), { headers: h });
}
};
Edge responses are often cached automatically, so the Vary entry matters. For authenticated paths, review Cache-Control: private as well.
2. Nginx
map $http_origin $cors_origin {
default "";
"https://app.example.com" $http_origin;
}
location /api/ {
add_header Vary "Origin" always;
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
add_header Access-Control-Allow-Headers "content-type, authorization" always;
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
add_header Access-Control-Allow-Headers "content-type, authorization" always;
add_header Content-Length 0;
add_header Content-Type text/plain;
return 204;
}
}
Two traps. First, map returns an empty string for unknown origins, and an empty header value is ignored by the browser — that is the intended behaviour, not a bug. Second, only add_header and return belong inside an if; other directives become unpredictable. Also remember that a child block that uses add_header does not inherit the parent's add_header lines.
3. Express
const ALLOWED = new Set(["https://app.example.com"]);
app.use(cors({
origin(origin, callback) {
if (!origin) return callback(null, false);
return callback(null, ALLOWED.has(origin));
},
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["content-type", "authorization"],
credentials: true,
maxAge: 600,
optionsSuccessStatus: 204
}));
With a function as origin, the middleware adds Vary: Origin for you. When you set headers yourself, call res.vary("Origin").
4. Apache
<IfModule mod_headers.c>
SetEnvIf Origin "^https://app\.example\.com$" CORS_OK=1
Header always set Vary "Origin" env=CORS_OK
Header always set Access-Control-Allow-Origin "%{Origin}e" env=CORS_OK
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS" env=CORS_OK
Header always set Access-Control-Allow-Headers "content-type, authorization" env=CORS_OK
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^OPTIONS$
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
Anchor the SetEnvIf pattern with ^ and $ so it matches the whole origin. Header always set also applies to error responses, which keeps CORS headers alive on 4xx replies.
5. Pre-deployment checklist
- No development or staging domain left on the allowlist.
- No
*anywhere thatcredentials: trueapplies. - The preflight answers 2xx and
Allow-Headerscovers every header actually sent. Vary: Originon every response, errors included.- The CDN cache rules do not strip or overwrite the CORS headers.
6. In CorsLab
The generator turns one allowlist into five snippets (Workers, Nginx, two Express variants, Apache). “Apply to simulator” feeds the same values back into the verdict so you can see them pass.
Put the same request and response into the simulator to see whether it passes and which header to change.
Open CorsLabFrequently asked questions
Should CORS be handled at the proxy or in the application?
In exactly one place. Handling it in both usually produces duplicated headers and a “multiple values” error.
Why does add_header disappear in Nginx?
A child block that uses add_header stops inheriting the parent's add_header lines. Put every header you need in the same block.
With a CDN in front of Nginx, where do I configure it?
Handling CORS at the edge and leaving the origin alone is the simplest setup. Configuring both easily produces duplicate headers.
Sources
Read next
- When a CORS preflight (OPTIONS) is sent, and what the browser checksThe exact conditions that make the browser send OPTIONS before the real request, the three headers it carries, and the order in which the response is checked.
- Access-Control-Allow-Origin, credentials: include and the wildcard banExact-match rules for Allow-Origin, the multiple-value error, why * is forbidden with credentials, and the three headers the rule applies to.
- Simple-request checks: method, headers and Content-TypeThe Fetch Standard safelist explained value by value, including the byte rules for header values and the Range exception.