Beyond fetch(), how does a Cloudflare Worker open an outbound TCP connection with connect() and serve a WebSocket with WebSocketPair?
answer
- a built-in module import
- a readable and a writable side
- two ends: keep one, return one
- status 101 with a webSocket
- close replies by compatibility date
basics
~20 sconnect() from cloudflare:sockets opens an outbound TCP socket with readable and writable streams, optionally TLS. WebSocketPair gives two linked sockets: the Worker calls accept() on one and returns the other in a 101 Response's webSocket option.
solid answer
~40 sFor raw TCP, `import { connect } from "cloudflare:sockets"` and call `connect({ hostname, port }, { secureTransport })` inside a handler. The `Socket` has a `readable` and a `writable` stream, an `opened` promise, `close()`, and `startTls()` when you chose `"starttls"`. Port 25, Cloudflare's own IP ranges, localhost and private addresses are refused, and HTTP on 80 or 443 should still use `fetch()`. For WebSockets, `new WebSocketPair()` returns two linked sockets: call `server.accept()`, attach `message` and `close` listeners, and return `new Response(null, { status: 101, webSocket: client })`. For compatibility dates from 2026-04-07 the runtime answers a peer's Close frame for you, and from 2026-03-17 binary messages arrive as `Blob` unless `binaryType` is `"arraybuffer"`. A TCP socket cannot be created at module scope or shared between requests.
code
javascript · 23 linesimport { connect } from "cloudflare:sockets";
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/live") {
if (request.headers.get("Upgrade") !== "websocket") {
return new Response("Expected a WebSocket upgrade", { status: 426 });
}
const [client, server] = Object.values(new WebSocketPair());
server.accept();
server.addEventListener("message", (event) => server.send(`ack:${event.data}`));
return new Response(null, { status: 101, webSocket: client });
}
const socket = connect({ hostname: "legacy-tcp.example.com", port: 7000 }, { secureTransport: "on" });
const writer = socket.writable.getWriter();
await writer.write(new TextEncoder().encode("STATUS\r\n"));
await writer.close();
return new Response(socket.readable, { headers: { "Content-Type": "text/plain" } });
},
};go deeper
Recall that connect() is imported from cloudflare:sockets and that a WebSocket is served by returning one end of a WebSocketPair in a 101 Response.
Explain the Socket's streams and secureTransport modes, the blocked destinations, accept(), and how close and binary handling depend on the compatibility date.
Diagnose socket failures in production: refused ports and addresses, connection limits, 1006 closes from an old compatibility date, and Blob-versus-ArrayBuffer handler bugs.
Judge when raw TCP from Workers is worth owning versus a managed path such as Hyperdrive, and when WebSocket state belongs in a Durable Object instead.
## Two APIs for traffic that is not one request and one response Most Worker code speaks HTTP through `fetch()`. Two runtime APIs cover the rest: `connect()` for **outbound TCP** to services with their own wire protocol, and `WebSocketPair` for **terminating a WebSocket** that a client opens to the Worker. | | `connect()` | `WebSocketPair` | |---|---|---| | Direction | Worker to a remote host | Client to the Worker | | Import | `cloudflare:sockets` | global | | Data | byte streams (`Uint8Array`) | messages (text or binary) | | Typical use | a mail, cache or database wire protocol | live updates, chat, echo | ## Outbound TCP with connect() `connect(address, options)` takes `{ hostname, port }` or a `"host:port"` string and returns a `Socket`: - `readable` and `writable` streams; the writable side accepts `Uint8Array` chunks. - `opened`, a promise resolved with `remoteAddress` and `localAddress` once connected, and `closed`, resolved when the socket ends. - `close()` to shut both sides. - `secureTransport`: `"off"` (default), `"on"` for TLS from the start, or `"starttls"` to upgrade later with `startTls()`, which returns a new socket and invalidates the old one. - `allowHalfOpen` (default `false`) to keep the writable side open after the remote end sends EOF. The platform restricts it: 1. Sockets must be created inside a handler, never at module scope, and cannot be shared across requests. 2. Port `25` is refused with `Connections to port 25 are prohibited`; Cloudflare's own IP ranges, `localhost` and private network addresses fail with `proxy request failed, cannot connect to the specified address`; a Worker connecting back to itself gets `TCP Loop detected`. 3. Each open socket counts toward the per-invocation limit on simultaneous connections. 4. Outbound connections leave from a prefix outside Cloudflare's published IP ranges, so an origin firewall cannot allow-list them by those ranges. 5. Inbound TCP to a Worker is not supported. For a database connection, the documentation points to Hyperdrive, which provides the same `connect()` API with pooling and query caching; for HTTP, `fetch()` remains the right tool. ## Serving a WebSocket with WebSocketPair `new WebSocketPair()` returns an object with two linked `WebSocket`s at keys `0` and `1`, conventionally destructured as `[client, server]`. The Worker keeps `server`, calls `server.accept()` to start handling it on Cloudflare's network, registers `message`, `close` and `error` listeners, and returns `client` to the runtime in `new Response(null, { status: 101, webSocket: client })`. Check the `Upgrade: websocket` header first and answer other requests normally. Incoming messages are limited to 32 MiB; a larger one closes the socket with code `1009`. Two behaviours changed this year and depend on the Worker's compatibility date: - From **2026-04-07** (`web_socket_auto_reply_to_close`), the runtime sends the reciprocal Close frame itself, and `readyState` is already `CLOSED` when the `close` event fires. Proxies that must close both sides in step pass `{ allowHalfOpen: true }` to `accept()`. - From **2026-03-17** (`websocket_standard_binary_type`), binary messages arrive as `Blob`, so a handler must `await event.data.arrayBuffer()`, unless it sets `binaryType = "arraybuffer"` before `accept()`. Each plain-Worker WebSocket is handled by the invocation that accepted it and shares nothing with other connections. When many clients must share state, such as a chat room, the documentation steers you to a Durable Object, whose WebSocket API also supports hibernation. ## Choosing the right tool - **HTTP to anything**: `fetch()`. A `connect()` call to port 80 or 443 is the wrong tool; the troubleshooting guide says to use `fetch()` for HTTP. - **A WebSocket to an upstream server**: `fetch()` with an `Upgrade: websocket` header, then `resp.webSocket.accept()`; this is also how to get half-open close handling for a client-side socket. - **A non-HTTP protocol to a public host**: `connect()`, with `secureTransport: "on"` whenever the protocol allows TLS. - **Clients connecting to the Worker in real time**: `WebSocketPair`, or a Durable Object once connections must share state. Whatever the choice, wrap socket creation and writes in `try...catch` and turn failures into a clear HTTP error for the caller.
- Clients of a Worker pinned to a 2025 compatibility date report close code 1006 when they disconnect. Why?Before compatibility date 2026-04-07, or with `web_socket_manual_reply_to_close`, a received Close frame leaves the socket `CLOSING` until code calls `close()`. A handler that never replies leaves the client waiting, which can surface as an abnormal `1006` closure. Call `server.close(event.code, reason)` in the `close` listener, or move to a date that auto-replies.
- How do you upgrade a plain TCP connection to TLS after a protocol's STARTTLS exchange?Open it with `connect(address, { secureTransport: "starttls" })`, exchange the plaintext greeting, then call `socket.startTls()`. It returns a new `Socket` that speaks TLS; the original socket is closed, so create new readers and writers from the returned one. Call `startTls()` only once.
- connect() is a global function in Workers, just like fetch().
- A Worker can relay mail by connecting to an SMTP server on port 25.
- A TCP socket opened at module scope can be reused across requests.
- WebSocketPair's server socket works without calling accept().
- With current compatibility dates, code must always call close() inside the close handler.
Assumes compatibility dates from 2026-04-07: the runtime auto-replies to Close frames (earlier dates leave the socket CLOSING until close()), and from 2026-03-17 binary WebSocket messages default to Blob.