# Rate-Limit Next.js API Routes and Server Actions with Redis

Stop abuse and runaway clients with a Redis rate limiter you can read in one sitting. It works in route handlers and Server Actions, returns proper 429 responses, and needs no extra service.

*Intermediate · 20 min · Updated Nov 18, 2026*

## What you'll build

- One shared `ioredis` connection that survives hot reloads
- An atomic fixed-window limiter in a single Redis round trip
- A sliding-window limiter with sorted sets for smoother limits
- `429 Too Many Requests` responses with `Retry-After` and `X-RateLimit-*` headers
- Limits keyed by user id or IP, used in route handlers and Server Actions

## Before you start

- Node.js 20 or newer
- A Next.js 16 app using the App Router
- A free CloudHike.dev account

## How rate limiting with Redis works

A rate limiter counts requests per caller and refuses them once the count passes a limit. The count must live somewhere every server instance can see. A variable in memory doesn't work on serverless hosts or with more than one instance, because each one keeps its own count. Redis is shared, fast and has expiring keys built in, so it is the usual choice.

| Algorithm | How it counts | Good | Watch out for |
| --- | --- | --- | --- |
| Fixed window | One counter per caller per window, such as per minute | One small key, very cheap | A burst at the edge of two windows can let through up to twice the limit |
| Sliding window | A sorted set with one entry per request in the last N seconds | Smooth and exact | One entry per request, so more memory at high limits |

Start with a fixed window. It's enough for most login forms, contact forms and APIs. Switch to a sliding window where bursts at window edges matter, such as paid API quotas.

## Step 1: Connect to Redis with one shared client

1. Sign in at [cloudhike.dev](https://cloudhike.dev/signup) and create a project.
2. Click **Deploy** on the **Redis** card.
3. Click **Copy as .env** and paste `REDIS_URL` into `.env.local`.

*.env.local*

```bash
# rediss:// (two s) when TLS is on
REDIS_URL=rediss://default:...@...
```

```bash
npm install ioredis server-only
```

Create one client per server process. In development, keep it on `globalThis`, so each hot reload does not open a new connection and leave the old one behind.

*lib/redis.ts*

```ts
import "server-only";
import Redis from "ioredis";

function createRedis() {
  const client = new Redis(process.env.REDIS_URL!, {
    // Fail fast instead of hanging a request when Redis is unreachable.
    maxRetriesPerRequest: 2,
    commandTimeout: 1000,
  });
  // Without a listener, ioredis logs every connection error loudly.
  client.on("error", (err) => console.error("Redis error:", err.message));
  return client;
}

const globalForRedis = globalThis as unknown as { redis?: Redis };

export const redis = globalForRedis.redis ?? createRedis();
if (process.env.NODE_ENV !== "production") globalForRedis.redis = redis;
```

> **Note:** `ioredis` needs a real TCP connection, so it runs in the Node.js runtime: route handlers, Server Actions, Server Components and `proxy.ts` (which uses Node.js by default in Next.js 16). It does not run in the Edge runtime.

## Step 2: Write an atomic fixed-window limiter

The classic version is `INCR` the counter, then `EXPIRE` it on the first hit. As two separate calls, that has a gap: if the process dies between them, the key never expires and the caller can end up blocked forever. On CloudHike Redis, which uses the `noeviction` policy, that key would also stay in memory for good.

A small Lua script fixes both. Redis runs a script as one atomic step, so the count and the expiry always happen together, in one round trip. It also returns how long the window has left.

*lib/rate-limit.ts*

```ts
import "server-only";
import { redis } from "@/lib/redis";

export type RateLimitResult = {
  allowed: boolean;
  limit: number;
  remaining: number;
  resetMs: number; // ms until the window resets
};

// KEYS[1] = counter key, ARGV[1] = window in ms.
// Returns { count, ms left in the window }.
const FIXED_WINDOW = `
local count = redis.call("INCR", KEYS[1])
local ttl = redis.call("PTTL", KEYS[1])
if ttl < 0 then
  redis.call("PEXPIRE", KEYS[1], ARGV[1])
  ttl = tonumber(ARGV[1])
end
return { count, ttl }
`;

export async function fixedWindow(id: string, limit: number, windowSec: number): Promise<RateLimitResult> {
  const windowMs = windowSec * 1000;
  const [count, ttl] = (await redis.eval(FIXED_WINDOW, 1, `rl:fw:${id}`, windowMs)) as [number, number];
  return {
    allowed: count <= limit,
    limit,
    remaining: Math.max(0, limit - count),
    resetMs: ttl,
  };
}
```

The `ttl < 0` check also repairs a key that somehow lost its expiry, so no counter can live forever.

### Prefer MULTI over Lua?

A `MULTI` transaction is atomic too. `PEXPIRE ... NX` (Redis 7) only sets the expiry if the key has none:

*lib/rate-limit.ts (MULTI version)*

```ts
const key = `rl:fw:${id}`;
const results = await redis.multi().incr(key).pexpire(key, windowMs, "NX").pttl(key).exec();
if (!results) throw new Error("Rate limit transaction was aborted");
const count = results[0][1] as number;
const ttl = results[2][1] as number;
```

## Step 3: Add a sliding-window limiter with sorted sets

A sliding window keeps one sorted-set entry per request, scored by its time. Each call drops entries older than the window, counts the rest, and adds the new request only if there is room. Refused requests are not added, so a client that keeps retrying doesn't push its own reset further away.

*lib/rate-limit.ts (add below fixedWindow)*

```ts
// KEYS[1] = sorted set, ARGV[1] = window in ms, ARGV[2] = limit,
// ARGV[3] = a unique id for this request.
// Uses Redis's own clock, so app servers with skewed clocks agree.
const SLIDING_WINDOW = `
local t = redis.call("TIME")
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local window = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])

