Deutsch
GuideSecurity · Web basics

CORS explained for vibe coders: what it protects and what it does not

What CORS really does, why it is not authentication, how preflight works, the credentials and wildcard rule, and how to set CORS headers on a Supabase Edge Function.

By Tim GeithnerPublished 6 min read

Short answer

CORS is a browser rule that decides whether JavaScript on one site may read the response from another. It is not authentication: curl, scripts and servers ignore it, and many requests still reach your server. Protect every endpoint with a real auth check, then use CORS headers to let your own frontend read the answers. Answer the OPTIONS preflight, list the headers your client sends, and never combine a reflected or wildcard origin with cookies.

Ask an AI about this page:ChatGPTClaude

On this page

Key takeaways

  • CORS decides whether browser JavaScript on another origin may read your response. That’s all.
  • It is not authentication. curl, scripts and servers ignore it, so every endpoint needs its own auth check.
  • A JSON body or an Authorization header triggers a preflight (OPTIONS). Answer it, or the real request never happens.
  • * cannot be combined with cookies. Reflecting any origin with Access-Control-Allow-Credentials: true is the real danger.
  • For Supabase Edge Functions, @supabase/server answers the preflight for you; restrict the origin when you know it.

What CORS is, in one paragraph

Browsers follow the same-origin policy: JavaScript loaded from https://your-app.example may not read responses from https://api.other.example unless that server says it may. CORS (Cross-Origin Resource Sharing) is the way the server says it. It sends headers such as Access-Control-Allow-Origin, and the browser decides whether your script gets to see the response. The Fetch Standard describes the protocol as a set of headers that “indicates whether a response can be shared cross-origin”. The key word is shared: CORS is about who may read, not who may ask.

An “origin” is scheme, host and port together. https://your-app.example and https://your-app.example:8443 are different origins, and so are http:// and https://.

What CORS is not

This is where most confusion comes from. CORS does not:

  • Authenticate anyone. It never checks who the caller is. A script on a server or a curl command doesn’t run in a browser, so it doesn’t care about CORS headers at all.
  • Stop requests from reaching your server in every case. For “simple” requests (see below) the browser sends the request first and only hides the response if the headers don’t allow it. Your function has already run by then.
  • Protect data that your endpoint hands out to anyone. If /functions/v1/export returns every customer to any caller, a strict Access-Control-Allow-Origin doesn’t help; an attacker just calls it from their own machine.

So the order is always: first an auth check that decides who may call and what they may get, then CORS headers so your own frontend can read the answer. Supabase’s guide on securing Edge Functions puts the protection in the auth layer: the platform checks the JWT, and your code uses a client scoped to the caller.

Simple requests and preflight

MDN splits cross-origin requests into two groups.

RequestPreflight?Typical example in an AI-built app
GET, HEAD or POST with only safelisted headers and a Content-Type of text/plain, multipart/form-data or application/x-www-form-urlencodedNo (“simple request”)A plain form post
Any other method (PUT, PATCH, DELETE)YesUpdating a record
Content-Type: application/jsonYesAlmost every fetch call to an Edge Function
An Authorization header or another custom header such as apikeyYesEvery call made with supabase.functions.invoke()

For a preflighted request, the browser first sends OPTIONS with Access-Control-Request-Method and Access-Control-Request-Headers. Only if the answer allows the method, the headers and the origin does it send the real request. If your function treats OPTIONS like a normal call, for example by requiring a JSON body or a token, the preflight fails and you see the famous CORS error in the console, even though the real problem is a missing OPTIONS branch.

Access-Control-Max-Age tells the browser how long it may reuse a preflight answer. MDN notes that browsers cap the value, so a large number won’t stick.

The credentials rule

By default, a cross-origin fetch does not send cookies. The frontend has to ask for it with credentials: "include". MDN defines credentials as cookies, TLS client certificates or authentication headers containing a username and password. When a request carries them:

  • the server must answer with Access-Control-Allow-Credentials: true, and
  • Access-Control-Allow-Origin must name one exact origin. The Fetch Standard says it plainly: with credentials mode “include”, the header “cannot be *”. The same applies to wildcard allowed headers and methods.

Developers who hit this rule often “fix” it by echoing whatever Origin the request sent back in Access-Control-Allow-Origin, together with Allow-Credentials: true. That makes every website on the internet a trusted origin for your logged-in users. It is the defect described in the fix for CORS wildcard with credentials.

CORS for Supabase Edge Functions

Supabase’s CORS guide shows the classic pattern: import corsHeaders from npm:@supabase/supabase-js@^2/cors (SDK 2.95.0 or later), return early for OPTIONS, and attach the same headers to every response. The headers allow the ones the Supabase client sends: authorization, x-client-info, apikey and content-type. The documented default for the origin is *.

If you use withSupabase from Supabase’s @supabase/server package, CORS is built in: it answers every OPTIONS request with 204 and the configured headers and adds them to every response. By default it uses the same headers as supabase-js. To restrict the origin, pass your own:

Safesupabase/functions/notes/index.ts
import { withSupabase } from "npm:@supabase/server@1";

export default {
  fetch: withSupabase(
    {
      auth: "user",
      cors: {
        headers: {
          "Access-Control-Allow-Origin": "https://your-app.example",
          "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
          "Access-Control-Allow-Methods": "POST, OPTIONS",
        },
      },
    },
    async (_req, ctx) => {
      // CORS is handled above; this line is what protects the data.
      const { data } = await ctx.supabase.from("notes").select("id, title");
      return Response.json(data);
    },
  ),
};

The security here comes from auth: "user" and ctx.supabase, which is scoped to the caller so row level security applies. The CORS block only decides that your site, and no other, may read the answer in a browser.

Several origins: production, preview, localhost

Access-Control-Allow-Origin takes exactly one origin or *, not a list. To allow several, check the request’s Origin against an allowlist and echo it only if it is on the list. MDN adds one important detail: when the answer depends on the origin, send Vary: Origin so caches don’t serve one origin’s answer to another.

supabase/functions/public-stats/index.ts (without @supabase/server)
const ALLOWED_ORIGINS = ["https://your-app.example", "https://preview.your-app.example"];

function corsHeaders(req: Request): Record<string, string> {
  const origin = req.headers.get("Origin") ?? "";
  return {
    "Access-Control-Allow-Origin": ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0]!,
    "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
    "Access-Control-Allow-Methods": "POST, OPTIONS",
    "Vary": "Origin",
  };
}

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders(req) });
  // Verify the caller here. CORS decides who may read the answer, not who may ask.
  return Response.json({ ok: true }, { headers: corsHeaders(req) });
});

The allowlist is an exact match. Don’t use “ends with” or “contains” checks such as origin.endsWith("your-app.example"): https://evil-your-app.example ends with that string too.

Debugging a CORS error

Browsers hide CORS failures from your JavaScript on purpose; MDN notes that the details only show up in the console. Work through it in this order:

Look at the network tab, not just the console

Find the OPTIONS request. If it failed or returned an error status, your function does not handle the preflight.

Compare the requested and allowed headers

The preflight lists what the browser wants in Access-Control-Request-Headers. Every name there must appear in your Access-Control-Allow-Headers.

Check the origin exactly

Scheme, host and port must match. http://localhost:5173 is not http://127.0.0.1:5173.

Check error responses too

If your function throws before it adds the CORS headers, the browser reports a CORS error instead of your real error. Add the headers to error responses as well, or let withSupabase do it.

A fix prompt for your AI builder

Clean up CORS on Supabase Edge Functions

Review every Supabase Edge Function in this project.

  1. Make sure each function verifies the caller before doing anything with user data or paid APIs (withSupabase with auth: “user” from npm:@supabase/server@1, or an equivalent token check). CORS headers are not an access check.
  2. Make sure OPTIONS requests are answered with status 204 and the CORS headers, before any auth or body parsing.
  3. Set Access-Control-Allow-Origin to our production origin (and preview origins via an exact-match allowlist with Vary: Origin) where the function is only called by our own frontend.
  4. Remove any code that copies the request’s Origin header into Access-Control-Allow-Origin without an allowlist, especially together with Access-Control-Allow-Credentials: true.
  5. Add the CORS headers to error responses too.

Show me every function you changed.

Frequently asked questions

Does CORS protect my API from other websites?

Only partly. CORS stops JavaScript on another site from reading your responses in a browser. It does not stop the request from being sent in every case, and it does nothing against curl, scripts or servers. Every endpoint still needs its own auth check.

Is Access-Control-Allow-Origin: * dangerous?

On its own, for an API that uses a bearer token in the Authorization header, it does not let other sites read your users’ data, because the browser does not attach that token by itself. It becomes dangerous with cookie-based auth: browsers refuse the wildcard for credentialed requests, and the common workaround, reflecting any Origin back with Access-Control-Allow-Credentials: true, lets every site read signed-in users’ data.

Why do I get a CORS error only on POST, not on GET?

Because your POST sends a JSON body or an Authorization header, which makes the browser send a preflight OPTIONS request first. If your function does not answer OPTIONS with the right headers, the real request is never sent. Handle OPTIONS at the top of the function.

Should I just turn CORS off to fix the error?

You can’t turn it off from the frontend; it is enforced by the browser. Fix it on the server by answering the preflight and returning Access-Control-Allow-Origin with your site’s origin. Browser extensions that disable CORS only hide the problem on your own machine.

Sources

  1. 1.Cross-Origin Resource Sharing (CORS) — MDN Web Docs
  2. 2.Access-Control-Allow-Credentials — MDN Web Docs
  3. 3.Fetch Standard: CORS protocol — WHATWG
  4. 4.CORS (Cross-Origin Resource Sharing) support for Invoking from the browser — Supabase Docs
  5. 5.Securing Edge Functions — Supabase Docs

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt