API Security Best Practices: Protecting Your Backend in 2026
API security is critical in today's interconnected world. A single vulnerability can compromise your entire system. Here are essential practices to secure your APIs.
Authentication and Authorization
Use Strong Authentication
Implement OAuth 2.0 or JWT (JSON Web Tokens) for authentication:
// JWT Example
const jwt = require('jsonwebtoken');
function generateToken(user) {
return jwt.sign(
{ userId: user.id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '24h' }
);
}
function verifyToken(token) {
try {
return jwt.verify(token, process.env.JWT_SECRET);
} catch (error) {
throw new Error('Invalid token');
}
}
Implement Role-Based Access Control (RBAC)
function authorize(requiredRole) {
return (req, res, next) => {
if (req.user.role !== requiredRole) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
// Usage
app.get('/admin/users', authenticate, authorize('admin'), getUsers);
Input Validation
Always validate and sanitize input:
const { body, validationResult } = require('express-validator');
app.post('/api/users',
[
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 8 }),
body('name').trim().escape()
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process request
}
);
Rate Limiting
Protect against abuse with rate limiting:
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP'
});
app.use('/api/', limiter);
HTTPS Only
Always use HTTPS in production:
// Force HTTPS
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https') {
res.redirect(`https://${req.header('host')}${req.url}`);
} else {
next();
}
});
CORS Configuration
Configure CORS properly:
const cors = require('cors');
app.use(cors({
origin: process.env.ALLOWED_ORIGINS.split(','),
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
SQL Injection Prevention
Use parameterized queries:
// Bad: SQL Injection vulnerable
const query = `SELECT * FROM users WHERE id = ${userId}`;
// Good: Parameterized query
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId]);
XSS Protection
Sanitize output and set security headers:
const helmet = require('helmet');
app.use(helmet());
// This sets various security headers including:
// - X-Content-Type-Options
// - X-Frame-Options
// - X-XSS-Protection
Error Handling
Don't expose sensitive information in errors:
// Bad
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message }); // Exposes stack trace
});
// Good
app.use((err, req, res, next) => {
console.error(err); // Log server-side
res.status(500).json({
error: 'Internal server error'
});
});
API Versioning
Version your APIs to maintain backward compatibility:
app.use('/api/v1', v1Routes);
app.use('/api/v2', v2Routes);
Monitoring and Logging
Implement comprehensive logging:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Log all API requests
app.use((req, res, next) => {
logger.info(`${req.method} ${req.path}`, {
ip: req.ip,
userAgent: req.get('user-agent')
});
next();
});
Security Checklist
- Implement authentication (JWT/OAuth)
- Use HTTPS in production
- Validate and sanitize all input
- Implement rate limiting
- Configure CORS properly
- Use parameterized queries
- Set security headers (Helmet)
- Don't expose sensitive errors
- Version your APIs
- Implement logging and monitoring
- Regular security audits
- Keep dependencies updated
Conclusion
API security requires a multi-layered approach. Implement these practices from the start, conduct regular security audits, and stay updated with the latest security threats. Remember, security is not a one-time task but an ongoing process.