WebSockets Integration

WebSockets keep a persistent connection open so your Aurelia components can react to server-side events instantly—no polling necessary. The Vite-powered Aurelia 2 starter already ships with everything you need to consume WebSockets from the browser; you only need a small client service and (optionally) a Node-based development server to broadcast messages while you iterate.


1. Optional: spin up a tiny WebSocket server

If you don’t already have a backend, you can scaffold a development server with the popular ws package:

npm install ws --save-dev
// scripts/dev-websocket-server.mjs
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (socket) => {
  console.log('Client connected');
  socket.send(JSON.stringify({ type: 'server-ready', timestamp: Date.now() }));

  socket.on('message', (data) => {
    // echo message to everyone (simple chat)
    wss.clients.forEach(client => {
      if (client.readyState === 1 /* WebSocket.OPEN */) {
        client.send(JSON.stringify({
          type: 'message',
          text: data.toString(),
          timestamp: Date.now(),
        }));
      }
    });
  });
});

console.log('WebSocket server listening on ws://localhost:8080');

Run it alongside npm run dev so both the Vite dev server and the WebSocket server stay active.


2. Configure an environment variable for the WebSocket URL

Keep the WebSocket endpoint in .env.local so you can point the frontend at different servers per environment:

Vite exposes variables prefixed with VITE_ via import.meta.env, letting you inject the URL without hard-coding it in source control.


3. Create a WebSocket client service

This service encapsulates connection lifecycle, JSON parsing, and basic logging. Because it’s registered as a singleton, every component that resolves IWebSocketClient shares the same connection.


4. Register the service when bootstrapping Aurelia


5. Build a chat component on top of the service

The single chat element now reflects server updates in real time and can safely send messages through the shared connection.


6. Tips & extensions

  • Reconnect logic: wrap the WebSocket instantiation in a helper that backs off and retries on close events when event.wasClean is false.

  • Binary data: switch to socket.binaryType = 'arraybuffer' and send typed arrays when transferring files or images.

  • Authentication: include JWTs or session tokens in the initial connection URL (e.g., ws://host?token=...) or upgrade request headers depending on your backend.

  • State integration: dispatch incoming messages into @aurelia/state or another store so multiple components can react without each subscribing to the socket.

With the connection wrapped in a DI-friendly service and the endpoint stored in environment variables, swapping between local, staging, and production WebSocket servers becomes trivial—and you avoid the legacy webpack-specific loader configuration entirely.

Last updated

Was this helpful?