Skip to content

Changelog

New updates and improvements at Cloudflare.

Back to all posts

Connect handler no longer requires an experimental flag

View as MarkdownAgent setup

Workers can now export a connect() handler without enabling any compatibility flag. Previously, using a connect() handler required the experimental compatibility flag, which cannot be enabled in production.

A connect() handler lets a Worker accept a TCP connection forwarded from another Worker over a service binding, and read and write raw bytes on it using a Socket object:

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

Another Worker forwards a connection to it by calling connect() on the service binding:

frontend-worker.jsjs
export default {
	async fetch(request, env) {
		const socket = env.BACKEND.connect("example.com:1234");
		return new Response(socket.readable);
	},
};

On the connect() handler side, socket.opened resolves with localAddress set to the address the caller passed to connect().

Direct inbound TCP connections remain unsupported at present.

For more information, refer to the connect handler documentation.