redis.call("ZREMRANGEBYSCORE", KEYS[1], 0, now - window)
local count = redis.call("ZCARD", KEYS[1])
local allowed = 0
if count < limit then
  redis.call("ZADD", KEYS[1], now, ARGV[3])
  count = count + 1
  allowed = 1
end
redis.call("PEXPIRE", KEYS[1], window)

local oldest = redis.call("ZRANGE", KEYS[1], 0, 0, "WITHSCORES")
local reset = window
if oldest[2] then reset = tonumber(oldest[2]) + window - now end
return { allowed, count, reset }
`;

export async function slidingWindow(id: string, limit: number, windowSec: number): Promise<RateLimitResult> {
  const windowMs = windowSec * 1000;
  const [allowed, count, reset] = (await redis.eval(
    SLIDING_WINDOW,
    1,
    `rl:sw:${id}`,
    windowMs,
    limit,
    crypto.randomUUID(),
  )) as [number, number, number];
  return {
    allowed: allowed === 1,
    limit,
    remaining: Math.max(0, limit - count),
    resetMs: Math.max(0, reset),
  };
}
```

When the caller is over the limit, `reset` is the time until the oldest request leaves the window, which is exactly when the next one will be allowed. The key always gets an expiry, so idle callers cost no memory.

> **Warning:** A sliding window stores one entry per allowed request. A limit of 1,000 per hour is 1,000 entries per busy caller. For big limits, use the fixed window, which is one small counter per caller.

## Step 4: Return 429 with Retry-After and X-RateLimit headers

Well-behaved clients read these headers to slow down by themselves. `Retry-After` is in seconds. `X-RateLimit-Reset` here is a Unix time in seconds, as GitHub's API uses. There is no single standard for the `X-RateLimit-*` headers, so document what yours mean.

*lib/rate-limit.ts (add at the end)*

```ts
export function rateLimitHeaders(r: RateLimitResult): Record<string, string> {
  const headers: Record<string, string> = {
    "X-RateLimit-Limit": String(r.limit),
    "X-RateLimit-Remaining": String(r.remaining),
    "X-RateLimit-Reset": String(Math.ceil((Date.now() + r.resetMs) / 1000)),
  };
  if (!r.allowed) headers["Retry-After"] = String(Math.max(1, Math.ceil(r.resetMs / 1000)));
  return headers;
}

export function tooManyRequests(r: RateLimitResult) {
  return Response.json(
    { error: "Too many requests. Please slow down." },
    { status: 429, headers: rateLimitHeaders(r) },
  );
}
```

