CORS and a dev proxy

A browser runs a page from one origin and lets its script call another only when the other answers with the right CORS headers. CORS is not a server security feature: a client without a browser ignores it completely. Its job is to let a JavaScript frontend on localhost:5173 call an API on localhost:8080 during development, and to keep a random page from reading the API with the user's cookies.

The CORS headers

The middleware below answers a preflight with 204 and names the origin, the methods and the headers it allows; a normal request gets the allow-origin header and goes on to the handler. The Vary: Origin header matters because the answer depends on the request's origin, and a cache that ignores it serves one origin's header to another.

package main import ( "fmt" "net/http" "net/http/httptest" ) func cors(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "https://app.example") w.Header().Add("Vary", "Origin") if r.Method == http.MethodOptions { w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") w.WriteHeader(http.StatusNoContent) return } next.ServeHTTP(w, r) }) } func main() { mux := http.NewServeMux() mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "notes") }) h := cors(mux) req := httptest.NewRequest("OPTIONS", "/notes", nil) req.Header.Set("Origin", "https://app.example") req.Header.Set("Access-Control-Request-Method", "GET") rec := httptest.NewRecorder() h.ServeHTTP(rec, req) fmt.Println("preflight status:", rec.Code) fmt.Println("allow-origin:", rec.Header().Get("Access-Control-Allow-Origin")) fmt.Println("allow-methods:", rec.Header().Get("Access-Control-Allow-Methods")) req = httptest.NewRequest("GET", "/notes", nil) req.Header.Set("Origin", "https://app.example") rec = httptest.NewRecorder() h.ServeHTTP(rec, req) fmt.Println("get status:", rec.Code, "body:", rec.Body.String()) }

go build -o app main.go && ./app

preflight status: 204
allow-origin: https://app.example
allow-methods: GET, POST, OPTIONS
get status: 200 body: notes

The preflight is the browser asking permission before the real request: it sends OPTIONS with the method and headers it wants, and the server answers with what it permits. The 204 means no body, which is what a preflight needs. A request whose method or header is not in the allow lists is stopped by the browser, not by the server.

An allowlist of origins

A fixed allow-origin of one site is a start, and a service with a preview deployment per branch needs a list. The middleware below echoes the origin only when it is allowed, and answers an unknown origin without the header, which the browser treats as a refusal. The status is still 200, because the server did its work and the browser is the one that withholds the answer.

package main import ( "fmt" "net/http" "net/http/httptest" ) var allowed = map[string]bool{ "https://app.example": true, } func cors(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") if allowed[origin] { w.Header().Set("Access-Control-Allow-Origin", origin) w.Header().Add("Vary", "Origin") } next.ServeHTTP(w, r) }) } func main() { mux := http.NewServeMux() mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "notes") }) h := cors(mux) for _, origin := range []string{"https://app.example", "https://evil.example"} { req := httptest.NewRequest("GET", "/notes", nil) req.Header.Set("Origin", origin) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) fmt.Printf("%s -> allow-origin=%q status=%d\n", origin, rec.Header().Get("Access-Control-Allow-Origin"), rec.Code) } }

go build -o app main.go && ./app

https://app.example -> allow-origin="https://app.example" status=200
https://evil.example -> allow-origin="" status=200

The second request has no allow-origin, so a browser on evil.example cannot read the body. A program that must refuse the request outright, for a non-browser client or for its logs, answers 403 in the middleware; the browser refuses either way, and the 403 is easier to see in a test.

A development proxy

A frontend dev server can also proxy the API to the backend, and the Go standard library has the proxy the other way round for services. NewSingleHostReverseProxy forwards the request to a target and copies the response back, with the path rewritten to the target's prefix. The program below proxies to a backend server and reads what the backend saw.

package main import ( "fmt" "io" "net/http" "net/http/httptest" "net/http/httputil" "net/url" ) func main() { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "backend saw %s %s\n", r.Method, r.URL.Path) })) defer backend.Close() target, err := url.Parse(backend.URL) if err != nil { panic(err) } proxy := httputil.NewSingleHostReverseProxy(target) frontend := httptest.NewServer(proxy) defer frontend.Close() resp, err := http.Get(frontend.URL + "/api/notes") if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Println("status:", resp.Status) fmt.Print("body: ", string(body)) }

