Rate limiting in Next.js middleware without Redis: working code and fair limits
Where middleware memory lives
Before writing code, it is important to understand what it is running on. The rate limiter stores counters, and the question is where to store them if Redis is not there.
- Self-hosted, one process `next start`. Middleware runs in the same Node.js process. A modular variable lives as long as the process is alive and is visible to all requests. The counter in
Mapworks correctly. - Several processes or containers behind a balancer. Each has its own
Map. The actual limit is multiplied by the number of processes. - Vercel and other serverless/edge platforms. Requests are distributed among many isolates in different regions, isolates are created and destroyed based on load. The counter in memory sees only part of the requests, and after a cold start it starts from zero.
Therefore, the in-memory rate limit on serverless is not a protection against a targeted attack, but a filter against rough outbursts that fall into one isolate: a loopy client, a simple script from one address.
Implementation: sliding window in memory
// lib/rate-limit.ts
type Entry = { hits: number[] };
const store = new Map<string, Entry>();
let lastSweep = Date.now();
export function rateLimit(key: string, limit: number, windowMs: number) {
const now = Date.now();
if (now - lastSweep > 60_000) { // периодическая очистка, чтобы Map не росла бесконечно
for (const [k, e] of store) {
if (e.hits.length === 0 || now - e.hits[e.hits.length - 1] > windowMs) store.delete(k);
}
lastSweep = now;
}
const entry = store.get(key) ?? { hits: [] };
entry.hits = entry.hits.filter((t) => now - t < windowMs);
if (entry.hits.length >= limit) {
store.set(key, entry);
const retryAfter = Math.ceil((windowMs - (now - entry.hits[0])) / 1000);
return { ok: false as const, retryAfter };
}
entry.hits.push(now);
store.set(key, entry);
return { ok: true as const, remaining: limit - entry.hits.length };
}Storing timestamps is more accurate than a fixed window (no double spike at the minute boundary), but consumes memory in proportion to the limit. For limits of the order of tens of requests per minute, this is not significant.
##Middleware
// middleware.ts
import { NextResponse, type NextRequest } from "next/server";
import { rateLimit } from "@/lib/rate-limit";
const RULES: { prefix: string; limit: number; windowMs: number }[] = [
{ prefix: "/api/auth/login", limit: 10, windowMs: 60_000 },
{ prefix: "/api/contact", limit: 5, windowMs: 60_000 },
{ prefix: "/api/", limit: 120, windowMs: 60_000 },
];
function clientIp(req: NextRequest): string {
const xff = req.headers.get("x-forwarded-for");
return xff?.split(",")[0]?.trim() || req.headers.get("x-real-ip") || "unknown";
}
export function middleware(req: NextRequest) {
const rule = RULES.find((r) => req.nextUrl.pathname.startsWith(r.prefix));
if (!rule) return NextResponse.next();
const res = rateLimit(`${rule.prefix}:${clientIp(req)}`, rule.limit, rule.windowMs);
if (!res.ok) {
return NextResponse.json(
{ error: "too many requests" },
{ status: 429, headers: { "Retry-After": String(res.retryAfter) } }
);
}
return NextResponse.next();
}
export const config = { matcher: ["/api/:path*"] };In Next.js 15, NextRequest no longer has the ip property, so the address is taken from the headers. You can only trust x-forwarded-for if the application is preceded by your proxy or platform that rewrites this header. On a bare next start without a proxy, the client will put anything in there and bypass the limit. On Vercel, there is a helper ipAddress from the @vercel/functions package to get the address.
How to close what middleware does not close
Password brute force. The attacker changes the IP through the proxy pool, and the address limit is useless. Protection—counter of failed attempts at the account level in the main database:
ALTER TABLE users ADD COLUMN failed_logins int NOT NULL DEFAULT 0; ALTER TABLE users ADD COLUMN locked_until timestamptz;
// при неудачном входе
await db.query(
`UPDATE users SET failed_logins = failed_logins + 1,
locked_until = CASE WHEN failed_logins + 1 >= 5 THEN now() + interval '15 minutes' END
WHERE email = $1`, [email]);
// при успешном — сбросить failed_logins и locked_untilThis works on any number of instances, because the state is in the database that you already have. Do not disclose whether the account exists in your response; the error message should be the same.
Form spam. Captcha or verification token (Cloudflare Turnstile, hCaptcha) is more effective than the IP limit, plus a hidden trap field for simple bots.
Volume attacks. This is a pre-application level task: rate limiting rules in Vercel Firewall, Cloudflare WAF or nginx limit_req on self-hosted. They count requests before they reach your code.
How to check
for i in $(seq 1 15); do
curl -s -o /dev/null -w "%{http_code}\n" -X POST https://example.com/api/auth/login \
-H 'Content-Type: application/json' -d '{"email":"a@b.c","password":"x"}'
doneOn self-hosted with one process, after the tenth request there will be 429. On serverless, the result may be uneven - this is a demonstration of the limitation.
When you shouldn't do it at all
If the application is on Vercel or behind Cloudflare, the built-in WAF rules will give a global limit without code and without the illusion of security. The in-memory option is justified on one self-hosted server or as an additional cheap layer, the weakness of which the team knows about.
Нужна реализация под ваш проект или аудит архитектуры?
Разрабатываем сайты на Next.js, Telegram-ботов, интеграции с CRM и ИИ-агентов под ключ.