Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

TanStack Start + Fastify + Drizzle SSE Demo

This project is a tiny chat-like demo for learning Server-Sent Events, or SSE.

It has two pages:

  • / shows a live message feed.
  • /send lets 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.

Run It

npm install
npm run db:migrate
npm run dev

Open:

The backend runs on http://localhost:4000.

Database Migrations

The database schema lives in backend/schema.ts.

When the schema changes, create a migration:

npm run db:generate

Apply pending migrations:

npm run db:migrate

This 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.

How SSE Works Here

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.

Message Flow

/send page
  -> POST /messages
  -> Fastify receives the text
  -> Drizzle inserts it into SQLite
  -> Fastify broadcasts event: message
  -> / page receives it live with EventSource

Clear works the same way:

Clear feed button
  -> DELETE /messages
  -> Fastify deletes rows from SQLite
  -> Fastify broadcasts event: clear
  -> / page empties the feed

Important Files

  • 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 run npm run db:migrate.

Backend Endpoints

  • 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.

Note About /sse In DevTools

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/events

Build

npm run build

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages