APIs with Express · Chapter 17 of 29

CORS

By the end of this chapter you can let the web pages of chosen partner sites read your API from the browser, answer the browser's preflight, and keep every other site out. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Production
  • 5 tasks
  • Express
  • In the all labs plan

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.

Why you need this

Kulhad Corner, the first partner café, has built a web page that takes orders from Tapri's API. "It works in curl," says their developer, "but the browser says it was blocked by CORS policy." Meera wants it open to two partner sites, Kulhad Corner and Bun Maska Co, and nobody else, with the admin routes closed to every other site.

Nothing you have written tells a browser who may read an answer, so it hides every answer from another site's script. Pasting Access-Control-Allow-Origin: * into every route opens the admin routes to every page on the web too, and it still fails once the café's page sends a cookie or a JSON order.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    cors: only listed café origins may read

    Export cors(options), which returns a middleware. options.origins is the list of allowed origins, such as ['https://kulhadcorner.in', 'https://bunmaska.co'].

    On every request, with or without an Origin header, it adds Origin to the Vary header and keeps what was there: a Vary of Accept-Encoding set earlier becomes Accept-Encoding, Origin.

    When the request's Origin header is exactly one of origins, it sets Access-Control-Allow-Origin to that same origin, never *. Any other origin, a near match such as http://kulhadcorner.in, or no Origin at all gets no Access-Control-Allow-Origin. Either way the request goes on to the route, which answers 200.

  2. Task 2

    cors: answer the browser's preflight

    A preflight is an OPTIONS request with an Access-Control-Request-Method header, and cors answers it itself instead of passing it on.

    From a listed origin it answers 204 with an empty body, Access-Control-Allow-Origin as in task 1, Access-Control-Allow-Methods (options.methods joined by ', ', default 'GET, POST'), Access-Control-Allow-Headers (options.headers joined by ', ', default 'Content-Type'), and Access-Control-Max-Age set to options.maxAge as text ('600'), but only when maxAge is given.

    From any other origin, or with no Origin, it answers 403 with { error: 'Origin not allowed' } and no Access-Control-Allow-Methods.

    An OPTIONS request without Access-Control-Request-Method is not a preflight: it goes on to the route like any other request.

  3. Task 3

    cors: credentials and exposed headers

    cors takes two more options, both off by default: credentials (false) and exposeHeaders ([]).

    For a listed origin, credentials: true adds Access-Control-Allow-Credentials: true, and a non-empty exposeHeaders adds Access-Control-Expose-Headers with the names joined by ', ' (['X-Request-Id', 'X-Total-Count'] gives 'X-Request-Id, X-Total-Count').

    An origin that is not listed gets neither header, and with the defaults a listed origin gets only Access-Control-Allow-Origin.

  4. Task 4

    createApp: open /api to the partner cafés, and only /api

    In createApp, use your cors for every path under /api, and only there, with origins partnerCafes, methods GET, POST, PATCH, headers Content-Type, X-Api-Key, credentials on, exposeHeaders X-Request-Id and maxAge 600.

    A preflight for OPTIONS /api/orders/7 from https://kulhadcorner.in then answers 204 with Access-Control-Allow-Methods 'GET, POST, PATCH', Access-Control-Allow-Headers 'Content-Type, X-Api-Key', Access-Control-Max-Age '600' and Access-Control-Allow-Credentials 'true'. PATCH /api/orders/7 with { "status": "ready" } answers 200 with { id: '7', status: 'ready' }, the café's origin and Access-Control-Expose-Headers 'X-Request-Id'. GET /api/menu from https://bunmaska.co answers the menu with that origin.

    GET /admin/stock still answers 200 with the stock, and neither it nor a preflight for it gets any Access-Control headers.

  5. Task 5 · interview question

    Interview: needsPreflight, which requests ask first

    Export needsPreflight({ method, headers }), which returns true when a browser would send a preflight before this request and false when the request is simple. headers is an object of header name to value, and may be missing.

    A request is simple when its method is GET, HEAD or POST, and every header it sets is Accept, Accept-Language, Content-Language, or a Content-Type whose type is application/x-www-form-urlencoded, multipart/form-data or text/plain. Any other method (PUT, PATCH, DELETE) or any other header (Authorization, X-Api-Key) means a preflight, so a POST with Content-Type application/json needs one.

    Header names ignore case, so does the type ('Text/Plain'), and anything after a ; in the Content-Type ('text/plain; charset=utf-8', 'multipart/form-data; boundary=x') does not count.

What you will learn

  • Access-Control-Allow-Origin: which site's script may read the answer, and why it needs Vary: Origin.
  • The preflight: the OPTIONS request a browser sends to ask first.
  • Simple requests: which requests go out without asking.
  • Credentials and exposed headers: cookies across sites, and the response headers a script may read.

More in Production

Build "CORS" yourself

Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.