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

# Authentication

> How to authenticate with the Nudj Platform APIs

The Nudj Platform APIs support two authentication header schemes. Both are verified by the **same** tRPC auth middleware (`apps/api/trpc/init.ts`) and both work on every endpoint — pick whichever suits your client.

1. **`Authorization: Bearer <token>`** — the modern, revocable, RBAC-scoped path. Recommended for new integrations.
2. **`x-api-token: <token>`** — the legacy alias. Still fully supported.

The middleware strips an optional `Bearer ` prefix from either header before verifying the signature, so the two paths are equivalent at the signature layer.

<CardGroup cols={2}>
  <Card title="Authorization: Bearer" icon="shield-halved">
    **Recommended for new integrations**

    RBAC-scoped, per-token revocation. Jump to [Authorization: Bearer](#authorization-bearer).
  </Card>

  <Card title="x-api-token" icon="key">
    **Legacy alias**

    Long-lived JWT. Jump to [x-api-token](#x-api-token).
  </Card>
</CardGroup>

## Authorization: Bearer

Bearer tokens are the modern auth path introduced across NUDJ-4411 / NUDJ-4819 / NUDJ-5354. They carry a `type` claim, support per-community RBAC scoping, and are verified against a revocation cache on every request — revoking one takes effect within seconds.

### Get a Bearer token

<Steps>
  <Step title="Open Developer Settings">
    Go to [Settings → Organisation → Developer](https://admin.nudj.cx/admin/settings/organisation?tab=developer).
  </Step>

  <Step title="Generate a token">
    Click **Generate New Token**. Pick a role (Viewer / Moderator / Manager / Admin / SuperAdmin) and optionally scope it to a specific community.
  </Step>

  <Step title="Copy it immediately">
    Tokens are shown once. Store in a secrets manager or env var — never commit.
  </Step>
</Steps>

### Use in requests

```bash theme={null}
Authorization: Bearer YOUR_API_TOKEN
```

The header is case-insensitive. Tokens are tied to the subdomain they were issued for — replaying a token against a different organisation's subdomain is rejected.

### Per-API support

| API         | `Authorization: Bearer` | `x-api-token` | Declared in OpenAPI spec |
| ----------- | ----------------------- | ------------- | ------------------------ |
| Integration | ✅                       | ✅             | Both                     |
| Admin       | ✅                       | ✅             | Both                     |
| Analytics   | ✅                       | ✅ (runtime)   | Bearer only              |

<Warning>
  The Analytics OpenAPI spec currently declares only the Bearer scheme under `securitySchemes`. The runtime still accepts `x-api-token`, but the Analytics playground UI surfaces only the Bearer input.
</Warning>

## x-api-token

### Get a token

Use the same Developer Settings page as above. Legacy tokens have no `type` claim and cannot be revoked individually — they remain valid until their expiry.

### Use in requests

```bash theme={null}
x-api-token: YOUR_API_TOKEN
```

The header is case-insensitive. An optional `Bearer ` prefix on the value is accepted:

```bash theme={null}
x-api-token: Bearer YOUR_API_TOKEN
```

### Revoke a Bearer token

Bearer tokens can be revoked individually via the Admin API:

```bash theme={null}
curl -X POST "https://{subdomain}.nudj.cx/api/v2/admin/auth-config/tokens/{tokenId}/revoke" \
  -H "Authorization: Bearer YOUR_ACTIVE_TOKEN"
```

## API base URLs

Each organisation has its own subdomain:

```
https://{your-subdomain}.nudj.cx/api/v2/{api-type}
```

Where `{api-type}` is one of `admin`, `integration`, or `analytics`.

| Organisation | Subdomain     | Admin API URL                              |
| ------------ | ------------- | ------------------------------------------ |
| Development  | `nudjdev`     | `https://nudjdev.nudj.cx/api/v2/admin`     |
| Staging      | `nudjstaging` | `https://nudjstaging.nudj.cx/api/v2/admin` |
| Your Org     | `yourcompany` | `https://yourcompany.nudj.cx/api/v2/admin` |

See [Organisation Domains](/api-reference/custom-domains) for white-label custom domains managed via the Admin API `/domains` endpoints.

## Testing authentication

<CodeGroup>
  ```bash Admin API theme={null}
  curl -X GET "https://your-subdomain.nudj.cx/api/v2/admin/communities?limit=10" \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```bash Integration API theme={null}
  curl -X GET "https://your-subdomain.nudj.cx/api/v2/integration/me" \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```bash Analytics API theme={null}
  curl -X GET "https://your-subdomain.nudj.cx/api/v2/analytics/users/overview" \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json"
  ```
</CodeGroup>

## Error responses

### 401 Unauthorized

```json theme={null}
{
  "message": "You must be logged in to access this endpoint.",
  "code": "UNAUTHORIZED",
  "data": { "httpStatus": 401, "path": "endpoint-name" }
}
```

**Common causes:**

* Missing or invalid token
* Expired token
* Token issued for a different organisation than the subdomain being requested
* Incorrect header format

### 403 Forbidden

```json theme={null}
{
  "message": "Insufficient permissions for this operation.",
  "code": "FORBIDDEN",
  "data": { "httpStatus": 403, "path": "endpoint-name" }
}
```

**Common causes:**

* Token lacks the required RBAC role
* Token scoped to a different community than the one the endpoint targets
* Endpoint requires a higher tier (admin vs moderator vs viewer)

See [Errors](/api-reference/errors) for the full list of error shapes across every status code.

## Other headers you may need

| Header                      | Purpose                                                 | See                                                                     |
| --------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------- |
| `x-language`                | Request translated response bodies in a specific locale | [Internationalization](/api-reference/internationalization)             |
| `x-user-access-token`       | User-level auth on embed/widget flows                   | [API link user authentication](/developer/api-link-user-authentication) |
| `x-admin-user-access-token` | Per-user RBAC when proxying through the admin app       | [OAuth/SSO integration](/developer/oauth-authentication)                |

## Security best practices

<Warning>
  Never expose API tokens in client-side JavaScript, public repositories, URL parameters, or browser storage.
</Warning>

1. **Store in secret managers** — use env vars or a secret store, never source control.
2. **Rotate regularly** — especially when team members change.
3. **Scope minimally** — use the least-privilege RBAC role the token actually needs.
4. **Revoke compromised Bearer tokens** — don't wait for them to expire.
5. **Use server-side requests only** — the APIs are not CORS-enabled for browser origins.

## Troubleshooting

<AccordionGroup>
  <Accordion title="Token is being rejected">
    * Verify no extra whitespace or line breaks.
    * Confirm the token hasn't been revoked.
    * Ensure you're hitting the correct subdomain — tokens are org-scoped.
  </Accordion>

  <Accordion title="Getting 404 errors">
    * Verify the full path including `/api/v2/`.
    * Check the API type (admin vs integration vs analytics).
    * Confirm the endpoint exists in the API reference.
  </Accordion>

  <Accordion title="Local development not working">
    * API runs on `https://localhost:3000` with a self-signed cert — use `--insecure` or `NODE_TLS_REJECT_UNAUTHORIZED=0`.
    * Confirm MongoDB is running and the org exists in the dev database.
  </Accordion>
</AccordionGroup>

## Need user-linked authentication?

<CardGroup cols={2}>
  <Card title="OAuth Integration" icon="shield-check" href="/developer/oauth-authentication">
    Configure OIDC so users can sign in via your existing auth provider.
  </Card>

  <Card title="API Link User Token" icon="user-check" href="/developer/api-link-user-authentication">
    Auto-sign authenticated users into Nudj using JWT tokens.
  </Card>
</CardGroup>

<Card title="Developer Settings" icon="gear" href="https://admin.nudj.cx/admin/settings/organisation?tab=developer">
  Access your API credentials and configuration.
</Card>
