🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Server Rendering••By Komal Nakrani

Astro CORS: Add CORS Headers to API Endpoints

Set Astro CORS headers on API endpoints: an allowlist of origins, an OPTIONS handler for preflight requests, Vary: Origin, and how checkOrigin affects form posts.

#Astro#Server Rendering#Astro CORS#API Endpoints

To enable CORS on an Astro endpoint, return an Access-Control-Allow-Origin header on its responses, and export an OPTIONS handler that answers the browser’s preflight request with the allowed methods and headers. Only do this for origins you trust, mark the route prerender = false so it runs on demand, and remember that Astro’s built-in checkOrigin protection rejects cross-site form-style POST requests before your handler sees them.

Key Takeaways

  • CORS headers tell browsers which other origins may read your endpoint’s responses; they do not stop servers or scripts from calling it.
  • Answer preflight OPTIONS requests with allowed methods, headers and a max age.
  • Echo the request’s Origin only if it is on an allowlist, and add Vary: Origin.
  • Cross-site POST requests with form, multipart or plain-text bodies get a 403 from security.checkOrigin; send JSON instead.

When you need CORS

Browsers block JavaScript on https://app.example.com from reading responses from https://api.example.com unless the API opts in with CORS headers. You need them when a different site, a separate frontend, or a browser extension calls your Astro endpoints with fetch(). Same-origin calls from your own Astro pages need nothing.

A reusable helper

// src/lib/cors.ts
const ALLOWED = new Set(['https://app.example.com', 'http://localhost:5173']);

export function corsHeaders(request: Request): Record<string, string> {
  const origin = request.headers.get('origin');
  if (!origin || !ALLOWED.has(origin)) return { Vary: 'Origin' };
  return {
    'Access-Control-Allow-Origin': origin,
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    'Access-Control-Max-Age': '86400',
    Vary: 'Origin',
  };
}

Echoing the specific origin, rather than *, lets you allow several sites and keeps credentials possible. Vary: Origin tells caches that the response differs by origin, so a CDN does not serve one site’s headers to another.

Use it in an endpoint

// src/pages/api/products.ts
import type { APIRoute } from 'astro';
import { corsHeaders } from '../../lib/cors';

export const prerender = false;

export const OPTIONS: APIRoute = ({ request }) =>
  new Response(null, { status: 204, headers: corsHeaders(request) });

export const GET: APIRoute = async ({ request }) => {
  const products = [{ id: 'p1', name: 'Mug' }];
  return Response.json(products, { headers: corsHeaders(request) });
};

export const POST: APIRoute = async ({ request }) => {
  const body = await request.json();
  // ...create the product
  return Response.json({ ok: true, received: body }, { status: 201, headers: corsHeaders(request) });
};

The browser sends OPTIONS before a POST with Content-Type: application/json or an Authorization header. Without an OPTIONS handler that returns these headers, the preflight fails and the browser never sends the real request. Every other method’s response needs the headers too, because the browser checks them again on the actual response. Our API endpoints guide covers the rest of the endpoint API.

Public read-only APIs

For an open, unauthenticated GET endpoint such as a public JSON feed, a wildcard is acceptable:

// src/pages/api/feed.json.ts
import type { APIRoute } from 'astro';

export const GET: APIRoute = () =>
  Response.json({ items: [] }, { headers: { 'Access-Control-Allow-Origin': '*' } });

This one can even stay prerendered: static JSON files with a wildcard header can also be served by setting the header in your host’s _headers file. Never combine * with Access-Control-Allow-Credentials: true; browsers reject it.

The checkOrigin trap

Astro’s security.checkOrigin is on by default. For on-demand routes it rejects unsafe requests (POST, PUT, PATCH, DELETE) from another origin when the body is application/x-www-form-urlencoded, multipart/form-data or text/plain, or when no content type is sent. The response is a 403 with the text “Cross-site POST form submissions are forbidden”, and your handler never runs.

That protects you from cross-site form attacks, and it means:

  • Cross-origin fetch() calls should send JSON with Content-Type: application/json. That passes the check and triggers a normal CORS preflight.
  • Cross-origin FormData uploads will be blocked. Either upload from the same origin or disable checkOrigin and add your own CSRF protection, such as a token check.

CORS in middleware

To apply the same headers to every /api/ route, set them in middleware after the handler runs:

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { corsHeaders } from './lib/cors';

export const onRequest = defineMiddleware(async (context, next) => {
  if (!context.url.pathname.startsWith('/api/')) return next();
  if (context.request.method === 'OPTIONS') {
    return new Response(null, { status: 204, headers: corsHeaders(context.request) });
  }
  const response = await next();
  for (const [k, v] of Object.entries(corsHeaders(context.request))) response.headers.set(k, v);
  return response;
});

See our Astro middleware guide for ordering several middleware functions. Static Astro themes do not need any of this until you add endpoints with an adapter.

FAQ

How do I enable CORS in Astro?

Add Access-Control-Allow-Origin (and for non-simple requests, allowed methods and headers) to the endpoint’s responses, and export an OPTIONS handler that returns the same headers with status 204.

Why does my cross-origin POST to Astro return 403?

security.checkOrigin blocks cross-site POST requests with form, multipart or plain-text bodies. Send JSON with Content-Type: application/json, or disable the check and add your own CSRF protection.

Should I use Access-Control-Allow-Origin: *?

Only for public, read-only data that needs no cookies or credentials. For anything else, echo specific trusted origins from an allowlist.

Do CORS headers protect my API?

No. CORS controls what browsers let other websites read. Servers, scripts and tools such as curl ignore it, so protect sensitive endpoints with authentication and rate limiting.