Now limit a route handler. Check first, before any slow or costly work:

*app/api/search/route.ts*

```ts
import { clientIp } from "@/lib/client-ip";
import { fixedWindow, rateLimitHeaders, tooManyRequests } from "@/lib/rate-limit";

export async function GET(request: Request) {
  // 30 searches per minute per IP address.
  const limit = await fixedWindow(`search:${await clientIp()}`, 30, 60);
  if (!limit.allowed) return tooManyRequests(limit);

  const q = new URL(request.url).searchParams.get("q") ?? "";
  const results = await search(q);

  return Response.json({ results }, { headers: rateLimitHeaders(limit) });
}

async function search(q: string) {
  // ...your real search here...
  return q ? [{ title: `Results for ${q}` }] : [];
}
```

Test it from a terminal. After 30 requests in a minute you should see `429` and a `Retry-After` header:

*Terminal*

```bash
for i in $(seq 1 35); do
  curl -s -o /dev/null -w "%{http_code} " "http://localhost:3000/api/search?q=test"
done; echo
curl -si "http://localhost:3000/api/search?q=test" | grep -i -E "^(retry-after|x-ratelimit)"
```

## Step 5: Key the limit by user id or IP address

What you count by decides who shares a limit. Use the **user id** when the caller is signed in. It is exact and can't be faked. Use the **IP address** for signed-out traffic such as login, sign-up and contact forms.

Next.js has no `request.ip` (it was removed in Next.js 15). Read the `x-forwarded-for` header that your host or proxy sets instead. In Next.js 16, `headers()` is async, so `await` it:

*lib/client-ip.ts*

```ts
import "server-only";
import { headers } from "next/headers";

// How many proxies you run in front of the app that append to
// x-forwarded-for. 1 fits most hosts and a single nginx or load balancer.
const TRUSTED_PROXIES = 1;

export async function clientIp(): Promise<string> {
  const h = await headers();
  const forwarded = h.get("x-forwarded-for");
  if (forwarded) {
    const hops = forwarded.split(",").map((s) => s.trim()).filter(Boolean);
    // Proxies append to the right. Entries further left can be typed
    // by the client, so count from the right.
    const ip = hops[Math.max(0, hops.length - TRUSTED_PROXIES)];
    if (ip) return ip;
  }
  return h.get("x-real-ip") ?? "unknown";
}
```

> **Warning:** `x-forwarded-for` is just a header, and anyone can send one. A client can send `x-forwarded-for: 1.2.3.4` with a new fake IP on every request. If your app takes the **left-most** entry, the client picks its own key and walks past the limit. Only trust entries your own proxies added, which are the right-most ones. Never expose the app directly to the internet without a proxy in front, or the header is entirely client-controlled.

- Many people can share one IP (offices, schools, mobile carriers). Keep IP limits generous, and tighter on the user id once they sign in.
- An IPv6 user can often switch between many addresses. For strict limits, key IPv6 by its first four groups (the /64 network).
- Combine keys for sensitive actions: limit login by IP and by the email being tried, so one attacker can't guess passwords for many accounts, and many IPs can't target one account.
- When no IP is found, every caller shares the `unknown` key. That fails safe, but check your host's headers in production.

## Step 6: Rate-limit Server Actions

A Server Action is a public POST endpoint. Anyone can call it with a script, even if your form hides the button. So put the limit **inside** the action, not in the form. Server Actions can't set response headers or a status code, so return a friendly message instead.

*app/contact/actions.ts*

