Skip to main content

Next.js API Routes

Protect your Next.js API routes with Unkey API key authentication. Copy-paste recipe for verifying keys in App Router route handlers.
1 min read

Two approaches: use the @unkey/nextjs wrapper for simplicity, or manual verification for full control.

The simplest way to protect Next.js API routes.

Install#

App Router#

app/api/protected/route.ts

Pages Router#

pages/api/protected.ts

Custom key extraction#

By default, withUnkey looks for a Bearer token in the Authorization header. Customize this:

Custom error handling#


Option 2: Manual Verification#

For full control over the authentication flow.

app/api/protected/route.ts

Reusable Middleware Pattern#

Create a helper for consistent auth across routes:

lib/auth.ts

Use it:

app/api/users/route.ts

Check Permissions#

Require specific permissions for sensitive endpoints:

app/api/admin/route.ts

Environment Setup#

.env.local
Warning

Never expose UNKEY_ROOT_KEY to the client. It should only be used in server-side code.