MongoDB + JWT Auth
The big one. JWT anatomy, access vs refresh tokens, rotation and reuse detection, Mongoose schemas, bcrypt, HttpOnly cookies, and a complete register / login / refresh / logout system.
Alright, this is the big one. Two major systems in one go — database + authentication. Let me split this into two clear parts because mixing them up is where most tutorials fail and leave you confused.
Part 1: The Token System — mental model, no code, just understanding. Part 2: MongoDB + Auth implementation — the full build.
PART 1: THE TOKEN SYSTEM — UNDERSTAND BEFORE YOU CODE
You're a frontend dev. You've used tokens. You've stored them in localStorage (don't lie, we all did it once). You've attached Authorization: Bearer ... headers. But you don't fully understand why there are two tokens and what each one does. Let's fix that.
The Problem That Tokens Solve
HTTP is stateless. Every request is a stranger. The server has amnesia. "I just logged in 2 seconds ago!" — the server doesn't care. Every request needs to prove who you are, every single time.
Session-based auth (the old way): You log in, server creates a session in memory/database, gives you a session ID cookie. Every request sends that cookie, server looks up the session. Problem: server stores state for every logged-in user. 10,000 users = 10,000 sessions in memory. Scale across multiple servers? Now you need sticky sessions or a shared session store. Pain.
Token-based auth (JWT): You log in, server creates a signed token containing your user info, gives it to you. Every request sends that token. Server doesn't store anything — it just verifies the signature and reads the data from the token itself. Stateless. Any server can verify it. Scales horizontally without shared state.
Analogy
Session auth is a hotel where the front desk keeps a ledger of every guest and gets phoned on every trip to a room — the desk must remember everyone. JWT auth is a keycard: the card itself carries your room number and checkout date, stamped with the hotel's unforgeable seal. Any door in the building can verify the card on the spot without calling the desk.
What's Inside a JWT
A JWT is three Base64-encoded chunks separated by dots:
eyJhbGciOiJIUzI1NiJ9 . eyJzdWIiOjEsInVzZXJuYW1lIjoiam9obiJ9 . abc123signature
HEADER . PAYLOAD . SIGNATURE{"alg":"HS256"} — algorithm used to sign
{"sub":1,"username":"john", "iat":1707700000,"exp":1707703600} — your
data, readable by anyone
HMAC(header + payload, secret) — tamper-proof seal
Header: Algorithm used to sign. You don't touch this.
Payload: Your data. User ID, username, roles, issued-at time (iat), expiration time (exp). Anyone can decode this. It's Base64, not encrypted. Never put passwords, secrets, or sensitive data here.
Signature: Server takes header + payload, hashes them with a secret key that only the server knows. When a token comes back, server re-hashes header + payload with the same secret and checks if the signature matches. If someone tampered with the payload (changed "roles": ["user"] to "roles": ["admin"]"), the signature won't match. Rejected.
Key insight for a frontend dev: JWTs are not encrypted. Go to jwt.io, paste any token — you'll see the payload. They're signed, which means tamper-proof, not secret. The server trusts the data in the token because it can verify no one changed it, not because it's hidden.
Analogy
A keycard is not a locked safe — anyone who picks it up can read the name and room number printed on it. What makes it trustworthy is the hologram seal: scratch out the room number and write in the penthouse, and the seal no longer matches. Signed means tamper-proof, not secret.
Why Two Tokens?
This is where frontend devs get confused. "Why can't I just have one token that lasts forever?"
Because of a fundamental security tradeoff:
Short-lived tokens = More secure (if stolen, attacker has limited time), but terrible UX (user has to log in every 15 minutes).
Long-lived tokens = Great UX (stay logged in for days), but terrible security (if stolen, attacker has access for days).
The two-token system solves both:
Access Token
- Purpose: Proves who you are on every API request
- Lifespan: Short — 15 minutes to 1 hour
- Where it lives: In memory (React state) or in an HttpOnly cookie
- Sent with: Every API request in the
Authorization: Bearerheader - If stolen: Attacker has 15 minutes max. Damage limited.
Refresh Token
- Purpose: Gets you a new access token without logging in again
- Lifespan: Long — 7 to 30 days
- Where it lives: HttpOnly, Secure cookie (never in localStorage, never in JS memory)
- Sent with: Only to the
/auth/refreshendpoint, automatically via cookie - If stolen: Attacker can generate new access tokens. That's why refresh tokens are stored in DB and can be revoked (invalidated server-side).
Analogy
The access token is your room keycard: it opens doors all day but expires quickly, so a lost card is a small problem. The refresh token is the ID you left on file at the front desk: you never carry it around the hotel, but when your keycard dies you present it once and walk away with a fresh card. Short-lived convenience in your pocket, long-lived trust locked at the desk.
The Complete Token Flow — Visual
Client: POST /auth/register { email, username, password }
Server: hash password, save user to DB
Server: return { message: "registered" }
no tokens yet — user needs to log in
Client: POST /auth/login { email, password }
Server: verify email + password against DB
Server: generate access token (15 min) + refresh token (7 days)
Server: save refresh token hash in DB (for revocation)
Server: return accessToken: "eyJhb..." in the response body, plus
Set-Cookie: refreshToken=abc; HttpOnly; Secure
Client: stores accessToken in memory (useState/context)
Client: refresh token is in the cookie (browser handles it)
Client: GET /tasks with header
Authorization: Bearer eyJhb... (access token)
Server: AuthGuard verifies token signature + expiry
Server: token valid → extract user → proceed
Server: return { success: true, data: [...tasks] }
Client: GET /tasks with an expired access token
Server: AuthGuard verifies → token expired → 401
Client: receives 401 → automatically calls POST /auth/refresh
(refresh token sent automatically via cookie — the browser does it)
Server: reads refresh token from cookie, verifies signature +
expiry, checks it exists in DB (not revoked)
Server: generates NEW access token + NEW refresh token, replaces the
old refresh token in DB
Server: return accessToken: "eyJnew..." plus
Set-Cookie: refreshToken=newAbc; HttpOnly; Secure
Client: retries the original GET /tasks with the new access token
this whole flow is invisible to the user
Client: POST /auth/logout
Server: deletes refresh token from DB (revoked)
Server: clears the refresh token cookie
Client: clears access token from memory
even if someone stole the refresh token, it's now invalid
⚡ Quick lookup — token lifecycle in one glance
register -> no tokens yet
login -> accessToken (memory, 15min) + refreshToken (HttpOnly cookie, 7d, hash in DB)
request -> Authorization: Bearer <accessToken>
expired -> 401 -> POST /auth/refresh (cookie) -> new access + new refresh (rotation)
logout -> refresh token deleted from DB + cookie cleared + memory clearedAnalogy
Read the whole flow as one hotel stay: registering is filling in the guest form, login is check-in where you receive a keycard while your ID goes on file, every API call is tapping the card on a door, refresh is swapping a dead card for a new one at the desk, and logout is checkout — the desk shreds your file so even a pickpocketed card leads nowhere.
Refresh Token Rotation — Why New Tokens Every Refresh
When you call /auth/refresh, the server gives you BOTH a new access token AND a new refresh token. The old refresh token is deleted from the DB. This is called rotation.
Why? If an attacker stole your refresh token and tries to use it after you've already refreshed (which replaced it), the old token won't exist in the DB anymore. The server detects it's been revoked and rejects it. If you're paranoid (you should be), you can even invalidate ALL of that user's refresh tokens when a reuse of a revoked token is detected — meaning the attacker triggered a "stolen token" alarm.
Analogy
Every time you swap keycards at the desk, the clerk also voids the old ID on file and issues a new one. If a thief later shows up holding your old ID, the desk knows instantly that something is wrong — that document should no longer exist — and cancels every card on the account, locking both the thief and the stolen card out of the entire hotel.
Frontend Storage — Where to Keep What
| Token | Storage | Why |
|---|---|---|
| Access Token | React state (useState/Context/Zustand) | Disappears on page refresh (more secure), short-lived anyway |
| Refresh Token | HttpOnly Secure cookie (set by server) | JavaScript can't access it (XSS-proof), sent automatically by browser |
"But if access token is in React state, it disappears on page refresh?" — Yes. That's the point. On page load, your app calls /auth/refresh. The browser sends the refresh cookie automatically. You get a new access token. Seamless. The user never sees a login screen unless the refresh token itself has expired.
"What about localStorage?" — Don't. Any XSS vulnerability means an attacker can read localStorage and steal your token. HttpOnly cookies are immune to XSS — JavaScript literally cannot access them. The browser manages them silently.
Analogy
Keeping a token in localStorage is like taping your keycard to the outside of your hotel room door — anyone walking the hallway (any injected script) can lift it. An HttpOnly cookie is a safe only hotel staff can open: your own JavaScript never touches it, so an attacker's JavaScript cannot either.
PART 2: THE IMPLEMENTATION — MongoDB + Auth
Now you understand what we're building. Let's build it.
Package Installation
npm install @nestjs/mongoose mongoose
npm install @nestjs/jwt @nestjs/config
npm install bcrypt cookie-parser
npm install -D @types/bcrypt @types/cookie-parser@nestjs/mongoose— NestJS wrapper around Mongoose (MongoDB ODM)@nestjs/jwt— NestJS wrapper around jsonwebtoken@nestjs/config— Environment variable management (.env file support)bcrypt— Password hashing (don't roll your own crypto)cookie-parser— Express middleware to parse cookies from requests
Environment Variables
.env
MONGODB_URI=mongodb://localhost:27017/nestjs-tasks
JWT_ACCESS_SECRET=your-super-secret-access-key-change-this
JWT_REFRESH_SECRET=your-super-secret-refresh-key-change-this
JWT_ACCESS_EXPIRATION=15m
JWT_REFRESH_EXPIRATION=7dTwo different secrets — access and refresh tokens are signed with different keys. If the access secret is somehow leaked, the attacker still can't forge refresh tokens (and vice versa). Defense in depth.
Analogy
The hotel uses one stamp for keycards and a different stamp for the IDs kept at the desk. A forger who copies the keycard stamp still cannot mint the documents the front desk trusts — two stamps, two locks, one breach contained.
Project Structure — The Full Picture
MongoDB + Mongoose — How It Works in NestJS
In raw Mongoose, you define schemas, create models, and use Model.find() etc. NestJS wraps this with decorators and DI:
Raw Mongoose: NestJS + Mongoose:
const schema = new Schema({...}) → @Schema() class User { @Prop() name }
const Model = model('User', schema) → @InjectModel(User.name) userModel: Model<User>
Model.find() → this.userModel.find()Same Mongoose underneath. NestJS adds type safety, DI, and module organization.
Analogy
The hotel's guest records room did not change — Mongoose is still the ledger. NestJS just gave every department a typed request form and an internal courier (dependency injection), so nobody wanders into the records room and rummages by hand.
User Schema and Module
src/users/schemas/user.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
@Schema({ timestamps: true }) // adds createdAt, updatedAt automatically
export class User {
@Prop({ required: true, unique: true, lowercase: true, trim: true })
email: string;
@Prop({ required: true, unique: true, trim: true })
username: string;
@Prop({ required: true })
password: string; // stored as bcrypt hash, never plaintext
@Prop({ type: [String], default: ['user'] })
roles: string[];
@Prop({ type: [String], default: [] })
refreshTokens: string[]; // hashed refresh tokens — array supports multiple devices
}
export type UserDocument = User & Document;
export const UserSchema = SchemaFactory.createForClass(User);Breaking down the schema decorators:
@Schema({ timestamps: true }) — Mongoose automatically manages createdAt and updatedAt fields. You never manually set these.
@Prop({ unique: true }) — MongoDB creates a unique index. Duplicate emails/usernames throw a MongoDB error (error code 11000 — we'll catch this).
@Prop({ lowercase: true, trim: true }) — Mongoose transforms the value before saving. " John@Email.COM " becomes "john@email.com". Data hygiene at the schema level.
refreshTokens: string[] — An array because a user might be logged in on their phone, laptop, and tablet simultaneously. Each device has its own refresh token. Logout from one device removes that token, not all of them. We store hashed tokens, not raw ones — same reason you hash passwords.
Analogy
One guest can hold cards from three simultaneous stays — phone, laptop, tablet — so the front desk keeps a small folder of IDs per guest rather than a single slot. Checking out one device pulls one document from the folder; the other cards keep working.
src/users/users.service.ts
import { Injectable, ConflictException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserDocument } from './schemas/user.schema';
import * as bcrypt from 'bcrypt';
@Injectable()
export class UsersService {
constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}
async findByEmail(email: string): Promise<UserDocument | null> {
return this.userModel.findOne({ email: email.toLowerCase() });
}
async findById(id: string): Promise<UserDocument | null> {
return this.userModel.findById(id);
}
async create(
email: string,
username: string,
hashedPassword: string,
): Promise<UserDocument> {
try {
return await this.userModel.create({
email,
username,
password: hashedPassword,
});
} catch (error) {
// MongoDB duplicate key error
if (error.code === 11000) {
const field = Object.keys(error.keyPattern)[0];
throw new ConflictException(`${field} already exists`);
}
throw error;
}
}
async addRefreshToken(userId: string, hashedToken: string): Promise<void> {
await this.userModel.findByIdAndUpdate(userId, {
$push: { refreshTokens: hashedToken },
});
}
async removeRefreshToken(userId: string, hashedToken: string): Promise<void> {
await this.userModel.findByIdAndUpdate(userId, {
$pull: { refreshTokens: hashedToken },
});
}
async removeAllRefreshTokens(userId: string): Promise<void> {
await this.userModel.findByIdAndUpdate(userId, {
$set: { refreshTokens: [] },
});
}
}@InjectModel(User.name) — This is how Mongoose models integrate with NestJS's DI. Instead of importing a model globally, you inject it. The module registration (below) tells NestJS which models exist.
error.code === 11000 — MongoDB's error code for unique constraint violation. We catch it and throw a clean NestJS ConflictException (409) instead of letting a raw Mongo error leak to the client.
$push / $pull — MongoDB array operators. $push adds to the array, $pull removes a matching element. Atomic operations — no race conditions.
src/users/users.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { UsersService } from './users.service';
import { User, UserSchema } from './schemas/user.schema';
@Module({
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
],
providers: [UsersService],
exports: [UsersService], // AuthModule needs access to UsersService
})
export class UsersModule {}MongooseModule.forFeature() — Registers Mongoose models within this module's scope. forFeature is for feature modules (specific schemas). forRoot (in AppModule) is for the connection itself.
exports: [UsersService] — Without this, UsersService is private to UsersModule. The AuthModule needs to look up users, so we export it. If you don't export, NestJS DI throws "can't resolve dependencies" — because it's enforcing module encapsulation.
Auth DTOs
src/auth/dto/register.dto.ts
import {
IsEmail, IsString, IsNotEmpty,
MinLength, MaxLength, Matches,
} from 'class-validator';
export class RegisterDto {
@IsEmail({}, { message: 'Please provide a valid email' })
email: string;
@IsString()
@IsNotEmpty()
@MinLength(3)
@MaxLength(20)
@Matches(/^[a-zA-Z0-9_]+$/, {
message: 'Username can only contain letters, numbers, and underscores',
})
username: string;
@IsString()
@MinLength(8, { message: 'Password must be at least 8 characters' })
@MaxLength(64)
@Matches(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, {
message:
'Password must contain at least one uppercase letter, one lowercase letter, and one number',
})
password: string;
}src/auth/dto/login.dto.ts
import { IsEmail, IsString, IsNotEmpty } from 'class-validator';
export class LoginDto {
@IsEmail()
email: string;
@IsString()
@IsNotEmpty()
password: string;
}Auth Service — The Brain
This is the longest file. Every line matters.
src/auth/auth.service.ts
import {
Injectable,
UnauthorizedException,
ForbiddenException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import * as bcrypt from 'bcrypt';
import { UsersService } from '../users/users.service';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
private configService: ConfigService,
) {}
// ========================
// REGISTER
// ========================
async register(registerDto: RegisterDto) {
const { email, username, password } = registerDto;
// Hash password — 12 salt rounds (industry standard)
const hashedPassword = await bcrypt.hash(password, 12);
const user = await this.usersService.create(email, username, hashedPassword);
return {
message: 'Registration successful',
user: {
id: user._id,
email: user.email,
username: user.username,
},
};
// No tokens on registration — user must log in explicitly
// This is a design choice. Some apps auto-login on register.
// Forcing explicit login is more secure (confirms credentials work).
}
// ========================
// LOGIN
// ========================
async login(loginDto: LoginDto) {
const { email, password } = loginDto;
// ① Find user by email
const user = await this.usersService.findByEmail(email);
if (!user) {
// Don't say "user not found" — that tells attackers which emails exist
throw new UnauthorizedException('Invalid credentials');
}
// ② Verify password
const passwordMatches = await bcrypt.compare(password, user.password);
if (!passwordMatches) {
// Same generic message — don't reveal whether email or password was wrong
throw new UnauthorizedException('Invalid credentials');
}
// ③ Generate both tokens
const tokens = await this.generateTokens(
user._id.toString(),
user.email,
user.roles,
);
// ④ Store hashed refresh token in DB
const hashedRefreshToken = await bcrypt.hash(tokens.refreshToken, 12);
await this.usersService.addRefreshToken(
user._id.toString(),
hashedRefreshToken,
);
return {
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
user: {
id: user._id,
email: user.email,
username: user.username,
roles: user.roles,
},
};
}
// ========================
// REFRESH
// ========================
async refresh(refreshToken: string) {
if (!refreshToken) {
throw new UnauthorizedException('Refresh token not provided');
}
// ① Verify the refresh token signature and expiry
let payload: any;
try {
payload = this.jwtService.verify(refreshToken, {
secret: this.configService.get<string>('JWT_REFRESH_SECRET'),
});
} catch {
throw new UnauthorizedException('Invalid or expired refresh token');
}
// ② Find the user
const user = await this.usersService.findById(payload.sub);
if (!user) {
throw new UnauthorizedException('User not found');
}
// ③ Check if this refresh token exists in user's stored tokens
// (it's hashed in DB, so we compare each one)
let matchedTokenHash: string | null = null;
for (const storedHash of user.refreshTokens) {
const isMatch = await bcrypt.compare(refreshToken, storedHash);
if (isMatch) {
matchedTokenHash = storedHash;
break;
}
}
if (!matchedTokenHash) {
// Token is valid (signature OK) but not in DB
// This means it was already used or revoked
// Possible token theft — invalidate ALL sessions for this user
await this.usersService.removeAllRefreshTokens(user._id.toString());
throw new ForbiddenException(
'Refresh token reuse detected — all sessions invalidated',
);
}
// ④ Remove old refresh token from DB
await this.usersService.removeRefreshToken(
user._id.toString(),
matchedTokenHash,
);
// ⑤ Generate new token pair (rotation)
const tokens = await this.generateTokens(
user._id.toString(),
user.email,
user.roles,
);
// ⑥ Store new hashed refresh token
const hashedRefreshToken = await bcrypt.hash(tokens.refreshToken, 12);
await this.usersService.addRefreshToken(
user._id.toString(),
hashedRefreshToken,
);
return {
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
};
}
// ========================
// LOGOUT
// ========================
async logout(refreshToken: string, userId: string) {
if (!refreshToken) {
return { message: 'Logged out' };
}
// Find and remove the specific refresh token
const user = await this.usersService.findById(userId);
if (user) {
for (const storedHash of user.refreshTokens) {
const isMatch = await bcrypt.compare(refreshToken, storedHash);
if (isMatch) {
await this.usersService.removeRefreshToken(userId, storedHash);
break;
}
}
}
return { message: 'Logged out' };
}
// ========================
// LOGOUT ALL DEVICES
// ========================
async logoutAll(userId: string) {
await this.usersService.removeAllRefreshTokens(userId);
return { message: 'Logged out from all devices' };
}
// ========================
// TOKEN GENERATION
// ========================
private async generateTokens(
userId: string,
email: string,
roles: string[],
) {
const payload = { sub: userId, email, roles };
const [accessToken, refreshToken] = await Promise.all([
this.jwtService.signAsync(payload, {
secret: this.configService.get<string>('JWT_ACCESS_SECRET'),
expiresIn: this.configService.get<string>('JWT_ACCESS_EXPIRATION'),
}),
this.jwtService.signAsync(
{ sub: userId }, // refresh token has minimal payload — just user ID
{
secret: this.configService.get<string>('JWT_REFRESH_SECRET'),
expiresIn: this.configService.get<string>('JWT_REFRESH_EXPIRATION'),
},
),
]);
return { accessToken, refreshToken };
}
}The critical parts explained:
Why "Invalid credentials" for both wrong email and wrong password? If you say "user not found" vs "wrong password," an attacker can enumerate which emails are registered. Always use the same generic message for both cases.
Why hash refresh tokens before storing? For the same reason you hash passwords. If your database is breached, attackers get hashed tokens that are useless. Raw tokens in DB = attackers can impersonate any user.
Analogy
Bcrypt is a paper shredder with one party trick: it can never reassemble the strips back into the document, but hand it a fresh copy and it can confirm whether that copy would shred into exactly the same strips. A stolen database of hashes is a warehouse of confetti — verifiable, never reversible.
Refresh token reuse detection: If someone tries to use a refresh token that's valid (signature checks out, not expired) but doesn't exist in the DB, it means that token was already rotated out. Either the legitimate user already refreshed (replacing it), or an attacker is replaying a stolen token. Either way, we nuke all sessions for that user. This is a real security feature used by Auth0 and other identity providers.
Analogy
Someone walks up with a perfectly genuine-looking ID that the desk already destroyed during the last card swap. There is only one way that document still exists: someone copied it. The desk does not debate the point — every keycard on the account is cancelled on the spot, and the real guest simply checks in again with their passport.
The concurrency gotcha
Strict reuse detection has one real-world sharp edge: if the same legitimate client fires two refreshes almost at once — two browser tabs, a double-click, an axios retry — the first rotates the token out, and the second arrives with a now-deleted (but genuine) token and gets flagged as a "reuse," nuking every session. The user is logged out for doing nothing wrong.
Production systems soften this with a short grace window (accept the immediately-previous token for a few seconds) or by serializing refreshes on the client (a single-flight lock so only one refresh is ever in flight). For this course, keep the strict version — it's the correct default and the capstone tests it — but know the trade-off exists so it doesn't surprise you in production.
Minimal refresh token payload: The access token carries { sub, email, roles } because controllers need that data on every request. The refresh token only carries { sub } (user ID) because it's only used to generate new tokens — it never authorizes API calls directly. Less data = less exposure.
Promise.all for token generation: Both tokens are signed independently — no reason to do them sequentially. Parallel is faster.
Auth Controller
src/auth/auth.controller.ts
import {
Controller, Post, Body, Res, Req,
HttpCode, HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { AuthService } from './auth.service';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import { Public } from '../common/decorators/public.decorator';
import { CurrentUser } from '../common/decorators/current-user.decorator';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Public()
@Post('register')
async register(@Body() registerDto: RegisterDto) {
return this.authService.register(registerDto);
}
@Public()
@Post('login')
@HttpCode(HttpStatus.OK) // POST defaults to 201, login should be 200
async login(
@Body() loginDto: LoginDto,
@Res({ passthrough: true }) response: Response,
) {
const result = await this.authService.login(loginDto);
// Set refresh token as HttpOnly cookie
this.setRefreshTokenCookie(response, result.refreshToken);
// Return access token in response body (frontend stores in memory)
return {
accessToken: result.accessToken,
user: result.user,
};
// Notice: refreshToken is NOT in the response body
// It's only in the cookie — JavaScript can't access it
}
@Public()
@Post('refresh')
@HttpCode(HttpStatus.OK)
async refresh(
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
) {
const refreshToken = request.cookies?.['refreshToken'];
const result = await this.authService.refresh(refreshToken);
// Set new refresh token cookie (rotation)
this.setRefreshTokenCookie(response, result.refreshToken);
return { accessToken: result.accessToken };
}
@Post('logout')
@HttpCode(HttpStatus.OK)
async logout(
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
@CurrentUser('sub') userId: string,
) {
const refreshToken = request.cookies?.['refreshToken'];
const result = await this.authService.logout(refreshToken, userId);
// Clear the cookie
response.clearCookie('refreshToken', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/auth',
});
return result;
}
@Post('logout-all')
@HttpCode(HttpStatus.OK)
async logoutAll(
@Res({ passthrough: true }) response: Response,
@CurrentUser('sub') userId: string,
) {
const result = await this.authService.logoutAll(userId);
response.clearCookie('refreshToken', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/auth',
});
return result;
}
// ========================
// COOKIE HELPER
// ========================
private setRefreshTokenCookie(response: Response, token: string) {
response.cookie('refreshToken', token, {
httpOnly: true, // JavaScript cannot access this cookie
secure: process.env.NODE_ENV === 'production', // HTTPS only in prod
sameSite: 'strict', // cookie sent only to same origin
path: '/auth', // cookie only sent to /auth/* routes
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days in milliseconds
});
}
}Critical details:
@Res({ passthrough: true }) — By default, if you inject @Res(), NestJS assumes you're handling the response manually and disables its automatic response handling (interceptors, serialization). passthrough: true tells NestJS: "I need the response object to set cookies, but I still want you to handle the return value normally." Without passthrough, your TransformInterceptor would stop working on these routes.
Cookie options explained:
| Option | Value | Why |
|---|---|---|
httpOnly | true | JavaScript can't read it. XSS can't steal it. |
secure | true in prod | Cookie only sent over HTTPS. Prevents interception. |
sameSite | 'strict' | Cookie not sent on cross-site requests. Prevents CSRF. |
path | '/auth' | Cookie only sent to /auth/* routes. Your /tasks endpoint never sees it. Minimal exposure. |
maxAge | 7 days | Browser auto-deletes after 7 days. Matches refresh token expiry. |
@Public() on login/register/refresh — These endpoints must be accessible without an access token (obviously). The @Public() decorator tells your AuthGuard to skip authentication.
Refresh token NOT in response body — This is intentional and critical. The refresh token only exists in the cookie. The frontend never touches it directly. The browser sends it automatically to /auth/refresh because of path: '/auth'. Your React code never stores, reads, or sends the refresh token manually.
Analogy
The desk never slides your ID back across the counter along with your keycard — it stays in the hotel's own vault, and only the front desk (the auth routes) ever opens that vault. The room doors upstairs never even learn the vault exists.
Updated Auth Guard — Real JWT
src/common/guards/auth.guard.ts
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private reflector: Reflector,
private jwtService: JwtService,
private configService: ConfigService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractToken(request);
if (!token) {
throw new UnauthorizedException('Access token not provided');
}
try {
// Verify with ACCESS secret (not refresh secret)
const payload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get<string>('JWT_ACCESS_SECRET'),
});
request['user'] = payload;
} catch {
throw new UnauthorizedException('Invalid or expired access token');
}
return true;
}
private extractToken(request: Request): string | null {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : null;
}
}Three things changed from the simulated version: JwtService and ConfigService are injected via DI, jwtService.verifyAsync() replaces the fake validation, and we explicitly verify against the access secret (not the refresh secret). Clean swap, no structural changes.
Auth Module
src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
@Module({
imports: [
UsersModule, // gives us access to UsersService (because it's exported)
JwtModule.register({}), // empty config — we pass secrets per-sign/verify call
],
controllers: [AuthController],
providers: [AuthService],
})
export class AuthModule {}JwtModule.register({}) — Empty config because we use different secrets for access vs refresh tokens. Instead of a global default, we pass the secret explicitly in each signAsync() and verifyAsync() call. More flexible.
Tasks — Migrated to MongoDB
src/tasks/schemas/task.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
@Schema({ timestamps: true })
export class Task {
@Prop({ required: true, maxlength: 100 })
title: string;
@Prop({ required: true, maxlength: 500 })
description: string;
@Prop({ default: false })
done: boolean;
@Prop({ type: Types.ObjectId, ref: 'User', required: true })
owner: Types.ObjectId; // who created this task
}
export type TaskDocument = Task & Document;
export const TaskSchema = SchemaFactory.createForClass(Task);owner: Types.ObjectId — Each task belongs to a user. ref: 'User' enables Mongoose's populate() if you ever need to fetch the full user with the task.
src/tasks/tasks.service.ts — Updated for MongoDB
import {
Injectable,
NotFoundException,
ForbiddenException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Task, TaskDocument } from './schemas/task.schema';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';
@Injectable()
export class TasksService {
constructor(
@InjectModel(Task.name) private taskModel: Model<TaskDocument>,
) {}
async findAll(userId: string): Promise<TaskDocument[]> {
// Users only see their own tasks
return this.taskModel.find({ owner: userId }).exec();
}
async findOne(id: string, userId: string): Promise<TaskDocument> {
const task = await this.taskModel.findById(id).exec();
if (!task) {
throw new NotFoundException(`Task with id ${id} not found`);
}
// Ensure the user owns this task
if (task.owner.toString() !== userId) {
throw new ForbiddenException('You do not own this task');
}
return task;
}
async create(
createTaskDto: CreateTaskDto,
userId: string,
): Promise<TaskDocument> {
return this.taskModel.create({
...createTaskDto,
owner: userId,
});
}
async update(
id: string,
updateTaskDto: UpdateTaskDto,
userId: string,
): Promise<TaskDocument> {
// findOne checks ownership
await this.findOne(id, userId);
const updated = await this.taskModel
.findByIdAndUpdate(id, updateTaskDto, { new: true })
.exec();
return updated;
}
async remove(id: string, userId: string): Promise<void> {
await this.findOne(id, userId);
await this.taskModel.findByIdAndDelete(id).exec();
}
}Every method takes userId — users can only access their own tasks. This is resource-level authorization. The guard checks "are you authenticated?" and "do you have the right role?" But "do you own this specific task?" is business logic — that belongs in the service, not in a guard.
src/tasks/tasks.controller.ts — Updated
import {
Controller, Get, Post, Patch, Delete,
Param, Body,
} from '@nestjs/common';
import { TasksService } from './tasks.service';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { Roles } from '../common/decorators/roles.decorator';
@Controller('tasks')
export class TasksController {
constructor(private readonly tasksService: TasksService) {}
@Get()
findAll(@CurrentUser('sub') userId: string) {
return this.tasksService.findAll(userId);
}
@Get(':id')
findOne(
@Param('id') id: string, // MongoDB IDs are strings, not numbers
@CurrentUser('sub') userId: string,
) {
return this.tasksService.findOne(id, userId);
}
@Post()
create(
@Body() createTaskDto: CreateTaskDto,
@CurrentUser('sub') userId: string,
) {
return this.tasksService.create(createTaskDto, userId);
}
@Patch(':id')
update(
@Param('id') id: string,
@Body() updateTaskDto: UpdateTaskDto,
@CurrentUser('sub') userId: string,
) {
return this.tasksService.update(id, updateTaskDto, userId);
}
@Roles('admin')
@Delete(':id')
remove(
@Param('id') id: string,
@CurrentUser('sub') userId: string,
) {
return this.tasksService.remove(id, userId);
}
}No more ParseIntPipe — MongoDB uses string ObjectIds, not integer IDs. You could add a custom ParseObjectIdPipe to validate the format, but keep it simple for now.
The payload keys changed — @CurrentUser('sub'), not 'id'/'username'
In Module 05 the simulated token attached { id, username, roles }, so you wrote @CurrentUser('id') and @CurrentUser('username'). The real JWT payload here is { sub, email, roles } — sub (subject) is the standard JWT claim for the user ID, and username isn't in the token at all. So every @CurrentUser('id') from Module 05 becomes @CurrentUser('sub'), and if you need the username you now look it up from the DB via UsersService. Same decorator, different keys — a silent undefined here is almost always this mismatch.
src/tasks/tasks.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TasksController } from './tasks.controller';
import { TasksService } from './tasks.service';
import { Task, TaskSchema } from './schemas/task.schema';
@Module({
imports: [
MongooseModule.forFeature([{ name: Task.name, schema: TaskSchema }]),
],
controllers: [TasksController],
providers: [TasksService],
})
export class TasksModule {}App Module — Everything Wired Together
src/app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { JwtModule } from '@nestjs/jwt';
import { APP_GUARD } from '@nestjs/core';
import { TasksModule } from './tasks/tasks.module';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { AuthGuard } from './common/guards/auth.guard';
import { RolesGuard } from './common/guards/roles.guard';
import { RequestLoggerMiddleware } from './common/middleware/request-logger.middleware';
@Module({
imports: [
// ① Load .env file
ConfigModule.forRoot({ isGlobal: true }),
// ② Connect to MongoDB
MongooseModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
uri: configService.get<string>('MONGODB_URI'),
}),
inject: [ConfigService],
}),
// ③ JWT available globally (for AuthGuard injection)
JwtModule.register({ global: true }),
// ④ Feature modules
UsersModule,
AuthModule,
TasksModule,
],
providers: [
{ provide: APP_GUARD, useClass: AuthGuard },
{ provide: APP_GUARD, useClass: RolesGuard },
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(RequestLoggerMiddleware).forRoutes('*');
}
}ConfigModule.forRoot({ isGlobal: true }) — Loads .env and makes ConfigService available everywhere without importing ConfigModule in each feature module. isGlobal saves you from repeating imports.
MongooseModule.forRootAsync() — forRootAsync lets you inject ConfigService to read the MongoDB URI from .env. forRoot() only takes a static string — useless for environment-based config.
JwtModule.register({ global: true }) — Makes JwtService injectable everywhere. Without global: true, you'd need to import JwtModule in every module that uses JwtService (like the guard). Since the guard is global, the JwtModule should be too.
Updated main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor';
import helmet from 'helmet';
import * as cookieParser from 'cookie-parser';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Express middleware
app.use(helmet());
app.use(cookieParser()); // ← required to parse cookies (refresh token)
app.enableCors({
origin: ['http://localhost:3001'],
credentials: true, // ← required for cookies to work cross-origin
});
// Pipes
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
// Filters
app.useGlobalFilters(new AllExceptionsFilter());
// Interceptors
app.useGlobalInterceptors(
new LoggingInterceptor(),
new TransformInterceptor(),
new TimeoutInterceptor(),
);
await app.listen(3000);
}
bootstrap();cookieParser() — Without this, request.cookies is undefined. This middleware parses the Cookie header into a usable object. Your refresh endpoint reads request.cookies['refreshToken'] — which only works because of this middleware.
credentials: true in CORS — Required for the browser to send cookies on cross-origin requests. Without this, your React app at localhost:3001 sends a refresh request to localhost:3000, and the browser strips the cookie. The refresh fails with "no token provided" and you spend 2 hours debugging CORS. Ask me how I know.
The Complete Frontend Flow — What Your React App Does
This is the part you've been waiting for. Here's how your React/Next.js frontend interacts with this backend:
// api.ts — your axios/fetch wrapper
// ① Login — called when user submits login form
async function login(email: string, password: string) {
const res = await fetch('http://localhost:3000/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // CRITICAL — tells browser to include/accept cookies
body: JSON.stringify({ email, password }),
});
const data = await res.json();
if (data.success) {
// Store access token in memory (React state, context, Zustand, etc.)
setAccessToken(data.data.accessToken);
// refresh token is already in an HttpOnly cookie — you can't see it, don't try
}
return data;
}
// ② Authenticated API call
async function fetchTasks() {
const res = await fetch('http://localhost:3000/tasks', {
headers: { 'Authorization': `Bearer ${getAccessToken()}` },
credentials: 'include',
});
if (res.status === 401) {
// Access token expired — try to refresh
const refreshed = await refreshTokens();
if (refreshed) {
// Retry the original request with new access token
return fetchTasks();
} else {
// Refresh also failed — redirect to login
redirectToLogin();
}
}
return res.json();
}
// ③ Refresh — called automatically when access token expires
async function refreshTokens(): Promise<boolean> {
const res = await fetch('http://localhost:3000/auth/refresh', {
method: 'POST',
credentials: 'include', // browser sends refresh cookie automatically
});
const data = await res.json();
if (data.success) {
setAccessToken(data.data.accessToken); // new access token in memory
return true;
// new refresh token is already set as cookie by the server
}
return false; // refresh failed — user needs to log in again
}
// ④ On page load/refresh — recover session
async function initAuth() {
// Access token was in memory — lost on page refresh
// Try to get a new one via refresh token (cookie is still there)
const success = await refreshTokens();
if (!success) {
// No valid refresh token — user is not logged in
redirectToLogin();
}
}
// ⑤ Logout
async function logout() {
await fetch('http://localhost:3000/auth/logout', {
method: 'POST',
headers: { 'Authorization': `Bearer ${getAccessToken()}` },
credentials: 'include',
});
setAccessToken(null); // clear from memory
redirectToLogin();
}credentials: 'include' — This is the most forgotten flag in frontend development. Without it, the browser won't send cookies on cross-origin requests, and won't accept Set-Cookie headers from the server. Every request to your NestJS API needs this.
Trace — Complete Login-to-Refresh Flow
User opens app (page load):
Browser sends refreshToken cookie (if it exists)
server returns new accessToken → frontend stores in memory → user is logged in
401 → redirect to login page
User logs in:
validate credentials → generate tokens
hash refresh token → save to MongoDB
Set-Cookie: refreshToken=xyz; HttpOnly; Secure
return { accessToken: "abc" }
stores "abc" in useState → user is authenticated
User fetches tasks (5 minutes later, token still valid):
User fetches tasks (20 minutes later, access token expired):
Browser: sends refreshToken cookie automatically
Server: verify refresh token → valid + exists in DB
Server: delete old refresh token from DB
Server: generate new access token + new refresh token
Server: Set-Cookie: refreshToken=newXyz; HttpOnly; Secure
Server: return { accessToken: "newAbc" }
user never saw a login screen — completely invisible
User logs out:
finds refresh token in DB → deletes it
Clear-Cookie: refreshToken
clears accessToken from memory → redirect to login
That's the complete system. MongoDB for persistence, JWT for stateless auth, refresh token rotation for security, HttpOnly cookies for XSS protection, and resource-level ownership checks for authorization. Every layer you built before (middleware, guards, interceptors, pipes, filters) is still working, untouched, doing exactly what it was designed to do.
Next logical steps when you're ready: testing (unit tests for services, e2e tests for auth flow), Swagger/OpenAPI documentation, or advanced patterns (custom decorators, dynamic modules, event-driven architecture). Your call.
