@joystick.js/node

Sending WebSocket Messages

How to send messages to clients using the connection.send() method and the websockets() function.

There are two ways to send a WebSocket message to a client:

  1. Via the connection.send() method on the connection object passed to your WebSocket endpoint’s on_open(), on_message(), and on_close() event handlers.
  2. Via the websockets() function available as a named export from @joystick.js/node.

Example Usage

Sending Messages via the Connection Object

/index.server.js

import joystick from '@joystick.js/node';

joystick.app({
  websockets: {
    example_endpoint: {
      on_open: (connection = {}) => {
        connection.send(JSON.stringify({ message: 'Hello from the server!' }));
      },
      on_message: (message = {}, connection = {}) => {
        connection.send(JSON.stringify({ message: 'Hello from the server!' }));
      },
      on_close: (code = 0, reason = '', connection = {}) => {
        connection.send(JSON.stringify({ message: 'Hello from the server!' }));
      },
    },
  },
  routes: { ... },
});

When sending messages using connection.send(), ensure the message is stringified as JSON (JSON.stringify()) because Joystick’s client-side WebSocket connection expects messages to be JSON-formatted.

Sending Messages via the websockets() Function

/index.server.js

import joystick, { websockets } from '@joystick.js/node';

joystick.app({
  websockets: {
    example_endpoint: {
      on_open: (connection = {}) => {
        websockets('example_endpoint').send({ message: 'Hello from the server!' });
      },
      on_message: (message = {}, connection = {}) => {
        websockets('example_endpoint').send({ message: 'Hello from the server!' });
      },
      on_close: (code = 0, reason = '', connection = {}) => {
        websockets('example_endpoint').send({ message: 'Hello from the server!' });
      },
    },
  },
  routes: { ... },
});

The websockets() function returns an object with a .send() method that automatically stringifies your message, allowing you to pass a plain JavaScript object.

Filtering Messages for Specific Clients

Sending a Message to a Specific ID

websockets('example_endpoint').send(
  { message: 'Hello from the server!' },
  'some_unique_id_abc123'
);

Here, the some_unique_id_abc123 string filters the message to only clients who passed the same ID in their WebSocket connection’s query.id.

API

Definition

websockets(websocket_name: string) => {
  send: (message: object, channel_id: string) => void
}

Parameters

websocket_name string required
The name of the WebSocket server to target.

Returns

{
  send: (message: object, channel_id: string) => void
}
send function required
A function that sends a message to clients connected to the specified WebSocket server. Accepts a message object (required) and an optional channel_id string to filter recipients.