AWS API Gateway WebSocket API with the Serverless Framework to Fulfill Front-end Real-time Update
Front-end real-time updating is a very common function for various applications e.g. Chat App, Real-time alerts and notifications. Normally, Web application, we use WebSocket to realize this function. But what If you implement your backend with AWS Lambda functions or serverless framework? Probably you already know that AWS provides WebSocket API of API Gateway.
What does WebSocket API do?
In a WebSocket API, the client and the server can both send messages to each other at any time. Backend servers can easily push data to connected users and devices, avoiding the need to implement complex polling mechanisms.
Some common use cases:
- Chat applications
- Real-time dashboards such as stock tickers
- Real-time alerts and notifications
For a brief introduction to WebSocket support in API Gateway, see Use API Gateway to Create WebSocket APIs.
💡In this tutorial, I will show you how to implement AWS WebSocket API with serverless framework. We will implement a broadcast function that if one user updates information, then we will broadcast to other online users in real-time.
💡I assume you already have your serverless project.
Backend WebSocket Function
The backend consists of an API Gateway WebSockets API, Lambda functions, and Dynamodb to save WebSocket connection Id.
In API Gateway you can create a WebSocket API as a stateful frontend for an AWS service (such as Lambda or DynamoDB) or for an HTTP endpoint. The WebSocket API invokes your backend based on the content of the messages it receives from client apps.
Define WebSocket API Message Routing
A route includes a route key, which is the value that is expected once a route selection expression is evaluated.
There are three predefined routes that can be used: $connect, $disconnect, and $default. In addition, you can create custom routes.
- API Gateway calls the $connect route when a persistent connection between the client and a WebSocket API is being initiated.
- API Gateway calls the $disconnect route when the client or the server disconnects from the API.
- API Gateway calls a custom route after the route selection expression is evaluated against the message if a matching route is found; the match determines which integration is invoked.
- API Gateway calls the $default route if the route selection expression cannot be evaluated against the message or if no matching route is found.
Learn more About WebSocket APIs in API Gateway
Now, let us create WebSocket API and configure the three predefined routes in serverless.yml.
Check the solution in below article link. It is integrated with Github gist codes snippet.