In our To-Do app, everyone must only see their own tasks. So before we build the task APIs, we need to know who is asking. That's authentication. Our database already has a User table from the last lesson.
The cinema ticket picture
At a cinema you show ID and pay once at the counter, and you get a ticket. After that, you just show the ticket at each door. Nobody asks for your ID again. The ticket has a stamp that's hard to fake.
- 1
π
Register
POST /api/auth/register with name, email, password. We save a hash of the password.
- 2
π
Login
POST /api/auth/login. If the password matches the hash, we give back a signed token (the ticket).
- 3
ποΈ
Use the token
Every later request sends Authorization: Bearer <token>.
- 4
π
Check at the door
requireAuth middleware checks the signature, finds the user id, lets the request in.
Install what we need
$bun add bcryptjs jsonwebtoken$bun add -d @types/jsonwebtoken
| Package | Job |
|---|---|
| bcryptjs | Turns a password into a hash, and checks a password against a hash |
| jsonwebtoken | Creates (signs) tokens and checks (verifies) them |
Add a long random secret to .env. The server uses it to sign tokens, so keep it private:
JWT_SECRET="change-me-to-a-long-random-string"π‘Our config/env.ts refuses to start if JWT_SECRET is shorter than 16 characters.
Rule 1: never store the real password
We store a hash: a scrambled version that can't be turned back. To log in, bcrypt scrambles the typed password the same way and compares.
password typed: secret123
password saved: $2b$10$Lx8...a long scrambled string...Step 1: The rules for the data (schema)
With Zod we say what a valid sign-up looks like. Note toLowerCase(): β[email protected]β and β[email protected]β become the same account.
import { z } from "zod";
export const registerSchema = z.object({
name: z.string().trim().min(1, "Name is required").max(100),
email: z.email("Enter a valid email").toLowerCase(),
password: z.string().min(8, "Password must be at least 8 characters"),
});
export const loginSchema = z.object({
email: z.email().toLowerCase(),
password: z.string().min(1),
});
export type RegisterInput = z.infer<typeof registerSchema>;
export type LoginInput = z.infer<typeof loginSchema>;Step 2: The service (the real work)
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { prisma } from "../../lib/prisma";
import { env } from "../../config/env";
import { HttpError } from "../../utils/http-error";
import type { LoginInput, RegisterInput } from "./auth.schema";
function makeToken(userId: number) {
return jwt.sign({ userId }, env.JWT_SECRET, { expiresIn: "7d" });
}
export async function register(data: RegisterInput) {
const exists = await prisma.user.findUnique({ where: { email: data.email } });
if (exists) throw new HttpError(409, "An account with this email already exists");
const password = await bcrypt.hash(data.password, 10); // never store the real password
const user = await prisma.user.create({
data: { ...data, password },
select: { id: true, name: true, email: true }, // never send the password back
});
return { user, token: makeToken(user.id) };
}
export async function login(data: LoginInput) {
const user = await prisma.user.findUnique({ where: { email: data.email } });
const ok = user && (await bcrypt.compare(data.password, user.password));
if (!user || !ok) throw new HttpError(401, "Wrong email or password"); // same message for both: don't reveal which
return { user: { id: user.id, name: user.name, email: user.email }, token: makeToken(user.id) };
}Four safety habits are hidden in these few lines:
- 409 if the email exists, so you don't get two accounts with one email.
- Hash with bcrypt (10 βroundsβ is a good default) before saving.
- Never return the password, not even the hash.
selectpicks only safe fields. - One message for any login failure, so attackers can't learn which emails have accounts.
Step 3: Controller and routes
import type { Request, Response } from "express";
import * as authService from "./auth.service";
export async function register(req: Request, res: Response) {
res.status(201).json(await authService.register(req.body));
}
export async function login(req: Request, res: Response) {
res.json(await authService.login(req.body));
}import { Router } from "express";
import * as auth from "./auth.controller";
import { validate } from "../../middlewares/validate";
import { loginSchema, registerSchema } from "./auth.schema";
export const authRouter = Router();
authRouter.post("/register", validate(registerSchema), auth.register); // POST /api/auth/register
authRouter.post("/login", validate(loginSchema), auth.login); // POST /api/auth/loginThen connect it in app.ts with app.use("/api/auth", authRouter);.
Step 4: The guard (auth middleware)
This middleware sits in front of any route that needs a logged-in user. It reads the token, checks the signature, and puts the user id in res.locals.userId for the controller to use:
import type { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { env } from "../config/env";
import { HttpError } from "../utils/http-error";
// Lets the request through only if it carries a valid token: "Authorization: Bearer <token>".
export function requireAuth(req: Request, res: Response, next: NextFunction) {
const header = req.headers.authorization ?? "";
const token = header.startsWith("Bearer ") ? header.slice(7) : null;
if (!token) throw new HttpError(401, "Please log in first");
try {
const payload = jwt.verify(token, env.JWT_SECRET) as { userId: number };
res.locals.userId = payload.userId; // controllers read the logged-in user from here
next();
} catch {
throw new HttpError(401, "Your session has expired. Please log in again");
}
}To protect all task routes at once, the tasks router starts with taskRouter.use(requireAuth);. You'll see it in the next lesson.
Try it
# Register$curl -X POST http://localhost:3000/api/auth/register -H "Content-Type: application/json" -d '{"name":"Asha","email":"[email protected]","password":"secret123"}'# Log in$curl -X POST http://localhost:3000/api/auth/login -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"secret123"}'
Real answers from our tested API:
{
"user": {
"id": 1,
"name": "Asha",
"email": "[email protected]"
},
"token": "eyJhbGciOiJIUzI1NiIs..."
}{
"error": "An account with this email already exists"
}{
"error": "Invalid input",
"details": [
{
"field": "name",
"message": "Name is required"
},
{
"field": "email",
"message": "Enter a valid email"
},
{
"field": "password",
"message": "Password must be at least 8 characters"
}
]
}{
"error": "Wrong email or password"
}{
"error": "Please log in first"
}Copy the token from the login response. In the next lesson you'll send it to create and read tasks.
Key takeaways
- βRegister hashes the password with bcrypt and saves the user; duplicates get 409.
- βLogin compares the password with the hash and returns a signed JWT.
- βThe token travels in the Authorization header; the auth middleware verifies it.
- βThe middleware puts the user id in res.locals so controllers know who is asking.
- βJWT_SECRET lives in .env and must be long and private.
Frequently asked questions
What is a JWT?
A JWT (JSON Web Token) is a signed piece of text the server gives you after you log in. It says 'this is user 1' and carries a signature only the server can make. You send it with every request, and the server checks the signature instead of asking for your password again.
Why hash passwords instead of encrypting them?
Hashing is one-way: you can check a password against the hash, but you can't turn the hash back into the password. So even if someone steals the database, they don't get users' passwords. bcrypt also adds a random 'salt' and is slow on purpose, which makes guessing very expensive.
Where should the app store the token?
Mobile apps keep it in secure storage. Web apps often use an httpOnly cookie, so page scripts can't read it. For learning, sending it in the Authorization header, as we do here, is the simplest and very common.
What's the difference between 401 and 403?
401 Unauthorized means 'I don't know who you are': no token, or a bad or expired one. 403 Forbidden means 'I know who you are, but you're not allowed to do this'.
Can I log out with JWT?
The app simply deletes its token. Tokens also expire on their own (ours after 7 days). If you need to cancel tokens instantly, real apps add short-lived tokens plus refresh tokens, a good next step after this course.
π§ Quick check: signup and login
1. What do you store in the database for a password?
2. How does the app prove who it is on later requests?
3. Login fails. Which message is safest?
4. Where should JWT_SECRET live?
Checking your accessβ¦