Node.js course · Part 4: The HTTP details · lab 4 of 9
Headers, cookies, CORS and caching
The parts of HTTP that decide whether your API is safe and fast: what headers do, how a session cookie should be written, who is allowed to call you from a browser, and what may be cached.
By the end you can
- Say what the common request and response headers are for
- Write a session cookie that JavaScript cannot steal and another site cannot send
- Decide which origins may call your API, and answer a preflight correctly
- Choose a caching rule per kind of resource, and answer 304 when nothing changed
Easier if you did first
step 1 of 4
What headers are for
If the body is the parcel, headers are everything written on the outside: what is inside, who sent it, how long it keeps, whether it may be copied.
A few earn their place in your head. Content-Type says what format the body is, and getting it wrong means the other side reads JSON as text. Authorization carries a token. Cookie carries whatever you set earlier. Origin says which site the browser was on when it made the request, and the browser sets it, not the page, which is why it can be trusted. Cache-Control says who may keep a copy and for how long. Set-Cookie is how you put something in the browser's jar.
The ones that protect you are not optional extras. A missing Content-Type breaks parsing. A missing SameSite on a cookie allows a whole class of attack. A careless Access-Control-Allow-Origin hands your API to any site that asks.
Five questions on the ones that matter.
What these words mean
- header
- A labelled fact attached to a request or response.
- Content-Type
- What format the body is, e.g. application/json.
- Origin
- The site the browser was on. Set by the browser, so a page cannot fake it.
- Set-Cookie
- A response header asking the browser to store something.
- Cache-Control
- Who may keep a copy of this response, and for how long.
- CORS
- The browser rule about which sites may read a response from your API.
question 1 of 5
Your API returns JSON but sends no Content-Type. What goes wrong?
question 2 of 5
Why mark a session cookie HttpOnly?
question 3 of 5
What does SameSite=Lax on a cookie prevent?
question 4 of 5
CORS blocked your front end from reading an API response. Who enforced that?
question 5 of 5
A response contains one customer's invoice. What must Cache-Control say?