Start learning free

LESSON 48 OF 58 · FULL-STACK: SHIPPING IT

What Browsers May Keep in JavaScript

Practice

A browser can keep a copy of an answer and use it again later, without downloading it. The server tells it what it may keep with the Cache-Control header. Without one, the browser decides by itself, and a visitor may get yesterday's answer.

At the start, /assets/app-4f2a.js answers 404: the starting code doesn't serve the assets folder yet. You serve it in step 5, kept for a year. Under Check, Cache-Control: None means the answer has no such header.

Three values cover the shop. no-store: keep no copy, always ask the server. no-cache: keep a copy, but ask the server before each use; if nothing changed, the server answers 304 and nothing is downloaded. max-age with immutable: keep it that many seconds and don't ask at all. That last one is safe only for a file whose name changes when its content does, like app-4f2a.js: the build names it after its content.

You set the header with res.set, and express.static writes it for you from its options. For example:

app.get("/opening-hours", (req, res) => {
  res.set("Cache-Control", "max-age=3600");
  res.json({ open: "9:00", close: "18:00" });
});
app.use("/photos", express.static("photos", { maxAge: "1d" }));

The opening hours may be kept an hour. The photos answer public, max-age=86400: a day, in seconds.

Your server must answer:

GET /                    →  200  Cache-Control: no-cache   (client/dist/index.html)
GET /cart                →  200  Cache-Control: no-cache   (client/dist/index.html)
GET /assets/app-4f2a.js  →  200  Cache-Control: public, max-age=31536000, immutable
GET /api/products        →  200  Cache-Control: no-store   (the 8 products)

Your task: in server/app.js, write a noStore middleware and use it for every path under /api, serve the assets folder of client/dist at /assets for a year with immutable, and make the catch-all route send index.html with no-cache.


Assignment
Follow the Coding Tutorial to give each kind of answer the Cache-Control it needs: the API, the files under /assets and index.html.


Hint
A middleware that sets a header must call next(), or the request never reaches the route. In the options of express.static, maxAge takes a string like "1d".


STEP 1 OF 6
    Ctrl + Enter to check

    Fsship Cache Headers in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free