WebSocket Trigger icon

WebSocket Trigger

Starts the workflow when a websocket is opened

Overview

The WebSocket Trigger node initiates an n8n workflow when a WebSocket connection is established to a specified URI. It allows users to define custom JavaScript code that executes upon opening the socket, enabling flexible registration or handshake logic (such as sending authentication tokens or initial messages). This node is particularly useful for integrating with real-time APIs, event-driven systems, or services that require persistent, bidirectional communication.

Practical examples:

  • Listening for live updates from a chat server.
  • Registering and authenticating with a third-party WebSocket API.
  • Receiving push notifications or streaming data into n8n workflows.

Properties

Name Meaning
URI The WebSocket endpoint to connect to (e.g., wss://example.com). Required.
Open Event Code Custom JavaScript code executed when the socket connects. Can use $send to send messages over the socket.

Output

  • The node outputs JSON data received from the WebSocket server.
  • Each message received is parsed (attempted as JSON; if parsing fails, it is returned as an object of characters).
  • The output structure depends on the incoming message format from the WebSocket server.
  • If the server sends binary data, it will be handled as a string or array of characters in the output.

Example output (if server sends JSON):

{
  "action": "update",
  "data": {
    "id": 123,
    "status": "active"
  }
}

If the message is not valid JSON:

{
  "0": "H",
  "1": "e",
  "2": "l",
  "3": "l",
  "4": "o"
}

Dependencies

  • External Service: Requires access to the specified WebSocket endpoint.
  • Optional Credentials: Can use OAuth2 credentials (oAuth2Api) if needed by the target service.
  • Node.js Dependency: Uses the ws library for WebSocket connections.

Troubleshooting

  • Connection Errors:
    • "WebSocket connection closed unexpectedly" — The node will attempt to reconnect after 5 seconds. Check the URI and network connectivity.
    • "errored websocket" — Indicates an error during connection or message handling. Review the console logs for details.
  • Invalid URI:
    • Ensure the URI starts with ws:// or wss://.
  • Malformed Open Event Code:
    • Syntax errors or exceptions in the custom code can prevent successful registration or message sending. Test your code snippet before deploying.
  • Authentication Issues:
    • If the WebSocket server requires authentication, ensure correct credentials are provided and used in the Open Event Code.

Links and References

Discussion