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

# useToken

> Fetch and auto-refresh a workspace-scoped embed token from your backend.

`useToken` is the sole client-side token acquisition hook. It `GET`s your token endpoint (default `/api/aiql`), stores the JWT, and refreshes it about 30 seconds before expiry.

## Import

```tsx theme={null}
import { useToken } from "@aiql.io/react";
```

## Usage

### Basic

```tsx theme={null}
const { token, status, error, reload, expiresAt } = useToken();
```

### Custom endpoint URL

```tsx theme={null}
const { token, status } = useToken("/api/custom-aiql-token");
```

### Handle status

```tsx theme={null}
function EmbedShell({ children }: { children: React.ReactNode }) {
  const { token, status, error, reload } = useToken();

  if (status === "loading" || status === "idle") {
    return <p>Loading…</p>;
  }

  if (status === "error" || !token) {
    return (
      <div>
        <p>{error ?? "Could not load embed token"}</p>
        <button type="button" onClick={reload}>
          Retry
        </button>
      </div>
    );
  }

  return <AiqlProvider token={token}>{children}</AiqlProvider>;
}
```

### Response shape from your endpoint

Your server should return JSON like:

```json theme={null}
{
  "ok": true,
  "token": "<jwt>",
  "expiresIn": 1800,
  "expiresAt": "2026-07-21T12:00:00.000Z"
}
```

The hook also accepts a raw `embedUrl` field and extracts the `token` query param when present.

## API Reference

### Parameters

| Parameter | Type     | Default       | Description                            |
| --------- | -------- | ------------- | -------------------------------------- |
| `url`     | `string` | `"/api/aiql"` | Endpoint that returns the embed token. |

### Return value

| Field       | Type                                        | Description                                            |
| ----------- | ------------------------------------------- | ------------------------------------------------------ |
| `token`     | `string \| null`                            | Current embed JWT, or `null` while loading / on error. |
| `status`    | `"idle" \| "loading" \| "ready" \| "error"` | Fetch lifecycle.                                       |
| `error`     | `string \| null`                            | Error message when `status` is `"error"`.              |
| `reload`    | `() => void`                                | Re-fetch the token immediately.                        |
| `expiresAt` | `string \| null`                            | ISO expiry time when known.                            |

See [Server handlers](/sdks/react/server/handlers) for the matching one-line backend.
