Developer

WebSocket API

Open persistent WebSocket connections to external real-time services from an applet method, managed by the native host.

ctx.sdk.ws opens persistent WebSocket connections to external services: real-time APIs, chat protocols, and streaming data feeds. Connections are managed by the native host, so you are not bound by browser restrictions on iframe WebSocket origins.

Scope required: network:ws

Usage

Inside a method run, reach the surface via ctx.sdk.ws. A connection handle is returned from connect; pass it to onMessage, send, and close.

import { defineMethod } from "@rightplace/applet-sdk/v2";

export const subscribe = defineMethod({
  name: "@wiredwp/feed.subscribe",
  async run({ topic }, ctx) {
    const conn = await ctx.sdk.ws.connect("wss://stream.example.com");

    ctx.sdk.ws.onMessage(conn, (msg) => {
      // handle the incoming message
    });

    await ctx.sdk.ws.send(conn, JSON.stringify({ type: "subscribe", topic }));

    // Later, when you no longer need the stream:
    await ctx.sdk.ws.close(conn);
  },
});

Operations

  • connect(url) opens a connection and resolves to a handle.
  • onMessage(conn, handler) registers a handler for incoming messages on that connection.
  • send(conn, data) sends a message through the connection.
  • close(conn) closes the connection.

Notes

  • Declare network:ws in applet.json::scopes[].
  • The host owns the socket lifecycle. Always close connections you no longer need so they do not linger past the work that opened them.
  • Use a wss:// URL for encrypted transport.
  • For request and response style traffic, prefer the HTTP API. WebSockets are for full-duplex, long-lived streams.
  • For cross-device messaging between instances of your own applet, use the Relay API instead.