Prerequisites

Skip the tutorial

We also have a Next.js example ready to deploy on Vercel.

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/nextjs package

  npm install @unkey/nextjs
3

Creating a protected route

Create a new route and add the following code

/app/protected/route.ts
import { NextRequestWithUnkeyContext, withUnkey } from '@unkey/nextjs';
import { NextResponse } from 'next/server';

export const POST = withUnkey(async (req) => {
  if (!req.unkey.valid) {
    return new NextResponse('unauthorized', { status: 403 });
  }

  // Process the request here
  // You have access to the verification response using `req.unkey`
  console.log(req.unkey);
  return new NextResponse('Your API key is valid!');
});
4

Running it

  bun run dev
5

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' \
  -H "Authorization: Bearer <KEY>"

It should return "Your API key is valid!" and log out {"keyId":"key_id","valid":true,"meta":{},"enabled":true,"permissions":[],"code":"VALID"} and potentially more information about the key, depending on what you set up in the dashboard.

What is next?

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