Skip to content

CORS

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

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.

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/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

Application code

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

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

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:

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)

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

# Cargo.toml
tower-http = { version = "0.6", features = ["cors"] }
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:

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]);

Hono ships a built-in cors middleware:

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:

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.

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
}

Type to search…

↑↓ navigate↵ selectEsc close