Overview
This guide covers everything you need to protect your Next.js application with Unkey, including App Router API routes, Pages Router endpoints, and reusable middleware patterns. What you’ll learn:- Quick setup with
@unkey/nextjswrapper - Manual verification for full control
- Reusable middleware patterns
- Permission-based access control
- Best practices for production
Prerequisites
- Unkey account (free)
- API created in your Unkey dashboard
- Next.js 13+ (App Router or Pages Router)
- Node.js 18+
Quick Start with @unkey/nextjs
The fastest way to get started is with the official Next.js wrapper.1
Install the SDK
2
Add your root key
Get a root key from Settings → Root Keys and add it to your environment:
.env.local
3
Create a protected App Router route
app/api/protected/route.ts
4
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.Pages Router
For Next.js Pages Router, wrap your API handler:pages/api/protected.ts
Custom Key Extraction
By default,withUnkey looks for a Bearer token in the Authorization header. Customize this:
Custom Error Handling
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
app/api/users/route.ts
Permission-Based Access Control
Require specific permissions for sensitive endpoints:app/api/admin/route.ts
Verification Response Data
After verification,req.unkey.data (or data in manual mode) contains:
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