opyebCorsLab

CORS configuration per server: Workers, Nginx, Express and Apache

Server config · 10 min

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).

  1. Echo only origins that are on your allowlist.
  2. List only the methods and headers you actually use.
  3. Answer OPTIONS quickly with a 2xx status.
  4. Add Vary: Origin to 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 that credentials: true applies.
  • The preflight answers 2xx and Allow-Headers covers every header actually sent.
  • Vary: Origin on 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 CorsLab

Frequently 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

0 bytes of your input sent to a server (advertising and affiliate widgets excluded)