Skip to main content

What you’ll build

A Next.js API route that limits each user to a set number of requests per time window. Excess requests get rejected with a 429. Time to complete: ~5 minutes

Prerequisites

1

Create a Next.js app

Skip if you have an existing project.
2

Install the SDK

3

Add your root key

Create or update .env.local:
.env.local
Never commit your root key. Add .env.local to .gitignore.
4

Create a rate-limited route

app/api/protected/route.ts
5

Run your app

6

Test it

First 10 requests return 200. Requests 11+ return 429:
Wait 60 seconds and the limit resets.

What’s in the response?

limiter.limit() returns:

Choosing an identifier

The identifier determines who gets rate limited. Common choices:

Creating a reusable limiter

For cleaner code, create a utility:
lib/ratelimit.ts
Then use in routes:
app/api/login/route.ts

Next steps

How it works

Understand the rate limiting architecture

Per-user overrides

Give specific users higher limits

SDK Reference

All configuration options

Add API key auth

Combine rate limiting with authentication

Troubleshooting

  • Check that UNKEY_ROOT_KEY is set in .env.local - Verify your root key has ratelimit.*.limit permission - Make sure you’re using the same identifier each request - Restart the dev server after changing .env.local
Create multiple Ratelimit instances with different namespaces and limits. Each namespace tracks limits independently.
Last modified on May 21, 2026