Defense-in-Depth for Modern Web APIs
Application Programming Interfaces (APIs) represent the primary bridge between frontend client applications, mobile interfaces, and database repositories. Consequently, they are the most targeted entry point for malicious actors, automated brute-force bots, and unauthorized data scraping.
In this guide, we examine production security patterns for authenticating requests, managing sessions, and throttling traffic.
1. Dual-Token Authentication & Refresh Token Rotation
Storing long-lived JWT access tokens in browser localStorage is an anti-pattern: any malicious third-party script or Cross-Site Scripting (XSS) vulnerability can immediately exfiltrate the token.
The industry-standard architecture utilizes Dual-Token Authentication:
- •Short-Lived Access Token (15 minutes): Kept in client memory or a secure cookie, used to authorize API endpoints.
- •Long-Lived Refresh Token (7 days): Stored strictly in an
HttpOnly,Secure,SameSite=Strictcookie. When the access token expires, the client calls a/api/auth/refreshendpoint.
// lib/auth/cookies.ts
import { NextResponse } from 'next/server';
export function setSecureAuthCookies(
res: NextResponse,
accessToken: string,
refreshToken: string
) {
// Access Token Cookie
res.cookies.set('prayxis_access_token', accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 15 * 60, // 15 minutes
path: '/',
});
// Refresh Token Cookie
res.cookies.set('prayxis_refresh_token', refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60, // 7 days
path: '/api/auth/refresh', // Restrict path to refresh endpoint only!
});
}2. Defending Against Cross-Origin Request Forgery (CORS & CSRF)
When serving APIs across different domains or subdomains:
- •**Never use wildcard
Access-Control-Allow-Origin: *** on authenticated endpoints that accept cookies or credentials. - •Explicitly validate incoming
Originheaders against an allowed domain whitelist:
const ALLOWED_ORIGINS = ['https://prayxis.in', 'https://admin.prayxis.in'];
export function corsMiddleware(req: Request) {
const origin = req.headers.get('origin') || '';
const isAllowed = ALLOWED_ORIGINS.includes(origin);
const headers = new Headers();
if (isAllowed) {
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Access-Control-Allow-Credentials', 'true');
headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
return headers;
}3. Sliding-Window Rate Limiting with Redis
Fixed-window rate limiters (e.g. allowing 100 requests per clock hour) can be bypassed by an attacker sending 100 requests at 11:59 and another 100 requests at 12:01.
A Sliding-Window Log using Redis sorted sets (ZSET) tracks request timestamps accurately:
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL!);
export async function checkSlidingRateLimit(
identifier: string,
limit: number = 60,
windowSeconds: number = 60
): Promise<{ allowed: boolean; remaining: number }> {
const now = Date.now();
const windowStart = now - windowSeconds * 1000;
const key = `rate_limit:${identifier}`;
const pipeline = redis.pipeline();
// 1. Remove timestamps outside the sliding window
pipeline.zremrangebyscore(key, 0, windowStart);
// 2. Add current request timestamp
pipeline.zadd(key, now, `${now}-${Math.random()}`);
// 3. Count remaining items in window
pipeline.zcard(key);
// 4. Set key TTL to auto-expire
pipeline.expire(key, windowSeconds);
const results = await pipeline.exec();
const currentCount = (results?.[2]?.[1] as number) || 0;
if (currentCount > limit) {
return { allowed: false, remaining: 0 };
}
return { allowed: true, remaining: limit - currentCount };
}4. Input Sanitization & Payload Size Defense
Always guard endpoints against Denial of Service (DoS) attacks caused by giant payloads:
- •Set strict request body size limits in your reverse proxy (e.g.
client_max_body_size 2Min Nginx or Next.js route segment configs). - •Enforce strict schemas using Zod to reject unexpected or polluted object prototypes.
Learn defensive software engineering and cybersecurity methodologies in the PRAYXIS Cybersecurity Virtual Internship.