3 Hours

12. API Security Best Practices

API Security

APIs are a primary attack vector for modern applications. This module covers essential API security practices including input validation, rate limiting, idempotency keys, and secure API design.

Input Validation: Never Trust Client Data

Always validate all input on the server side. Client-side validation is for UX only — it can be bypassed.

JavaScript
const Joi = require('joi');

const userSchema = Joi.object({
    email: Joi.string().email().required().max(255),
    name: Joi.string().min(2).max(100).required(),
    age: Joi.number().integer().min(0).max(150),
    website: Joi.string().uri().allow('')
});

function validateInput(schema) {
    return (req, res, next) => {
        const { error, value } = schema.validate(req.body);

        if (error) {
            return res.status(400).json({
                error: 'Validation failed',
                details: error.details.map(d => d.message)
            });
        }

        req.validatedBody = value;
        next();
    };
}

app.post('/api/users', validateInput(userSchema), createUser);
Validate everything: Headers, query parameters, path parameters, and request body. Never trust any client input.

Rate Limiting: Prevent Abuse

Rate limiting protects your API from brute-force attacks, DDoS, and resource exhaustion.

JavaScript
const rateLimit = require('express-rate-limit');

// General API: 100 requests per 15 minutes
const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 100,
    message: 'Too many requests from this IP'
});

// Login endpoint: 5 attempts per 15 minutes (prevent brute force)
const authLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 5,
    skipSuccessfulRequests: true  // Don't count successful logins
});

app.use('/api/', apiLimiter);
app.use('/api/auth/login', authLimiter);
app.use('/api/auth/register', authLimiter);
Always rate limit: Authentication endpoints, password reset, and any endpoint that could be abused.

Idempotency Keys: Prevent Duplicate Operations

Idempotency keys allow clients to safely retry requests without causing duplicate operations (like double charging).

JavaScript
const idempotencyKeys = new Map();  // Use Redis in production

app.post('/api/payments', async (req, res) => {
    const idempotencyKey = req.headers['idempotency-key'];

    if (!idempotencyKey) {
        return res.status(400).json({ error: 'Missing idempotency key' });
    }

    // Check if request already processed
    const existing = idempotencyKeys.get(idempotencyKey);
    if (existing) {
        return res.json(existing.response);
    }

    // Process request
    const result = await processPayment(req.body);

    // Store result with 24-hour TTL
    idempotencyKeys.set(idempotencyKey, {
        response: result,
        expiresAt: Date.now() + 86400000
    });

    res.json(result);
});

// Client generates unique key for each operation
const idempotencyKey = `${userId}-${Date.now()}-${Math.random()}`;
fetch('/api/payments', {
    method: 'POST',
    headers: {
        'Idempotency-Key': idempotencyKey
    }
});
Critical for payments: Always implement idempotency for POST/PUT endpoints that create or update resources.

Request Size Limits

Prevent DoS attacks via large payloads by limiting request sizes.

JavaScript
// Limit JSON body size to 1MB
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true, limit: '1mb' }));

// Limit file uploads to 5MB
const multer = require('multer');
const upload = multer({ limits: { fileSize: 5 * 1024 * 1024 } });

Timeout Configuration

Prevent slowloris attacks by setting appropriate timeouts.

JavaScript
const server = app.listen(3000);

// Server timeout
server.timeout = 30000;  // 30 seconds

// Request timeout middleware
app.use((req, res, next) => {
    req.setTimeout(30000, () => {
        res.status(408).json({ error: 'Request timeout' });
    });
    next();
});

API Security Checklist

Text
Input validation on all endpoints
Rate limiting on all public endpoints
Idempotency keys for POST/PUT endpoints
Request size limits (1MB for JSON, 5MB for uploads)
Timeout configuration (30 seconds)
HTTPS only (enforce with redirect)
CORS with specific origins (never '*')
Authentication on all non-public endpoints
Proper error messages (no stack traces)
Audit logging for sensitive operations
Run this checklist before every production deployment.

Knowledge Check

Ready to test your understanding of 12. API Security Best Practices?

Back