Rate-limit auth, costly and public API endpoints per account or API key plus IP, in Route Handlers and Server Actions, with counters in a shared store (a Postgres upsert by default). Return 429 with Retry-After and trust only your platform's client-IP header.
Must-have checklist
Must
Rate-limit login, sign-up, password reset, OTP send and verify, and verification-email resend, per submitted identifier and per IP.
Stops credential stuffing, OTP brute force, and email or SMS bombing.
Limit AI calls, email and SMS sends, and exports per account, with both a short-window limit and a daily quota.
One script can run up a provider bill in minutes (OWASP API4:2023).
Key limits by account id or API key when known, plus the client IP; never by IP alone.
Users behind one NAT share an IP, and attackers spread attempts across many IPs.
Read the client IP only from a header your platform sets (for example x-real-ip on Vercel, CF-Connecting-IP behind Cloudflare); never the leftmost X-Forwarded-For value.
Clients can set X-Forwarded-For, so trusting it lets an attacker choose their own bucket.
Keep counters in a shared store (Postgres, Redis, or the platform's limiter), never in process memory.
Each serverless instance has its own memory, and in-memory counts reset on restart.
Increment and read the counter in one atomic statement (INSERT ... ON CONFLICT DO UPDATE ... RETURNING); never SELECT then UPDATE.
Read-then-write lets concurrent requests slip past the limit.
Check the limit inside each Route Handler and Server Action before any expensive work; treat proxy.ts and WAF rules as an extra, coarse layer.
A proxy matcher that skips a path also skips the Server Functions on that path.
Return 429 with Retry-After (seconds) from Route Handlers, and a typed rate-limited result with the retry time from Server Actions.
Set a short timeout on limiter calls and choose fail-open or fail-closed per endpoint; fail closed on auth and costly endpoints and alert on store errors.
Some limiter libraries allow requests by default when the store times out.
Delete expired counter rows with a scheduled job and index the window column; don't rely on in-process timers in serverless.
Should
When keying by IP, group IPv6 addresses by prefix (at least /64) instead of using the full address.
One customer usually gets a whole /56 or /48 and can rotate addresses inside it.
Store an HMAC of emails and IPs in counter keys instead of raw values, and keep rows only as long as the longest window.
The counter table then holds no readable personal data.
Set spending caps or billing alerts with your SMS, email and AI providers.
Rate limits cap request rates, not total spend.
Log rate-limit rejections per endpoint and key type, and alert on spikes.
Spikes reveal attacks, and steady rejections of real users reveal limits set too low.
Decisions to make
Asked before building01Where does the app run, and what sits in front of it?
02Will any limited endpoint take sustained high traffic, such as a public API with many clients?
03Do you already run Redis or a managed Redis-compatible service?
04Which counting algorithm fits the limited endpoints?
05What should happen when the limiter store is down or times out?
06Do you need to block request floods before they reach your functions and database?
Options
3 comparedPostgres counter table with an atomic upsert
Examples, not endorsements: rate-limiter-flexible (Postgres store)
- You already run Postgres and don't want another service
- Limits guard auth and costly endpoints at modest request rates
- You want counters in the same database, region and backups as your data
- Limited endpoints take sustained high request rates (each check is a write)
- Your database is already the bottleneck
- Adds one indexed write and a database round trip per limited request
- Needs a scheduled cleanup job and some vacuum headroom
Redis or a managed Redis-compatible store
Examples, not endorsements: Upstash Ratelimit, rate-limiter-flexible (Redis or Valkey store)
- A public API or other endpoint takes high request rates
- You already run Redis, or want sliding-window and token-bucket algorithms built in
- You would add a new service only to limit a few auth endpoints
- Another service to pay for, secure and monitor
- Check what the library does on a store timeout; some allow the request
Platform or WAF rate limiting at the edge
Examples, not endorsements: Vercel WAF rate limiting, Cloudflare rate limiting rules, AWS WAF rate-based rules
- You want to drop per-IP floods before they reach functions and the database
- You want limits without writing or running counter code
- You need per-account or per-API-key limits and your plan only counts by IP
- You need exact global counts (counters are kept per region or data center)
- Keys, window lengths and rule counts depend on the plan
- Configuration lives in a dashboard, outside the repo and code review
Why this approach
A Postgres counter table with one atomic upsert per check works across every serverless instance, adds no new service, and is enough for auth and costly endpoints, which see modest request rates. Run the check inside the Route Handler or Server Action, where you know the account or API key, not in proxy.ts. Add platform or WAF rate limiting in front when you need to drop per-IP floods before they reach your functions. Move counters to Redis or a managed Redis-compatible service when a public API or other high-volume endpoint makes one database write per request too expensive.
Lenses
Limit login, sign-up, password reset, OTP send and verify, and verification-email resend by both the submitted identifier (normalised email or account id) and the client IP. The OWASP Authentication Cheat Sheet ties failed-login counters to the account, because per-IP limits alone miss attacks spread across many addresses. Key public APIs by API key. Take the IP only from a header your platform sets: Vercel overwrites X-Forwarded-For and also sends x-real-ip; Cloudflare recommends CF-Connecting-IP; behind your own proxy, scan X-Forwarded-For from the right and take the first address your proxies didn't add. The leftmost value is whatever the client sent. Run the check inside each Server Action, because a proxy.ts matcher that skips a path also skips its Server Functions. Fail closed on auth and costly endpoints so a store outage can't open them to brute force. Rate limits slow attackers but don't stop them; OWASP treats them as one layer next to MFA and monitoring.
Version notes
middleware.tsis renamed toproxy.ts; Proxy runs on Node.js by default but is not meant for slow data fetching, so keep store lookups in handlers.- Server Functions are POST requests to the route that uses them; a Proxy matcher that excludes the path also skips them, so check limits inside each action.
NextRequest.ipwas removed in v15; read the client IP from your host's trusted header or helper.- In-memory counters are per instance and reset on restart; keep counts in a shared store or use your host's rate limiting.
date_bin(), used here to bucket timestamps into windows, exists from PostgreSQL 14.INSERT ... ON CONFLICT DO UPDATEguarantees an atomic insert-or-update outcome under concurrency; addRETURNINGto read the new count in the same statement.UNLOGGEDtables are faster but are truncated after a crash and are not replicated to standby servers.
- If Redis doesn't answer within the timeout (default 5 s), the request is allowed; set a shorter timeout and handle the fail mode yourself on sensitive endpoints.
- The ephemeral cache of blocked identifiers lives in instance memory; create the limiter outside the handler so it is reused.
- Multi-region mode syncs asynchronously and can exceed the limit slightly; token bucket is not supported there.
checkRateLimitneeds a matching rate limit ID configured as a rule in the Vercel Firewall dashboard.- A custom
rateLimitKeyreplaces the default client-IP bucket; build a compound key yourself to limit by IP and account together. - Counters are tracked per region, so a key hit from several regions can exceed the configured limit.
- The
timeoutoption exists from 1.2.6; decide per endpoint what a timeout means.
Verify checks
Failed logins for one email sent from several different IPs are rejected with 429 once the per-account limit is reached.
Login attempts for many different emails from one IP are rejected with 429 once the per-IP limit is reached.
Every 429 response has a Retry-After header with a positive whole number of seconds that matches when the window resets.
The client-IP helper ignores client-supplied X-Forwarded-For entries and returns only the address set by the trusted platform or proxy.
With a limit of N, sending 5N concurrent requests for one key allows exactly N and rejects the rest.
The limit still holds when requests alternate between two app instances, and after an instance restarts.
Calling a limited Server Action or Route Handler directly, without passing through proxy.ts, is still rate limited.
With the limiter store unreachable, endpoints follow the chosen fail mode (for example 503 on auth and costly endpoints), and an error is logged.
An account that reaches its daily quota on an AI, SMS or email endpoint is blocked until the quota resets, whatever IP it uses.
The cleanup job deletes counter rows older than the longest window and keeps rows for current windows.
Counter keys contain no raw email addresses or IP addresses.
Common mistakes
- Counting in process memory (a
Mapor an LRU cache): each serverless instance keeps its own count, which resets on restart. - Keying only by IP, so users behind one NAT block each other while attackers rotate IPs.
- Trusting the leftmost
X-Forwarded-Forvalue, which any client can set. - Reading the count and then writing it in two statements, so concurrent requests slip past the limit.
- Limiting only in
proxy.ts, leaving Server Actions and Route Handlers that the matcher skips unprotected. - Returning 200 with an error body, or a 500, instead of 429 with
Retry-After. - Never deleting old counter rows, so the table and its indexes grow forever.
- Using a library's default timeout without knowing that it lets requests through when the store is down.
- Limiting OTP sends but not OTP verification, so short codes can be brute-forced.
- Caching a limited route publicly, so a CDN serves it without running the limiter.