Documentation
Use cases
WebSockets

WebSockets

WebSockets are great for bringing real-time updates to a web application. They allow sending events from the backend application to the frontend (JavaScript) application.

Implementing WebSockets implies maintaining a long-lived connection between the JavaScript client and the backend. As you can imagine, that is not possible with AWS Lambda. Indeed, Lambda only runs code on events: it is impossible to run code continuously.

API Gateway can solve that problem (opens in a new tab): API Gateway maintains the long-lived WebSocket connections and invokes Lambda when an event happens (connection, disconnection, message).

To handle WebSocket events, extend the WebsocketHandler class:

use Bref\Context\Context;
use Bref\Event\ApiGateway\WebsocketEvent;
use Bref\Event\ApiGateway\WebsocketHandler;
use Bref\Event\Http\HttpResponse;
 
class MyHandler extends WebsocketHandler
{
    public function handleWebsocket(WebsocketEvent $event, Context $context): HttpResponse
    {
        $route = $event->getRouteKey();
        $eventType = $event->getEventType();
        $body = $event->getBody();
 
        return new HttpResponse('ok');
    }
}

To send a message to a client connected you can use bref/api-gateway-websocket-client library (opens in a new tab) to make an http request to the endpoint provided by AWS.

Learn more about using WebSockets in serverless.yml in the Serverless Framework documentation (opens in a new tab).

💡

A complete WebSocket example is available in Serverless Visually Explained (opens in a new tab).