# WebSocket API

WebSocket API allows your Function to act as a full WebSocket server or client and proxy bidirectional traffic to backend services. This unlocks real-time use cases such as chat, multiplayer games, telemetry dashboards, and AI inference streams—all served directly from the edge for sub-second latency.

:::note
At the moment, this capability is exclusively accessible to customers with **Business**, **Enterprise**, and **Mission-Critical** Support, also available in the **Reserved Capacity** or **Saving Plan** contracts. [Contact the Support team](https://tickets.azion.com/en/support/loginen/support/login/new) to request access to this capability.
:::

## Server and Client Modes

- Use the `upgradeWebSocket()` function to handle server-side WebSocket upgrade requests.
- For client-side, outbound connections, use the standard `WebSocket(url)` API.

## Broadcast Helpers

- Easily broadcast messages to all connected clients using built-in helpers, enabling efficient fan-out with minimal code.

## Metrics and Logs

These events are visible in Real-Time Metrics and LogStream, helping you monitor connection and message activities.

- `websocket.connection.accepted`
- `message.sent`
- `message.received`

## Firewall Support

- Firewall rules can inspect WebSocket traffic before the upgrade process is finalized.
- Ensure your firewall policies are configured to handle WebSocket connections as needed.

## Example

```javascript
export default {
    async fetch(request, env, ctx) {
        // Check if the request is a WebSocket upgrade
        if (request.headers.get("upgrade") === "websocket") {
            // Use the upgradeWebSocket function to handle the WebSocket upgrade
            const { response, socket } = upgradeWebSocket(request);

            // Handle WebSocket events
            socket.addEventListener("open", () => {
                console.log("WebSocket connection established");
            });

            socket.addEventListener("message", (event) => {
                console.log(`Message received: ${event.data}`);
                socket.send("pong"); // Respond with "pong"
            });

            socket.addEventListener("close", () => {
                console.log("WebSocket connection closed");
            });

            socket.addEventListener("error", (error) => {
                console.error("WebSocket error:", error);
            });

            // Return the response to complete the WebSocket upgrade
            return response;
        }

        // If the request is not a WebSocket upgrade, serve a simple HTML page
        const htmlContent = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>WebSocket Example</title>
            </head>
            <body>
                <h1>WebSocket Example</h1>
                <script>
                    const socket = new WebSocket("wss://" + location.host);
                    socket.onopen = () => console.log("WebSocket connected");
                    socket.onmessage = (event) => console.log("Message from server:", event.data);
                    socket.onclose = () => console.log("WebSocket disconnected");
                    socket.onerror = (error) => console.error("WebSocket error:", error);
                </script>
            </body>
            </html>
        `;

        return new Response(htmlContent, {
            status: 200,
            headers: { "Content-Type": "text/html" },
        });
    },
};
```