Module 06 · Lesson 6.2
Sessions and Password Handling
On this page
- What you will learn
- Sessions, cookies and how long they last
- Password handling: hash, salt, never store
- Sign-in links, second factors and rate limiting
- ADR-004: use an established authentication library
- Step-by-step workflow
- Working with an assistant on sign-in
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- 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.
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 password | Can the original be recovered? | Verdict |
|---|---|---|
| Plain text | Yes, by anyone who sees the database or a backup. | Never. |
| Encrypted | Yes, 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-256 | No, but a thief can try billions of guesses a second. | Too weak for passwords. |
| Slow, salted hash made for passwords | No, 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.
// 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
hashPasswordmakes 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.verifyPasswordreads the settings and the salt from the record, hashes the attempt the same way and compares the two results.timingSafeEqualcompares 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.
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: falseThe 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.
Sign-in links, second factors and rate limiting
The best password is one nobody has to remember. Tidewell's patients are not trained staff, and most visit rarely.
So patients get a one-time sign-in link by email. Staff keep a password and add a second proof.
| Who | How they sign in | What proves it is them |
|---|---|---|
| Patient | Types their email address and receives a one-time link. | Access to that email inbox. |
| Staff | Email address, password and a code from an authenticator app. | Something they know, plus something they hold. |
One-time sign-in links
- The link holds a long random token. A good library stores only a fingerprint (a hash) of it, not the token itself.
- The token works once and expires after a short time. Check your library's default and set it deliberately.
- The page answers the same way for any email address: "If that address is registered, we have sent a link." It never says whether the address exists.
- The weak point is the inbox. Anyone who can read the patient's email can sign in. That risk is accepted for booking a physiotherapy appointment. It would not be acceptable for everything, so the practice manager should know it was a choice.
- The email is sent through the outside email service you build in the lesson Integrating an External Service.
Second factors for staff
A second factor is a second kind of proof. An authenticator app on a phone shows a six-digit code that changes every half minute. A stolen password alone is no longer enough.
The Multifactor Authentication Cheat Sheet (opens in a new tab) explains the options. Decide who helps a physiotherapist who loses their phone. It is a task for the practice manager.
Rate limiting and honest messages
Rate limiting means slowing down someone who keeps trying. A person who fails ten times in a minute is probably not a person. Libraries and hosting services offer this.
Be careful with permanent lockouts. They let a stranger lock out a real member of staff by guessing on purpose.
Messages should not help a guesser. "Email or password is wrong" is better than "no such email". The library normally handles this, and the Authentication Cheat Sheet (opens in a new tab) lists more such details.
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.
# 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 build | Use instead |
|---|---|
| Password hashing and storage | The password handling of your library or identity service. |
| Session ids and session storage | The library's server-side sessions. |
| One-time sign-in tokens | The library's sign-in link feature. |
| Second-factor codes | The library's or service's authenticator support. |
| Random-number code for secrets | The platform's secure random source, through the library. |
| Encryption schemes or token signing | A well-known library, used as its docs describe. |
| Lockout and guess-limiting logic | The library's or hosting service's rate limiting. |
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
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.
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.
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.
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_SECRETto.env.exampleas a fake value.What you should see: Settings that match the rules above, and no secret in the repository.
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.
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.
- Sign-in request
Link or password
- Library checks proof
And second factor
- Server session
Record created
- Cookie with id
HttpOnly, Secure
- getSession
Email to a role
- Permission checks
Next lesson
The library owns the first four boxes. Tidewell owns the last two.
Working with an assistant on sign-in
| Task | Assistant's part | Your part |
|---|---|---|
| Compare libraries | Summarises 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-004 | Writes 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 settings | Compares 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 code | Nothing. Use the library. | Say no to any draft that stores or checks passwords by hand. |
| Choose session lengths | Nothing. 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.
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.
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.
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.
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.
- Session Management Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Session ids, cookie attributes, expiry and sign-out.
- Password Storage Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Why passwords are hashed, and which settings to use. The numbers change over time, so read the current page.
- NIST Special Publication 800-63B(opens in a new tab)
NIST · Official documentation · Government guidance on authenticators and passwords. Read the current edition.
- Set-Cookie header(opens in a new tab)
MDN Web Docs · Official documentation · The cookie attributes used in this lesson.
- Auth.js | Authentication for the Web(opens in a new tab)
Auth.js · Official documentation · One example of an authentication library for web applications. Check that it fits your project and is current.
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.