# Quick Start & Best Practices

### What's covered in this page:

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

### Code Examples Language:

All examples on this page use **JavaScript (Node.js)** with the `socket.io-client` library. For complete examples in other languages (Python, Browser), see the [Code Examples](https://docs.lsports.eu/lsports/products/defend/websocket-connection/code-examples) page.

***

### Quick Start

Get connected in under 5 minutes with this minimal JavaScript example.

#### Prerequisites

* Node.js installed
* Socket.IO client library: \`npm install socket.io-client\`
* Your Customer ID (provided by LSports)
* Valid access token from ARENA360 [Authentication Guide](https://docs.lsports.eu/lsports/products/defend/integration-guide/authentication)

#### Minimal Connection Example

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

const socket = io("wss://rms.lsports.cloud", {
  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

Understanding the connection lifecycle ensures your application handles all states correctly.

#### 1. Connect

Establish WSS connection with 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 connection, emit the `join` event to join 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 and receive real-time events:

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

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

#### 4. Handle Disconnection

Handle graceful disconnection and reconnection:

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

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

***

### Best Practices

Follow these recommendations for a robust, production-ready implementation.

#### Security Recommendations

1. **Use WSS (TLS) -** Always use secure WebSocket connections
   * Always use `wss://` for encrypted connections
   * Never use unencrypted `ws://` in production
2. **Use Short-Lived Tokens -** Enable auto-reconnection with exponential backoff
   * Access tokens expire every 30 minutes
   * Implement automatic token refresh before expiration
   * Never hardcode tokens in client-side code
   * re-emit `join` event after reconnecting
3. **Secure Token Storage**&#x20;
   * Store tokens securely (environment variables, secure storage)
   * Never expose tokens in URLs or query strings
   * Never hardcode tokens in client-side code
   * Rotate tokens regularly<br>
4. **Validate Origins**
   * For browser clients, ensure your domain is whitelisted
   * Contact LSports to configure CORS for your domains

#### Recommended Settings

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

#### Reconnection Strategy

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

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

socket.on("reconnect_attempt", (attemptNumber) => {
  console.log(`Reconnection attempt ${attemptNumber}`);
  // Refresh token if needed before reconnecting
});

socket.on("reconnect_failed", () => {
  console.error("Failed to reconnect after all attempts");
  // Implement fallback logic (e.g., notify user, switch to polling API)
});
```

#### Token Refresh Before Expiration

```javascript
// Refresh token 2 minutes before expiration
const TOKEN_REFRESH_BUFFER = 2 * 60 * 1000; // 2 minutes

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

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

// Check token expiry periodically
setInterval(refreshTokenIfNeeded, 60000);
```

#### Connection Health Monitoring

```javascript
// Monitor connection health
socket.on("ping", () => {
  console.log("Ping received from server");
});

socket.on("pong", (latency) => {
  console.log(`Pong - latency: ${latency}ms`);
});

// Detect stale connections
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);
```
