Skip to main content

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

Quick Start

1

Create a Hono app

Choose your preferred runtime when prompted.
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:
Test with valid key
You should see:
Without a key, you’ll get a 401:
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 for Authorization: Bearer <token>. You can customize this:

Permission-Based Routes

Require specific permissions for certain routes:
src/index.ts
Or verify permissions during the initial key check:

Context Data

After verification, c.get("unkey") contains:

Deployment

Node.js

Bun

Cloudflare Workers

For Cloudflare Workers, use wrangler secrets:
Update your worker to read from env:
src/index.ts
Deploy:

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

  • Ensure the key hasn’t expired or been revoked
  • Verify the header format: Authorization: Bearer YOUR_KEY
  • For Node.js: Install dotenv and add import 'dotenv/config' at the top
  • For Bun: .env is loaded automatically
  • For Cloudflare Workers: Use wrangler secret or wrangler.toml