Overview
This guide covers everything you need to protect your Hono application with Unkey using the official@unkey/hono middleware. Hono works everywhere: Node.js, Bun, Cloudflare Workers, and more.
What you’ll learn:
- Quick setup with
@unkey/hono - Protecting specific routes
- Custom error handling
- Permission-based access
- Deployment patterns
Prerequisites
- Unkey account (free)
- API created in your Unkey dashboard
- Node.js 18+ or Bun
Quick Start
1
Create a Hono app
2
Install the Unkey middleware
3
Add your root key
Create a
.env file:.env
The Hono middleware verifies keys directly against your root key.
4
Add the middleware
Update
src/index.ts:src/index.ts
5
Run your app
6
Test it
Create a test key in your Unkey dashboard, then:You should see:Without a key, you’ll get a 401:
Test with valid key
Test without key
Protecting Specific Routes
Instead of protecting all routes, apply middleware to specific paths:src/index.ts
Middleware Options
Customize the middleware behavior:Custom Key Extraction
By default, the middleware looks forAuthorization: Bearer <token>. You can customize this:
Permission-Based Routes
Require specific permissions for certain routes:src/index.ts
Context Data
After verification,c.get("unkey") contains:
Deployment
Node.js
Bun
Cloudflare Workers
For Cloudflare Workers, use wrangler secrets:src/index.ts
Next Steps
Add rate limiting
Limit requests per key
Set usage limits
Limit requests with credit-based billing
Add permissions
Fine-grained access control
Hono SDK Reference
Full middleware 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 header format:
Authorization: Bearer YOUR_KEY
Environment variables not loading?
Environment variables not loading?
- For Node.js: Install
dotenvand addimport 'dotenv/config'at the top - For Bun:
.envis loaded automatically - For Cloudflare Workers: Use
wrangler secretorwrangler.toml