Security is not a feature you add at the end. It is a set of practices you follow from the first commit. Here are the twelve things we check before any Node.js API goes to production.
## 1. Input validation on every endpoint
Use class-validator or zod on every incoming request body, query parameter, and URL parameter. Reject anything that does not match the expected shape before it reaches your business logic.
## 2. Rate limiting
Apply rate limits to all public endpoints. For authentication endpoints (login, register, password reset), use stricter limits. A simple in-memory rate limiter works for single-server setups. Use Redis-backed limiting if you run multiple instances.
## 3. Authentication tokens
Use short-lived JWTs (15 minutes) with refresh token rotation. Store refresh tokens in the database so you can revoke them. Never store sensitive data in the JWT payload.
## 4. CORS configuration
Whitelist specific origins. Never use wildcard (*) in production. Include only the domains that actually need to call your API.
## 5. Helmet middleware
Add the helmet package. It sets security headers (Content-Security-Policy, X-Content-Type-Options, etc.) with sensible defaults.
## 6. SQL injection prevention
Use an ORM like Prisma or parameterized queries. Never interpolate user input into SQL strings. This sounds obvious, but raw query escapes still show up in production code.
## 7. Dependency auditing
Run npm audit or pnpm audit in your CI pipeline. Fix critical and high vulnerabilities before deploying. Check weekly for new advisories.
## 8. Environment variables
Never hardcode secrets. Use .env files locally and secret management services in production. Rotate credentials on a schedule.
## 9. Error handling
Never expose stack traces or internal error details to clients. Log the full error server-side. Return a generic error message to the client with a reference ID they can share with support.
## 10. File upload validation
If your API accepts file uploads, validate file type, size, and content. Do not trust the Content-Type header. Check the file signature (magic bytes).
## 11. Logging
Log every authentication event (login, logout, failed attempt). Log every data mutation. Include the user ID, timestamp, and affected resource. This audit trail is essential for incident response.
## 12. HTTPS everywhere
Force HTTPS on all endpoints. Redirect HTTP to HTTPS. Set HSTS headers. Use TLS 1.2 or later.
