# Quick Start & Best Practices

This page covers:

* A minimal connection example to get started immediately
* Step-by-step connection lifecycle
* Production-ready best practices for reliability and security

All examples use **JavaScript (Node.js)** with the `socket.io-client` library. For Python and browser examples, see the [Code Examples](/u/defend/websocket-connection/code-examples.md) page.

***

## Quick Start

### Prerequisites

* Node.js installed
* Socket.IO client: `npm install socket.io-client`
* Your Customer ID (provided by LSports)
* A valid access token — see the [Authentication Guide](/u/defend/integration-guide/authentication.md)

### Minimal Connection Example

```javascript
const io = require("socket.io-client");

const socket = io("wss://rms.lsports.eu", {
  path: "/rms-socket/socket.io",
  transports: ["websocket", "polling"],
  extraHeaders: {
    Authorization: "Bearer YOUR_ACCESS_TOKEN",
    customerid: "YOUR_CUSTOMER_ID",
  },
});

socket.on("connect", () => {
  console.log("Connected!");
  socket.emit("join", {}, (response) => {
    console.log("Joined room:", response.room);
  });
});

socket.on("RESERVE_BET_ACCEPT", (data) => {
  console.log("Bet accepted:", data);
});

socket.on("connect_error", (error) => {
  console.error("Connection failed:", error.message);
});
```

***

## Connection Lifecycle

### 1. Connect

Establish a WSS connection with your authentication headers. Upon successful connection, the server sends an `announcements` event:

```javascript
socket.on("announcements", (data) => {
  // { message: "A new user has joined!" }
});
```

### 2. Join Room

After connecting, emit the `join` event to enter your designated room:

```javascript
socket.on("connect", () => {
  socket.emit("join", {}, (response) => {
    // Response contains:
    // {
    //   room: "123-54",   // CustomerId-PlatformId
    //   customerId: 123,
    //   platformId: 54
    // }
  });
});
```

### 3. Receive Messages

Listen for events on your subscribed room:

```javascript
socket.on("RESERVE_BET_ACCEPT", (data) => {
  console.log("Bet accepted:", data);
});

socket.on("RESERVE_BET_REJECT", (data) => {
  console.log("Bet rejected:", data);
});
```

### 4. Handle Disconnection

Handle graceful disconnection and reconnection:

```javascript
socket.on("disconnect", (reason) => {
  if (reason === "io server disconnect") {
    socket.connect(); // Server initiated — reconnect manually
  }
  // Other reasons: client will auto-reconnect
});

socket.on("reconnect", () => {
  console.log("Reconnected");
  socket.emit("join", {}); // Re-join room after reconnection
});
```

***

## Best Practices

### Security

1. **Always use WSS** — Never use unencrypted `ws://` in production
2. **Use short-lived tokens** — Access tokens expire every 30 minutes. Implement automatic token refresh before expiration and re-emit `join` after reconnecting
3. **Secure token storage** — Use environment variables; never hardcode tokens in client-side code or expose them in URLs

### Recommended Configuration

```javascript
const socket = io(SERVER_URL, {
  path: "/rms-socket/socket.io",
  transports: ["websocket", "polling"],
  extraHeaders: {
    Authorization: `Bearer ${ACCESS_TOKEN}`,
    customerid: CUSTOMER_ID,
  },
  reconnection: true,
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 30000,
  randomizationFactor: 0.5,
});
```

### Token Refresh Before Expiration

```javascript
const TOKEN_REFRESH_BUFFER = 2 * 60 * 1000; // 2 minutes before expiry

async function refreshTokenIfNeeded() {
  const tokenExpiry = getTokenExpiry(currentToken);
  const now = Date.now();

  if (tokenExpiry - now < TOKEN_REFRESH_BUFFER) {
    const newToken = await refreshAccessToken(refreshToken);
    socket.disconnect();
    socket.io.opts.extraHeaders.Authorization = `Bearer ${newToken}`;
    socket.connect();
  }
}

setInterval(refreshTokenIfNeeded, 60000);
```

### Connection Health Monitoring

```javascript
let lastActivity = Date.now();

socket.onAny(() => {
  lastActivity = Date.now();
});

setInterval(() => {
  const inactiveFor = Date.now() - lastActivity;
  if (inactiveFor > 60000) {
    console.warn("No activity for 60s — connection may be stale");
  }
}, 30000);
```

***

## Related

* [Code Examples](/u/defend/websocket-connection/code-examples.md) — Full examples in JavaScript, Python, and Browser
* [Error Handling](/u/defend/websocket-connection/error-handling.md) — Error codes and troubleshooting
* [Authentication Guide](/u/defend/integration-guide/authentication.md) — Obtaining access tokens


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.lsports.eu/u/defend/websocket-connection/quick-start-and-best-practices.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
