Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Authentication and Security

Passwords, Sessions and Cookies

Hash passwords with scrypt, keep login state in signed cookies or server sessions, set HttpOnly and SameSite flags, and stop CSRF with tokens in Fastify apps.

JWT Authentication with Fastify showed one way to remember who a user is. This lesson covers the other pieces of a login system: storing passwords safely, keeping a session on the server, setting cookies correctly, and defending against cross-site request forgery (CSRF).

Fastify gives you @fastify/cookie, @fastify/session and @fastify/csrf-protection for these jobs. Those packages are not installed on this site, so the plugin calls are read-only. The runnable examples use node:crypto and the small Fastify-like stand-in, which shows exactly what the plugins do.

A safe login system

Hash passwords Slow, salted, never reversible.
Cookie with a session id Random, signed, HttpOnly.
Server-side session Data lives on your side.
CSRF token Proves the form came from you.

Each layer covers a different attack.

1 / 2

Never store passwords, store hashes

If your database leaks, plain passwords expose users on every other site where they reused them. A password hash is a one-way function: you can check a guess against it, but you cannot get the password back. Good password hashing is deliberately slow and uses a random salt per user, so identical passwords produce different hashes and precomputed tables are useless.

Node includes scrypt, a memory-hard password function, in node:crypto. Use the async version in a server so you do not block the event loop (see Performance Tuning Fastify Applications).

Node.js Hash and check passwords with scrypt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The stored string carries its own scheme and salt, so you can later move to stronger settings and still verify old hashes. In real projects most people use a maintained package such as argon2 or bcrypt; the idea is the same.

Check a password even when the username does not exist (against a dummy hash). Otherwise "user not found" returns much faster than "wrong password", and the timing reveals which accounts exist.

Cookies

A cookie is a small value the browser stores and sends back with every request to your site. The server sets it with a Set-Cookie header. The flags matter more than the value:

Flag Purpose
HttpOnly JavaScript cannot read it, so XSS cannot steal it.
Secure Sent only over HTTPS.
SameSite=Lax or Strict Not sent on most cross-site requests, which blocks many CSRF attacks.
Max-Age / Expires How long it lives; omit for a session cookie.
Path, Domain Which URLs receive it; keep them narrow.

With the real plugin, you register it once and use reply.setCookie and request.cookies:

JavaScript
import cookie from '@fastify/cookie';
await app.register(cookie, { secret: process.env.COOKIE_SECRET });   // enables signed cookies

reply.setCookie('sid', sessionId, {
  httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge: 60 * 60 * 8, signed: true,
});

Server-side sessions

A session keeps the user's data on the server (memory, Redis, a database) and gives the browser only a random session id in a cookie. Compared with a JWT in storage, a session can be ended instantly (delete it) and holds as much data as you like.

The id must be unpredictable (use randomBytes, never a counter) and the cookie should be signed so tampering is detected. The next example builds the whole mechanism: a login route that creates a session and sets a signed sid cookie, a preHandler that loads the session, and a logout that destroys it.

Node.js Sessions with a signed cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The logout works instantly because the server forgot the session, even though the browser still holds the old cookie. A JWT cannot do that without extra bookkeeping.

For production, @fastify/session supplies the same flow with pluggable stores (Redis, SQL). The default memory store loses everything on restart and leaks memory, so it is for development only.

CSRF: forged requests from other sites

Browsers attach cookies automatically. If a logged-in user visits a malicious page, that page can make the browser send POST /transfer to your site with the user's cookie. This is cross-site request forgery. Defenses, best first:

  1. SameSite=Lax or Strict cookies. Modern browsers then withhold the cookie on cross-site POSTs.
  2. A CSRF token that the page must send in a header or hidden field. A different site cannot read it, so it cannot include it.
  3. Check the Origin header on state-changing requests.

Tokens are tied to the session and compared in constant time:

Node.js A session-bound CSRF token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

APIs that use Authorization: Bearer headers (not cookies) are not vulnerable to CSRF, because browsers do not add that header on their own. CSRF matters whenever authentication travels in a cookie.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a password hash use a random salt?

    A unique salt per user makes identical passwords hash differently and defeats precomputed tables.
  2. 2. Which cookie flag stops JavaScript on the page from reading the session id?

    HttpOnly hides the cookie from document.cookie, which limits what an XSS attack can steal.
  3. 3. What is one advantage of server-side sessions over a stateless JWT?

    The server owns the session record, so deleting it logs the user out everywhere at once.
  4. 4. When is CSRF mainly a concern?

    Browsers add cookies to cross-site requests on their own. Bearer headers are added by your code, so they are not forged this way.

Summary

  • Store salted, slow hashes (scrypt, argon2, bcrypt), compare in constant time, and never reveal whether the username or the password was wrong.
  • Session cookies should be random, signed, HttpOnly, Secure and SameSite.
  • Server-side sessions can be revoked at once; use Redis or a database store in production, not the memory store.
  • CSRF needs SameSite, tokens or an Origin check whenever cookies authenticate requests.
  • Real plugins: @fastify/cookie, @fastify/session, @fastify/csrf-protection.

Next: Security Headers, CORS and Rate Limiting