Skip to content

Module 06 · Lesson 6.2

Sessions and Password Handling

40 minUpdated 19 Nov 2026Part of Authentication and Integrations · New Project Creation
On this page
  1. What you will learn
  2. Sessions, cookies and how long they last
  3. Password handling: hash, salt, never store
  4. Sign-in links, second factors and rate limiting
  5. ADR-004: use an established authentication library
  6. Step-by-step workflow
  7. Working with an assistant on sign-in
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

When you leave a coat at a cloakroom, you get a numbered ticket. You do not show your ID again each time you walk past. The ticket is meaningless to anyone else, as long as nobody copies it. A web session works the same way.

In this lesson you learn what a session is, which cookie settings protect it, how long Tidewell's sessions last, and how passwords are kept safely. You also write the decision record that says Tidewell will not build its own sign-in. A few short programs show what the libraries do for you. They are for understanding, not to ship.

What you will learn

  • Explain what a session is and how a cookie holds its id.
  • Set the cookie attributes and expiry rules that protect a session.
  • Describe why passwords are hashed with a slow, salted function and never encrypted or stored as text.
  • Write a decision record that chooses an established authentication library, and list what you must never build yourself.

Before you start

  • Completed Authentication Versus Authorisation, or know the difference between proving who someone is and deciding what they may do.
  • Access to any capable AI assistant.
  • Optional: Node.js and the project from earlier lessons, if you want to run the examples.

Sessions, cookies and how long they last

The web has no memory. Each request arrives as a stranger. A session is the server's way of remembering that this browser already proved who it is, so people sign in once and not on every click.

Session
A record on the server that says "this browser is signed in as this person", with a start time and a last-seen time.
Session id
A long random code that names one session. It is the cloakroom ticket. Alone, it carries no information.
Cookie
A small piece of text that the server asks the browser to keep and send back with every request to the same site.
Sign-out
Ending the session. The server deletes its record, so the ticket stops working.
WhereWhat is keptWhy
The browserA cookie holding only the session id.The id is the only thing the browser needs to send back.
The serverThe session record: which user, when it started, when it was last used.The server stays in charge. It can end any session at once.
The sign-in library's tablesCredentials, sign-in tokens and sessions, in the library's own format.Tidewell follows the library's docs and does not edit these tables by hand.

The cookie settings that protect a session

A cookie has settings, called attributes. Four of them matter most for a session. Here is a short program that builds the header.

A library does this for you. This code is for understanding the library, not to ship instead of it.

TypeScriptteach-cookie.ts (for understanding, not to ship)
// FOR UNDERSTANDING, NOT TO SHIP. A sign-in library builds this header for you.
import { randomBytes } from "node:crypto";

export const SESSION_COOKIE_NAME = "tw_session";

// 32 random bytes: far too many possibilities to guess. The id means nothing by itself.
export function newSessionId(): string {
  return randomBytes(32).toString("base64url");
}

export function buildSessionCookie(sessionId: string, maxAgeSeconds: number): string {
  return [
    `${SESSION_COOKIE_NAME}=${sessionId}`,
    `Max-Age=${maxAgeSeconds}`,
    "Path=/",
    "HttpOnly", // page scripts cannot read it
    "Secure", // sent only over HTTPS
    "SameSite=Lax", // not sent with most requests started by other sites
  ].join("; ");
}

// Sign-out: an empty value that expires at once. The server also deletes its own session record.
export function buildSignOutCookie(): string {
  return buildSessionCookie("", 0);
}
SettingWhat it doesPlain-words picture
HttpOnlyPage scripts cannot read the cookie.The ticket is in a sealed pocket. A script injected into a page cannot pull it out.
SecureThe browser sends it only over HTTPS.The ticket is never shouted across a crowded street.
SameSite=LaxThe browser leaves it off most requests that another website starts.A stranger's website cannot make your browser show your ticket by itself. It is one layer against cross-site request forgery, where another site tricks your browser into sending a request.
Path=/The cookie applies to the whole site.The ticket works at every counter.
Max-AgeHow many seconds the browser keeps it.A hint only. The server must still enforce the real limit.
See the Set-Cookie page on MDN for the full list of attributes and what each browser does.
The session id and the two headersCaptured from a real run
session id length: 43 | only URL-safe characters: true
two ids differ: true
tw_session=EXAMPLE-ID; Max-Age=28800; Path=/; HttpOnly; Secure; SameSite=Lax
tw_session=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax
  • The id is 43 characters of random text. It comes from 32 random bytes, which is far too many possibilities to guess.
  • The first header starts a session of 8 hours (28800 seconds).
  • The second header is sign-out. It sends an empty value that expires at once. The server must also delete its own record, or someone who copied the id could still use it.

