Skip to Content
πŸŽ‰ Bref 3.0 is released. Read more β†’

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 : 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  to make an http request to the endpoint provided by AWS.

Learn more about using WebSockets in serverless.yml in the Serverless Framework documentation .

A complete WebSocket example is available in Serverless Visually Explained .

Last updated on