Build a guestbook · Exercise 02

Connect a database

Save your guestbook's entries in a database so they last and every visitor sees the same ones.

Connect a database

Your guestbook works until the server restarts. To keep entries, and to make sure every visitor sees the same ones, they need to live in a database.

What you’ll build

The same guestbook, with its entries stored in D1, Cloudflare’s SQL database. You’ll write the table as a migration, point both routes at it, and deploy, so the guestbook is live for real.

A table, as a migration

A migration is a numbered SQL file that changes your database’s schema. They run in order, each one only once, so you can change the table later without losing what’s in it:

migrations/0001_create_entries.sqlCREATE TABLE entries (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  message TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

Your Worker reads and writes it through a binding, with ? placeholders for anything a visitor typed:

await env.DB.prepare("INSERT INTO entries (name, message) VALUES (?, ?)")
  .bind(name, message)
  .run();

Why it matters

  • D1 is a SQL database (SQLite) that your Worker reaches through its binding, with no connection string or password in your code.
  • Local development and production have separate databases, so experiments on your machine never touch the real guestbook.

Prerequisites

  • You’ve completed Build the UI and still have that project on disk.