Skip to main content

Next.js

Add API key authentication to your Next.js API routes using Unkey. Verify keys in route handlers to protect your server-side endpoints.
3 min read

What you'll build#

A Next.js API route that requires a valid API key on every request. Invalid or missing keys get rejected with a 401.

Time to complete: ~5 minutes

Prerequisites#

Create a Next.js app#

Skip this if you have an existing project.

Install the Unkey SDK#

Add your root key#

Get a root key from Settings → Root Keys and add it to your environment:

.env.local
Warning
Never commit your root key. Add .env.local to .gitignore.

Create a protected route#

Create a new API route that requires authentication:

app/api/protected/route.ts
Tip

The withUnkey wrapper handles key extraction, verification, and error responses automatically. Invalid keys never reach your handler.

Start your server#

Test it#

First, create a test key in your Unkey dashboard, then:

Test with valid key

You should see:

Now try without a key:

Test without key

You'll get a 401 Unauthorized response.

What's in req.unkey?#

After verification, req.unkey.data contains:

FieldTypeDescription
validbooleanWhether the key passed all checks
codestringStatus code (VALID, NOT_FOUND, RATE_LIMITED, etc.)
keyIdstringThe key's unique identifier
namestring?Human-readable name of the key
metaobject?Custom metadata associated with the key
expiresnumber?Unix timestamp (in milliseconds) when the key will expire. (if set)
creditsnumber?Remaining uses (if usage limits set)
enabledbooleanWhether the key is enabled
rolesstring[]?Permissions attached to the key
permissionsstring[]?Permissions attached to the key
identityobject?Identity info if externalId was set when creating the key
ratelimitsobject[]?Rate limit states (if rate limiting configured)
Note

data.meta is your custom key metadata (set via meta when creating the key). This is different from the response's top-level meta which contains requestId.

Next steps#

Troubleshooting#

Getting 401 even with a valid key?
  • Ensure the key hasn't expired or been revoked - Verify the Authorization header format: Bearer YOUR_KEY (note the space) - Check that your root key has the verify_key permission
Environment variable not loading?
  • Restart your dev server after adding .env.local - Make sure the file is in your project root - Check for typos in the variable name