Skip to main content
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
Never expose UNKEY_ROOT_KEY to the client. It should only be used in server-side code.
Last modified on May 6, 2026