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

# SDK Overview

> Install the official TypeScript SDK and start reading and writing data from your frontend or server.

The `@urbackend/sdk` package is the official TypeScript SDK for urBackend. It wraps the REST API with typed methods for auth, database, and storage — no manual `fetch` calls required.

## Installation

```bash theme={null}
npm install @urbackend/sdk
```

## Initialize the client

Import the default export and call it with your API key:

```typescript theme={null}
import urBackend from '@urbackend/sdk';

const client = urBackend({ apiKey: 'YOUR_API_KEY' });
```

The factory accepts a `UrBackendConfig` object:

| Option | Type | Required | Description |
| - | - | - | - |
| `apiKey` | `string` | Yes | Your project's API key. |
| `baseUrl` | `string` | No | Override the default API base URL. |
| `headers` | `Record<string, string>` | No | Additional headers sent with every request. |

## Quick example

```typescript theme={null}
import urBackend from '@urbackend/sdk';

const client = urBackend({ apiKey: process.env.URBACKEND_API_KEY });

// Log in an existing user
const { accessToken } = await client.auth.login({
  email: 'alice@example.com',
  password: 'secret123'
});

// Insert a document with RLS support (passing the user token)
const product = await client.db.insert('products', { name: 'Chair', price: 99 }, accessToken);

// Fetch documents with filtering and sorting
const products = await client.db.getAll('products', { 
  filter: { price_gt: 50 },
  sort: 'price:asc'
});

// ⚠️ Server-side only — requires a secret key (sk_live_...).
// Do not use this initialization in browser/client code.
const serverClient = urBackend({ apiKey: process.env.URBACKEND_SECRET_KEY });

await serverClient.mail.send({
  to: 'user@example.com',
  subject: 'Order Confirmed',
  text: 'Your chair is on the way!'
});
```

## TypeScript generics

Database methods accept a generic type parameter so returned documents are fully typed:

```typescript theme={null}
interface Product {
  _id: string;
  name: string;
  price: number;
}

const products = await client.db.getAll<Product>('products');
// products is Product[]

const product = await client.db.getOne<Product>('products', '507f1f77bcf86cd799439011');
// product is Product
```

## Error handling

Import the error classes to handle specific failure modes:

```typescript theme={null}
import urBackend, { AuthError, NotFoundError, RateLimitError } from '@urbackend/sdk';

const client = urBackend({ apiKey: process.env.URBACKEND_API_KEY });

try {
  const product = await client.db.getOne('products', id);
} catch (e) {
  if (e instanceof NotFoundError) {
    console.error('Document not found');
  } else if (e instanceof AuthError) {
    console.error('Invalid or missing API key');
  } else if (e instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${e.retryAfter}s`);
  } else {
    throw e;
  }
}
```

| Error class | HTTP status | When thrown |
| - | - | - |
| `AuthError` | 401 / 403 | Invalid API key or missing token |
| `NotFoundError` | 404 | Document or resource not found |
| `RateLimitError` | 429 | Too many requests (100 req / 15 min per IP) |
| `ValidationError` | 400 | Request body failed validation |
| `StorageError` | varies | Storage-specific failures |
| `UrBackendError` | varies | Base class for all SDK errors |

## API key security

<Warning>
  Use `pk_live_...` (publishable key) in frontend/browser code. It allows read operations by default, and write operations only if RLS is enabled.

  Use `sk_live_...` (secret key) in server-side code only. It allows full CRUD access. Never expose it in client-side bundles or public repositories.
</Warning>

The SDK logs a console warning if it detects you are using a **Secret Key** (`sk_live_...`) in a browser context.

## Explore the SDK

<CardGroup cols={2}>
  <Card title="Auth" icon="lock" href="/sdk/auth">
    Login, logout, profile updates, and social auth.
  </Card>

  <Card title="Database" icon="database" href="/sdk/database">
    CRUD operations, query building, and RLS support.
  </Card>

  <Card title="Storage" icon="cloud" href="/sdk/storage">
    Upload files and get back a public CDN URL.
  </Card>

  <Card title="Schema" icon="brackets-curly" href="/sdk/schema">
    Inspect collection definitions and field types.
  </Card>

  <Card title="Mail" icon="envelope" href="/sdk/mail">
    Send transactional emails from your server.
  </Card>
</CardGroup>


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