How I built a chat app using Streams API, Next.JS, Redis and Vercel
Last week I added a chat feature to Sanity. In this article, I'll guide through how I built it using Streams API, Next.js, Redis and Vercel.
Before we start, a quick disclaimer: there are much better ways to build a chat application, for example by using WebSockets. Vercel unfortunately doesn't support WebSockets and I didn't want to spin a dedicated server, which is why I used Streams API. Using Streams API the way I use it here is most likely not the best use of resources but it works and is a good enough solution for my small scale use. If you're on the same boat, keep reading.
If the chat takes off, I'll have to move it to a dedicated Socket.io server, a serverless WebSocket on AWS, or something similar to reduce costs.
Storing messages in Redis
I use the KV (Redis) database from Vercel to store the last 100 messages. Here is the code used to send and read messages.
import { MAX_CHAT_MESSAGE_LENGTH } from "@/utils";
const MAX_MESSAGES = 100;
export const addChatMessage = async ({