Building a Realtime Chat App with Actors
In this guide, we're building a realtime chat application using the Rivet library. The app consists of:
-
ChatRoom Actor: A server-side component that:
- Uses tags to create separate chat channels
- Stores the message history in persistent state
- Provides methods for sending messages and retrieving history
- Broadcasts new messages to all connected clients
-
Web Client: A browser-based UI that:
- Prompts users for username and channel name
- Connects to the appropriate channel via tags
- Displays the chat interface
- Loads message history on connection
- Shows new messages in realtime
- Allows users to send messages
Set up your project
Create a new actor project:
This command creates a new Rivet actor project with the necessary configuration files and dependencies. We’re using the counter template as a starting point and will modify it for our chat application.
Define the Chat Room actor
Create a file called src/chat-room.ts and add the base class structure:
Step 1: Initialize the actor state
First, add the _onInitialize method to set up the initial state:
This method runs when the actor is first created, initializing an empty messages array.
Step 2: Add message sending functionality
Next, add the method to send messages:
This method:
- Takes a username and message as parameters
- Adds the message to the actor’s state for persistence
- Broadcasts the message to all connected clients
Step 3: Add history retrieval
Finally, add a method to retrieve chat history:
This method allows clients to fetch all previous messages when they connect.
Step 4: Deploy to Rivet
Deploy your actor with:
Follow the prompts to:
- Sign in to your Rivet account
- Create or select a project
- Choose an environment
After deployment, you’ll receive your Actor Manager URL, which clients will use to connect to your chat room.
Build a web client
Create a simple web client to interact with your chat room:
Step 1: Create the HTML structure
Step 2: Add the client script
Add this script tag just before the closing </head> tag:
Step 3: Load messages and listen for updates
Update your init function and add the addMessage helper function:
Step 4: Handle sending messages
Add the form submit handler to your init function: