API Security Checklist

Security isn't a feature — it's a requirement. This checklist covers the essential protections every API needs before going to production.

Authentication & Authorization

JWT Best Practices

javascript
// ✅ Good: Short-lived tokens with refresh
const accessToken = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '15m', algorithm: 'HS256' }
);
const refreshToken = jwt.sign(
{ userId: user.id },
process.env.REFRESH_SECRET,
{ expiresIn: '7d' }
);

RBAC (Role-Based Access Control)

javascript
function authorize(...roles) {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({
error: 'Insufficient permissions',
});
}
next();
};
}
app.delete('/api/posts/:id', authorize('admin', 'editor'), deletePost);

Input Validation

Never trust user input:

javascript
import { z } from 'zod';
const createPostSchema = z.object({
title: z.string().min(1).max(255),
content: z.string().min(10),
categoryId: z.number().int().positive(),
tags: z.array(z.number().int()).max(10).optional(),
});
app.post('/api/posts', (req, res) => {
const result = createPostSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.issues });
}
// Proceed with validated data
});

Security Headers

HeaderValuePurpose
X-Content-Type-Options
nosniff
Prevent MIME sniffing
X-Frame-Options
DENY
Prevent clickjacking
Strict-Transport-Security
max-age=31536000
Force HTTPS
Content-Security-Policy
default-src 'self'
Prevent XSS
X-XSS-Protection
0
Disable legacy XSS filter

SQL Injection Prevention

Always use parameterized queries:

javascript
// ❌ NEVER do this
const query = `SELECT * FROM users WHERE id = ${userId}`;
// ✅ Always do this
const query = 'SELECT * FROM users WHERE id = ?';
const [rows] = await db.execute(query, [userId]);

The Full Checklist

  • ✅ Use HTTPS everywhere
  • ✅ Implement rate limiting
  • ✅ Validate all inputs
  • ✅ Use parameterized queries
  • ✅ Set security headers
  • ✅ Use short-lived JWTs
  • ✅ Implement RBAC
  • ✅ Log security events
  • ✅ Enable CORS properly
  • ✅ Keep dependencies updated

Summary

API security is about defense in depth. No single measure is enough — layer authentication, validation, rate limiting, and proper headers to build an API that's resilient against common attacks.