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

# NPM Packages: SDK and React

> Installing and using @leaderos/headless-sdk and @leaderos/headless-react.

You can call the Headless API by hand with `fetch`, but the official packages add type safety, error handling and Next.js integration.

| Package | Purpose | Environment |
| - | - | - |
| `@leaderos/headless-sdk` | Typed, `fetch`-based API client | Browser, Node.js 18+, Next.js, Deno, Bun |
| `@leaderos/headless-react` | Provider, hooks, `<PoweredBy/>`, `<Turnstile/>` | React 18+ |
| `@leaderos/headless-react/next` | Server client and API proxy route | Next.js (App Router) |
| `@leaderos/headless-mcp` | MCP server for AI | [MCP page](https://developer.leaderos.net/headless/en/mcp.md) |
| `create-leaderos-theme` | Project generator | [Setup page](https://developer.leaderos.net/headless/en/create-leaderos-theme.md) |

> [!NOTE]
>
> If you use `create-leaderos-theme`, the packages come pre-installed. This page is for adding them to an existing project or understanding how they work.

## @leaderos/headless-sdk

### Installation

```bash theme={null}
npm install @leaderos/headless-sdk
```

### Creating a client

```ts theme={null}
import { createClient, localStorageTokenStore, isLeaderOSError } from '@leaderos/headless-sdk';

const leaderos = createClient({
  baseUrl: 'https://your-site.com',       // no trailing slash
  publicKey: 'pk_live_XXXXXXXX',          // Settings → Headless API
  tokenStore: localStorageTokenStore(),   // for SPAs; see below for Next.js
});
```

### Usage

The SDK mirrors the API groups:

```ts theme={null}
const { data: config } = await leaderos.site.config();
await leaderos.auth.login({ username, password });
const { data: cart } = await leaderos.cart.items();
const { data: posts, meta } = await leaderos.blog.posts.list({ page: 2 });
```

Available groups include `site`, `auth`, `account`, `store`, `cart`, `payments`, `credits`, `chest`, `forum`, `support`, `blog`, `help`, `suggestions`, `applications`, `forms` and `server` (play, vote, staff). To see which method maps to which endpoint, check the `operationId` values in OpenAPI.

### Error handling

```ts theme={null}
try {
  const { data: intent } = await leaderos.cart.checkout({ paymentGateway: 'stripe', terms: true });
  leaderos.payments.start(intent); // sends the browser to the payment page
} catch (error) {
  if (isLeaderOSError(error)) {
    if (error.code === 'CONTACT_REQUIRED') { /* ask for name/phone */ }
    if (error.code === 'VALIDATION_FAILED') console.log(error.fieldError('email'));
    console.log(error.status, error.fields, error.details);
  }
}
```

`LeaderOSError` fields: `code`, `status`, `fields`, `details`. **Branch on `code`, not on `message`.**

### Per-request options

The last parameter of every method is an `options` object (`query`, `headers`, `signal`, `fetch`):

```ts theme={null}
await leaderos.blog.posts.list({ page: 1 }, {
  headers: { 'X-Locale': 'en' },
  signal: controller.signal,
  fetch: { next: { revalidate: 60 } }, // Next.js cache
});
```

### Types

All schemas generated from OpenAPI are exported:

```ts theme={null}
import type { Cart, StoreProduct, ForumThread, User } from '@leaderos/headless-sdk';
```

## @leaderos/headless-react

### Installation

```bash theme={null}
npm install @leaderos/headless-react @leaderos/headless-sdk react
```

### Provider and hooks

```tsx theme={null}
import { LeaderOSProvider, createBrowserClient, useLeaderOS, useUser, useModule, PoweredBy, Turnstile } from '@leaderos/headless-react';

<LeaderOSProvider client={createBrowserClient()} config={config} user={user}>
  {children}
</LeaderOSProvider>
```

| Component / hook | Purpose |
| - | - |
| `useLeaderOS()` | Gives the API client in client components |
| `useUser()` | Current user; `setCredits(data)` updates the balance without a refetch |
| `useModule('forum')` | Is the module active? |
| `useApi((api) => api.blog.posts.list(), [])` | Simple data-fetching hook |
| `<PoweredBy config={config} />` | **Mandatory** "Powered by LeaderOS" link |
| `<Turnstile page="login" onToken={setToken} />` | Cloudflare Turnstile; renders nothing when no captcha is needed |

> [!WARNING]
>
> Do not delete, hide or replace `<PoweredBy />`. It can only be removed when `config.branding.canRemove` is `true`.

## Next.js integration

Environment variables (`.env.local`):

```bash theme={null}
LEADEROS_URL=https://your-site.com
LEADEROS_PUBLIC_KEY=pk_live_XXXXXXXX
```

### Server client (Server Components / Server Actions)

```ts theme={null}
// lib/leaderos.ts
import { cookies, headers } from 'next/headers';
import { createServerClient } from '@leaderos/headless-react/next';

export const leaderos = async () =>
  createServerClient({ cookies: await cookies(), headers: await headers() });
```

This client reads the user token from the `httpOnly` cookie and forwards the visitor's IP to the API via `X-Forwarded-For`.

```tsx theme={null}
// app/blog/page.tsx
import { leaderos } from '@/lib/leaderos';

export default async function Blog() {
  const api = await leaderos();
  const { data: posts } = await api.blog.posts.list();
  return posts.map((p) => <h2 key={p.id}>{p.title}</h2>);
}
```

### Proxy route (browser requests)

```ts theme={null}
// app/headless/v1/[...path]/route.ts
import { createProxyHandler } from '@leaderos/headless-react/next';
export const { GET, POST, PUT, PATCH, DELETE } = createProxyHandler();
```

The browser client (`createBrowserClient()`) sends its requests to this route. The proxy:

* adds the public key and user token on the server (**the browser never sees the token**),
* writes the token to an `httpOnly` cookie on login/registration, rotates it on password/e-mail change and clears it on logout,
* blocks cross-site mutating requests.

This means you do not even need CORS settings, because the browser only talks to your own domain.

> [!TIP]
>
> The public key may be visible in the browser, but with the proxy it never is. Using the proxy in production is recommended.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.