Introduction to WebSockets and AWS Services
WebSocket is a communication protocol enabling full-duplex communication channels over a single TCP connection. It is widely used for real-time applications like chat apps, live updates, and collaborative tools. AWS provides robust services such as API Gateway and Lambda to help developers build scalable, serverless WebSocket applications.
This guide will walk you through building a real-time front-end application using AWS WebSocket API Gateway, Lambda, and React.js.
Understanding WebSocket Communication
WebSockets operate on persistent connections between clients and servers, allowing bidirectional data exchange. Unlike HTTP, which is request-response-based, WebSockets provide a continuous communication stream, making them ideal for real-time use cases.
Key AWS Components: API Gateway, Lambda, and IAM
- API Gateway: Manages WebSocket connections and routes messages.
- Lambda: Executes custom backend logic in response to WebSocket events.
- IAM: Handles secure access control for API Gateway and Lambda.
Setting Up Your WebSocket API in AWS
Creating the API Gateway WebSocket API
- Navigate to the API Gateway Console.
- Choose WebSocket API and provide a name and endpoint.
- Define the Route Selection Expression, such as $request.body.action, to route messages based on the action field in incoming JSON messages.
Defining Route Selection Expressions and Routes
- Add routes like:
- $connect: Handles connection events.
- $disconnect: Handles disconnection events.
- Custom routes (e.g., sendMessage, broadcastMessage).
- Associate each route with a Lambda function for processing.
Integrating with a Single Lambda Function
Lambda Function Implementation
Create a Lambda function to handle WebSocket events:
const AWS = require(‘aws-sdk’);
const ddb = new AWS.DynamoDB.DocumentClient();
const { CONNECTIONS_TABLE } = process.env;
exports.handler = async (event) => {
const { requestContext, body } = event;
const connectionId = requestContext.connectionId;
const action = JSON.parse(body).action;
if (action === ‘sendMessage’) {
// Example logic for handling a custom route
}
return { statusCode: 200 };
};
Handling WebSocket Events: Connect, Disconnect, and Custom Routes
- $connect: Store the connection ID in DynamoDB for tracking.
- $disconnect: Remove the connection ID from DynamoDB.
- Custom routes: Implement business logic such as sending or broadcasting messages.
Managing User Connections within Lambda
Use DynamoDB to maintain active WebSocket connection IDs:
- On $connect, add the connection ID to the table.
- On $disconnect, delete the connection ID.
Broadcasting Public and Private Messages
Use the PostToConnection API to send messages:
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
endpoint: event.requestContext.domainName + ‘/’ + event.requestContext.stage,
});
// Send a message to a specific connection
await apigwManagementApi.postToConnection({
ConnectionId: connectionId,
Data: JSON.stringify(message),
}).promise();
Configuring Permissions and Deploying Your API
Granting Lambda Function Access to API Gateway
- Attach the AmazonAPIGatewayInvokeFullAccess policy to the Lambda role.
- Add necessary permissions for DynamoDB (e.g., dynamodb:PutItem, dynamodb:DeleteItem).
Deploying the WebSocket API to a Stage
- Deploy the API Gateway to a stage (e.g., dev).
- Note the WebSocket endpoint URL for testing.
Testing Your WebSocket API with Postman
Connecting to the WebSocket Endpoint
- Use Postman’s WebSocket feature.
- Connect to wss://<your-api-id>.execute-api.<region>.amazonaws.com/dev.
Sending JSON Messages with Different Actions
Send payloads like:
{
“action”: “sendMessage”,
“message”: “Hello, WebSocket!”
}
Implementing WebSockets in React.js
Leveraging the websocket Library
Install the library:
npm install websocket
Reference Code for React Integration
import { w3cwebsocket as W3CWebSocket } from ‘websocket’;
const client = new W3CWebSocket(‘wss://<your-api-id>.execute-api.<region>.amazonaws.com/dev’);
client.onopen = () => {
console.log(‘WebSocket Client Connected’);
};
client.onmessage = (message) => {
console.log(message.data);
};
client.send(JSON.stringify({ action: ‘sendMessage’, message: ‘Hello from React!’ }));
Following this guide, you can build and deploy real-time applications using AWS WebSocket API Gateway, Lambda, and React.js, ensuring a scalable and efficient solution for your needs.
References
Tutorial: Create a WebSocket chat app with a WebSocket API, Lambda and DynamoDB