mercureact/doc/WebSockets.md

1.5 KiB

Websockets with Mercureact

Enable WebSockets by adding the websocket handler to a http listener.

const conn = new WebSocket("wss:///.well-known/mercure?token=" + jwt + "&topic=/product/420");
conn.onmessage = function (message) {
    const update = JSON.parse(message);
    // do something with update.data, update.topic[] and update.event
};

Security

WebSockets are more difficult to secure than SSEs, which means some tricks will have to be applied.

Right now that means in-band authentication. This works alongside and identical to anonymous susbcriptions for SSE events. Additionally, tokens and topics are not parsed from the URL at the moment. See below for how to handle auth and subscriptions.

Protocol

The client sends plaintext (for now) consisting of a verb (command) and arguments. Arguments containing spaces must be quoted, and special characters escaped.

To authenticate, the client should send auth followed by a space and the JWT token. If the server has disabled anonymous subscriptions, this MUST be the first message sent when connected, and the client will be disconnected if authentication fails.

To subscribe, the client sends subscribe followed by a space-separated list of topics.

To unsubscribe, the client sends unsubscribe followed by a space-separated list of topics.

Responses

All messages from the server are JSON frames.

The server will respond with {"ok":true} if the command was accepted, and {"ok":false} otherwise.

Events are sent with the keys event, topic and data.