Build a web app with SQLite
Build and deploy a small web app with a page, a JSON API and a SQLite database, then change its schema safely.
This guide builds a to-do list: one HTML page, a JSON API, and a SQLite database that keeps the data. It takes about ten minutes and ends with a deployed App. The same structure works for any App that owns its data.
1. Create the App
ccp init todos --template static
cd todos
ccp db create --type sqliteccp init scaffolds index.ts (your handler) and public/index.html (your
page). Answer yes when it offers to create and link an App; if you skipped
that, run ccp deploy once before creating the database. ccp db create --type sqlite binds a database to the App and prints its ID. There is nothing
to add to .env.
2. Add types for env.DB
Copy the env.DB declaration into
globals.d.ts so your handler type-checks.
3. Keep the SQL in one module
Create db.ts. Putting every statement here keeps SQL out of your routes and
gives you one place to change when the schema changes.
const migrations = [
`CREATE TABLE todos (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)`,
];
async function migrate() {
await env.DB.query("CREATE TABLE IF NOT EXISTS migrations (id INTEGER PRIMARY KEY)");
const applied = await env.DB.query("SELECT id FROM migrations");
for (let id = applied.length; id < migrations.length; id++) {
await env.DB.batch([
{ sql: "INSERT INTO migrations (id) VALUES (?)", params: [id] },
{ sql: migrations[id] },
]);
}
}
let ready: Promise<void> | undefined;
function schema() {
ready ??= migrate().catch((error) => {
ready = undefined;
throw error;
});
return ready;
}
export async function listTodos() {
await schema();
return env.DB.query("SELECT id, title, done FROM todos ORDER BY id DESC LIMIT 100");
}
export async function addTodo(title: string) {
await schema();
const [todo] = await env.DB.query(
"INSERT INTO todos (title) VALUES (?) RETURNING id, title, done",
[title],
);
return todo;
}
export async function setDone(id: number, done: boolean) {
await schema();
const [todo] = await env.DB.query(
"UPDATE todos SET done = ? WHERE id = ? RETURNING id, title, done",
[done ? 1 : 0, id],
);
return todo;
}
export async function clearDone() {
await schema();
const removed = await env.DB.query("DELETE FROM todos WHERE done = 1 RETURNING id");
return removed.length;
}Three things to copy into your own App:
schema()applies each migration once. A fresh database sets itself up on the first request, and themigrationstable records what has run. Each migration and its record go in onebatch, so a migration either applies fully or not at all.- Every value is a
?parameter. Never build SQL from request input. RETURNINGreports what changed.setDonereturnsundefinedwhen the ID doesn't exist, which the route turns into a404.
4. Add the API routes
Replace index.ts:
import { addTodo, clearDone, listTodos, setDone } from "./db";
export async function handler(request: Request): Promise<Response> {
const url = new URL(request.url);
if (!url.pathname.startsWith("/api/")) {
return new Response(__pages["index.html"], {
headers: { "Content-Type": "text/html" },
});
}
try {
if (url.pathname === "/api/todos" && request.method === "GET") {
return Response.json(await listTodos());
}
if (url.pathname === "/api/todos" && request.method === "POST") {
const { title } = (await request.json().catch(() => null)) ?? {};
if (typeof title !== "string" || !title.trim()) {
return Response.json({ error: "Give the to-do a title." }, { status: 400 });
}
return Response.json(await addTodo(title.trim()), { status: 201 });
}
if (url.pathname === "/api/todos/done" && request.method === "DELETE") {
return Response.json({ removed: await clearDone() });
}
const match = url.pathname.match(/^\/api\/todos\/(\d+)$/);
if (match && request.method === "PATCH") {
const { done } = (await request.json().catch(() => null)) ?? {};
const todo = await setDone(Number(match[1]), Boolean(done));
return todo
? Response.json(todo)
: Response.json({ error: "That to-do no longer exists." }, { status: 404 });
}
return Response.json({ error: "Not found" }, { status: 404 });
} catch (error) {
console.error(error);
return Response.json(
{ error: "Something went wrong. Try again." },
{ status: 500 },
);
}
}The catch logs the failure, which you can read with ccp logs, and gives the
browser a plain sentence instead of a stack trace.
5. Add the page
Replace public/index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>To-dos</title>
</head>
<body>
<h1>To-dos</h1>
<form id="new"><input name="title" placeholder="What needs doing?" required /></form>
<ul id="list"></ul>
<button id="clear">Clear completed</button>
<script type="module">
const list = document.querySelector("#list");
async function api(path, method = "GET", body) {
const response = await fetch(path, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined,
});
const data = await response.json();
if (!response.ok) throw new Error(data.error);
return data;
}
async function render() {
const todos = await api("/api/todos").catch((error) => {
list.textContent = error.message;
});
if (!todos) return;
list.replaceChildren(
...todos.map((todo) => {
const box = Object.assign(document.createElement("input"), {
type: "checkbox",
checked: todo.done === 1,
});
box.onchange = () =>
api(`/api/todos/${todo.id}`, "PATCH", { done: box.checked }).then(render);
const item = document.createElement("li");
item.append(box, ` ${todo.title}`);
return item;
}),
);
}
document.querySelector("#new").onsubmit = async (event) => {
event.preventDefault();
await api("/api/todos", "POST", { title: event.target.title.value });
event.target.reset();
render();
};
document.querySelector("#clear").onclick = () =>
api("/api/todos/done", "DELETE").then(render);
render();
</script>
</body>
</html>done comes back as 0 or 1, because SQLite stores booleans as integers.
6. Deploy and try it
env.DB works only in a deployed App, so test on a preview deployment:
ccp deploy
# › https://abc123.clusterbase.dev
curl -X POST https://abc123.clusterbase.dev/api/todos \
-H "Content-Type: application/json" -d '{"title":"Ship it"}'
# {"done":0,"id":1,"title":"Ship it"}Open the preview URL to use the page, then release it:
ccp deploy --prodPreview and production deployments share one database, so the to-do you added on the preview is already there in production.
7. Change the schema later
To change the schema, add a statement as the last entry of migrations in
db.ts. Never edit or reorder an entry that has already run. To give to-dos a
due date, add this line after the CREATE TABLE entry:
"ALTER TABLE todos ADD COLUMN due_on TEXT",Deploy a preview and open it; the first request applies the migration. Because the preview and production share the database, two things follow:
- A migration applied by any preview is permanent. Only deploy migrations you intend to ship, and keep their position in the list.
- Production is now running against the new schema. Add columns and tables first, and remove old ones only in a later deploy, after production no longer reads them.
If two requests apply the same migration at once, one of them fails and succeeds when retried.
Patterns for larger Apps
| Need | Pattern |
|---|---|
| Several writes that must all apply | One env.DB.batch. |
| Create a row only if it doesn't exist | ON CONFLICT DO NOTHING RETURNING, as shown under Errors. |
| Per-user data | Add a user_id column and filter on it in every statement. See OIDC for sign-in. |
| Fast lookups | Append a CREATE INDEX migration for columns you filter or sort by. |
| Long lists | Page with LIMIT and a cursor to stay under the result limit. |
See SQLite for the full env.DB reference, limits and
errors.