Skip to main content
@unkey/nextjs (version ) exports withUnkey, a wrapper for App Router route handlers that the API key before your code runs. Unlike the Hono middleware, it rejects invalid keys by default, so your handler only runs for valid keys.
You need a root key with the permissions listed on this page. Create one in the dashboard under Settings > Root Keys, and pass it as Authorization: Bearer <root key>. See Permission reference for every permission.

Install

Protect a route handler

app/api/hello/route.ts
The wrapper reads the bearer token from the authorization header and calls keys.verifyKey:
  • No key: it responds 401 {"error":"unauthorized"}.
  • Invalid key: it responds 401 Unauthorized.
  • Valid key: it puts the full result in req.unkey and runs your handler. The second context argument (route params) works as usual.
If the verify call gets an unexpected response, such as a 502 from a proxy, the wrapper logs it and responds 500 Internal Server Error. Other failures (a rejected root key, a throttled request, a 500, a connection failure or timeout) aren’t caught, so Next.js returns its own 500. To control that response, verify with @unkey/api directly.

Options

string
required
Root key used to call keys.verifyKey.
string
A permission query the key must satisfy for the verification to be valid.
string[]
Tags recorded with the verification for analytics filtering.
(req: NextRequest) => string | null | Response | NextResponse
Read the key yourself, for example new URL(req.url).searchParams.get("key"). Return a response to send it instead. Return null for the default 401.
(req: NextRequest, result: UnkeyContext) => Response | NextResponse | Promise<...>
Replace the default 401 Unauthorized for keys that verify as invalid. result.data.code says why.
(req: NextRequest, err: errors.APIError) => Response | NextResponse | Promise<...>
Replace the default logged error and 500. Only called for unexpected responses, not for the other failures described above.

Customize the responses

Next steps

Verifying keys

What the verification result contains.

@unkey/api

Create keys and call other endpoints from server code.
Last modified on September 29, 2026