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
Add your root key
Create a
.env file:.env
The Hono middleware verifies keys directly against your root key.
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:
| 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 |
credits | number? | Remaining uses (if usage limits set) |
enabled | boolean | Whether the key is enabled |
roles | string[]? | Named role(s) assigned to the key |
permissions | string[]? | List of individual permissions |
identity | object? | Identity info if externalId was set |
ratelimits | object[]? | Rate limit states (if configured) |
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