Contracts and security

Configure CORS deliberately

Allow browser clients from known origins without confusing CORS with authentication or general server security.

8 minute lesson

~~~

Browsers restrict scripts from reading cross-origin responses unless the server grants permission through CORS response headers.

Allow only the methods, headers, origins, and credential behavior the browser application needs. CORS does not stop curl or another server from making a request, so it is never a replacement for authentication or authorization.

An origin is the scheme, host, and port tuple, not a path or loose hostname suffix. For a preflight, the browser sends OPTIONS with the intended method and headers; the API answers whether the real request may proceed. The preflight carries no credentials, even when the eventual request will.

If credentialed browser requests are allowed, return the exact approved origin rather than *, enable credentials deliberately, and vary the response by Origin so caches do not reuse permission for another site. Test an allowed origin, a rejected origin, and this explicit preflight:

curl -i -X OPTIONS http://localhost:3000/books \
  -H 'Origin: http://localhost:5173' \
  -H 'Access-Control-Request-Method: POST' \
  -H 'Access-Control-Request-Headers: content-type'

Add a development origin allowlist and inspect both a simple request and an OPTIONS preflight.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →