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

# WebSocket Authentication

> Learn how to authenticate WebSocket connections to the Zeplo real-time API using API keys, session cookies, and token-based auth.

# WebSocket Authentication

Every WebSocket connection to Zeplo must be authenticated. This page covers the three authentication methods available and how to handle authentication failures.

## Authentication Methods

| Method | Use Case |
| - | - |
| API Key (query param) | Server-to-server integrations, bots |
| API Key (auth event) | Client-side applications where query params are visible |
| Session Cookie | Zeplo Dashboard and embedded widgets |

> [!NOTE]
>
> All three methods grant the same level of access. Choose the method that best fits your application's architecture and security requirements.

## Token-Based Authentication

### Via Query Parameter

Pass your API key as the `token` query parameter in the connection URL. This is the simplest method and works well for server-side connections.

**1. Construct the connection URL**

Append your API key as the `token` query parameter:

```
wss://zeplo.ai?token=zp_live_abc123...
```

**2. Connect using Socket.IO**

```javascript theme={null}
import { io } from "socket.io-client";

const socket = io("wss://zeplo.ai", {
  query: {
    token: "zp_live_abc123...",
  },
  transports: ["websocket"],
});
```

**3. Verify the connection**

```javascript theme={null}
socket.on("connect", () => {
  console.log("Authenticated and connected:", socket.id);
});

socket.on("connect_error", (err) => {
  if (err.message === "Invalid authentication") {
    console.error("Authentication failed. Check your API key.");
  }
});
```

### Via Auth Event

For client-side applications where you want to avoid exposing the token in the URL, pass credentials through Socket.IO's `auth` option:

```javascript theme={null}
import { io } from "socket.io-client";

const socket = io("wss://zeplo.ai", {
  auth: {
    token: "zp_live_abc123...",
  },
  transports: ["websocket"],
});
```

The server reads the token from the `auth` payload during the handshake.

> [!NOTE]
>
> The `auth` option sends the token in the Socket.IO handshake payload rather than in the URL. This prevents the token from appearing in server access logs or browser network panels.

## Session Cookie Authentication

For dashboard and widget connections where the user is already authenticated via the Zeplo web interface, session cookies are sent automatically by the browser:

```javascript theme={null}
import { io } from "socket.io-client";

// No token needed — the browser sends session cookies automatically
const socket = io("wss://zeplo.ai", {
  transports: ["websocket"],
});
```

> [!NOTE]
>
> Session cookie authentication only works for users who are logged into the Zeplo Dashboard. For external integrations, use API key authentication instead.

## API Key Authentication

API keys are the recommended method for external integrations, bots, and server-side applications.

### Creating an API Key

1. Navigate to **Settings > API Keys** in the Zeplo Dashboard.
2. Click **Create API Key**.
3. Give the key a descriptive name (for example, "Live Chat Bot").
4. Select the required permissions (messaging, contacts, campaigns, webhooks).
5. Copy the key immediately — it is shown only once.

### Using the API Key

```javascript theme={null}
import { io } from "socket.io-client";

const socket = io("wss://zeplo.ai", {
  auth: {
    token: process.env.ZEPLO_API_KEY,
  },
  transports: ["websocket"],
});

socket.on("connect", () => {
  console.log("Connected with API key auth");
});
```

> [!WARNING]
>
> **Never expose your API key in client-side JavaScript.** API keys are intended for server-side use. For browser-based applications, use a backend proxy to authenticate the WebSocket connection, or use the session cookie method if the user is logged into the Zeplo Dashboard.

## Error Handling

Authentication failures are delivered through the `connect_error` event. Handle these gracefully in your application:

```javascript theme={null}
socket.on("connect_error", (err) => {
  switch (err.message) {
    case "Invalid authentication":
      console.error("The provided token is invalid or revoked.");
      break;
    case "Token expired":
      console.error("The API key has expired. Generate a new one.");
      break;
    case "Insufficient permissions":
      console.error("The API key does not have the required permissions.");
      break;
    case "Rate limit exceeded":
      console.error("Too many connection attempts. Retry later.");
      break;
    default:
      console.error("Connection error:", err.message);
  }
});
```

### Reconnection with Authentication

Socket.IO reconnects automatically, but you may need to refresh the token on reconnection if you are using short-lived tokens:

```javascript theme={null}
const socket = io("wss://zeplo.ai", {
  auth: (cb) => {
    // Called on every connection and reconnection
    cb({ token: getFreshToken() });
  },
  transports: ["websocket"],
});

function getFreshToken() {
  // Fetch a new token from your backend if needed
  return process.env.ZEPLO_API_KEY;
}
```

> [!NOTE]
>
> Using the `auth` callback function ensures that a fresh token is provided on every reconnection attempt. This is especially important if your tokens have a short expiration time.

## Token Security Best Practices

> [!WARNING]
>
> Treat your API keys like passwords. Compromised keys give full access to your Zeplo account within the granted permission scope.

* **Store keys in environment variables** on your server. Never commit them to source control.
* **Use separate keys** for development and production environments.
* **Rotate keys regularly** by creating a new key, updating your application, and then revoking the old key.
* **Restrict permissions** to only what each integration needs. A bot that only sends messages does not need campaign management permissions.
* **Monitor key usage** in the Zeplo Dashboard. If you see unexpected activity, revoke the key immediately.


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