This project is a tiny chat-like demo for learning Server-Sent Events, or SSE.
It has two pages:
/shows a live message feed./sendlets you write and save a new message.- The home page also has a clear button.
When you send a message, Fastify saves it in SQLite using Drizzle, then pushes the saved message to the live feed with SSE.
npm install
npm run db:migrate
npm run devOpen:
- Live feed: http://localhost:3000
- Send page: http://localhost:3000/send
The backend runs on http://localhost:4000.
The database schema lives in backend/schema.ts.
When the schema changes, create a migration:
npm run db:generateApply pending migrations:
npm run db:migrateThis project stores migration files in drizzle/.
Do not create tables manually in backend/server.ts. The server expects the database to be prepared by migrations.
SSE is a one-way live connection from the server to the browser.
The browser opens a connection:
new EventSource('http://localhost:4000/messages/events')Fastify keeps that HTTP response open. When a new message is saved, Fastify writes a small text event:
event: message
data: {"id":1,"body":"Hello","createdAt":"..."}
The blank line at the end is important. It tells the browser that one SSE message is complete.
/send page
-> POST /messages
-> Fastify receives the text
-> Drizzle inserts it into SQLite
-> Fastify broadcasts event: message
-> / page receives it live with EventSourceClear works the same way:
Clear feed button
-> DELETE /messages
-> Fastify deletes rows from SQLite
-> Fastify broadcasts event: clear
-> / page empties the feed-
backend/server.ts
Fastify server, REST endpoints, and SSE endpoint. -
backend/schema.ts
Drizzle table definitions used by migrations and queries. -
backend/migrate.ts
Runs pending Drizzle migrations against SQLite. -
src/routes/index.tsx
Home page. Opens the SSE connection and displays live messages. -
src/routes/send.tsx
Form page. Sends new messages to the backend. -
messages.db
Local SQLite database created when you runnpm run db:migrate.
-
POST /messages
Saves a new message. -
DELETE /messages
Deletes all saved messages and clears open feeds. -
GET /messages/events
SSE stream used by the home page.
In Chrome DevTools you may see another EventSource request named sse.
That one comes from TanStack dev tools in development. Our app's SSE endpoint is:
http://localhost:4000/messages/eventsnpm run build