APIs with Express · Chapter 14 of 29

Cookies and sessions

By the end of this chapter you can remember who logged in, with a signed cookie that points to a session on the server, and end that session for real. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The Tapri API
  • 6 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

Meera wants a dashboard where staff see today's orders, and only staff. Ravi checks it on his phone between deliveries. "Log in once in the morning," she says, "not on every page."

HTTP forgets the client after every request. With what you know, the name and pin would travel with every request, or the server would hand out a cookie like user=ravi, which anyone can edit to user=meera.

What you build: 6 tasks

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

  1. Task 1

    parseCookies: the Cookie header, by hand

    Export parseCookies(header), which turns a Cookie request header into an object of name to value, and returns {} for undefined or ''.

    Pairs are separated by ;. In each pair the name is everything before the first = and the value everything after it, so 'sid=abc.def==' gives sid 'abc.def=='. Names and values are trimmed (' spaced = value ' gives spaced 'value'), double quotes around a value are removed ('q="hello world"' gives 'hello world'), and %-encoding is decoded ('Meera%20Iyer' gives 'Meera Iyer'). A value that does not decode, such as '%E0%A4%A', is kept as it was, and the other cookies still come through.

    A piece with no = ('flag') or with no name ('=nameless') is skipped, and when a name comes twice the first value wins: 'a=1; a=2' gives { a: '1' }.

  2. Task 2

    signCookie and unsignCookie: catch a forged cookie

    Export signCookie(value, secret), which returns the value, a dot, and the HMAC-SHA256 of the value with the secret, in base64url: signCookie('order-42', secret) is 'order-42.' followed by 43 characters.

    Export unsignCookie(signed, secret), which returns the original value when the signature after the last dot is right for that value and secret ('a.b.c' signed comes back as 'a.b.c'), and false for anything else: a changed value, a changed signature, a signature made with another secret, no dot ('order-42'), an empty signature ('order-42.'), a signature of a different length, or undefined. It never throws.

    Compare the signatures with crypto.timingSafeEqual, not with ===.

  3. Task 3

    POST /login: a session and a safe cookie

    In createApp({ secret, now, sessions }), add POST /login with the JSON body { name, pin }. The name must be one of staff's own names (meera with pin '4040', ravi with '2525'), and the pin must match. Anything else, toString or an empty body included, answers 401 with { error: 'Wrong name or pin' }, sets no cookie and starts no session.

    On success, store a session in the sessions Map you were given, under a new random id from crypto.randomUUID(), as { user, expiresAt: now() + SESSION_MS }. Set the cookie sid to signCookie(id, secret) with httpOnly, secure, sameSite 'lax', path '/' and maxAge SESSION_MS, so the header says HttpOnly, Secure, SameSite=Lax, Path=/ and Max-Age=1800. Answer 200 with { user }, for example { user: 'ravi' }.

    The cookie holds only the signed id: the user's name is not in it.

  4. Task 4

    GET /me: who is logged in, and no forged cookies

    In createApp, read the cookies of every request with parseCookies from the Cookie header, which may hold other cookies too ('theme=dark; sid=...; lang=kn').

    Add GET /me. When the sid cookie's signature is right for the secret and its id is in sessions, it answers 200 with { user }, for example { user: 'meera' }.

    Anything else answers 401 with { error: 'Please log in' }: no cookie, the real id without a signature, an id signed with another secret, an edited signature, or a well signed id with no session.

  5. Task 5

    Sessions that end after 30 minutes

    A session lasts SESSION_MS (30 minutes) after login, measured with the injected now(). 29 minutes after login GET /me still answers 200. Once now() reaches expiresAt, GET /me answers 401 with { error: 'Session expired' } and deletes the session from the sessions Map.

    After that it is gone for good: even if the clock goes back, the same cookie answers 401 with { error: 'Please log in' }.

  6. Task 6 · interview question

    Interview: POST /logout, so a copied cookie stops working

    Add POST /logout. It deletes the session of the request's sid cookie from the sessions Map, clears the sid cookie (path '/'), and answers 204 with no body. The Set-Cookie header then starts with 'sid=;' and holds Expires=Thu, 01 Jan 1970.

    Afterwards the same cookie, sent again by someone who copied it, answers 401 on GET /me. Other users' sessions stay: Ravi is still logged in after Meera logs out.

What you will learn

  • Cookies: a header the server sets and the browser sends back, and the options that keep it safe.
  • Signing: an HMAC that shows whether a cookie was edited.
  • Sessions: the data stays on the server, the cookie holds only a signed random id, and sessions expire.
  • Logging out for real: why clearing the cookie is not enough.

More in The Tapri API

Build "Cookies and sessions" 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.