go build -o app main.go && ./app

status: 200 OK
body: backend saw GET /api/notes

The reverse proxy forwards headers and status, and it keeps the path unless a rewrite is set. A dev setup often uses the frontend tool's proxy instead, because the frontend server already owns the port the browser opened; the Go proxy is for a service that fronts another one, and it is the piece an API gateway is built from.

The same origin in production

In production the frontend and the API can share one origin: the Go server serves the built page and the API under the same host, so the browser makes no cross-origin request and no CORS header is needed. The program below serves a page and an API from one mux.

package main import ( "fmt" "io" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "<h1>app</h1>") }) mux.HandleFunc("GET /api/notes", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, `[{"id":1}]`) }) srv := httptest.NewServer(mux) defer srv.Close() for _, path := range []string{"/", "/api/notes"} { resp, err := http.Get(srv.URL + path) if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Printf("%s -> %d %s", path, resp.StatusCode, body) } }

go build -o app main.go && ./app

/ -> 200 <h1>app</h1>
/api/notes -> 200 [{"id":1}]

One origin is the simplest CORS policy: there is nothing to allow, because there is no cross-origin request. The development setup with two servers needs the headers, so the middleware is enabled by configuration in development and off in production; the capstone service embeds the built frontend and serves both from one process.

CORS is a browser rule

Three facts keep CORS debugging short. A curl request ignores it, so a failing browser call and a working curl call say the server is fine and the headers are missing. A preflight failure is a browser console message and no request in the server log, because the real request never happened. And Access-Control-Allow-Credentials cannot be combined with * as the origin: a request that sends cookies needs the exact origin echoed back, which is why the allowlist form is the one a real application uses.

The next lesson bounds the server that answers these requests, because an open connection with no timeout is the cheapest way to take a Go service down.

Exercises

  1. Send an OPTIONS request with Access-Control-Request-Method: DELETE to the middleware. What does it answer, and what would the browser do with the real request?
  2. Put Vary: Origin in a response with a fixed origin and one with an allowlist. Which one needs it, and what does a cache do without it?
  3. Point the proxy at a backend under /backend with a path rewrite. What does the backend see, and why is the rewrite a function?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does CORS protect?

    Answer

    A browser page from reading another origin without permission

    A non-browser client ignores it.

  2. What does a preflight request ask?

    Answer

    Whether the method and headers are allowed for the origin

    It is an OPTIONS request before the real one.

  3. Why add Vary: Origin?

    Answer

    The response depends on the request origin, so caches must key on it

    Without it a cache serves one origin's header to another.

  4. What does the server answer an unknown origin?

    Answer

    The response without an allow-origin header, which the browser refuses

    A 403 is the explicit alternative.

  5. What does NewSingleHostReverseProxy do?

    Answer

    Forwards requests to a target URL and copies the responses

    It is the base of a gateway.

  6. When is no CORS header needed?

    Answer

    When the page and the API share one origin

    There is no cross-origin request.

  7. Why does a failing preflight leave no request in the log?

    Answer

    The browser never sends the real request

    Only the OPTIONS reached the server.

  8. What can Access-Control-Allow-Credentials not use?

    Answer

    A wildcard origin

    Cookies need the exact origin.

  9. Why is curl unaffected by CORS?

    Answer

    CORS is enforced by the browser, not the server

    It is a browser rule.

  10. When should the CORS middleware be enabled?

    Answer

    In development with two origins, off when the frontend is embedded

    One origin in production needs no header.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev