Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/cloudflare/partykit/llms.txt

Use this file to discover all available pages before exploring further.

The WebSocket named export from partysocket is a drop-in replacement for the standard browser WebSocket API. It automatically reconnects when a connection drops, buffers messages sent while disconnected, supports dynamic and async URL providers, and works across browsers, Node.js, React Native, Cloudflare Workers, Deno, and Bun — without any dependencies on Window, the DOM, or an EventEmitter library.

Import

import { WebSocket } from "partysocket";
This is the ReconnectingWebSocket class re-exported under the familiar WebSocket name. It is intentionally API-compatible with the browser’s built-in WebSocket so you can swap it in with minimal changes.

Constructor

new WebSocket(
  url: UrlProvider,
  protocols?: ProtocolsProvider,
  options?: Options
)
url
UrlProvider
required
The WebSocket endpoint to connect to. Can be a plain string, a function that returns a string, or an async function that resolves to a string. The function is re-evaluated before every connection attempt, making it easy to inject fresh tokens or rotate between endpoints.
protocols
ProtocolsProvider
Optional sub-protocol(s). Accepts a static value or a (possibly async) function that returns one before each connection attempt. See ProtocolsProvider below.
options
Options
Reconnection and behaviour options. See Options below.

Types

UrlProvider

type UrlProvider =
  | string
  | (() => string)
  | (() => Promise<string>);
The URL parameter accepts three forms:
FormWhen to use
stringStatic endpoint that never changes.
() => stringDynamic URL computed synchronously (e.g. round-robin).
() => Promise<string>Async URL — e.g. fetch a short-lived signed URL or auth token before each connect.

ProtocolsProvider

type ProtocolsProvider =
  | null
  | string
  | string[]
  | (() => string | string[] | null)
  | (() => Promise<string | string[] | null>);
The protocols parameter mirrors UrlProvider in flexibility. Pass null to opt out of sub-protocols, or a function to generate them fresh before each connection.

Options

type Options = {
  WebSocket?: any;
  maxReconnectionDelay?: number;
  minReconnectionDelay?: number;
  reconnectionDelayGrowFactor?: number;
  minUptime?: number;
  connectionTimeout?: number;
  maxRetries?: number;
  maxEnqueuedMessages?: number;
  startClosed?: boolean;
  shouldReconnectOnClose?: (event: CloseEvent) => boolean;
  debug?: boolean;
  debugLogger?: (...args: any[]) => void;
};
WebSocket
any
Custom WebSocket constructor. Required in environments without a global WebSocket, such as older Node.js. Install the ws package and pass it here.
maxReconnectionDelay
number
Maximum delay between reconnection attempts in milliseconds. Default: 10000.
minReconnectionDelay
number
Minimum delay between reconnection attempts in milliseconds. Default: 3000.
reconnectionDelayGrowFactor
number
Factor by which the reconnection delay grows after each failed attempt. Default: 1.3.
minUptime
number
Minimum time in milliseconds a connection must remain open to be considered stable and reset the retry counter. Default: 5000.
connectionTimeout
number
Milliseconds to wait for open before treating the attempt as a timeout and retrying. Default: 4000.
maxRetries
number
Maximum total reconnection attempts before giving up. Default: Infinity.
maxEnqueuedMessages
number
Maximum number of messages to buffer while disconnected. Default: Infinity.
startClosed
boolean
When true, the socket starts in CLOSED state and does not connect until reconnect() is called explicitly. Default: false.
shouldReconnectOnClose
(event: CloseEvent) => boolean
Called on each close event. Return false to prevent automatic reconnection for that specific close (e.g. intentional server-side termination).
debug
boolean
Enables verbose internal logging. Default: false.
debugLogger
(...args: any[]) => void
Custom log function used when debug is true. Defaults to console.log.

Properties