How long a session lasts

A session needs two clocks. One counts the total time since sign-in. The other counts the time since the last request.

The practice manager confirmed Tidewell's rules: staff sessions end after 8 hours, or after 30 minutes without activity. Patient sessions end after 7 days. These are business decisions, so the code points to who made them.

TypeScriptsrc/lib/auth/session-rules.ts
// src/lib/auth/session-rules.ts
// Decision: practice manager, 2026-11-19. Staff sessions end after 8 hours, or after
// 30 minutes without activity. Patient sessions end after 7 days.
import type { Role } from "./permissions";

const MINUTE = 60 * 1000;

export const SESSION_LIMITS = {
  staff: { maxAgeMs: 8 * 60 * MINUTE, idleMs: 30 * MINUTE },
  patient: { maxAgeMs: 7 * 24 * 60 * MINUTE, idleMs: null },
} as const;

export function isSessionExpired(role: Role, startedAt: Date, lastSeenAt: Date, now: Date): boolean {
  const limits = role === "patient" ? SESSION_LIMITS.patient : SESSION_LIMITS.staff;
  if (now.getTime() - startedAt.getTime() >= limits.maxAgeMs) return true;
  return limits.idleMs !== null && now.getTime() - lastSeenAt.getTime() >= limits.idleMs;
}

In the real application, you give these numbers to the sign-in library in its settings. The function above shows the same rule in plain code, so you can test it with fixed times. Here are six cases.

Expiry rules with fixed timesCaptured from a real run
staff, 7 h 59 min in, active a minute ago: still valid
staff, 8 h 00 min in: expired
staff, 2 h in, quiet for 29 min: still valid
staff, 2 h in, quiet for 30 min: expired
patient, 6 days in, quiet for 5 days: still valid
patient, 7 days in: expired

Look at the edges. At exactly 8 hours, or exactly 30 minutes idle, the session is over. The code uses "greater than or equal".

Whether the edge counts as in or out is a small decision. Choose it, write it down and test it, just like the 24-hour rule in Module 4.

Password handling: hash, salt, never store

Staff at Tidewell will sign in with an email address and a password. The system must be able to check a password.

It must never be able to read one back. That sounds impossible until you meet the hash.

Way of keeping a passwordCan the original be recovered?Verdict
Plain textYes, by anyone who sees the database or a backup.Never.
EncryptedYes, by anyone who gets the key. The key has to live somewhere the program can reach.Not for passwords.
Fast hash, such as a single round of SHA-256No, but a thief can try billions of guesses a second.Too weak for passwords.
Slow, salted hash made for passwordsNo, and each guess is costly for a thief.The right way.
Hash
A one-way scramble. The same input always gives the same output, but you cannot work backwards from the output. It is like a meat grinder: easy to grind, impossible to turn back into a steak.
Salt
A random value added before hashing, and stored beside the hash. Two people with the same password get different hashes, so a thief cannot crack them all at once.
Slow on purpose
A password hash is built to take a noticeable moment. One check at sign-in costs nothing. A million guesses cost a thief a great deal.

Here is what a password library does, in about twenty lines. It uses scrypt, a password hash built into Node.

This code is for understanding, not to ship. A library also chooses safe settings, updates them over time, and upgrades old hashes at the next sign-in.

TypeScriptteach-password.ts (for understanding, not to ship)
// FOR UNDERSTANDING, NOT TO SHIP. This is the kind of work a sign-in library does for you.
import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";

const KEY_LENGTH = 32;
const COST = { N: 16384, r: 8, p: 1 }; // Node's defaults, kept low so the demo is quick

export function hashPassword(password: string, salt: Buffer = randomBytes(16)): string {
  const hash = scryptSync(password, salt, KEY_LENGTH, COST);
  return ["scrypt", COST.N, COST.r, COST.p, salt.toString("hex"), hash.toString("hex")].join("$");
}

export function verifyPassword(password: string, stored: string): boolean {
  const [scheme, n, r, p, saltHex, hashHex] = stored.split("$");
  if (scheme !== "scrypt" || !saltHex || !hashHex) return false;
  const expected = Buffer.from(hashHex, "hex");
  const actual = scryptSync(password, Buffer.from(saltHex, "hex"), expected.length, {
    N: Number(n),
    r: Number(r),
    p: Number(p),
  });
  return timingSafeEqual(actual, expected); // compares without stopping at the first difference
}

