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

# Getting Started

> Get started with Brook SDK in minutes

## Introduction

Brook is a real-time fault-tolerant pub/sub SDK for JavaScript, Go, and React applications. It provides WebSocket connectivity with automatic reconnection, message replay for missed messages, and seamless integration with your favorite frameworks.

## Features

* Real-time messaging with WebSocket
* Automatic reconnection with exponential backoff
* Message replay for missed messages
* React hooks for seamless integration
* Lightweight and performant
* Full TypeScript support

## Installation

### Package Manager

Install Brook SDK using your preferred package manager:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @aptly-sdk/brook
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @aptly-sdk/brook
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @aptly-sdk/brook
    ```
  </Tab>
</Tabs>

### CDN (Browser)

For quick prototypes or simple HTML pages, use the CDN version:

```html theme={null}
<script type="module">
  import Brook from 'https://cdn.jsdelivr.net/npm/@aptly-sdk/brook@0.0.27/+esm';

  const client = new Brook({ apiKey: 'your-api-key' });
  // Your code here...
</script>
```

<Note>
  See the [JavaScript SDK guide](/javascript-sdk#using-brook-with-cdn-esm) for a complete browser example.
</Note>

## Get Your API Key

Before using the Brook SDK, you'll need to get your API key from the [Console](https://console.aptly.cloud/brook).

<Steps>
  <Step title="Visit the Console">
    Navigate to [https://console.aptly.cloud/brook](https://console.aptly.cloud/brook)
  </Step>

  <Step title="Sign in or create an account">
    Create a new account or sign in to your existing account
  </Step>

  <Step title="Generate API Key">
    Copy your API key from the dashboard
  </Step>
</Steps>

<Warning>
  Keep your API key secure and never commit it to version control. Use environment variables to store it safely.
</Warning>

## Understanding Key Types

Aptly provides two types of API keys:

<Tabs>
  <Tab title="Public Key (pk_)">
    **For client-side applications**

    Use public keys in browsers, mobile apps, and any client-side code. These keys are protected by origin validation.

    ```javascript theme={null}
    // Safe to use in frontend code
    const client = new Brook({ apiKey: 'pk_abc123...' });
    ```
  </Tab>

  <Tab title="Server Key (sk_)">
    **For server-side applications**

    Use server keys in backend services, APIs, and serverless functions. These keys have no origin restrictions.

    <Warning>
      Never expose server keys in client-side code. Always use environment variables.
    </Warning>

    ```javascript theme={null}
    // Backend only - use environment variables
    const client = new Brook({ apiKey: process.env.APTLY_SERVER_KEY });
    ```
  </Tab>
</Tabs>

<Card title="Learn More About Authentication" icon="lock" href="/authentication">
  Read the complete guide on Public Keys vs Server Keys
</Card>

## Quick Start

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    import Brook from '@aptly-sdk/brook';

    // Initialize the client
    const client = new Brook({ apiKey: 'your-api-key' });

    // Connect to the server
    await client.connect();

    // Create a channel
    const channel = client.realtime.channel('my-topic');

    // Subscribe to messages
    channel.stream((message, metadata) => {
      console.log('Received:', message);
      console.log('Metadata:', metadata);
    });

    // Publish a message
    await channel.publish({ text: 'Hello World!' });
    ```
  </Tab>

  <Tab title="React">
    ```jsx theme={null}
    import { useState } from 'react';
    import Brook from '@aptly-sdk/brook';
    import { BrookProvider, useStream, usePublish } from '@aptly-sdk/brook/react';

    // Initialize the client
    const client = new Brook({ apiKey: 'your-api-key' });

    function App() {
      return (
        <BrookProvider config={client}>
          <MyComponent />
        </BrookProvider>
      );
    }

    function MyComponent() {
      const [latestMessage, setLatestMessage] = useState(null);
      const publish = usePublish('my-topic');

      useStream('my-topic', (message, metadata) => {
        setLatestMessage(message);
      });

      const handleSend = () => {
        publish({ text: 'Hello from React!' });
      };

      return (
        <div>
          <p>Latest message: {JSON.stringify(latestMessage)}</p>
          <button onClick={handleSend}>Send Message</button>
        </div>
      );
    }
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    package main

    import (
        "fmt"
        "log"
        "time"

        aptly "github.com/aptly-cloud/go"
    )

    func main() {
        // Initialize the client
        client, err := aptly.NewClient(aptly.Config{
            APIKey: "your-api-key",
        })
        if err != nil {
            log.Fatal(err)
        }
        defer client.Cleanup()

        // Connect to the server
        client.Connect()

        // Create a channel
        channel, _ := client.Realtime().Channel("my-topic")

        // Subscribe to messages
        channel.Stream(func(data interface{}, metadata aptly.MessageMetadata) {
            fmt.Printf("Received: %v\n", data)
            fmt.Printf("Metadata: %+v\n", metadata)
        })

        // Publish a message
        channel.Publish(map[string]string{
            "text": "Hello World!",
        })

        // Keep running
        time.Sleep(30 * time.Second)
    }
    ```
  </Tab>

  <Tab title="Browser/CDN">
    ```html theme={null}
    <!DOCTYPE html>
    <html>
    <head>
      <title>Brook Demo</title>
    </head>
    <body>
      <div id="messages"></div>
      <button id="sendBtn">Send Message</button>

      <script type="module">
        import Brook from 'https://cdn.jsdelivr.net/npm/@aptly-sdk/brook@0.0.27/+esm';

        const client = new Brook({ apiKey: 'your-api-key' });
        await client.connect();

        const channel = client.realtime.channel('my-topic');

        channel.stream((message, metadata) => {
          const div = document.getElementById('messages');
          div.innerHTML += `<p>${JSON.stringify(message)}</p>`;
        });

        document.getElementById('sendBtn').onclick = async () => {
          await channel.publish({ text: 'Hello!' });
        };
      </script>
    </body>
    </html>
    ```
  </Tab>
</Tabs>

## Next Steps

<CardGroup cols={2}>
  <Card title="JavaScript SDK" icon="js" href="/javascript-sdk">
    Learn how to use Brook with vanilla JavaScript
  </Card>

  <Card title="Go SDK" icon="golang" href="/go-sdk">
    Build real-time applications with Go
  </Card>

  <Card title="React SDK" icon="react" href="/react-sdk">
    Integrate Brook into your React applications
  </Card>

  <Card title="REST API" icon="code" href="/rest-api">
    Publish messages using REST API with curl or fetch
  </Card>
</CardGroup>

## Demo

Check out our [Live Demo](https://demo.aptly.cloud) to see Brook in action.
