« all posts

Cloudflare Under Attack CORS solution

Recently, my client’s site was being DDoSed. Two domains had to interact with each other: the primary domain and the API. But as soon as I enabled “Under Attack” mode, the CORS stopped working. The only solution that worked for me was adding a custom “Snippet” under the “Rules” -> “Snippets” page.

const ALLOWED = new Set([
  "https://example.com",
  "http://another.example.com",
]);

export default {
  async fetch(request) {
    const origin = request.headers.get("Origin");
    const allow = ALLOWED.has(origin) ? origin : "https://example.com";

    const cors = {
      "Access-Control-Allow-Origin": allow,
      "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type, Authorization",
      "Access-Control-Allow-Credentials": "true",
    };

    if (request.method === "OPTIONS") {
      return new Response(null, { status: 200, headers: cors });
    }

    const resp = await fetch(request);
    const out = new Response(resp.body, resp);

    for (const [k, v] of Object.entries(cors)) out.headers.set(k, v);

    return out;
  },
};

Note: “Snippets” appears to be a paid feature available under Cloudflare’s 25$ tier.