Using reconnecting-websocket ============================ This guide shows how to setup the websockets to automatically reconnect from the client without using a 3rd part library. Why use reconnecting websockets? ------------------------------- Browser WebSocket connections can close for many reasons, including: * temporary network loss; * browser sleep or tab suspension; * API Gateway timeouts; * server restarts; * mobile network changes. The browser's built-in ``WebSocket`` class does not automatically reconnect. Using WebSocket tokens ---------------------- Recent versions of this package can use short-lived, single-use WebSocket tokens to protect authenticated WebSocket connections. When token protection is enabled, the browser should: #. request a WebSocket token from Django; #. open the WebSocket connection with that token; #. request a fresh token whenever a new connection is required. The token should be passed using the ``ws_token`` query string parameter. Example connection URL: .. code-block:: text wss://ws.example.com?ws_token=&channel=my-example-channel Token-aware reconnecting example -------------------------------- The important difference with token-based connections is that a reconnect should use a fresh token. A previously used token should not be reused. This example shows creating a class to handle connection, token exchange, sending messages and reconnecting. As this package supports grouping WebSocket sessions by channel the example also includes how to add the ``channel`` query string parameter to the WebSocket URL. The server can then use the channel name to send messages to all active connections associated with that channel. .. code-block:: html Subclassing the WebSocketManager object --------------------------------------- To subclass the base WebSocketManager class to add in your own functionality you could follow the below implementation. .. code-block:: html Sending messages to Django -------------------------- Messages sent from the browser should be JSON encoded. By default, the ``action`` value is used by API Gateway as the route selection key. .. code-block:: html If you have created a custom API Gateway route named ``notifications``, you can send a message to that route like this: .. code-block:: html Sending a toast notification request ------------------------------------ A common pattern is to send a message to Django and then receive a message back that the frontend displays as a toast. Example browser message: .. code-block:: javascript wmsWebSocketManager.send("default", { type: "toast", level: "success", message: "The browser is connected" }); Example frontend message handler: .. code-block:: javascript class CustomWebSocketManager extends WebSocketManager { onMessage(event) { // Call the parent implementation first (optional) super.onMessage(event); const message = JSON.parse(event.data); if (message.type === "toast") { this.showToast(message.level, message.message); return; } console.log("WebSocket message received:", message); } showToast(level, message) { console.log(`[${level}] ${message}`); } } Notes and recommendations ------------------------- When using reconnecting WebSockets: * always handle ``onopen``, ``onmessage``, ``onerror``, and ``onclose``; * expect connections to close and reconnect; * use a fresh WebSocket token for every new connection when token protection is enabled; * include a ``channel`` query string value when you want to group connections; * send JSON payloads from the browser; * include the correct ``action`` value for route selection; * validate all incoming messages in Django; * avoid sending sensitive data unless the connection is authenticated and authorised. Related pages ------------- See also: * :doc:`api_gateway_setup`; * :doc:`adding_new_routes`; * :doc:`configuration`; * :doc:`cleanup`.