WebSockets & Real-time
Implement real-time applications using Cloudflare Workers and WebSockets for interactive experiences.
WebSockets & Real-time is a free Edge Computing with Cloudflare Workers & Deno lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Edge Computing with Cloudflare Workers & Deno learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Real-time Apps with WebSockets
What are WebSockets? They enable real-time, two-way communication between a client (like your browser) and a server. Unlike traditional HTTP requests, WebSockets keep a persistent connection open.
This is perfect for applications needing instant updates, like chat apps, live dashboards, or online games.
HTTP vs. WebSocket Connection
Traditional HTTP is stateless and request-response based. Each action needs a new request from the client.
WebSockets, however, establish a single, long-lived connection. Once open, both client and server can send messages anytime without waiting for a request.
- HTTP: Client requests, server responds, connection closes.
- WebSocket: Client requests upgrade, server approves, connection stays open.
The WebSocket Upgrade
Before a WebSocket connection is established, an initial HTTP request is made. The client sends an "Upgrade" header, indicating its desire to switch protocols.
If the server supports WebSockets, it responds with an "101 Switching Protocols" status code, upgrading the connection from HTTP to WebSocket protocol. This is known as the WebSocket Handshake.
Cloudflare Workers & WebSockets
Cloudflare Workers are ideal for handling WebSockets at the edge. They can act as the server endpoint, managing connections and processing real-time messages directly where your users are.
Workers provide a WebSocketPair API to easily upgrade an incoming HTTP request into a WebSocket connection, simplifying the handshake process.
Worker WebSocket Upgrade
Let's create a Worker that accepts an incoming WebSocket connection. We'll use new WebSocketPair() to manage the connection.
Try running this example. To test, you'd typically connect using a WebSocket client (e.g., a browser's developer console or a dedicated tool).
export default {
async fetch(request) {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
const { 0: client, 1: server } = new WebSocketPair();
server.accept(); // Accept the WebSocket connection
server.addEventListener('message', event => {
console.log('Received message:', event.data);
// We'll add logic to send messages back soon!
});
server.addEventListener('close', event => {
console.log('WebSocket closed:', event.code, event.reason);
});
server.addEventListener('error', event => {
console.error('WebSocket error:', event.message);
});
return new Response(null, {
status: 101,
webSocket: client,
});
},
};WebSocket Event Listeners
Once a WebSocket connection is established, you can listen for various events on the server-side WebSocket object:
'open': Connection successfully established.'message': A message is received from the client. The message data is inevent.data.'close': The connection is closed by either side.'error': An error occurred on the connection.
These allow your Worker to react dynamically to client interactions.
Echoing Messages
In the previous code, we added an event listener for 'message'. Let's extend it to ensure the Worker echoes back any message it receives.
The server.send(message) method allows the Worker to send data back to the connected client. This creates a simple "echo" server.
export default {
async fetch(request) {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
const { 0: client, 1: server } = new WebSocketPair();
server.accept();
server.addEventListener('message', event => {
const message = event.data;
console.log('Received message:', message);
// Echo the message back to the client
server.send(`Echo from Worker: ${message}`);
});
server.addEventListener('close', event => {
console.log('WebSocket closed');
});
server.addEventListener('error', event => {
console.error('WebSocket error:', event);
});
return new Response(null, {
status: 101,
webSocket: client,
});
},
};Real-time Broadcasting
An echo server is a good start, but many real-time apps need to send messages to multiple connected clients (broadcasting).
For example, in a chat application, when one user sends a message, all other users in the chat room should receive it.
Cloudflare Workers, being stateless by default, need a mechanism to manage these connections across requests. This is where Durable Objects become incredibly useful for maintaining state and managing multiple WebSocket connections for a shared resource.
(We'll explore Durable Objects in a later lesson!)
Securing WebSockets
Just like HTTP, WebSocket connections should be secured. Always use wss:// (WebSocket Secure) instead of ws://.
wss:// connections are encrypted using TLS/SSL, preventing eavesdropping and tampering. Cloudflare Workers handle TLS termination automatically, so your connections are secured by default when deployed.
- Use
wss://for production. - Implement authentication/authorization.
- Validate all incoming messages.
Check Your Understanding
Consider a Cloudflare Worker that aims to establish a WebSocket connection with a client.
Recap: WebSockets at the Edge
Great job! You've learned how to implement real-time communication with WebSockets using Cloudflare Workers.
- WebSockets enable persistent, two-way communication.
- Workers use
WebSocketPairand101 Switching Protocolsfor the handshake. - Event listeners (
'message','close','error') manage connection lifecycle. - Always use
wss://for secure connections.
In future lessons, we'll dive into Durable Objects to manage state across multiple WebSocket connections for advanced real-time applications.
Frequently asked questions
Is the “WebSockets & Real-time” lesson free?
Yes — the full text of “WebSockets & Real-time” is free to read here on the web, and the Edge Computing with Cloudflare Workers & Deno course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Edge Computing with Cloudflare Workers & Deno course, upgrade to CoddyKit PRO.
What will I learn in “WebSockets & Real-time”?
Implement real-time applications using Cloudflare Workers and WebSockets for interactive experiences. You practise Edge Computing with Cloudflare Workers & Deno with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Edge Computing with Cloudflare Workers & Deno?
No prior experience is required. Edge Computing with Cloudflare Workers & Deno on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “WebSockets & Real-time” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Edge Computing with Cloudflare Workers & Deno lesson?
Yes. Every Edge Computing with Cloudflare Workers & Deno lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.