The sign-up and login flow
Follow one account from the sign-up form to a session cookie: what each layer does, what to store, and the small decisions that leak accounts.
Calling the API from the clientDesigning the schema from features
The sign-up and login flow
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Authentication answers who you are and authorization answers what you may do, and the API signals them differently: 401 for not signed in, and a 403 or 404 for not allowed.
- The database stores a salted, deliberately slow hash of the password, never the password, so a stolen table does not hand over every account.
- A login endpoint should give the same answer for an unknown email and a wrong password, so it cannot be used to discover who has an account.
- After a successful login the server creates a random session id, stores it with an expiry, and sends it in a cookie marked HttpOnly.
- Sign-up needs two kinds of validation, the shared schema for the format and a database uniqueness check that returns a 409 with a field error.
Follow one account through the stack
Authentication looks like one feature, but it is a relay race across every layer. Here is Taskboard’s sign-up and first login, in order:
- Browser. The form validates the email and a 10-character minimum with the shared schema, then sends
POST /api/signup. - API. Validates again, hashes the password, inserts a row.
- Database. Enforces that the email is unique.
- Browser. Sends
POST /api/loginwith the same credentials. - API. Looks up the user, checks the hash, creates a session, answers with a cookie.
- Browser. Stores the cookie and attaches it to every later request automatically.
Each step has one job, and most real incidents come from someone doing a step’s job in the wrong layer. This lesson walks each, with the code I ran (Node 26.13.1, Hono 4.13.20).
Store a hash, not the password
Imagine your database leaks. If it contains passwords, every account is lost, including accounts on other sites where users reused them. If it contains hashes, the attacker has to guess each password one at a time.
An ordinary fast hash such as SHA-256 is the wrong tool. Attackers can compute billions per second. A password hash is deliberately slow and salted (mixed with a random value per user, so equal passwords differ, and precomputed tables do not work). Node ships scrypt in its standard library:
import { scryptSync, randomBytes, timingSafeEqual } from "node:crypto";
const hash = (pw: string) => {
const salt = randomBytes(16);
return salt.toString("hex") + ":" + scryptSync(pw, salt, 32).toString("hex");
};
const verify = (pw: string, stored: string) => {
const [salt, h] = stored.split(":");
return timingSafeEqual(scryptSync(pw, Buffer.from(salt, "hex"), 32), Buffer.from(h, "hex"));
};
timingSafeEqual compares in constant time, so the comparison does not leak how many leading bytes matched. Password hashing and credential storage goes through the cost parameters and the alternatives, such as argon2 and bcrypt. In production, use a maintained auth library or a hosted identity provider rather than hand-rolling this; the point here is knowing what it is doing.
Sign-up has two validators
The shared Zod schema from earlier handles the format. The database handles uniqueness, because only it can say who already registered. I ran sign-up twice with the same address:
{"id":1}
{"error":{"code":"email_taken","message":"That email already has an account","fields":{"email":["Already registered"]}}} [409]
Note the status. 422 means “the input is malformed”. 409 means “the input is fine but conflicts with what exists”, and it still carries a fields entry so the form can show the message under the email input. The rule: let the database constraint decide. Checking “does this email exist?” and then inserting has a race, since two requests can both pass the check. The unique index turns the second into an error you catch.
One honest trade-off: telling a stranger “that email is registered” lets them test which emails have accounts. Some products accept that for usability, others send an email either way and show the same page. Choose deliberately.
Login: one answer for two failures
const u = db.prepare("select * from users where email=?").get(email);
if (!u || !verify(password, u.password_hash))
throw new ApiError(401, "bad_credentials", "Email or password is wrong");
An unknown email and a wrong password return the identical 401 body; I confirmed it with a wrong password and got {"error":{"code":"bad_credentials","message":"Email or password is wrong"}} [401]. If the messages differed, an attacker could script addresses and learn who has an account. (A subtler leak remains: the unknown-email path skips the slow hash and returns faster. A real system hashes a dummy value to even that out, and rate-limits attempts, covered in rate limiting implementation in your app.)
From login to a session
On success the server creates a random identifier and stores it with an owner and an expiry:
const sid = randomBytes(32).toString("base64url");
db.prepare("insert into sessions values (?,?,?)").run(sid, u.id, Date.now() + 7 * 864e5);
setCookie(c, "sid", sid, { httpOnly: true, sameSite: "Lax", path: "/", maxAge: 7 * 86400 });
The response header I saw was:
set-cookie: sid=--FeNNvAQyaT_kEq3ukp_N2zaVS7PCKXMP6PHfR8Llw; Max-Age=604800; Path=/; HttpOnly; SameSite=Lax
The cookie holds a random id and nothing else. Who the user is, and when the session ends, live in the server’s table. That is a session in the sense this roadmap uses. The next lesson compares it with sending a signed token instead. Note I omitted Secure for local HTTP; in production it must be on, which the cookie-settings lesson covers.
Afterwards, GET /api/me with the cookie returned {"id":1}, and without it 401 unauthenticated. Logout deletes the row, so the id stops working even if someone copied it. That is something a stateless token cannot do as easily.
Think of it as a coat check
A good analogy: the session cookie is a coat-check ticket. The ticket has a random number and means nothing by itself. The venue keeps the coat, and the mapping from ticket to coat. Lose the ticket and someone else could collect your coat, which is why the ticket must be hard to guess (32 random bytes) and hard to steal (HttpOnly). Cancel the ticket at the desk and it is worthless immediately.
Pitfalls to avoid
- Storing anything reversible. No plain text, no encryption you can undo, no fast hash.
- Different errors for different failures. One message, one status.
- Logging passwords. A request logger that prints bodies will print them. Redact.
- Rolling your own beyond learning. Hosted identity or a maintained library has threat models you will not think of. Authentication in a Node API shows how the pieces are usually wired.
What the video covers
WittCode’s “Node Login Signup System with Express Sessions Bcrypt” is about 28 minutes, published March 2024. Its description says it builds a Node login and signup system, using bcrypt to hash passwords and express-session to handle authentication. This lesson embeds the chapters from 2:45 to 20:30: “What is a Session?”, the express-session middleware, handling sessions, authorization middleware, user login at 13:01, user signup at 16:17, password security at 17:37 and protected routes at 19:32. The earlier chapters on project setup and the Pug view engine, and what follows 20:30, are left out, and the description plugs the creator’s own product. It uses Express rather than Hono, and the lesson’s Argon2 choice, generic login errors and 409 on duplicate email are my own. I could not read a transcript, so I rely on the title, description and chapters. Fireship’s short session-versus-token video and a longer authentication explainer are linked for the comparison.
Where this fits
You have a session id in a cookie. A single-page app has other options, and the choice has security consequences. Next: sessions vs tokens in a SPA.
Check yourself
What should the users table store instead of the password?
A hash produced by a slow algorithm such as scrypt, along with a random salt, so the original password cannot be read back and identical passwords do not produce identical hashes.
Why does the login endpoint answer 'Email or password is wrong' for both failures?
If it said which one was wrong, an attacker could test addresses and learn which ones have accounts.
What does the browser hold after a successful login?
A session cookie containing a random id, and nothing else, because the account details and the expiry live in the server's session table.
What status does a duplicate sign-up return in Taskboard, and why not 422?
It returns 409, because the input was well formed but conflicts with existing state, and it carries a field error so the form can show it under the email.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.