Realtime apps in AWS with SST
Use SST to build and deploy a realtime chat app to AWS.
We are going to use SST to build and deploy a realtime chat app on AWS.
Before you get started, make sure to configure your AWS credentials.
1. Create a project
Let’s start by creating a Node.js app.
Init SST
Now let’s initialize SST in our app.
Select the defaults and pick AWS. This’ll create a sst.config.ts
file in your project root.
Start dev mode
Run the following to start dev mode. This’ll start SST and your Next.js app.
Once complete, click on MyWeb in the sidebar and open your Next.js app in your browser.
2. Add Realtime
Let’s add the Realtime
component and link it to the Next.js app. Update your sst.config.ts
.
This component allows us to set up topics that can be subscribed to. The authorizer
function can be used control who has access to these.
Add an authorizer
Add the following to a new authorizer.ts
file in your project root.
Here we are saying that a user with a valid token has access to publish and subscribe to any topic namespaced user the app and stage name.
In production, we would validate the given token against our database or auth provider.
3. Create the chat UI
Now let’s create a chat interface in our app. Create a new component in components/chat.tsx
with the following.
Here we are going to publish a message that’s submitted to the given topic. We’ll create the realtime connection below.
Add some styles.
Install the npm package.
Add to the page
Let’s use the component in our page. Replace the Home
component in app/page.tsx
.
Here we are going to publish and subscribe to a topic called sst-chat
, namespaced under the name of the app and the stage our app is deployed to.
4. Create a connection
When our chat component loads, it’ll create a new connection to our realtime service. Add the following below the imports in components/chat.tsx
.
We are using a placeholder token here. In production this might be a user’s session token.
Now let’s subscribe to it and save the messages we receive. Add this to the Chat
component.
Head over to the local Next.js app in your browser, http://localhost:3000
and try sending a message, you should see it appear right away. You can also open a new browser window and see them appear in both places.
5. Deploy your app
Now let’s deploy your app to AWS.
You can use any stage name here but it’s good to create a new stage for production.
Congrats! Your app should now be live!
Next you can:
- Let users create chat rooms
- Save them to a database
- Only show messages from the right chat rooms
This’ll help you build realtime apps for production.
Connect the console
As a next step, you can setup the SST Console to git push to deploy your app and monitor it for any issues.
You can create a free account and connect it to your AWS account.