Production-Ready Session Authentication and Serverless Rate Limiting in Next.js
Why in-memory rate limiters fail on serverless deployments and how to combine Upstash Redis, HTTP-only cookies, and origin verification in Next.js API routes.
Abdul Malek
Full-Stack Developer (MERN & Next.js)
Why In-Memory Maps Fail in Serverless Functions
A JavaScript `new Map()` rate limiter works during `next dev` because a single Node.js process handles every request. In production on Vercel, API routes scale across ephemeral serverless instances—meaning a brute-force script can hit different instances or wait for cold starts to bypass an in-memory counter.
Sliding-Window Rate Limiting with Upstash Redis
Using `@upstash/ratelimit` over HTTP REST (`@upstash/redis`) provides a shared, low-latency counter across all serverless instances. Crucially, if Redis is temporarily unreachable, the helper should log the warning and fail open so legitimate visitors are not locked out of sending a contact inquiry.
export async function consumeAuthRateLimit(request, action) {
try {
const limiter = getAuthLimiter();
const ip = getClientIp(request);
const { success } = await limiter.limit(`${action}:${ip}`);
return !success;
} catch (err) {
console.error('Auth rate-limit check failed:', err?.message);
return false;
}
}Storing Hashed Session Tokens in MongoDB
Even if a database read leak were ever to occur, raw session tokens should never sit in plain text in a collection. By generating a 32-byte random token (`randomBytes(32).toString("base64url")`), sending the raw token only in an `HttpOnly; SameSite=Lax` cookie, and storing `createHash("sha256").update(token).digest("hex")` in `PortfolioSession`, active sessions cannot be hijacked from a database dump.
Defense-in-Depth for Public Contact & Auth Endpoints
Public endpoints like `POST /api/contact` benefit from layered protection: checking the `Origin` header (`hasValidOrigin`), enforcing `content-length` byte limits, sanitizing newline characters (`\r\n`) in email headers to prevent SMTP header injection, and rate limiting by client IP.
Real-World Implementation
See how these patterns were applied in production by reading the related project case study.
Related Technical Articles
Architecting a Multi-Admin E-Commerce & CMS Platform with Next.js and MongoDB
A practical engineering breakdown of server-verified order pricing, role-based access control, and schema design for a production Next.js and MongoDB commerce platform.
Read article Cloud & Media Engineering · 5 min readImplementing Secure Signed Cloudinary Media Uploads in Next.js App Router
How to upload high-resolution project screenshots and 100 MB walkthrough videos directly from the browser to Cloudinary using server-issued SHA-1 signatures.
Read article