# API Keys in Your Routes

> Accept customer API keys on your own /api endpoints with authorizeApiKey: scope, sessionless path, owner-filtered service and the requests customers send.

*Canonical: https://makerkit.dev/docs/void-cloudflare/mcp-server/api-keys*

---

The same keys that reach the MCP server can authenticate your own JSON endpoints. The kit ships no REST endpoint for them: you add the ones your product needs. Only `API_ACCESS_KEYS` has to be on ([Turn It On](./overview#turn-it-on)).

Customers create and revoke keys on **Settings → API keys** ([API Keys](../account/api-keys)).

## Checklist

To accept keys on a new route, in this order:

1. [Add a scope](#1-add-a-scope).
2. [Create the route](#2-create-the-route) with the generator.
3. [Mark the path sessionless](#3-mark-the-path-sessionless).
4. [Authorize in the handler](#4-authorize-in-the-handler) with `authorizeApiKey`.
5. [Filter by the account](#5-filter-by-the-account).
6. [Test it](#6-test-it).

When you finish, a customer can call the route with their key and sees only their own account's rows.

## How Customers Call It

```bash
curl https://your-app.com/api/projects \
  -H "x-api-key: $MY_APP_API_KEY"
```

- The key goes in `x-api-key` only. A request that also sends `Authorization`, or puts a key, `api_key` or `access_token` in the URL, is refused.
- Every request reads live state: a revoked or expired key fails on the next call.
- Refusals are JSON `{ "code": … }` with the HTTP status ([Request Error Codes](../authentication/api-access#request-error-codes)). Over the limit: `429` with `Retry-After`.

## 1. Add a Scope

Add it to `apiAccessScopes` in `apps/web/config/api-access.config.server.ts`, as in [Adding Tools](./adding-tools#1-add-a-scope). One catalogue serves routes and MCP tools.

## 2. Create the Route

```bash
pnpm kit:generate route projects --methods get --public
```

Replace the generated `{ ok: true }` body with the handler in [Authorize in the Handler](#4-authorize-in-the-handler).

**Why `--public`:** it skips the generated session check. A key route must not read the browser session too, because one request could carry a cookie and a key for different users.

## 3. Mark the Path Sessionless

Add the **exact** path to `SESSIONLESS_PATHS` in `apps/web/lib/sessionless-paths.ts`:

```ts
export const SESSIONLESS_PATHS = new Set([
  // ...
  '/api/mcp',
  '/api/projects',
]);
```

**Why:** without it, the session middleware touches the database before the key's rate limit runs.

Never add a prefix.

## 4. Authorize in the Handler

```ts
// apps/web/routes/api/projects.ts
import { defineHandler } from 'void';

import { authorizeApiKey } from '#/lib/api-access.server.ts';
import { findAccountProjects } from '#/db/projects.server.ts';

export const GET = defineHandler(async (c) => {
  const { account } = await authorizeApiKey({
    c,
    requiredScopes: ['projects:read'],
  });

  return { projects: await findAccountProjects(account) };
});
```

Call `authorizeApiKey` first, before reading a body. It checks the rate limits, the key, its owner, the scopes and your [policies](../authentication/api-access#customer-policies), and throws the HTTP refusal itself. It returns:

```ts
{
  keyId,                                    // the key's id: for audit, never the secret
  account,                                  // { kind: 'personal' | 'organization', id }
  scopes,                                   // the key's effective scopes today
}
```

## 5. Filter by the Account

- **The query uses `account` as the owner,** as in [Write the Query and Service](./adding-tools#2-write-the-query-and-service). Move real logic into a `*.service.ts`.
- **Ignore any user, account or organization id in the request.**
- **Check every resource id the caller sends** against `account.id`.

**For a write** (`POST`, `PUT`, `DELETE`):

1. Call `authorizeApiKey` inside that handler too.
2. Validate the body with `defineHandler.withValidator` ([API Routes](../development-guide/api-routes)).
3. Record audit with `recordSystemAudit`.

Server clients send no `Origin`, so the cross-site check doesn't block them.

## 6. Test It

1. Create a key with `projects:read` and `curl` the route: `200`.
2. No header: `401 API_KEY_REQUIRED`. A key without the scope: `403 INSUFFICIENT_SCOPE`. Revoked: `401 INVALID_API_KEY`.
3. Personal and organization keys each see only their own rows.

`apps/web/lib/__tests__/api-key-authorization.server.test.ts` covers the helper's refusals.
