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.
Security is mostly about covering the basics consistently. Run through this list on every API you ship.
helmet sets headers that reduce common attacks such as clickjacking and MIME sniffing.
app.use(helmet());
Limit requests per IP, with a much stricter limit on login and password reset routes. This slows brute force attacks and abusive scraping.
Parse body, query and params with a schema library like Zod and reject anything unexpected. Never trust the client, even your own frontend.
Allow only your real frontend origins and set credentials: true only when you use cookies. A wildcard origin with credentials is a serious mistake.
Use bcrypt or argon2. Never log passwords or tokens, and never return password hashes in a response.
Use an ORM or parameterized queries. For MongoDB, validate types so a request cannot send an object where a string is expected and bypass a filter.
Set a body size limit, for example express.json({ limit: '1mb' }), to avoid memory exhaustion.
Store secrets in environment variables, never in git. Rotate any secret that has been exposed.
In production, return a generic message and log details on the server. Stack traces help attackers.
Run npm audit regularly and keep packages updated. Remove libraries you no longer use.
Headers, rate limits, validation, tight CORS, hashed passwords and careful secrets. Do these on every project and most attacks fail.
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.
Implement secure login with short-lived access tokens, rotating refresh tokens and httpOnly cookies, and avoid the common JWT mistakes.