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

# JavaScript SDK

> Official TypeScript/JavaScript SDK for the Mixpeek API

<Note>
  The Mixpeek JavaScript SDK is auto-generated from our OpenAPI specification and always stays in sync with the latest API features.
</Note>

## Features

* **100% Type-Safe** - Built with TypeScript for complete type safety
* **Runtime Validation** - Zod schemas for request/response validation
* **Modern** - Supports both CommonJS and ESM
* **Promise-Based** - Clean async/await API
* **Developer-Friendly** - Intuitive method names and excellent autocomplete

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install mixpeek
  ```

  ```bash yarn theme={null}
  yarn add mixpeek
  ```

  ```bash pnpm theme={null}
  pnpm add mixpeek
  ```
</CodeGroup>

## Quick Start

```typescript theme={null}
import { Mixpeek } from 'mixpeek';

// Initialize the client
const client = new Mixpeek({
  apiKey: process.env.MIXPEEK_API_KEY,
  namespace: 'my-namespace'
});

// List collections
const collections = await client.collections.listCollections();
console.log('Collections:', collections);

// Create a collection
const newCollection = await client.collections.createCollection({
  alias: 'my-collection',
  description: 'My first collection'
});

// Execute a retriever
const results = await client.retrievers.executeRetriever({
  retrieverId: 'ret_abc123',
  query: 'find relevant documents'
});
```

## Configuration

### Environment Variables

```bash theme={null}
# Required
MIXPEEK_API_KEY=mxp_sk_your_api_key_here

# Optional
MIXPEEK_BASE_URL=https://api.mixpeek.com  # Default
MIXPEEK_NAMESPACE=default                 # Default
```

### Constructor Options

```typescript theme={null}
const client = new Mixpeek({
  apiKey: 'sk_...',              // Required (or set MIXPEEK_API_KEY)
  baseUrl: 'https://...',        // Optional: custom API endpoint
  namespace: 'my-namespace',     // Optional: namespace for isolation
  timeout: 30000,                // Optional: request timeout in ms
  axiosConfig: {                 // Optional: additional axios config
    // Any axios configuration options
  }
});
```

<Tip>
  You can create API keys in the Mixpeek dashboard under Organization Settings.
</Tip>

## Core Operations

### Collections

```typescript theme={null}
// Create a collection
const collection = await client.collections.createCollection({
  alias: 'my-collection',
  description: 'Store multimodal documents',
  metadata: { project: 'demo' }
});

// Get a collection
const retrieved = await client.collections.getCollection({
  collectionIdentifier: 'my-collection'
});

// List all collections
const allCollections = await client.collections.listCollections();

// Delete a collection
await client.collections.deleteCollection({
  collectionIdentifier: 'my-collection'
});
```

### Retrievers

```typescript theme={null}
// Create a retriever
const retriever = await client.retrievers.createRetriever({
  retrieverName: 'semantic-search',
  description: 'Search across all documents',
  collectionIdentifiers: ['my-collection'],
  stages: [
    {
      type: 'embed',
      model: 'openai-text-embedding-3-small'
    },
    {
      type: 'vector_search',
      top_k: 10
    }
  ]
});

// Execute a retriever
const results = await client.retrievers.executeRetriever({
  retrieverId: retriever.retrieverId,
  query: 'find relevant documents about AI'
});

// List retrievers
const retrievers = await client.retrievers.listRetrievers();
```

### Documents

```typescript theme={null}
// Upload documents to a collection
const documents = await client.documents.uploadDocuments({
  collectionId: 'col_abc123',
  documents: [
    {
      url: 's3://bucket/video.mp4',
      metadata: { title: 'Demo Video' }
    },
    {
      url: 's3://bucket/image.jpg',
      metadata: { title: 'Demo Image' }
    }
  ]
});

// Search documents
const searchResults = await client.documents.searchDocuments({
  collectionId: 'col_abc123',
  query: 'search query',
  limit: 20
});
```

### Buckets (Object Storage)

```typescript theme={null}
// Create a bucket
const bucket = await client.buckets.createBucket({
  alias: 'my-bucket',
  provider: 's3',
  credentials: {
    accessKeyId: 'YOUR_ACCESS_KEY',
    secretAccessKey: 'YOUR_SECRET_KEY',
    region: 'us-east-1'
  }
});

