Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 84 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,86 @@
# turso-per-user

[Vercel's Turso Per User Starter](https://github.com/notrab/turso-per-user-starter) on
**Cloudflare Workers**, deployed by [Orun](https://github.com/sourceplane/orun) to stage
and prod on every merge, and then packaged as an Orun baseline.

This commit is the repository's frame: `intent.yaml` (with the placeholder
workspace `ws_CHANGE_ME`, so CI plans nothing until it is linked), the Orun
CI workflow, the shared TypeScript and ESLint configuration, and the spec
index. The work is tracked as an epic under [`specs/epics`](specs/epics/README.md).
The [Turso Per User Starter](https://github.com/notrab/turso-per-user-starter)
([notrab/turso-per-user-starter](https://github.com/notrab/turso-per-user-starter),
Vercel's "Turso Per User Starter" template, demo at
https://turso-per-user-starter.vercel.app) — a Next.js todo app where every
user who signs up with Clerk gets a database of their own, created through
Turso's Platform API — running on **Cloudflare Workers + Static Assets**
through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), deployed by
[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge.
Packaging it as an Orun baseline is the next milestone (TP2).

The template's code is the code. What the port adds is the Workers build,
the monorepo wrapper, a test package and the deploy contract; what it
changes is what Workers and a fresh, unattended deployment force. Turso
stays the SaaS it is upstream — each user's database is created in the
owner's Turso organization by its Platform API and reached over libSQL's
HTTP protocol (`@libsql/client/web`, the client that runs on Workers); there
is no database on Cloudflare. Clerk's and Turso's keys are Orun secrets the
owner stores after the build, handed to the Worker as Worker secrets; until
they are, the site says what to connect instead of failing. Clerk's webhook
is checked against the raw body it was signed over, and answers 503 until
its secret is stored. Inter is self-hosted, and the template's GitHub links
are the site's own source. See
[`specs/epics/turso-per-user`](specs/epics/turso-per-user/README.md) for the
design, the milestones and the as-built status, including every departure.

## What is here (the site)

| Surface | Where |
|---|---|
| The site's name, source link and origin | `apps/web/app/site.ts` |
| The landing, sign-up and sign-in (Clerk) | `apps/web/app/page.tsx`, `apps/web/app/(unauthenticated)` |
| The dashboard: the user's todos, in the user's own database (server actions) | `apps/web/app/(authenticated)` |
| `/welcome` (the user's database created on first visit), `/dump.sql` (downloaded), `/webhooks/clerk`, `/api/health` (the deploy's smoke) | `apps/web/app/welcome`, `apps/web/app/(authenticated)/dump.sql`, `apps/web/app/webhooks/clerk`, `apps/web/app/api/health` |
| Whether Clerk and Turso are connected; the Platform API calls; the user's database | `apps/web/lib/clerk.ts`, `apps/web/lib/turso.ts`, `apps/web/lib/db.ts` |
| The todo queries, and the webhook (signature first) | `apps/web/lib/todos.ts`, `apps/web/lib/webhook.ts` |
| The schema every user's database is seeded with | `apps/web/db/schema.ts`, `apps/web/migrations`, `apps/web/dump.sql` |
| The Worker-secret push (Clerk's secret key, the webhook's secret, Turso's four values) | `tooling/wire/worker-secrets.mjs` |
| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.jsonc`, `component.yaml` |
| Tests | `tests/web` (vitest) |

## Getting started

```bash
pnpm install
pnpm typecheck
pnpm lint
pnpm test
pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next
```

The build needs no Turso value, and of Clerk only its publishable key (and
the knowledge that a secret key exists): without both of Clerk's keys it
builds the "connect Clerk" site. With the keys in `apps/web/.env.local`
(`apps/web/.env.example`), `pnpm --filter @app/web dev` signs users up and
creates their databases; `pnpm --filter @app/web preview` serves the built
Worker with the same keys from `apps/web/.dev.vars`.

## How it maps to Vercel

| Vercel | Here |
|---|---|
| Next.js 14 hosting on Vercel's runtime | Next.js 16.3.8 in one Cloudflare Worker (`.open-next/worker.js`) + Static Assets, built by `next build --webpack` and OpenNext |
| `@libsql/client` (its Node entry) | `@libsql/client/web`: libSQL's HTTP protocol over `fetch`, no native module — each user's Turso database, as upstream |
| Turso's Platform API (`@tursodatabase/api`) | The same client and calls (create from the seed database in the `default` group; look up), from the Worker |
| `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`, `CLERK_SECRET_KEY`, `CLERK_WEBHOOK_SECRET`, `TURSO_*` as project env vars | Orun secrets per environment the owner stores, read by the build as optional refs; the publishable key is inlined at build, the rest handed to the Worker as Worker secrets — no bundle holds one |
| Missing keys (Clerk's middleware throws; the Platform API client throws on import) | The not-connected site: the landing renders, sign-in and the dashboard say what to connect, the webhook answers 503 — never a 500 |
| `middleware.ts` (`clerkMiddleware()`) | `proxy.ts` (Next 16's name), `clerkMiddleware()` once Clerk is connected |
| The webhook verified a re-serialised `req.json()` | Verified against the raw body Svix signed, before it is parsed |
| `next/font/google` (Inter) | Inter self-hosted from `@fontsource-variable/inter` (OFL-1.1) |
| `app/opengraph-image.png` | The same image served from `public/` and named in `metadata` on `metadataBase` |
| The landing's "GitHub Repo" and the user menu's "Star repository" (the template's repository) | The site's own source link |
| Deploy on push | Orun deploys `<repo>-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`), smoke-tested |

## Licence

The template carries no licence: no LICENSE file, no `license` in its
`package.json`, no licence section in its README, and GitHub records none.
This repository keeps the template's credit (the links above).

## CI

| Workflow | What it runs | Ships to a site |
|---|---|---|
| `ci.yml` | the Orun pipeline, and the only workflow a site carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the site built and dry-deployed per environment; the tests' `quick-check` lane installs and checks the package, it does not run them), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone is the check; a merge deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes |
28 changes: 28 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Clerk: the application whose sign-up and sign-in this site uses. Create one
# at https://dashboard.clerk.com and copy its keys (API keys → Next.js). Both,
# or the site builds without Clerk and shows how to connect it. In a deployed
# environment they are the CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY Orun
# secrets (README → Connect Clerk); never commit them.
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=
CLERK_SECRET_KEY=

# Optional. Clerk's webhook (user.created) at <site>/webhooks/clerk creates a
# new user's database in the background; its signing secret (README → The
# webhook). Without it the database is created on the user's first visit.
CLERK_WEBHOOK_SECRET=

# Turso: the organization every user's database is created in (README →
# Connect Turso). Read per request; without all four a signed-in user is told
# Turso is not connected yet.
# turso auth api-tokens mint <name>
TURSO_API_TOKEN=
# your personal or organization name
TURSO_ORG=
# the seed database every user's database is created from: turso db create <name>
TURSO_DATABASE_NAME=
# turso group tokens create default
TURSO_GROUP_AUTH_TOKEN=

# Optional. The site's public origin (the Open Graph image's absolute URL);
# the Orun build sets it to the environment's SITE_URL or Worker URL.
NEXT_PUBLIC_SITE_URL=http://localhost:3000
9 changes: 9 additions & 0 deletions apps/web/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->

# This is NOT the Next.js you know

This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.

This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.

<!-- END:nextjs-agent-rules -->
33 changes: 33 additions & 0 deletions apps/web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# apps/web — the site

The Turso Per User Starter
([notrab/turso-per-user-starter](https://github.com/notrab/turso-per-user-starter)),
running on Cloudflare Workers + Static Assets:

- The landing, and Clerk's sign-up and sign-in (`app/page.tsx`,
`app/(unauthenticated)`, `proxy.ts`)
- The dashboard: the signed-in user's todos, read and written by server
actions in the user's own Turso database (`app/(authenticated)`,
`lib/db.ts`, `lib/todos.ts`)
- The user's database created through Turso's Platform API — by Clerk's
`user.created` webhook (`app/webhooks/clerk`, `lib/webhook.ts`) or on their
first visit (`app/welcome`) — from the seed database (`lib/turso.ts`); the
schema is `db/schema.ts`, `migrations/`, `dump.sql`
- `/dump.sql` downloads the user's database; `/api/health` is the deploy's
smoke
- Tailwind 3, Inter self-hosted

Clerk is connected when the build had both its keys (`lib/clerk.ts`); Turso
when the Worker holds its four values (`lib/turso.ts`); until then the pages
say what to connect. The site's name and the repository its landing links to
are in `app/site.ts`.

```bash
cp .env.example .env.local # and fill in the keys
pnpm dev # next dev on http://localhost:3000
pnpm build # next build --webpack + opennextjs-cloudflare build → .open-next/
pnpm preview # wrangler dev over the built Worker (the keys from .dev.vars)
```

How it is deployed — per environment, on merge to `main` — is the
repository's README and `component.yaml` beside this file.
43 changes: 43 additions & 0 deletions apps/web/app/(authenticated)/dashboard/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"use server";

import { revalidatePath } from "next/cache";

import { getDatabaseClient } from "@/lib/db";
import { deleteTodo, flipTodo, insertTodo } from "@/lib/todos";

export type TodoItem = {
id: number;
description: string;
};

export const addTodo = async (formData: FormData) => {
const client = await getDatabaseClient();

const description = formData.get("description") as string;

if (!client) return null;

await insertTodo(client, description);

revalidatePath("/dashboard");
};

export const removeTodo = async (id: number) => {
const client = await getDatabaseClient();

if (!client) return null;

await deleteTodo(client, id);

revalidatePath("/dashboard");
};

export const toggleTodo = async (id: number) => {
const client = await getDatabaseClient();

if (!client) return null;

await flipTodo(client, id);

revalidatePath("/dashboard");
};
48 changes: 48 additions & 0 deletions apps/web/app/(authenticated)/dashboard/form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"use client";

import { useRef } from "react";
import { useFormStatus } from "react-dom";

import { addTodo } from "./actions";

export function Form({ onSubmit }: { onSubmit: (formData: FormData) => void }) {
const formRef = useRef<HTMLFormElement>(null);

const handleSubmit = async (formData: FormData) => {
await onSubmit(formData);
formRef.current?.reset();
};

return (
<form
action={handleSubmit}
className="flex items-center justify-between rounded bg-brunswick-green p-6 shadow-sm"
ref={formRef}
>
<div className="flex w-full items-center space-x-3">
<span className="p-1 text-3xl">☑️</span>
<input
id="description"
name="description"
placeholder="Insert new todo"
className="w-full text-white bg-transparent placeholder:text-white/30 outline-none"
required
aria-label="Description of todo"
type="text"
autoFocus
/>
</div>
<Submit />
</form>
);
}

export function Submit() {
const { pending } = useFormStatus();

return (
<button type="submit" aria-disabled={pending} className="sr-only">
Add
</button>
);
}
15 changes: 15 additions & 0 deletions apps/web/app/(authenticated)/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Todos } from "./todos";

export default async function Page() {
return (
<div className="space-y-3">
<div className="pb-6 text-center">
<h1 className="text-3xl font-black tracking-tight text-white">Todos</h1>
<p className="text-white/60">
The todos you add below are created inside your own database.
</p>
</div>
<Todos />
</div>
);
}
67 changes: 67 additions & 0 deletions apps/web/app/(authenticated)/dashboard/todo-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"use client";

import { useOptimistic } from "react";
import { InferSelectModel } from "drizzle-orm";

import * as schema from "@/db/schema";
import { Todo } from "./todo";
import { Form } from "./form";
import { addTodo, removeTodo, toggleTodo } from "./actions";

type Todo = InferSelectModel<typeof schema.todos>;

export function TodoList({ initialTodos }: { initialTodos: Todo[] }) {
const [optimisticTodos, addOptimisticTodo] = useOptimistic<
Todo[],
{ action: "add" | "remove" | "toggle"; todo: Todo }
>(initialTodos, (state, { action, todo }) => {
switch (action) {
case "add":
return [...state, todo];
case "remove":
return state.filter((t) => t.id !== todo.id);
case "toggle":
return state.map((t) =>
t.id === todo.id ? { ...t, completed: !t.completed } : t,
);
}
});

const handleAddTodo = async (formData: FormData) => {
const description = formData.get("description") as string;
const newTodo = {
id: Date.now(), // Temporary ID
description,
completed: false,
};
addOptimisticTodo({ action: "add", todo: newTodo });
await addTodo(formData);
};

const handleRemoveTodo = async (id: number) => {
addOptimisticTodo({ action: "remove", todo: { id } as Todo });
await removeTodo(id);
};

const handleToggleTodo = async (id: number) => {
addOptimisticTodo({
action: "toggle",
todo: optimisticTodos.find((t) => t.id === id) as Todo,
});
await toggleTodo(id);
};

return (
<div className="space-y-3">
{optimisticTodos.map((todo) => (
<Todo
key={todo.id}
item={todo}
onRemove={handleRemoveTodo}
onToggle={handleToggleTodo}
/>
))}
<Form onSubmit={handleAddTodo} />
</div>
);
}
Loading
Loading