What each part does

  • hashPassword makes a random salt, runs scrypt, and returns one text record with the settings, the salt and the hash. The record can be stored in one database column.
  • verifyPassword reads the settings and the salt from the record, hashes the attempt the same way and compares the two results.
  • timingSafeEqual compares without stopping at the first different byte. A plain comparison can leak, through tiny timing differences, how much of a guess was right.
  • The settings are Node's defaults, chosen to keep the demo quick. Real settings need to be stronger. The OWASP cheat sheet lists current minimums, and a library applies them for you.
Hashing and checking with a fixed saltCaptured from a real run
stored: scrypt$16384$8$1$30313233343536373839616263646566$feb6d0d1b11e89366be41eb099a85816efb766e0d5f59984b6593dd084011fd0
same password verifies: true
wrong password verifies: false
garbage record verifies: false
two random salts give different records: true
both still verify: true
the record contains the password: false

The first line is the stored record. The salt is fixed here only so that every run prints the same text.

In real use each password gets its own random salt, as the fifth line shows. The last line proves the password itself is nowhere in the record.

What makes a good password policy

NIST's current guidance on passwords favours length. It also favours checking new passwords against lists of known leaked ones. It argues against forcing odd character rules and forced changes every few months.

Read the NIST SP 800-63B (opens in a new tab) text for the details. For staff, a password manager helps a lot.

ADR-004: use an established authentication library

The safest sign-in code is code you did not write. Teams that build their own tend to repeat old mistakes. So Tidewell records one clear decision, in the same format as the three earlier records from the lesson Architecture Decision Records.

Markdowndocs/adr/004-use-an-established-authentication-library.md
# ADR-004: Use an established authentication library

Status: Accepted
Date: 2026-11-19

## Context
Patients and staff must sign in, and the system holds personal data
(CON-01). One developer with an assistant builds it, and a local
contractor maintains it later (D6). Getting password storage, sessions
or sign-in tokens wrong is costly and easy to do.

## Options considered
A. Write our own sign-in, password storage and session code.
B. Use an established library inside the application.
C. Use a hosted identity service.

## Decision
Tidewell does not write its own sign-in, password storage or session
code. It uses an established library or identity service, named in the
pull request that adds it, after checking its documentation, its
maintenance and where it stores data.
- Patients sign in with a one-time link sent to their email.
- Staff sign in with email, password and an authenticator app code.
- The library stores credentials, sign-in tokens and sessions in its
  own tables, following its documentation.
- Server-side sessions. Staff: 8 hours, or 30 minutes idle. Patients: 7 days.
- Tidewell's own table app_users links a signed-in email to a role.

## Consequences
- We depend on the library and must apply its security updates.
- A hosted service means personal data is held by a third party, so the
  owner must approve where it is held (CON-01).
- Roles and permissions stay in Tidewell's own code and tests.

## Revisit when
- The library is no longer maintained, or
- A hosted service cannot keep data where the owner requires.

What are the options in practice? Examples include Auth.js, a library that runs inside your application. Others are self-hosted identity servers such as Keycloak, and hosted services such as Auth0 or Amazon Cognito.

PromptFable is independent and has no link with any of them. None is the best choice for everyone, so read each one's documentation, check that it is still actively maintained, and see Auth.js (opens in a new tab) as one starting point.

What you should never build yourself

Never buildUse instead
Password hashing and storageThe password handling of your library or identity service.
Session ids and session storageThe library's server-side sessions.
One-time sign-in tokensThe library's sign-in link feature.
Second-factor codesThe library's or service's authenticator support.
Random-number code for secretsThe platform's secure random source, through the library.
Encryption schemes or token signingA well-known library, used as its docs describe.
Lockout and guess-limiting logicThe library's or hosting service's rate limiting.
Writing small teaching programs, like the ones above, is good for learning. Shipping them in place of a library is the mistake.

The library needs a secret of its own to sign and protect its data. Add it to the configuration the way you did in the lesson Configuration and Secrets. In Tidewell it is AUTH_SECRET.

The real value lives only in .env.local and the hosting settings. The name your library expects may differ, so follow its docs.

