API Security
Authentication, authorization, rate limiting, input validation, and CORS.
Overview
Secure APIs protect against common attacks and unauthorized access.
Key Concepts
- Authentication — Verify user identity
- Authorization — Control resource access
- Rate Limiting — Prevent abuse
- Input Validation — Sanitize all inputs
- CORS — Control cross-origin requests
Code Examples
// app/api/auth/route.js
import { NextResponse } from 'next/server';
import { verifyToken } from '@/lib/auth';
export async function middleware(request) {
const token = request.headers.get('authorization')?.replace('Bearer ', '');
if (!token) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const payload = await verifyToken(token);
request.headers.set('x-user-id', payload.sub);
return NextResponse.next();
} catch {
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
}
}
// Rate limiting
const rateLimit = new Map();
export function checkRateLimit(ip, limit = 100, windowMs = 60000) {
const now = Date.now();
const requests = rateLimit.get(ip) || [];
const recentRequests = requests.filter(time => now - time < windowMs);
if (recentRequests.length >= limit) {
return false;
}
recentRequests.push(now);
rateLimit.set(ip, recentRequests);
return true;
}
// Input validation with Zod
import { z } from 'zod';
const createPostSchema = z.object({
title: z.string().min(1).max(200),
content: z.string().min(1).max(5000),
tags: z.array(z.string()).max(5).optional()
});
export async function POST(request) {
const body = await request.json();
const result = createPostSchema.safeParse(body);
if (!result.success) {
return NextResponse.json(
{ errors: result.error.flatten().fieldErrors },
{ status: 400 }
);
}
// Safe to use result.data
const post = await db.posts.create({ data: result.data });
return NextResponse.json({ data: post }, { status: 201 });
}
Practice
Implement comprehensive API security with auth, rate limiting, and validation.