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

# Your First Databite Server

> Step-by-step guide to create and run your first Databite server with connectors

## Overview

This guide walks you through setting up a Databite server from scratch. You'll learn how to install dependencies, configure connectors, and start serving REST API endpoints for your frontend applications.

## Prerequisites

* Node.js >= 16.0.0
* npm or pnpm
* A connector you want to use (we'll use Slack in this example)

## Step 1: Create a New Project

Create a new directory for your server:

```bash theme={null}
mkdir my-databite-server
cd my-databite-server
npm init -y
```

## Step 2: Install Dependencies

Install the core Databite packages:

```bash theme={null}
npm install @databite/server @databite/engine @databite/connectors @databite/types
```

## Step 3: Create Environment Configuration

Create a `.env` file for your secrets:

```bash theme={null}
# .env
SLACK_CLIENT_ID=your-slack-app-client-id
SLACK_CLIENT_SECRET=your-slack-app-client-secret
SLACK_REDIRECT_URI=http://localhost:3001/auth/slack/callback
```

## Step 4: Create the Server

Create `server.ts`:

```typescript theme={null}
import { DatabiteServer } from "@databite/server";
import { slack } from "@databite/connectors";

async function main() {
  // Create server with basic configuration
  const server = new DatabiteServer({
    port: 3001,
    engineConfig: {
      connectors: [slack],
    },
  });

  // Add Slack integration
  await server.addIntegration(
    slack.createIntegration("My Slack Integration", {
      clientId: process.env.SLACK_CLIENT_ID!,
      clientSecret: process.env.SLACK_CLIENT_SECRET!,
      redirectUri: process.env.SLACK_REDIRECT_URI!,
      scopes: ["chat:write", "channels:read"],
    })
  );

  // Start the server
  await server.start();

  console.log("🚀 Databite server running at http://localhost:3001");
}

main().catch(console.error);
```

## Step 5: Configure Connection Storage

By default, Databite uses an in-memory connection store that loses all connection data when the server stops. For development and testing, this is fine, but for production you'll want persistent storage.

### In-Memory Store (Default)

The current setup uses `InMemoryConnectionStore`, which:

* Stores connections in memory only
* Loses all data when the server restarts
* Is perfect for development and testing

### Adding a Persistent Store

* For production, implement the `ConnectionStore` interface with your database of choice:
* Avoid file-based storage for production as it can lead to data corruption and doesn't handle concurrent access well.

```typescript theme={null}
import { DatabiteServer, ConnectionStore, Connection } from "@databite/server";
import { ConnectionStore as EngineConnectionStore } from "@databite/engine";

// Example PostgreSQL connection store
class PostgresConnectionStore implements EngineConnectionStore {
  constructor(private db: any) {} // Your database client

  async create(connection: Connection<any>): Promise<Connection<any>> {
    // Insert into your database
    const result = await this.db.query(
      'INSERT INTO connections (id, integration_id, connector_id, config, sync_interval, active_syncs, metadata, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *',
      [connection.id, connection.integrationId, connection.connectorId, JSON.stringify(connection.config), connection.syncInterval, JSON.stringify(connection.activeSyncs || []), JSON.stringify(connection.metadata || {}), new Date(), new Date()]
    );
    return result.rows[0];
  }

  async read(connectionId: string): Promise<Connection<any> | undefined> {
    // Select from your database
    const result = await this.db.query('SELECT * FROM connections WHERE id = $1', [connectionId]);
    return result.rows[0];
  }

  async readAll(params?: { page?: number; limit?: number }): Promise<{ data: Connection<any>[]; pagination: { page: number; limit: number; total: number; totalPages: number; hasNext: boolean; hasPrev: boolean } }> {
    // Select all from your database with pagination
    const page = params?.page || 1;
    const limit = params?.limit || 10;
    const offset = (page - 1) * limit;
    
    const countResult = await this.db.query('SELECT COUNT(*) FROM connections');
    const total = parseInt(countResult.rows[0].count);
    const totalPages = Math.ceil(total / limit);
    
    const result = await this.db.query('SELECT * FROM connections ORDER BY created_at DESC LIMIT $1 OFFSET $2', [limit, offset]);
    
    return {
      data: result.rows,
      pagination: {
        page,
        limit,
        total,
        totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1,
      },
    };
  }

  async update(connection: Connection<any>): Promise<Connection<any>> {
    // Update in your database
    const result = await this.db.query(
      'UPDATE connections SET config = $1, sync_interval = $2, active_syncs = $3, metadata = $4, updated_at = $5 WHERE id = $6 RETURNING *',
      [JSON.stringify(connection.config), connection.syncInterval, JSON.stringify(connection.activeSyncs || []), JSON.stringify(connection.metadata || {}), new Date(), connection.id]
    );
    return result.rows[0];
  }

  async delete(connectionId: string): Promise<void> {
    // Delete from your database
    await this.db.query('DELETE FROM connections WHERE id = $1', [connectionId]);
  }
}

// Use your database store
const server = new DatabiteServer({
  port: 3001,
  engineConfig: {
    connectors: [slack],
    connectionStore: new PostgresConnectionStore(dbClient),
  },
});
```

## Step 6: Run Your Server

You can run your server directly with ts-node:

```bash theme={null}
npm install --save-dev ts-node
npx ts-node server.ts
```

## Step 7: Test Your Server

Test the health endpoint:

```bash theme={null}
curl http://localhost:3001/api/health
```

List available integrations:

```bash theme={null}
curl http://localhost:3001/api/integrations
```

## Step 9: Add Security (Production)

For production, add security configuration:

```typescript theme={null}
const server = new DatabiteServer({
  port: 3001,
  engineConfig: {
    connectors: [slack],
  },
  security: {
    rateLimit: { windowMs: 15 * 60 * 1000, max: 100 },
    allowedOrigins: ["https://yourdomain.com"],
    enableHelmet: true,
    enableRateLimit: true,
  },
});
```

## Next Steps

* Connect your frontend using [@databite/connect](/packages/connect)
* Add more connectors from [@databite/connectors](/packages/connectors)
