Prerequisites

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";

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

export const POST = (async (req) => {
  const identifier = getUserId(); // or ip or anything else you want
  const ratelimit = await unkey.limit(identifier)
  if (!ratelimit.success){
   return new NextResponse("Please try again later", {status: 429});
  }

  return new NextResponse('Hello!');
});
5

Running it

  bun run dev
6

Try it out

Go to https://app.unkey.com and create a new key. Then verify it with our new server:

curl -XPOST 'http://localhost:3000/protected'

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, check out some resources below to continue your journey.

Was this page helpful?