---
title: "CORS"
description: "Cross-origin resource sharing: headers, preflight handling, and where to enforce it (application code vs. Caddy)."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# CORS

Your frontend lives at `app.example.com`. Your API lives at `api.example.com`.
From the browser's perspective, those are different origins: different hostname,
different rules. When `app.example.com` makes a `fetch()` call to
`api.example.com`, the browser blocks it by default and shows a CORS error.

CORS (Cross-Origin Resource Sharing) is the protocol that lets `api.example.com`
opt in to that request. The API responds with headers declaring which origins,
methods, and headers it permits. The browser reads those headers and decides
whether to expose the response to the page; the server never blocks the
request, the browser does.

This only applies to browser-initiated requests. Server-to-server calls between
`app.example.com` and `api.example.com` are unaffected; CORS is a browser
enforcement mechanism, not a network one.

## The headers

| Header                             | What it controls                                                       |
| ---------------------------------- | ---------------------------------------------------------------------- |
| `Access-Control-Allow-Origin`      | Which origins may read the response                                    |
| `Access-Control-Allow-Methods`     | Which HTTP methods are permitted                                       |
| `Access-Control-Allow-Headers`     | Which request headers the browser may send                             |
| `Access-Control-Allow-Credentials` | Whether cookies and auth headers are included in cross-origin requests |
| `Access-Control-Max-Age`           | How long (seconds) the browser can cache a preflight response          |

## Preflight requests

Before sending a request that could have side effects (non-GET, or with custom
headers), the browser sends a preflight: an `OPTIONS` request to the same URL.
The server must respond with the CORS headers and a `204 No Content`. If it
doesn't, the browser blocks the real request.

```http
OPTIONS /v1/users HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Authorization, Content-Type
```

```http
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 86400
```

:::caution
`Access-Control-Allow-Origin: *` (wildcard) cannot be combined with
`Access-Control-Allow-Credentials: true`. If you need to send cookies or `Authorization` headers
cross-origin, you must reflect a specific origin.
:::

## Application code

Use application-level CORS when you need per-route control, dynamic origin
allowlists, or credential support.

### Go

A middleware that validates the request `Origin` against an allowlist and
handles the preflight:

```go
func corsMiddleware(allowed []string) func(http.Handler) http.Handler {
    set := make(map[string]bool, len(allowed))
    for _, o := range allowed {
        set[o] = true
    }

    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            origin := r.Header.Get("Origin")
            if set[origin] {
                w.Header().Set("Access-Control-Allow-Origin", origin)
                w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
                w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
                w.Header().Set("Access-Control-Max-Age", "86400")
                // Vary tells caches that the response differs by Origin.
                w.Header().Add("Vary", "Origin")
            }

            if r.Method == http.MethodOptions {
                w.WriteHeader(http.StatusNoContent)
                return
            }

            next.ServeHTTP(w, r)
        })
    }
}
```

Wire it into the server:

```go
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/users", handleListUsers)
mux.HandleFunc("POST /v1/users", handleCreateUser)

handler := corsMiddleware([]string{
    "https://app.example.com",
    "https://admin.example.com",
})(mux)

http.ListenAndServe(":8080", handler)
```

### Rust (axum)

Use `tower-http`'s `CorsLayer`, which axum integrates with directly:

```toml
# Cargo.toml
tower-http = { version = "0.6", features = ["cors"] }
```

```rust
use axum::{Router, routing::get};
use http::{HeaderValue, Method, header};
use tower_http::cors::CorsLayer;

fn app() -> Router {
    let cors = CorsLayer::new()
        .allow_origin([
            "https://app.example.com".parse::<HeaderValue>().unwrap(),
            "https://admin.example.com".parse::<HeaderValue>().unwrap(),
        ])
        .allow_methods([
            Method::GET,
            Method::POST,
            Method::PUT,
            Method::PATCH,
            Method::DELETE,
        ])
        .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE])
        .max_age(std::time::Duration::from_secs(86400));

    Router::new()
        .route("/v1/users", get(list_users).post(create_user))
        .layer(cors)
}
```

`CorsLayer` handles preflight `OPTIONS` responses automatically.

For credentialed requests (cookies, `Authorization`), keep the explicit origin
list and enable credentials. Reflecting arbitrary origins alongside
`allow_credentials(true)` would defeat the allowlist entirely:

```rust
let cors = CorsLayer::new()
    .allow_origin([
        "https://app.example.com".parse::<HeaderValue>().unwrap(),
        "https://admin.example.com".parse::<HeaderValue>().unwrap(),
    ])
    .allow_credentials(true)
    .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]);
```

### TypeScript (Hono)

Hono ships a built-in `cors` middleware:

```ts
import { Hono } from "hono";
import { cors } from "hono/cors";

const app = new Hono();

app.use(
  "/v1/*",
  cors({
    origin: ["https://app.example.com", "https://admin.example.com"],
    allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
    allowHeaders: ["Authorization", "Content-Type"],
    maxAge: 86400,
  }),
);
```

For credentialed requests, keep the explicit origin list; Hono reflects the
matching entry back. Reflecting every request origin alongside
`credentials: true` would defeat the allowlist entirely:

```ts
app.use(
  "/v1/*",
  cors({
    origin: ["https://app.example.com", "https://admin.example.com"],
    allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
    allowHeaders: ["Authorization", "Content-Type"],
    credentials: true,
  }),
);
```

## Caddy

Caddy can set CORS headers at the proxy layer, keeping them out of application
code entirely. This is a good fit when all routes on a domain share the same
policy and you don't need credential support. For Caddy installation and basic
reverse-proxy setup, see [VPS Setup](https://codex.mirio.dev/linux/vps-setup/).

```caddy
api.example.com {
    header Access-Control-Allow-Origin  "https://app.example.com"
    header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
    header Access-Control-Allow-Headers "Authorization, Content-Type"
    header Access-Control-Max-Age       "86400"

    # Respond to preflight requests before they reach the upstream.
    @preflight {
        method OPTIONS
    }
    respond @preflight 204

    reverse_proxy localhost:8080
}
```

:::note
The Caddy approach only works cleanly with a single allowed origin. If you need to allow multiple
origins and reflect the matching one back, that logic belongs in application code; Caddy's
`header` directive sets a static value.
:::

Source: https://codex.mirio.dev/web/rest-apis/cors/index.mdx
