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 minutesPrerequisites
- Unkey account (free)
- API created in your Unkey dashboard
Add your root key
Get a root key from Settings → Root Keys and add it to your environment:
.env.local
Create a protected route
Create a new API route that requires authentication:
app/api/protected/route.ts
Test it
First, create a test key in your Unkey dashboard, then:You should see:Now try without a key:You’ll get a
Test with valid key
Test without key
401 Unauthorized response.What’s in req.unkey?
After verification, req.unkey.data contains:
| Field | Type | Description |
|---|---|---|
valid | boolean | Whether the key passed all checks |
code | string | Status code (VALID, NOT_FOUND, RATE_LIMITED, etc.) |
keyId | string | The key’s unique identifier |
name | string? | Human-readable name of the key |
meta | object? | Custom metadata associated with the key |
expires | number? | Unix timestamp (in milliseconds) when the key will expire. (if set) |
credits | number? | Remaining uses (if usage limits set) |
enabled | boolean | Whether the key is enabled |
roles | string[]? | Permissions attached to the key |
permissions | string[]? | Permissions attached to the key |
identity | object? | Identity info if externalId was set when creating the key |
ratelimits | object[]? | Rate limit states (if rate limiting configured) |
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
Add rate limiting
Limit requests per key
Set usage limits
Cap total requests per key
Add permissions
Fine-grained access control
Next.js SDK Reference
Full SDK documentation
Troubleshooting
Getting 401 even with a valid key?
Getting 401 even with a valid key?
- Ensure the key hasn’t expired or been revoked
- Verify the
Authorizationheader format:Bearer YOUR_KEY(note the space) - Check that your root key has the
verify_keypermission
Environment variable not loading?
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