```ts
"use server";

import { clientIp } from "@/lib/client-ip";
import { fixedWindow, slidingWindow } from "@/lib/rate-limit";

export type ContactState = { ok: boolean; message: string } | null;

export async function sendContact(_prev: ContactState, form: FormData): Promise<ContactState> {
  const ip = await clientIp();

  // 3 messages per 10 minutes per IP, and 20 per day per IP.
  const [short, daily] = await Promise.all([slidingWindow(`contact:${ip}`, 3, 600), fixedWindow(`contact-day:${ip}`, 20, 86_400)]);
  const blocked = [short, daily].find((r) => !r.allowed);
  if (blocked) {
    const minutes = Math.ceil(blocked.resetMs / 60_000);
    return { ok: false, message: `Too many messages. Try again in ${minutes} minute${minutes === 1 ? "" : "s"}.` };
  }

  const email = String(form.get("email") ?? "").trim();
  const message = String(form.get("message") ?? "").trim();
  if (!email || message.length < 10) {
    return { ok: false, message: "Please add your email and a message." };
  }

  // ...send the email or save the message here...
  return { ok: true, message: "Thanks! We'll be in touch." };
}
```

Use it with `useActionState` in a Client Component, exactly as in [sending email from Next.js](https://cloudhike.dev/guides/send-email-nextjs#contact-form). For signed-in actions, key by the user id instead, for example `fixedWindow("post:" + userId, 10, 60)`.

### Should the limit go in proxy.ts?

You can. `proxy.ts` runs before every matched request, in the Node.js runtime, so `ioredis` works there. But it adds a Redis call to every request it matches, including pages and assets if your matcher is broad. Most apps are better off limiting the few routes and actions that need it, with limits tuned to each one.

## Production checklist

- Add `REDIS_URL` to your host's environment variables.
- Every rate limit key gets an expiry. CloudHike Redis uses the `noeviction` policy, so keys without one stay until you delete them. See the [Redis docs](https://cloudhike.dev/docs/redis#patterns).
- Decide what happens when Redis is down. Wrap the check in `try/catch` and allow the request (fail open) for normal routes. Refuse it (fail closed) for login and other attack targets.
- Check how your host sets `x-forwarded-for`, and set `TRUSTED_PROXIES` to match.
- Return `Retry-After` on every `429`, and make your own client code wait that long before it retries.
- Log or count `429`s, so you notice when a limit is too tight for real users.
- Watch memory on the Redis card. Sizes and prices are on the [pricing page](https://cloudhike.dev/pricing).

*Fail open on Redis errors*

```ts
import { fixedWindow, type RateLimitResult } from "@/lib/rate-limit";

export async function safeLimit(id: string, limit: number, windowSec: number): Promise<RateLimitResult> {
  try {
    return await fixedWindow(id, limit, windowSec);
  } catch (err) {
    console.error("Rate limit check failed, allowing request", err);
    return { allowed: true, limit, remaining: limit, resetMs: windowSec * 1000 };
  }
}
```

## FAQ

### How do I rate limit API routes in Next.js?

Count requests per caller in a shared store such as Redis, and check the count at the start of each route handler. When the caller is over the limit, return a 429 response with a Retry-After header. In-memory counters do not work on serverless hosts, because each instance keeps its own count.

### Can I rate limit Next.js Server Actions?

Yes. Call the limiter at the top of the action, keyed by the user id or the IP address from the x-forwarded-for header. Server Actions cannot return a 429 status, so return an error message for the form to show.

### What is the difference between a fixed window and a sliding window rate limit?

A fixed window resets a counter at fixed times, such as every minute. It is cheap, but a burst around the reset can let through up to twice the limit. A sliding window counts the requests in the last N seconds at every moment, so it is smooth and exact, but it stores one entry per request.

### Is x-forwarded-for safe to use for rate limiting?

Only the entries your own proxies or host added. Clients can send any x-forwarded-for value they like, so taking the left-most entry lets an attacker pick a new key on every request. Count from the right, by the number of proxies you trust.

### Do I need Upstash or another package to rate limit Next.js?

No. Any Redis works, and the limiter is a short Lua script run with ioredis. Packages add more algorithms and analytics, but the core idea is the same: count per key, with an expiry.