Step-by-step workflow

  1. Step 1: Decide how each group signs in

    List who signs in and how: patients by link, staff by password and a second factor. Take the list to the practice manager.

    What you should see: A short table of groups and sign-in methods.

  2. Step 2: Write the decision record

    Use the ADR format. Name the options, the decision and the cost. Leave the product name for the pull request that adds it.

    What you should see: ADR-004 in docs/adr.

  3. Step 3: Choose a library or service from its documentation

    Check what it supports, whether it is still maintained, and where it stores data. If it is hosted, ask the clinic owner where the data may be held.

    What you should see: A written choice with the reasons and the data location.

  4. Step 4: Set the cookie and the session limits

    Use the library's settings for HttpOnly, Secure, SameSite=Lax, and the staff and patient lengths. Add AUTH_SECRET to .env.example as a fake value.

    What you should see: Settings that match the rules above, and no secret in the repository.

  5. Step 5: Check the cookie in the browser

    Sign in on a test copy with a made-up account. Open the browser's developer tools and look at the cookie's flags and its expiry.

    What you should see: HttpOnly, Secure and SameSite=Lax all show as set.

  6. Step 6: Test sign-out and expiry

    Sign out, then try to use the old cookie. Wait past the idle limit on a test setting. Both must give 401.

    What you should see: A dead session is refused, not just forgotten by the browser.

From a sign-in request to a trusted session
  1. Sign-in request

    Link or password

  2. Library checks proof

    And second factor

  3. Server session

    Record created

  4. Cookie with id

    HttpOnly, Secure

  5. getSession

    Email to a role

  6. Permission checks

    Next lesson

The library owns the first four boxes. Tidewell owns the last two.

Working with an assistant on sign-in

TaskAssistant's partYour part
Compare librariesSummarises features and trade-offs from their documents.Open each library's own docs. Check that features and function names are real and current.
Draft ADR-004Writes the first version from your notes.Check the rules and the session lengths. Add the product name only after you have read its docs.
Review your settingsCompares your cookie and session settings with a checklist.Confirm in the browser tools. Do not trust a description of the settings.
Write sign-in or hashing codeNothing. Use the library.Say no to any draft that stores or checks passwords by hand.
Choose session lengthsNothing. It guesses.Take the question to the practice manager and record the answer.

Conclusion and your next step

A session is a random ticket in an HttpOnly, Secure cookie, backed by a record on the server that can end at any time. Passwords are hashed with a slow, salted function, never kept as text or encrypted. And the sign-in code itself comes from an established library, because ADR-004 says so.

Your next step: write ADR-004 for your capstone, with your own sign-in methods and session limits marked as decisions for the right role. Then continue to Roles and Permissions, where you link a signed-in email to a role and enforce the permission table on the server.

For more on spotting weaknesses before they ship, try the Threat Model a New Feature prompt or read How to Prevent AI Hallucinations in Code Generation.

Reusable prompt

Sign-in and session design review

Asks the assistant to check a sign-in and session design against known good practice, and to list gaps and decisions, without writing code or picking a product.

You are reviewing a sign-in and session design. Do not write code. Do not recommend a specific product. Do not invent features of any library.

Fictional clinic: Tidewell Physiotherapy. Stack: TypeScript, Next.js App Router, PostgreSQL. Personal data is held under the clinic's data-protection duties.

Design so far:
- Patients sign in with a one-time link sent to their email. Staff sign in with email, password and an authenticator app code.
- An established library handles credentials, sign-in tokens and sessions. We write none of that ourselves.
- Sessions are kept on the server. The browser holds only an opaque random id in a cookie with HttpOnly, Secure, SameSite=Lax and Path=/.
- Staff sessions end after 8 hours or 30 minutes without activity. Patient sessions end after 7 days. Sign-out deletes the server session.
- A table app_users links a confirmed email to a role.

Tasks:
1. List weaknesses or missing pieces, each with the reason it matters. Cover sign-out, expiry, account switch-off, rate limiting, sign-in messages, logging and recovery of a lost second factor.
2. For each item, say whether the library should handle it or Tidewell must decide it.
3. List what to check in the browser's developer tools after sign-in.
4. List every question that needs a person's decision under "Decision needed", with the role who should decide.
5. Mark anything you are unsure about as "Check the library's documentation".
Show the reusable template

Replace each {{placeholder}} with your own details.

You are reviewing a sign-in and session design. Do not write code. Do not recommend a specific product. Do not invent features of any library.

Context: {{organisation_stack_and_data_duties}}

Design so far:
{{sign_in_methods_session_rules_and_cookie_settings}}

Tasks:
1. List weaknesses or missing pieces, each with the reason it matters. Cover sign-out, expiry, account switch-off, rate limiting, sign-in messages, logging and recovery of a lost second factor.
2. For each item, say whether the library should handle it or we must decide it.
3. List what to check in the browser's developer tools after sign-in.
4. List every question that needs a person's decision under "Decision needed", with the role who should decide.
5. Mark anything you are unsure about as "Check the library's documentation".

Expected output and limitations

A short list of gaps with a reason for each, a note on who owns each item (the library or the team), a browser checklist, and a Decision needed list with roles. A good answer refuses to name products and flags what it cannot verify.

