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

# Authentication

> How to authenticate with the PolarGrid API

# Authentication

All PolarGrid API requests require authentication using an API key.

## API Keys

API keys are created in the <a href="https://app.polargrid.ai/dashboard/settings?tab=api-keys" target="_blank">PolarGrid Console</a> and start with `pg_`.

### Creating a Key

1. Open the API Keys page — either click **Generate API Key** (or **Manage API Keys**) on the Dashboard Overview, or go to <a href="https://app.polargrid.ai/dashboard/settings?tab=api-keys" target="_blank">**Settings → API Keys**</a> in the sidebar
2. Click **Generate New Key**
3. Give it a descriptive name (e.g., "Production App", "Development")
4. Select permissions: `read-write` (default), `read-only`, or `admin`
5. Copy the key immediately — it won't be shown again

### Using Your Key

The SDKs handle authentication automatically — just pass your API key:

<CodeGroup>
  ```javascript JavaScript theme={null}
  const client = await PolarGrid.create({
    apiKey: 'pg_your_api_key',
  });
  ```

  ```python Python theme={null}
  client = await PolarGrid.create(api_key="pg_your_api_key")
  ```
</CodeGroup>

### Raw HTTP (cURL)

Send your `pg_*` API key directly to the edge. Pick a region with the autorouter (one request) or pin one.

```bash theme={null}
export API_KEY="pg_your_api_key"

# Option A — auto: ask the autorouter for the best edge for the caller.
# Returns {region, name, endpoint, ttl}. The endpoint is the actual base URL.
EDGE=$(curl -s https://autorouter.polargrid.ai/v1/route | jq -r .endpoint)

# Option B — pinned: hardcode a region instead
# EDGE="https://api.yto-01.edge.polargrid.ai"

# Call the edge directly with your API key.
curl -s -X POST "$EDGE/v1/chat/completions" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "qwen-3.5-27b", "messages": [{"role": "user", "content": "Hi"}]}'
```

<Note>
  The autorouter (`autorouter.polargrid.ai`) is a discovery endpoint — it serves `GET /v1/route` only. It does not proxy `/v1/chat/completions`, `/v1/models`, or any other inference traffic; POST against it is rejected by CloudFront with 403.
</Note>

## Playground vs API

The **Playground** in the Console uses your **real `pg_*` API key** — the same key from [Creating a Key](#creating-a-key) above. There is no separate "playground token".

<Steps>
  <Step title="Open the Playground">
    Click **Playground** in the Console sidebar.
  </Step>

  <Step title="Select your key">
    Pick a saved key from the Playground's API key dropdown, or paste one manually.
  </Step>
</Steps>

<Note>
  Under the hood, the Playground sends your API key directly to the nearest edge — the same flow as a raw cURL call.
</Note>

## Environment Variables

We recommend storing your API key in an environment variable:

```bash theme={null}
export POLARGRID_API_KEY="pg_your_api_key"
```

The SDKs automatically read from this variable:

<CodeGroup>
  ```javascript JavaScript theme={null}
  // No need to pass apiKey if POLARGRID_API_KEY is set
  const client = await PolarGrid.create();
  ```

  ```python Python theme={null}
  # No need to pass api_key if POLARGRID_API_KEY is set
  client = await PolarGrid.create()
  ```
</CodeGroup>

## Permission Levels

| Level        | Description                                                                                                 |
| ------------ | ----------------------------------------------------------------------------------------------------------- |
| `read-write` | Default for keys minted from the Console. Recommended for typical SDK / API usage.                          |
| `read-only`  | Same data-plane access today; intended for callers that should not mint LiveKit room tokens (`/v1/tokens`). |
| `admin`      | Same data-plane access plus the ability to mint LiveKit room tokens.                                        |

<Note>
  The inference endpoints (`/v1/chat/completions`, `/v1/completions`, `/v1/models`, `/v1/audio/*`) are not currently scope-gated — any active key can call them. Scope enforcement is presently scoped to `/v1/tokens`. Default to `read-write` unless you have a specific reason to narrow.
</Note>

## Troubleshooting Auth Errors

| HTTP Code | Error                            | Cause                                                                               | Fix                                                                                                                                                                        |
| --------- | -------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `401`     | `Invalid API key`                | API key not recognized, revoked, or deleted                                         | Verify the key is correct and active in the <a href="https://app.polargrid.ai/dashboard/settings?tab=api-keys" target="_blank">Console</a>. If revoked, generate a new key |
| `403`     | `{"Message": null}` or Forbidden | Request blocked by infrastructure (CloudFront/WAF) before reaching the auth service | Ensure you're using the correct endpoint URL and that your request includes valid headers. See [Regions](/guides/regions)                                                  |

## Advanced: Session Tokens (CLI / Management Plane)

For most users, the `pg_*` API key sent as `Authorization: Bearer pg_*` is all you need -- edge endpoints accept it directly and no token exchange is required.

The CLI and management-plane APIs (org management, key listing) use a separate session-token flow: the CLI exchanges a `pg_*` key via `POST https://auth.polargrid.ai/v1/auth/session` to obtain a short-lived JWT for those endpoints. This is handled automatically by `polargrid login` and is not needed for inference.

| Token         | Default Lifetime | Purpose                                       |
| ------------- | ---------------- | --------------------------------------------- |
| Session (JWT) | 24 hours         | Authorizes CLI / management-plane requests    |
| Refresh       | 30 days          | Extends the session without re-authenticating |

<Note>
  Edge inference endpoints (`/v1/chat/completions`, `/v1/audio/*`, `/v1/models`) do **not** require a JWT -- send your `pg_*` API key directly as a bearer token. The session-token flow above applies only to CLI and management-plane operations.
</Note>

## Security Best Practices

<Warning>
  Never commit API keys to source control or expose them in client-side code.
</Warning>

* Use environment variables for API keys
* Rotate keys periodically
* Use separate keys for development and production
* Revoke keys immediately if compromised

## CLI Authentication

The CLI supports two authentication methods:

### Browser Login (Interactive)

```bash theme={null}
polargrid login
```

Opens your browser for OAuth authentication. Best for development.

### API Key (CI/CD)

```bash theme={null}
export POLARGRID_API_KEY="pg_your_api_key"
polargrid test inference --region toronto --prompt "Hello"
```

No login needed — just set the environment variable.
