How to create a WebSocket API with serverless
In this example we will look at how to create a serverless WebSocket API on AWS using Serverless Stack (SST). You’ll be able to connect to the WebSocket API and send messages to all the connected clients in real time.
Requirements
- Node.js >= 10.15.1
- We’ll be using Node.js (or ES) in this example but you can also use TypeScript
- An AWS account with the AWS CLI configured locally
Create an SST app
Let’s start by creating an SST app.
$ npx create-serverless-stack@latest websocket
$ cd websocket
By default our app will be deployed to an environment (or stage) called dev
and the us-east-1
AWS region. This can be changed in the sst.json
in your project root.
{
"name": "websocket",
"stage": "dev",
"region": "us-east-1"
}
Project layout
An SST app is made up of two parts.
-
stacks/
— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
stacks/
directory of your project. SST uses AWS CDK, to create the infrastructure. -
src/
— App CodeThe code that’s run when your API is invoked is placed in the
src/
directory of your project.
Storing connections
We are going to use Amazon DynamoDB to store the connection ids from all the clients connected to our WebSocket API. DynamoDB is a reliable and highly-performant NoSQL database that can be configured as a true serverless database. Meaning that it’ll scale up and down automatically. And you won’t get charged if you are not using it.
Replace the stacks/MyStack.js
with the following.
import * as sst from "@serverless-stack/resources";
export default class MyStack extends sst.Stack {
constructor(scope, id, props) {
super(scope, id, props);
// Create the table
const table = new sst.Table(this, "Connections", {
fields: {
id: sst.TableFieldType.STRING,
},
primaryIndex: { partitionKey: "id" },
});
}
}
This creates a serverless DynamoDB table using sst.Table
. It has a primary key called id
. Our table is going to look something like this:
id |
---|
abcd1234 |
Where the id
is the connection id as a string.
Setting up the WebSocket API
Now let’s add the WebSocket API.
Add this below the sst.Table
definition in stacks/MyStack.js
.
// Create the WebSocket API
const api = new sst.WebSocketApi(this, "Api", {
defaultFunctionProps: {
environment: {
tableName: table.dynamodbTable.tableName,
},
},
routes: {
$connect: "src/connect.main",
$disconnect: "src/disconnect.main",
sendmessage: "src/sendMessage.main",
},
});
// Allow the API to access the table
api.attachPermissions([table]);
// Show the API endpoint in the output
this.addOutputs({
ApiEndpoint: api.url,
});
We are creating a WebSocket API using the sst.WebSocketApi
construct. It has a couple of routes; the $connect
and $disconnect
handles the requests when a client connects or disconnects from our WebSocket API. The sendmessage
route handles the request when a client wants to send a message to all the connected clients.
We also pass in the name of our DynamoDB table to our API as an environment variable called tableName
. And we allow our API to access (read and write) the table instance we just created.
Connecting clients
Now in our functions, let’s first handle the case when a client connects to our WebSocket API.
Add the following to src/connect.js
.
import AWS from "aws-sdk";
const dynamoDb = new AWS.DynamoDB.DocumentClient();
export async function main(event) {
const params = {
TableName: process.env.tableName,
Item: {
id: event.requestContext.connectionId,
},
};
await dynamoDb.put(params).promise();
return { statusCode: 200, body: "Connected" };
}
Here when a new client connects, we grab the connection id from event.requestContext.connectionId
and store it in our table.
We are using the aws-sdk
, so let’s install it.
$ npm install aws-sdk
Disconnecting clients
Similarly, we’ll remove the connection id from the table when a client disconnects.
Add the following to src/disconnect.js
.
import AWS from "aws-sdk";
const dynamoDb = new AWS.DynamoDB.DocumentClient();
export async function main(event) {
const params = {
TableName: process.env.tableName,
Key: {
id: event.requestContext.connectionId,
},
};
await dynamoDb.delete(params).promise();
return { statusCode: 200, body: "Disconnected" };
}
Now before handling the sendmessage
route, let’s do a quick test. We’ll leave a placeholder function there for now.
Add this to src/sendMessage.js
.
export async function main(event) {
return { statusCode: 200, body: "Message sent" };
}
Starting your dev environment
SST features a Live Lambda Development environment that allows you to work on your serverless apps live.
$ npx sst start
The first time you run this command it’ll take a couple of minutes to deploy your app and a debug stack to power the Live Lambda Development environment.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-websocket-my-stack: deploying...
✅ dev-websocket-my-stack
Stack dev-websocket-my-stack
Status: deployed
Outputs:
ApiEndpoint: wss://61op9sj4wc.execute-api.us-east-1.amazonaws.com/dev
The ApiEndpoint
is the WebSocket API we just created. Let’s test our endpoint.
Head over to WebSocket Echo Test to create a WebSocket client that’ll connect to our API.
Enter the ApiEndpoint
from above as the Location and hit Connect.
You should see CONNECTED
being printed out in the Log.
Sending messages
Now let’s update our function to send messages.
Replace your src/sendMessage.js
with:
import AWS from "aws-sdk";
const TableName = process.env.tableName;
const dynamoDb = new AWS.DynamoDB.DocumentClient();
export async function main(event) {
const messageData = JSON.parse(event.body).data;
const { stage, domainName } = event.requestContext;
// Get all the connections
const connections = await dynamoDb
.scan({ TableName, ProjectionExpression: "id" })
.promise();
const apiG = new AWS.ApiGatewayManagementApi({
endpoint: `${domainName}/${stage}`,
});
const postToConnection = async function ({ id }) {
try {
// Send the message to the given client
await apiG
.postToConnection({ ConnectionId: id, Data: messageData })
.promise();
} catch (e) {
if (e.statusCode === 410) {
// Remove stale connections
await dynamoDb.delete({ TableName, Key: { id } }).promise();
}
}
};
// Iterate through all the connections
await Promise.all(connections.Items.map(postToConnection));
return { statusCode: 200, body: "Message sent" };
}
We are doing a couple of things here:
- We first JSON decode our message body.
- Then we grab all the connection ids from our table.
- We iterate through all the ids and use the
postToConnection
method of theAWS.ApiGatewayManagementApi
class to send out our message. - If it fails to send the message because the connection has gone stale, we delete the connection id from our table.
Now let’s do a complete test!
Create another client by opening the WebSocket Echo Test page in a different browser window. Just like before, paste the ApiEndpoint
as the Location and hit Connect.
Once connected, paste the following into the Message field and hit Send.
{"action":"sendmessage", "data":"Hello World"}
You’ll notice in the Log that it sends the message (SENT:
) and receives it as well (RECEIVED:
).
Also, if you flip back to our original WebSocket client window, you’ll notice that the message was received there as well!
Deploying to prod
To wrap things up we’ll deploy our app to prod.
$ npx sst deploy --stage prod
This allows us to separate our environments, so when we are working in dev
, it doesn’t break the API for our users.
Cleaning up
Finally, you can remove the resources created in this example using the following commands.
$ npx sst remove
$ npx sst remove --stage prod
Conclusion
And that’s it! You’ve got a brand new serverless WebSocket API. A local development environment, to test and make changes. And it’s deployed to production as well, so you can share it with your users. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!
Example repo for reference
github.com/serverless-stack/serverless-stack/tree/master/examples/websocketFor help and discussion
Comments on this exampleMore Examples
APIs
-
REST API
Building a simple REST API.
-
TypeScript REST API
Building a REST API with TypeScript.
-
Go REST API
Building a REST API with Golang.
-
Custom Domains
Using a custom domain in an API.
Web Apps
Mobile Apps
GraphQL
Databases
-
DynamoDB
Using DynamoDB in a serverless API.
-
MongoDB Atlas
Using MongoDB Atlas in a serverless API.
-
PostgreSQL
Using PostgreSQL and Aurora in a serverless API.
-
CRUD DynamoDB
Building a CRUD API with DynamoDB.
Authentication
Using AWS IAM
-
Cognito IAM
Authenticating with Cognito User Pool and Identity Pool.
-
Facebook Auth
Authenticating a serverless API with Facebook.
-
Google Auth
Authenticating a serverless API with Google.
-
Twitter Auth
Authenticating a serverless API with Twitter.
-
Auth0 IAM
Authenticating a serverless API with Auth0.
Using JWT
-
Cognito JWT
Adding JWT authentication with Cognito.
-
Auth0 JWT
Adding JWT authentication with Auth0.
Async Tasks
-
Cron
A simple serverless Cron job.
-
Queues
A simple queue system with SQS.
-
Pub/Sub
A simple pub/sub system with SNS.
-
Resize Images
Automatically resize images uploaded to S3.
Editors
-
Debug With VS Code
Using VS Code to debug serverless apps.
-
Debug With WebStorm
Using WebStorm to debug serverless apps.
-
Debug With IntelliJ
Using IntelliJ IDEA to debug serverless apps.
Monitoring
Miscellaneous
-
Lambda Layers
Using the chrome-aws-lambda layer to take screenshots.
-
Middy Validator
Use Middy to validate API request and responses.