🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Server Rendering••By Komal Nakrani

Astro Rate Limit: Throttle Endpoints and Actions

Add an Astro rate limit to endpoints and actions: a fixed-window limiter keyed by client IP, 429 responses with Retry-After, and shared storage for serverless.

#Astro#Server Rendering#Astro Rate Limit#Security#Endpoints

To rate limit Astro endpoints, count requests per client (usually by context.clientAddress) within a time window, and return a 429 Too Many Requests response with a Retry-After header once the count passes your limit. An in-memory counter works on a single long-running server such as the Node adapter; serverless and edge deployments need shared storage such as Redis or Cloudflare KV, or the platform’s own rate limiting rules.

Key Takeaways

  • Rate limiting only applies to on-demand routes; static pages are served by the CDN.
  • Key limits by client IP, or by user ID when the visitor is signed in.
  • Return 429 with Retry-After, or throw ActionError with code TOO_MANY_REQUESTS in actions.
  • In-memory limits reset on every cold start and are per instance; use shared storage in production serverless.

A small fixed-window limiter

// src/lib/rate-limit.ts
type Bucket = { count: number; resetAt: number };
const buckets = new Map<string, Bucket>();

// ponytail: in-memory, per instance; swap for Redis/KV when running more than one server
export function rateLimit(key: string, limit: number, windowMs: number) {
  const now = Date.now();
  let bucket = buckets.get(key);
  if (!bucket || bucket.resetAt <= now) {
    bucket = { count: 0, resetAt: now + windowMs };
    buckets.set(key, bucket);
  }
  bucket.count++;
  if (buckets.size > 10_000) {
    for (const [k, b] of buckets) if (b.resetAt <= now) buckets.delete(k);
  }
  return {
    ok: bucket.count <= limit,
    remaining: Math.max(0, limit - bucket.count),
    retryAfter: Math.ceil((bucket.resetAt - now) / 1000),
  };
}

A fixed window counts requests from the first hit until the window ends, then starts again. It is simple and good enough for contact forms, login attempts and small APIs. The cleanup loop stops the map from growing forever.

Use it in an endpoint

// src/pages/api/contact.ts
import type { APIRoute } from 'astro';
import { rateLimit } from '../../lib/rate-limit';

export const prerender = false;

export const POST: APIRoute = async ({ request, clientAddress }) => {
  const rl = rateLimit(`contact:${clientAddress}`, 5, 60_000);
  if (!rl.ok) {
    return new Response('Too many requests', {
      status: 429,
      headers: { 'Retry-After': String(rl.retryAfter) },
    });
  }

  const data = await request.formData();
  // ...send the message
  return new Response(null, { status: 204 });
};

This allows five submissions per minute per IP. Prefix the key with the route name so limits for different endpoints do not share a counter. clientAddress only exists on on-demand routes; see getting the visitor’s IP in Astro for how it behaves behind proxies.

Use it in an action

Actions can throw a typed error that the client receives with status 429:

// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
import { rateLimit } from '../lib/rate-limit';

export const server = {
  subscribe: defineAction({
    accept: 'form',
    input: z.object({ email: z.email() }),
    handler: async ({ email }, context) => {
      const rl = rateLimit(`subscribe:${context.clientAddress}`, 3, 10 * 60_000);
      if (!rl.ok) {
        throw new ActionError({
          code: 'TOO_MANY_REQUESTS',
          message: `Try again in ${rl.retryAfter} seconds.`,
        });
      }
      // ...add to your list
      return { ok: true };
    },
  }),
};

Our Astro Actions guide shows how to display the error message on the form.

Rate limit every API route at once

To cover all routes under /api/, run the check in middleware instead:

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { rateLimit } from './lib/rate-limit';

export const onRequest = defineMiddleware((context, next) => {
  if (context.isPrerendered || !context.url.pathname.startsWith('/api/')) return next();
  const rl = rateLimit(`api:${context.clientAddress}`, 60, 60_000);
  if (!rl.ok) {
    return new Response('Too many requests', { status: 429, headers: { 'Retry-After': String(rl.retryAfter) } });
  }
  return next();
});

Serverless and edge deployments

On Vercel, Netlify Functions or Cloudflare Workers, each request may hit a different instance, and instances start fresh. An in-memory map then limits almost nothing. Options:

  • Shared store. Keep counters in Redis (for example a hosted Redis service), Cloudflare KV or Durable Objects. Replace the Map with an atomic increment and an expiry.
  • Platform rules. Cloudflare’s WAF rate limiting rules and similar firewall features block abusive clients before your code runs, which also saves function invocations.
  • Both. Coarse platform limits for floods, precise per-user limits in code.

Rate limiting is one item on our Astro security checklist. The Astro themes in our catalog are static, so add an adapter first if you need limited endpoints.

FAQ

How do I rate limit an API endpoint in Astro?

Count requests per client IP in a time window inside the endpoint or middleware, and return 429 with a Retry-After header when the count exceeds the limit. Use shared storage if you run more than one server instance.

Does Astro have built-in rate limiting?

No. Astro limits request body sizes for actions, but request rate limiting is up to your code or your hosting platform’s firewall.

Why does my in-memory rate limiter not work on Vercel?

Serverless functions run in many short-lived instances, each with its own memory. Counters reset and are not shared, so use Redis, KV or the platform’s rate limiting instead.

What status code should a rate limit return?

429 Too Many Requests, with a Retry-After header giving the number of seconds until the client can try again.