Skip to content

Connect Handler

Last updated View as MarkdownAgent setup

Background

Export a connect() handler to let a Worker accept an inbound TCP connection and read and write raw bytes on it. The handler receives a Socket object, the same type returned by connect() from cloudflare:sockets for outbound connections.

A Worker receives a connection in its connect() handler when another Worker forwards a TCP connection to it over a service binding, by calling connect() on the binding:

// Worker A forwards a TCP connection to Worker B over a service binding
export default {
	async fetch(request, env) {
		const socket = env.BACKEND.connect("example.com:1234");
		// Read from and write to socket.readable / socket.writable
		return new Response(socket.readable);
	},
};

Syntax

export default {
	async connect(socket, env, ctx) {
		const writer = socket.writable.getWriter();
		await writer.write(new TextEncoder().encode("hello"));
		await writer.close();
	},
};
interface Env {}

export default {
	async connect(socket: Socket, env: Env, ctx: ExecutionContext) {
		const writer = socket.writable.getWriter();
		await writer.write(new TextEncoder().encode("hello"));
		await writer.close();
	},
} satisfies ExportedHandler<Env>;

You can also implement connect() as a method on a WorkerEntrypoint class, which lets a single Worker expose a connect() handler alongside other RPC methods:

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"));
		await writer.close();
	}
}

Parameters

  • socket Socket
    • The inbound Socket used to read and write raw bytes on the connection.
    • socket.opened resolves with a SocketInfo object. On a connect() handler, localAddress is set to the address the caller passed to connect() on the service binding.
  • env object
  • ctx object

A Worker that does not export a connect() handler rejects any connection forwarded to it.

  • TCP sockets — Create outbound TCP connections and work with the Socket API.
  • Service bindings — Call one Worker from another, including forwarding TCP connections with connect().

Was this helpful?