Skip to main content

Hono

Add API key authentication to your Hono application using Unkey middleware. Protect routes with automatic key verification on requests.
3 min read

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#

Want to skip ahead?

Clone the complete example and run it locally.

Create a Hono app#

Choose your preferred runtime (Node.js, Bun, Cloudflare Workers, etc.)

Install the Unkey middleware#

Add your root key#

Create a .env file:

.env
Note
The Hono middleware verifies keys directly against your root key.

Add the middleware#

Update src/index.ts:

src/index.ts

Run your app#

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, you can apply the middleware to specific paths:

src/index.ts

What's in the context?#

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

FieldTypeDescription
validbooleanWhether the key passed all checks
codestringStatus code (VALID, NOT_FOUND, RATE_LIMITED, etc.)
keyIdstringThe key's unique identifier
namestring?Human-readable name of the key
metaobject?Custom metadata associated with the key
expiresnumber?Unix timestamp (in milliseconds) when the key will expire. (if set)
creditsnumber?Remaining uses (if usage limits set)
enabledbooleanWhether the key is enabled
rolesstring[]?Named role(s) assigned to the key, each representing a set of permissions
permissionsstring[]?List of individual permissions granted to the key
identityobject?Identity info if externalId was set when creating the key
ratelimitsobject[]?Rate limit states (if rate limiting configured)

Middleware options#

Next steps#

Troubleshooting#

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?
  • 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
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.