NestJS REST API Best Practices That Scale
Module boundaries, DTO validation, guards, exception filters and configuration: the NestJS structure that stays clean as your API grows.
JWT login is easy to build and easy to get wrong. This is a setup that holds up in production.
A short access token limits the damage if it leaks. The refresh token lets users stay signed in without typing a password.
Putting tokens in localStorage exposes them to any script on the page. An httpOnly cookie cannot be read by JavaScript at all.
res.cookie('refresh_token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 30 * 24 * 60 * 60 * 1000,
});
Each time a refresh token is used, issue a new one and invalidate the old one. Save a hash of the token in the database. If an old token is ever presented again, someone has copied it, so revoke the whole session.
Use bcrypt or argon2 with a sensible cost factor. Never store plain text or fast hashes like plain SHA-256.
A small middleware verifies the access token, loads the user and attaches it to the request. Role checks sit on top of that.
Short access token, rotating refresh token, httpOnly cookies, hashed passwords and rate limiting. That combination covers the majority of real-world risk.
Module boundaries, DTO validation, guards, exception filters and configuration: the NestJS structure that stays clean as your API grows.
Schema design, migrations, relations, transactions and performance tips for using Prisma with PostgreSQL, MySQL or MongoDB.
Write a small, secure Node.js Docker image with multi-stage builds, layer caching and docker compose for local development.