The connect() handler receives inbound TCP connections as a Socket. Use the socket's readable and writable streams to inspect data, implement a TCP protocol, or proxy the connection to another service.
export default {
async connect(socket, env, ctx) {
const { remoteAddress, localAddress } = await socket.opened;
console.log("TCP connection opened", {
remoteAddress,
localAddress,
});
await socket.readable.pipeTo(socket.writable);
},
};export default {
async connect(
socket: Socket,
env: Env,
ctx: ExecutionContext,
): Promise<void> {
const { remoteAddress, localAddress } = await socket.opened;
console.log("TCP connection opened", {
remoteAddress,
localAddress,
});
await socket.readable.pipeTo(socket.writable);
},
} satisfies ExportedHandler<Env>;The example echoes each byte back to the client. Await all stream operations that must remain active for the connection. When the handler's returned promise settles, the inbound socket closes. A Worker without a connect() handler rejects forwarded TCP connections.
socket(Socket) — The established inbound connection.socket.readablecontains bytes sent by the client.socket.writablesends bytes to the client.socket.openedresolves toSocketInfo, which contains the connection addresses.socket.closedsettles when the connection closes.
env(Env) — The Worker's bindings.ctx(ExecutionContext) — The handler's execution context.
The handler returns void or Promise<void>. Keep the returned promise pending while the Worker is processing the connection.
Inbound sockets preserve TCP half-closes. When a client closes its writable side, the Worker can continue sending data through socket.writable. Set allowHalfOpen: true on outbound sockets when a proxy must preserve this behavior.
For connections delivered by Spectrum, remoteAddress contains the original client's IP address and source port. Extract the IP address for client identification, such as rate limiting.
localAddress contains the destination IP address and Spectrum edge port. Use the port to identify which application port received the connection.
Addresses include the port, such as 203.0.113.7:12345. IPv6 addresses use brackets, such as [2001:db8::1]:12345. remoteAddress is undefined when client address metadata is unavailable.
For service bindings, localAddress contains the address the caller passed to connect().
Spectrum Enterprise can terminate TLS before forwarding the connection to the Worker. Without Spectrum TLS termination, the Worker can proxy encrypted bytes to a backend service that terminates TLS.
Calling socket.startTls() on an inbound socket delivered by Spectrum is not supported, including when Spectrum TLS termination is turned off.
SMTP on port 587 and IMAP on port 143 can negotiate a TLS upgrade with STARTTLS. Proxy these connections to a backend that handles the upgrade and TLS handshake. Spectrum TLS termination expects TLS from the start of the connection.
The TCP connect() handler does not require a compatibility flag. Deploy the Worker before selecting it as a Spectrum origin.
Another Worker can open a TCP connection through a service binding. This caller returns the bytes sent by the receiving Worker:
export default {
fetch(request, env) {
const socket = env.BACKEND.connect("backend:1234");
return new Response(socket.readable);
},
};export default {
fetch(request, env) {
const socket = env.BACKEND.connect("backend:1234");
return new Response(socket.readable);
},
} satisfies ExportedHandler<Env>;The receiving Worker can export a connect() handler or implement it on a WorkerEntrypoint class. Configure the BACKEND binding to target this entrypoint:
import { WorkerEntrypoint } from "cloudflare:workers";
export class Backend extends WorkerEntrypoint {
async connect(socket) {
const writer = socket.writable.getWriter();
await writer.write(new TextEncoder().encode("Hello from Worker B\n"));
await writer.close();
}
}import { WorkerEntrypoint } from "cloudflare:workers";
export class Backend extends WorkerEntrypoint {
async connect(socket: Socket): Promise<void> {
const writer = socket.writable.getWriter();
await writer.write(new TextEncoder().encode("Hello from Worker B\n"));
await writer.close();
}
}The following handler creates an outbound TCP socket and pipes data in both directions:
import { connect } from "cloudflare:sockets";
export default {
async connect(socket) {
const upstream = connect(
{ hostname: "origin.example.com", port: 5432 },
{ allowHalfOpen: true },
);
try {
await upstream.opened;
await Promise.all([
socket.readable.pipeTo(upstream.writable),
upstream.readable.pipeTo(socket.writable),
]);
} finally {
await Promise.allSettled([socket.close(), upstream.close()]);
}
},
};import { connect } from "cloudflare:sockets";
export default {
async connect(socket: Socket): Promise<void> {
const upstream = connect(
{ hostname: "origin.example.com", port: 5432 },
{ allowHalfOpen: true },
);
try {
await upstream.opened;
await Promise.all([
socket.readable.pipeTo(upstream.writable),
upstream.readable.pipeTo(socket.writable),
]);
} finally {
await Promise.allSettled([socket.close(), upstream.close()]);
}
},
} satisfies ExportedHandler;Set allowHalfOpen: true on intermediate sockets when either side must continue sending after receiving an end-of-file signal.
Outbound TCP connections to Cloudflare IP addresses are blocked. Do not connect the Worker back to its own Spectrum hostname. Refer to TCP socket considerations.
Configure a raw TCP listener in wrangler.jsonc for your connect() handler:
{
"connect": [{ "protocol": "tcp", "port": 8788 }],
}[[connect]]
protocol = "tcp"
port = 8_788-
Start local development:
npx wrangler devyarn wrangler devpnpm wrangler dev -
Connect a TCP client to port
8788:echo "Hello, Worker" | nc localhost 8788
Wrangler serves HTTP on port 8787 by default. The separate TCP port is set by the connect configuration; it does not follow the HTTP port automatically.
For example, to test a local gRPC client, connect it to localhost:8788. Refer to Bidirectional gRPC with Workers and Containers for a complete example.
Create a Spectrum application with the Worker as its origin. Spectrum accepts connections on the configured hostname and edge port, then invokes this handler.
Refer to Route TCP traffic to a Worker for dashboard, Cloudflare CLI, and REST API instructions.