WebSocket
The WebSocket API of Azion Runtime: how a function accepts a WebSocket upgrade, opens an outbound connection, and where its events appear.
The WebSocket API of Azion Runtime lets a function act as a WebSocket server or as a WebSocket client, and carry bidirectional traffic to backend services. The function itself accepts or opens the connection, which separates this API from WebSocket Proxy, where an application only carries the connection to a WebSocket server at your origin. Use the WebSocket API for real-time workloads such as chat, multiplayer games, telemetry dashboards, and AI inference streams.
Availability
The WebSocket API is available to customers with Business, Enterprise, or Mission-Critical Support, and to customers with a Reserved Capacity or Saving Plan contract. To request access, contact Technical Support.
Server and client modes
A deployed function reaches both modes through two globals:
| Global | Mode | Description |
|---|---|---|
upgradeWebSocket(request) | Server | Accepts the WebSocket upgrade of an incoming request. Returns an object with response and socket: return response from the handler to complete the upgrade, and use socket to send and receive messages. |
WebSocket(url) | Client | The standard WebSocket constructor. Opens an outbound WebSocket connection from the function to url. |
upgradeWebSocket() accepts only a request whose upgrade header contains websocket. Called with any other request, it throws TypeError: Invalid Header: 'upgrade' header must contain 'websocket', so check the header before the call, as the example below does.
Azion Runtime also provides helpers that broadcast a message to every connected client, so one function can fan out a message to all of its connections.
Metrics and logs
WebSocket activity produces three events, which appear in Real-Time Metrics and Data Stream to help you monitor connections and messages:
websocket.connection.acceptedmessage.sentmessage.received
Firewall inspection
The rules of a firewall can inspect WebSocket traffic before the upgrade completes. Check that your firewall rules let through the WebSocket connections that your function must accept.
Example
This handler accepts a WebSocket upgrade when the request carries upgrade: websocket, logs the open, message, close, and error events of the socket, and answers each message with pong. Any other request receives an HTML page whose script opens a WebSocket connection back to the same host:
A deployed function returns this response to a request without the upgrade header. The body is the HTML page, with its line breaks escaped: