What you’ll build
A Hono app with API key authentication using the@unkey/hono middleware. All routes (or specific ones) require a valid API key.
Time to complete: ~5 minutes
Prerequisites
- Unkey account (free)
- Keyspace created in your Unkey dashboard
- Node.js 18+ or Bun
Want to skip ahead?
Clone the complete example and run it locally.
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, you can apply the middleware to specific paths:src/index.ts
What’s in the context?
After verification,c.get("unkey") contains:
Middleware options
Next steps
Add rate limiting
Limit requests per key
Set usage limits
Cap total requests per key
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: Usewrangler secretorwrangler.toml
Deploying to Cloudflare Workers?
Deploying to Cloudflare Workers?
Use wrangler secrets for your root key:Then access it from your Hono bindings. Add
UNKEY_ROOT_KEY to your Bindings type and read it via ctx.env.UNKEY_ROOT_KEY or env.UNKEY_ROOT_KEY in your handlers.