Securing Your Node.js API: A Practical Checklist for 2024
A hands-on security checklist for Node.js APIs covering authentication, input validation, rate limiting, CORS, SQL injection prevention, and more. Based on OWASP Top 10.
API security isn't optional โ it's the foundation of every trustworthy application. In this guide, we'll walk through a practical security checklist based on the OWASP Top 10, specifically tailored for Node.js applications.
1. Authentication & Authorization
Never roll your own authentication. Use battle-tested libraries:
- NextAuth.js / Auth.js: For full-stack Next.js applications
- Passport.js: For Express applications
- bcrypt: For password hashing (minimum 12 rounds)
- JWT: Short-lived access tokens (15 min) + refresh tokens (7 days)
2. Input Validation
Never trust client input. Validate everything:
import { z } from 'zod';
const createUserSchema = z.object({
email: z.string().email().max(255),
password: z.string().min(8).max(128),
name: z.string().min(1).max(100).trim(),
});
Use Zod or Joi at every API boundary. This prevents injection attacks, buffer overflows, and data corruption.
3. Rate Limiting
Protect against brute-force and DDoS attacks:
- Login endpoints: 5 attempts per 15 minutes per IP
- API endpoints: 100 requests per minute per user
- Public endpoints: 30 requests per minute per IP
4. SQL Injection Prevention
If you're using Prisma, you're already protected โ Prisma parameterizes all queries. But if you're writing raw SQL, always use parameterized queries:
// โ NEVER do this
const users = await prisma.$queryRawUnsafe(`SELECT * FROM users WHERE email = '${email}'`);
// โ
Always parameterize
const users = await prisma.$queryRaw`SELECT * FROM users WHERE email = ${email}`;
5. CORS Configuration
Restrict cross-origin requests to known domains only. Never use origin: '*' in production.
6. Security Headers
Set these headers on every response:
- Content-Security-Policy
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY
- Strict-Transport-Security (HSTS)
- Referrer-Policy: strict-origin-when-cross-origin
7. Dependency Management
Run npm audit regularly and update dependencies. Use Dependabot or Renovate for automated dependency updates. Remove unused packages.
8. Logging & Monitoring
Log security-relevant events (failed logins, permission denials, input validation failures) and monitor for anomalies. Never log sensitive data like passwords, tokens, or PII.
Conclusion
Security is a continuous process, not a one-time checklist. Implement these practices from day one, conduct regular audits, and stay updated on emerging threats. Your users trust you with their data โ honor that trust.
Comments (1)
The section on rate limiting was really useful. I just implemented it on our production API and it already caught several brute-force attempts. Security isn't optional!