> ## Documentation Index
> Fetch the complete documentation index at: https://unkey.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# @unkey/hono

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

> 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](https://unkey.com).

<Card icon="github" title="github.com/unkeyed/sdks/tree/main/hono" href="https://github.com/unkeyed/sdks/tree/main/hono" />

## Install

<CodeGroup>
  ```bash npm theme={"theme":"kanagawa-wave"}
   npm install @unkey/hono
  ```

  ```bash pnpm theme={"theme":"kanagawa-wave"}
   pnpm add @unkey/hono
  ```

  ```bash yarn theme={"theme":"kanagawa-wave"}
   yarn add @unkey/hono
  ```

  ```bash bun theme={"theme":"kanagawa-wave"}
   bun install @unkey/hono
  ```
</CodeGroup>

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](https://app.unkey.com/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")`.

```ts theme={"theme":"kanagawa-wave"}
import { Hono } from "hono";
import { type UnkeyContext, unkey } from "@unkey/hono";

const app = new Hono<{ Variables: { unkey: UnkeyContext } }>();

app.use(
  "*",
  unkey({
    rootKey: process.env.UNKEY_ROOT_KEY!,
  }),
);

app.get("/somewhere", (c) => {
  // access the unkey response here to get metadata of the key etc
  const keyInfo = c.get("unkey");

  return c.text(`Hello ${keyInfo.identity?.externalId ?? "user"}!`);
});
```

## Customizing the middleware

### Header

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.

```ts theme={"theme":"kanagawa-wave"}
app.use(
  "*",
  unkey({
    rootKey: process.env.UNKEY_ROOT_KEY!,
    getKey: (c) => c.req.header("x-api-key"),
  }),
);
```

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

```ts theme={"theme":"kanagawa-wave"}
c.json({ error: "unauthorized" }, { status: 401 });
```

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

```ts theme={"theme":"kanagawa-wave"}
app.use(
  "*",
  unkey({
    rootKey: process.env.UNKEY_ROOT_KEY!,
    getKey: (c) => {
      const key = c.req.header("x-api-key");
      if (!key) {
        return c.text("missing api key", 401);
      }
      return key;
    },
  }),
);
```

### Handle errors

```ts theme={"theme":"kanagawa-wave"}
app.use(
  "*",
  unkey({
    rootKey: process.env.UNKEY_ROOT_KEY!,
    onError: (c, err) => {
      // handle error
      return c.text("unauthorized", 401);
    },
  }),
);
```

### 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](/platform/apis/keys#verify-a-key) for the full `response` object.

```ts theme={"theme":"kanagawa-wave"}
app.use(
  "*",
  unkey({
    rootKey: process.env.UNKEY_ROOT_KEY!,
    handleInvalidKey: (c, result) => {
      return c.json(
        {
          error: "unauthorized",
          reason: result.code,
        },
        401,
      );
    },
  }),
);
```

### Pass verification tags

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

```ts theme={"theme":"kanagawa-wave"}
(c, next) =>
  unkey({
    rootKey: process.env.UNKEY_ROOT_KEY!,
    tags: [`path=${c.req.path}`],
  })(c, next);
```
