---
title: API tokens
description: Bearer tokens for scripts, CLIs and MCP clients.
---

# API tokens

```ts
createAuth({ /* … */ tokens: { prefix: "leads" } }); // tokens look like leads_…
```

## Create and manage (settings page)

```ts
const created = await auth.tokens.create({ name: "CLI", scopes: ["deals:read"], expiresInDays: 90 });
// { ok: true, token: "leads_…", apiToken: { id, name, prefix, scopes, … } }
```

Show `token` once. Only its SHA-256 hash is stored. Creating a token needs a recent sign-in or `{ password }`, and e-mails the user a notice.

```ts
await auth.tokens.list();          // never includes the token itself
await auth.tokens.revoke({ id });
```

Options: `scopes` (strings you define), `expiresInDays` (1–3650, default never), `workspaceId` (ties the token to one workspace).

## Use a token

Clients send `Authorization: Bearer leads_…`. `auth.user()` and `auth.session()` accept it like a cookie:

```ts
// src/routes/api/deals.ts
GET: async ({ request }) => {
  const current = await auth.withRequest(request).session();
  if (!current) return new Response("Unauthorized", { status: 401 });
  if (!current.scopes?.includes("deals:read")) return new Response("Forbidden", { status: 403 });
  return Response.json(await listDeals(current.user.id));
},
```

- `session.method` is `"token"`, and `scopes` holds the token's scopes.
- `session.workspaceId` is the token's workspace, or null.
- A token can read: `user()`, `session()`, and the workspace reads (`requireMember`, `current`, `list`, `members`, `invites`), only in its own workspace when it has one.
- A token cannot change anything through the package: account, sessions, 2FA, tokens and every workspace change return `forbidden`. Your own API routes decide what a token may do in your app.
- The package does not check `scopes`. Check them in your routes.
- A password reset and `auth.users.setPassword` delete all of the user's tokens.

## MCP servers

An MCP server over HTTP can use the same check: read the bearer token, and answer 401 when `session()` is null. OAuth 2.1 for MCP clients is planned as a separate module.
