Skip to main content

Prerequisites

  • Created your Unkey account
  • Created an Unkey root key with the following permissions:
    • ratelimit.*.create_namespace - to create namespaces
    • ratelimit.*.limit - to check rate limits
1

Create Next.js Application

Run the following command to init your Next.js project
npx create-next-app@latest
2

Install

Now install the @unkey/ratelimit package
npm install @unkey/ratelimit
3

Add Root Key to env

Add your root key to your .env file
UNKEY_ROOT_KEY="YOUR_KEY"
4

Creating a protected route

Create a new route and add the following code
/app/protected/route.ts
import { NextResponse } from 'next/server';
import { Ratelimit } from "@unkey/ratelimit";


if (!process.env.UNKEY_ROOT_KEY) {
  throw new Error("UNKEY_ROOT_KEY environment variable is not set");
}

const limiter = new Ratelimit({
  namespace: "next-example",
  limit: 2,
  duration: "30s",
  rootKey: process.env.UNKEY_ROOT_KEY
});

export const POST = async (req: Request) => {
  // Extract user identifier from request headers
  // Use any identifier: userId, visitorId, IP address, etc.
  const identifier = req.headers.get('x-user-id') ?? 'anonymous';

  const ratelimit = await limiter.limit(identifier);

  if (!ratelimit.success) {
    return NextResponse.json(
      { error: "Please try again later" },
      { status: 429 }
    );
  }

  return NextResponse.json({ message: "Hello!" });
};
5

Running it

npm run dev
6

Try it out

Test your ratelimited endpoint:
curl -XPOST 'http://localhost:3000/protected' \
  -H "x-user-id: test-user"
You will need to curl a few times to see the ratelimiting error. Once you do, you, you will need to wait to perform the action again.

What is next?

Now that you’ve seen the power of Unkey ratelimiting, check out some resources below to continue your journey.