Skip to main content
Protect Hono routes with API keys. The code works on Node, Bun, Deno, and Cloudflare Workers. Only how you read the root key changes. Use the @unkey/hono middleware to have verification handled for you, or write a few lines with @unkey/api to control every response.
You need a root key with the permissions listed on this page. Create one in the dashboard under Settings > Root Keys. See Permission reference for every permission.
1

Create a root key and a keyspace

In the dashboard, go to Settings > Root Keys and create a root key with api.*.create_api, api.*.create_key, and api.*.verify_key. Put it in your server’s UNKEY_ROOT_KEY environment variable. Never send it to a browser or mobile app.Then create a keyspace, which holds your keys. Use Keyspaces (APIs) in the dashboard, or apis.createApi:
create a keyspace
Keep the data.apiId from the response. You need it to create keys. See Root keys for more on root keys.
2

Install the SDK

@unkey/hono (version ) is the middleware. @unkey/api (version ) is the client for creating keys and for the hand-written version.
3

Create a key for a user

Create a key from your backend when a user signs up or asks for one. externalId links the key to the user, so verification tells you who’s calling. meta comes back on every verification. You get data.key only once: show it to the user and store only data.keyId.
Every field is described in Creating keys.
4

Verify the key in a middleware

With @unkey/hono, the unkey() middleware reads the bearer token, it, and stores the result in the unkey context variable. handleInvalidKey decides the response for a bad key.onError only runs for unexpected responses, such as a 502 from a proxy. A rejected root key, a throttled request, a 500, or a network failure is thrown instead, so catch those in Hono’s app.onError if you want one response for every authentication failure.
Keep next() outside the try. Otherwise an error in a route handler is caught here and answered as an authentication failure.The middleware also takes permissions (a permission query every key must pass), tags, and getKey (for keys sent somewhere other than the Authorization header).
5

Handle the outcome codes

keys.verifyKey returns HTTP 200 for every outcome. Check data.valid, then data.code for the reason, and return the matching status from your API:Remaining credits are in data.credits, and each checked rate limit is in data.ratelimits with remaining and reset. The call only fails with an HTTP error (which the SDKs throw) when the call itself is wrong, such as a bad root key or a malformed body. See Verifying keys for every field.
6

Next steps

Verifying keys

Every request field, the order of checks, and every response field.

Credits and refill

Meter usage per key and refill balances on a schedule.

Cookbook

Copy-ready recipes for rate limits, billing, and subscription tiers.
Last modified on September 29, 2026