This site is not affiliated with or endorsed by Cloudflare, Inc. It showcases deployable experiments across most Cloudflare products.
Edge Platform

WebSocket Echo

WebSocket echo server on Cloudflare Workers - bidirectional realtime messaging reference implementation

Upgrade HTTP requests to WebSocket connections and echo every message back from the edge using the Workers WebSocket API.

API Reference

GET /echo

Accepts a WebSocket upgrade and echoes each message with an echo: prefix.

Requires Upgrade: websocket on the incoming request.

Example Request

Connect with any WebSocket client:

websocat wss://your-worker.workers.dev/echo

Send hello and receive echo: hello.

Non-WebSocket Response

When the request is not a WebSocket upgrade, the worker returns HTTP 426:

{
  "error": "Expected WebSocket upgrade request (Upgrade: websocket)",
  "code": "NOT_WEBSOCKET"
}

Error Codes

  • 426 - Request missing WebSocket upgrade (NOT_WEBSOCKET)

Use Cases

  • Learn WebSocket upgrades with WebSocketPair in Workers
  • Test real-time clients against a minimal echo server
  • Prototype bidirectional edge apps before adding Durable Objects
  • Debug WebSocket connectivity from browsers and CLI tools

Limitations

  • Echo server only; no persistence, rooms, or broadcast between clients
  • No authentication or explicit message size limits in this demo
  • WebSocket connections are subject to Worker CPU and duration limits

Use in your project

Copy these files into an existing Worker. Prefer Deployment to try the full experiment first. Source: apps/experiments/websocket-echo.

DependenciesNoneBindingsNonePlatformWebSockets
const ECHO_PREFIX = "echo: ";export function createEchoWebSocket(): Response {  const pair = new WebSocketPair();  const client = pair[0];  const server = pair[1];  server.accept();  server.addEventListener("message", (event) => {    const payload = typeof event.data === "string" ? event.data : String(event.data);    server.send(`${ECHO_PREFIX}${payload}`);  });  server.addEventListener("close", () => {    server.close();  });  return new Response(null, {    status: 101,    webSocket: client,  });}export function isWebSocketUpgrade(request: Request): boolean {  const upgrade = request.headers.get("Upgrade");  return upgrade?.toLowerCase() === "websocket";}export { ECHO_PREFIX };

Deployment

Click the deploy button

Deploy to Cloudflare Workers

Deploy

No additional configuration required.

Test your deployment

Connect with websocat, a browser WebSocket client, or your app's WebSocket library to wss://your-worker.workers.dev/echo.

Local Development

cd apps/experiments/websocket-echo
npm install
npm run dev

Connect to ws://localhost:8787/echo with a WebSocket client.

Cloudflare Features Used

  • Workers - Edge compute runtime
  • WebSockets - WebSocketPair for bidirectional messaging

On this page