Sample responseIllustrative — your output will differ
1. Gaps
   - Account switch-off: when a staff account is made inactive, sessions must stop working at once.
     Owner: Tidewell (check app_users.active on every request).
   - Lost phone: no recovery route for the second factor is described.
     Owner: Tidewell decides the route; the library provides the mechanism.
   - Logging: make sure session ids, tokens and cookies are never logged.

3. Browser checks
   Cookie has HttpOnly, Secure and SameSite=Lax. Expiry matches the role. Sign-out removes it.

4. Decision needed
   Who helps a physiotherapist who loses their phone? Role: practice manager.
   Is a sign-in link by email enough for patients? Role: practice manager.

5. Check the library's documentation
   Whether rate limiting is built in or must be added at the hosting layer.

Limitations to keep in mind

  • The assistant reviews your description, not your running system. Only the browser tools and your own tests show what is really set.
  • It may describe features a library does not have. Treat every feature claim as unverified until you find it in the docs.
  • A review is a checklist, not a security test. For anything serious, ask an experienced person to review the setup.

Common errors and how to fix them

Session ids are kept in local storage or a normal script variable.

Why it happens: It was the easy way to send the id with each request.

Fix: Use an HttpOnly cookie set by the library, so page scripts cannot read the id.

Sign-out only clears the cookie.

Why it happens: The server's session record was left alive.

Fix: Delete the server session on sign-out and test that the old cookie now gives 401.

Passwords are encrypted, or hashed with one fast round.

Why it happens: Encryption and hashing were mixed up, or a general hash was used.

Fix: Do not write this at all. Use the password handling of an established library or service.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Sign-in decisions for Ferngate

Ferngate's mechanics share one tablet. The owner also signs in from a phone. Write a short ADR for Ferngate's sign-in, list the session-length questions for the owner, and say what you would check in the browser after sign-in.

You will need

  • Note: mechanics have greasy hands and a tablet on a workbench. The internet is unreliable.
  • Note: the owner has not decided who may sign in, or how long a session should last.
  • The ADR format from the lesson Architecture Decision Records.

Acceptance criteria

Your work is done when every one of these is true.

Hints (2)
  • A long session on a shared tablet is convenient and risky. A short one is safe and annoying. Write both sides.
  • Ask what a mechanic should do when the connection drops while they are signed in.
Show a model answer

A strong answer compares writing a sign-in system, using a library, and using a hosted service, and rejects the first because the team cannot afford to get it wrong. It names no winning product. It records the shared tablet as the key risk: whoever uses the tablet next could act as the last person, so the owner must choose between short idle limits and frequent sign-ins, or a quick way to switch mechanics. Session lengths stay as open questions with the owner's name beside them. The browser checks list HttpOnly, Secure and SameSite, the expiry, and that sign-out kills the old cookie. It also mentions the unreliable connection, because a failed request must not leave a half-signed-in screen.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why are passwords hashed instead of encrypted?
    Show the answer and explanation

    Answer: B. Encryption is designed to be reversed by anyone with the key, and the key must sit near the program. A hash is one-way. Speed is a tempting reason, but a password hash is made slow on purpose. Encryption is secure for many things. It is simply the wrong tool for passwords.

  2. 2.A staff member signs out. What must happen on the server?
    Show the answer and explanation

    Answer: B. The cookie is only a ticket. If the record stays alive, anyone who copied the id can keep using it. Trusting the browser to delete the cookie is tempting, but the browser is not under the server's control.

  3. 3.Node has a built-in scrypt function. Should Tidewell write its own password storage with it?
    Show the answer and explanation

    Answer: B. A good primitive is only one part of safe password handling. Settings must stay current, hashes must be upgraded, guesses limited and resets protected. A random salt is necessary but far from enough, which is why the last option is tempting and still wrong.

Frequently asked questions

What is a session in web development?

A session is the server's record that a browser has already signed in. The browser holds only a random id in a cookie, and the server looks up who it belongs to. The server can end the session at any time.

Where should I store the session id in the browser?

Keep it in an HttpOnly cookie that the server sets. Page scripts cannot read an HttpOnly cookie, so an injected script cannot steal it. Local storage is readable by any script on the page, so avoid it for session ids.

What is the difference between hashing and encrypting a password?

Encryption can be undone with a key. A hash cannot be undone. A site that checks passwords only needs to compare hashes, so it never needs the original, and a slow salted hash makes stolen data hard to crack.

Should I build my own login system?

Almost never. Sign-in code has many small details that are easy to get wrong, and mistakes are costly. Use an established library or identity service, read its documentation, and keep your own code for the rules that are unique to your product.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.