// List buckets
const buckets = await client.buckets.listBuckets();
```

## Error Handling

```typescript theme={null}
try {
  const collection = await client.collections.getCollection({
    collectionIdentifier: 'non-existent'
  });
} catch (error) {
  if (error.response) {
    // API error
    console.error('Status:', error.response.status);
    console.error('Message:', error.response.data?.error?.message);
  } else if (error.request) {
    // Network error
    console.error('Network error:', error.message);
  } else {
    // Other error
    console.error('Error:', error.message);
  }
}
```

## TypeScript Support

The SDK is built with TypeScript and provides full type definitions:

```typescript theme={null}
import { Mixpeek, MixpeekOptions } from 'mixpeek';
import type {
  Collection,
  Retriever,
  CreateCollectionRequest,
  CreateRetrieverRequest
} from 'mixpeek';

// All types are fully typed
const options: MixpeekOptions = {
  apiKey: 'sk_...',
  namespace: 'default'
};

const client = new Mixpeek(options);

// TypeScript will autocomplete and type-check all methods
const collection: Collection = await client.collections.createCollection({
  alias: 'typed-collection'
  // TypeScript will suggest all available fields
});
```

## Advanced Usage

### Custom Axios Configuration

```typescript theme={null}
const client = new Mixpeek({
  apiKey: 'sk_...',
  axiosConfig: {
    timeout: 60000,
    headers: {
      'X-Custom-Header': 'value'
    },
    proxy: {
      host: 'proxy.example.com',
      port: 8080
    }
  }
});
```

### Updating Configuration

```typescript theme={null}
const client = new Mixpeek({ apiKey: 'sk_old' });

// Update API key
client.setApiKey('sk_new');

// Update namespace
client.setNamespace('new-namespace');

// Get current configuration
const config = client.getConfig();
console.log(config);
// { apiKey: 'sk_new...', baseUrl: '...', namespace: 'new-namespace' }
```

## Framework Examples

### Next.js

```typescript theme={null}
// app/api/search/route.ts
import { Mixpeek } from 'mixpeek';
import { NextResponse } from 'next/server';

const client = new Mixpeek({
  apiKey: process.env.MIXPEEK_API_KEY!,
  namespace: process.env.MIXPEEK_NAMESPACE
});

export async function POST(request: Request) {
  const { query } = await request.json();

  try {
    const results = await client.retrievers.executeRetriever({
      retrieverId: 'ret_abc123',
      query
    });

    return NextResponse.json(results);
  } catch (error) {
    return NextResponse.json(
      { error: 'Search failed' },
      { status: 500 }
    );
  }
}
```

### Express

```typescript theme={null}
import express from 'express';
import { Mixpeek } from 'mixpeek';

const app = express();
const client = new Mixpeek({
  apiKey: process.env.MIXPEEK_API_KEY,
  namespace: process.env.MIXPEEK_NAMESPACE
});

app.post('/api/search', async (req, res) => {
  try {
    const results = await client.retrievers.executeRetriever({
      retrieverId: 'ret_abc123',
      query: req.body.query
    });
    res.json(results);
  } catch (error) {
    res.status(500).json({ error: 'Search failed' });
  }
});

app.listen(3000);
```

## Resources

<CardGroup cols={2}>
  <Card title="NPM Package" icon="npm" href="https://www.npmjs.com/package/mixpeek">
    View on NPM
  </Card>

  <Card title="GitHub Repository" icon="github" href="https://github.com/mixpeek/javascript-sdk">
    Source code and issues
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference">
    Complete API documentation
  </Card>

  <Card title="OpenAPI Spec" icon="file-code" href="https://api.mixpeek.com/docs/openapi.json">
    OpenAPI specification
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Quickstart" icon="rocket" href="/overview/quickstart">
    Get started with Mixpeek
  </Card>

  <Card title="Python SDK" icon="python" href="/integrations/developer-tools/python-sdk">
    Use the Python SDK
  </Card>

  <Card title="MCP Server" icon="robot" href="/integrations/developer-tools/mcp-server">
    Use Mixpeek with AI assistants
  </Card>

  <Card title="Examples" icon="book-open" href="https://mixpeek.com/recipes">
    View example implementations
  </Card>
</CardGroup>
