Skip to main content

@unkey/hono

Use the @unkey/hono middleware to authenticate API keys in your Hono.js application. Automatic key verification with typed context injection.
2 min read

Hono - [炎] means flame🔥 in Japanese - is a small, simple, and ultrafast web framework for the Edges. It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Vercel, Netlify, Lagon, AWS Lambda, Lambda@Edge, and Node.js.

@unkey/hono offers a middleware for authenticating API keys with unkey.

github.com/unkeyed/sdks/tree/main/hono

Install#

Let's dive straight in. The minimal setup looks like this. You need a root key with permission to verify keys. Go to /settings/root-keys and create a key with the verify_key permission.

By default it tries to grab the API key from the Authorization header and then verifies it with Unkey. The result of the verification will be written to the context and can be accessed with c.get("unkey").

Customizing the middleware#

By default the middleware tries to grab the API key from the Authorization header. You can change this by passing a custom header name to the middleware.

If the header is missing the middleware will return a 401 error response like this:

To customize the response in case the header is missing, just return a response from the getKey function.

Handle errors#

Handle invalid keys#

By default the middleware will not do anything with the verification response other than writing it to the context. However you most likely would like to just return a 401 response if the key is invalid and not continue with the request.

To do this you can pass a handleInvalidKey handler to the middleware. See the key verification docs for the full response object.

Pass verification tags#

You can pass tags to the verification request to help you filter keys later.