readyState
number
Current connection state. See constants below.
url
string
The URL as reported by the underlying WebSocket. Empty string while no connection exists.
retryCount
number
Number of reconnection attempts made since the last stable open.
bufferedAmount
number
Total byte size of messages queued via send() but not yet transmitted, including both the internal queue and the underlying socket’s buffer.
binaryType
BinaryType
How binary messages are received ("blob" or "arraybuffer"). Default: "blob".
protocol
string
The sub-protocol selected by the server, or an empty string.
extensions
string
Extensions negotiated by the server, or an empty string.
shouldReconnect
boolean
true while the socket is in automatic-reconnect mode. Becomes false after close() is called.
onopen
((event: Event) => void) | null
Inline event handler for the open event.
onmessage
((event: MessageEvent) => void) | null
Inline event handler for the message event.
onclose
((event: CloseEvent) => void) | null
Inline event handler for the close event.
onerror
((event: ErrorEvent) => void) | null
Inline event handler for the error event.

Constants

ConstantValueDescription
WebSocket.CONNECTING0Connection not yet open.
WebSocket.OPEN1Connection open and ready.
WebSocket.CLOSING2Closing handshake in progress.
WebSocket.CLOSED3Connection closed or could not open.
The same constants are also available as instance properties.

Methods

send

send(data: string | ArrayBuffer | Blob | ArrayBufferView): boolean
Transmits data. Returns true if sent immediately over an open connection, false if the message was queued. Buffered messages are flushed before the next open event.

close

close(code?: number, reason?: string): void
Permanently closes the connection and disables automatic reconnection. The close event fires synchronously.

reconnect

reconnect(code?: number, reason?: string): void
Re-opens the connection and resets the retry counter. Use this after startClosed: true or to force a fresh connection.

drainQueuedMessages

drainQueuedMessages(): Message[]
Returns and clears all messages buffered by send() that were never transmitted. Useful when swapping out a socket instance and wanting to forward unsent messages to its replacement.

addEventListener

addEventListener(
  type: "open" | "close" | "message" | "error",
  listener: EventListener
): void

removeEventListener

removeEventListener(
  type: "open" | "close" | "message" | "error",
  listener: EventListener
): void

Usage examples

Simple drop-in replacement

import { WebSocket } from "partysocket";

const ws = new WebSocket("wss://my.site.com");

ws.addEventListener("open", () => {
  ws.send("hello!");
});

ws.addEventListener("message", (event) => {
  console.log("received:", event.data);
});

Async URL provider — fresh auth token per connection

import { WebSocket } from "partysocket";

const ws = new WebSocket(async () => {
  const token = await getSessionToken();
  return `wss://my.site.com/${token}`;
});

Round-robin URL provider

import { WebSocket } from "partysocket";

const urls = [
  "wss://us.my.site.com",
  "wss://eu.my.site.com",
  "wss://ap.my.site.com",
];
let urlIndex = 0;

const ws = new WebSocket(() => urls[urlIndex++ % urls.length]);

Dynamic sub-protocols

import { WebSocket } from "partysocket";

const protocols = ["v1", "v2", ["v3.1", "v3.2"]];
let protocolsIndex = 0;

const ws = new WebSocket(
  "wss://my.site.com",
  () => protocols[protocolsIndex++ % protocols.length]
);

Custom options and Node.js WebSocket

import { WebSocket } from "partysocket";
import WS from "ws";

const ws = new WebSocket("wss://my.site.com", [], {
  WebSocket: WS,
  connectionTimeout: 1000,
  maxRetries: 10,
});

Conditional reconnection

import { WebSocket } from "partysocket";

const ws = new WebSocket("wss://my.site.com", undefined, {
  // Only reconnect on abnormal closures (code 1006) —
  // let intentional server-side closes (code 1000) end the session.
  shouldReconnectOnClose: (event) => event.code !== 1000,
});

Deferred connect

import { WebSocket } from "partysocket";

const ws = new WebSocket("wss://my.site.com", undefined, {
  startClosed: true,
});

// Connect later, when you're ready:
ws.reconnect();
If you need environment-specific polyfills for EventTarget, import partysocket/event-target-polyfill before any other partysocket imports.

Build docs developers (and LLMs) love