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
79 changes: 71 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,73 @@
# postgres-kysely

[Vercel's Postgres + Kysely Next.js Starter](https://github.com/vercel/examples/tree/main/storage/postgres-kysely) 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).
Vercel's [Postgres + Kysely Next.js Starter](https://github.com/vercel/examples/tree/main/storage/postgres-kysely)
— a page that reads a `profiles` table with Kysely and seeds it on first
use — running on **Cloudflare Workers + Static Assets** through
[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the
database a **Supabase Postgres** project reached through **Cloudflare
Hyperdrive**, both provisioned by Terraform through
[Orun](https://github.com/sourceplane/orun) and the schema applied by Orun's
`db-migrate` (the way the [Lumen baseline](https://github.com/sourceplane/lumen)
does it), 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 (KY2).

The template's code is the code. What the port changes is what the Workers
runtime and a fresh, unattended deployment force: upstream's `db` resolves
to a Kysely client per request over the Hyperdrive binding (`lib/kysely.ts`),
its call sites unchanged, and the table is created by migrations before the
app serves rather than by the page's first request — upstream's
`createTable('profiles').ifNotExists()` from the page fails for one of two
requests that race through it on a fresh database. The page
still writes its three seed rows the first time it finds the table empty,
which is safe to race. Every table in `public` has row-level security, so
Supabase's Data API serves none of it. See [`specs/epics/postgres-kysely`](specs/epics/postgres-kysely/README.md)
for the design, the milestones and the as-built status, including every
departure.

## What is here (the product)

| Surface | Where |
|---|---|
| The product's name (the page's heading and its title) | `apps/web/lib/site.ts` |
| The page and the table | `apps/web/app/page.tsx`, `apps/web/components/table.tsx` |
| The per-request Kysely client (Hyperdrive first, `POSTGRES_URL` fallback) and its types, the seed | `apps/web/lib/kysely.ts`, `apps/web/lib/seed.ts` |
| The database check the deploy smoke-tests | `apps/web/app/api/health/route.ts` |
| Workers build, bindings and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc` (committed), `component.yaml` |
| The schema as migrations, and Lumen's runner | `packages/db` (`@saas/db` — the name the db-migrate composition builds); `apps/web/scripts/migrate.mjs` applies the same files to a local database through Kysely's `Migrator` |
| The Supabase project, the Hyperdrive config, the migration step | `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive`, `infra/db-migrate` |
| Tests | `tests/web`, `tests/db` (vitest; `tests/db` runs the migrations in PGlite) |

## Getting started

```bash
pnpm install
pnpm run wire:fixture # re-render apps/web/wrangler.jsonc from its template (committed; this changes nothing)
pnpm typecheck
pnpm lint
pnpm test
pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next
```

The build needs no database. Running it locally — a Postgres on
`localhost:54322` (`supabase start`), `pnpm --filter @app/web db:migrate`,
then `next dev` or `wrangler dev` — is in the product's README
(`.baseline/product/README.md`), which is what a product built from here
carries.

## How it maps to Vercel

| Vercel | Here |
|---|---|
| Next.js hosting | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets |
| Vercel Postgres (`POSTGRES_URL`), a module-level Kysely `db` | The Supabase project's Postgres through Hyperdrive: `db` is still upstream's export, resolved to a Kysely client per request from `env.HYPERDRIVE.connectionString` (postgres.js under `kysely-postgres-js`, its type fetch left on); `POSTGRES_URL` is for local work without wrangler |
| The page creates the table on its first request (Kysely's schema builder) | `infra/db-migrate` applies `packages/db/src/migrations` (the table, then row-level security) per environment, after the project and the Hyperdrive config exist, before the Worker deploys; the page writes only the seed rows |
| `preferredRegion = 'home'` | Dropped: a Worker runs near its visitor; Hyperdrive pools near the database |
| A database created in the dashboard | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (one config per environment), ids and credentials as orun secrets |
| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, provisioned, migrated, deployed |

## CI

| Workflow | What it runs | Ships to a product |
|---|---|---|
| `ci.yml` | the Orun pipeline, and the only workflow a product carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the app built and dry-deployed per environment, both Terraform roots checked and planned, the migrations planned), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone runs and nothing waits for it — the landing was checked in the build box; a merge applies, migrates and deploys stage → prod. The lanes do not typecheck, lint or run the tests: `baseline.yml`'s e2e tier does, on the landing, before each tag. 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 |
9 changes: 9 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Local development only — the Worker never reads this file; its database is
# the HYPERDRIVE binding (wrangler.jsonc's localConnectionString locally).
#
# A Postgres connection string for Kysely's Migrator (`pnpm db:migrate`, which
# defaults to the Supabase CLI's database below) and for `next dev` without
# wrangler.
POSTGRES_URL=postgres://postgres:postgres@localhost:54322/postgres
# Optional: the site's public origin for metadata.
NEXT_PUBLIC_SITE_URL=http://localhost:3000
34 changes: 34 additions & 0 deletions apps/web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# @app/web — the Postgres + Kysely page on Cloudflare Workers

Vercel's [Postgres + Kysely Next.js Starter](https://github.com/vercel/examples/tree/main/storage/postgres-kysely)
([demo](https://postgres-kysely.vercel.app/)): one page that selects every
row of a `profiles` table through [Kysely](https://kysely.dev/) and shows how
long the query took. Here it is built by
[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare) into one
Worker plus Static Assets, and its Postgres is reached through the Worker's
`HYPERDRIVE` binding.

| File | What it does |
|---|---|
| `lib/site.ts` | The product's name: the page's heading and its `<title>` |
| `lib/kysely.ts` | Upstream's `Database` types and `db`: a Kysely client per request over `kysely-postgres-js` — the `HYPERDRIVE` binding's connection string on the Worker, `POSTGRES_URL` without a Cloudflare context — and Kysely's `sql` |
| `lib/seed.ts` | The three demo profiles, inserted `ON CONFLICT (email) DO NOTHING` the first time the page finds the table empty |
| `components/table.tsx` | Selects the rows, seeds an empty table (reading it back with a query Hyperdrive's cache cannot answer), says so when the migrations have not run |
| `app/api/health/route.ts` | 200 only when the database answers through the binding and the table exists with row-level security |
| `scripts/migrate.mjs`, `scripts/app-migrations.mjs` | `pnpm db:migrate`: Kysely's `Migrator` applies `packages/db`'s migrations to a local database (POSTGRES_URL), its ledger in schema `kysely`; the deployed databases are migrated by db-migrate from the same files |
| `wrangler.template.jsonc` → `wrangler.jsonc` | The Worker's config; the render is committed (`pnpm run wire:fixture`) |

The table is created by the migrations, never by the page: upstream ran
`db.schema.createTable('profiles').ifNotExists()` from its first request,
which fails for one of two requests that race through it on a fresh
database.

postgres.js keeps its default `fetch_types`: kysely-postgres-js runs every
query on a reserved connection, and postgres.js 3.4 never hands a fresh
connection to a waiting reserve with the type fetch off.

```bash
pnpm db:migrate # the schema, into POSTGRES_URL (default: the Supabase CLI's localhost:54322)
pnpm dev # next dev, with the Worker's bindings through wrangler's platform proxy
pnpm build && pnpm preview # the built Worker under wrangler dev
```
30 changes: 30 additions & 0 deletions apps/web/app/api/health/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { db, sql } from '@/lib/kysely'

// Not upstream's: the deploy's smoke check and the bootstrap's probes read
// this. The home page proves the Worker deployed; this proves what a page
// render cannot say on its own — the HYPERDRIVE binding names a real config,
// Hyperdrive reaches the Supabase database, and db-migrate applied the schema:
// the `profiles` table exists, with row-level security on.
export const dynamic = 'force-dynamic'

export async function GET() {
const headers = { 'cache-control': 'no-store' }
try {
const { rows } = await sql<{ profiles: string | null; rls: boolean }>`
select to_regclass('public.profiles')::text as profiles,
coalesce((select relrowsecurity from pg_class
where oid = to_regclass('public.profiles')), false) as rls`.execute(db)
const [row] = rows
const ok = Boolean(row?.profiles) && row?.rls === true
return Response.json(
{ ok, database: 'reachable', schema: ok ? 'migrated' : 'missing' },
{ status: ok ? 200 : 503, headers }
)
} catch (error) {
console.error('health: database check failed', error)
return Response.json(
{ ok: false, database: 'unreachable' },
{ status: 503, headers }
)
}
}
Binary file added apps/web/app/favicon.ico
Binary file not shown.
19 changes: 19 additions & 0 deletions apps/web/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}

body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}
28 changes: 28 additions & 0 deletions apps/web/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import './globals.css'
import { Inter } from 'next/font/google'
import { SITE_NAME } from '@/lib/site'

export const metadata = {
metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000'),
title: SITE_NAME,
description:
'A simple Next.js app with a Postgres database and Kysely as the ORM',
}

const inter = Inter({
variable: '--font-inter',
subsets: ['latin'],
display: 'swap',
})

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.variable}>{children}</body>
</html>
)
}
Binary file added apps/web/app/opengraph-image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
92 changes: 92 additions & 0 deletions apps/web/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import Image from 'next/image'
import Link from 'next/link'
import { Suspense } from 'react'
import Table from '@/components/table'
import TablePlaceholder from '@/components/table-placeholder'
import ExpandingArrow from '@/components/expanding-arrow'
import { SITE_NAME } from '@/lib/site'

export const dynamic = 'force-dynamic'

export default function Home() {
return (
<main className="relative flex min-h-screen flex-col items-center justify-center">
<Link
href="https://github.com/sourceplane/postgres-kysely"
className="group mt-20 sm:mt-0 rounded-full flex space-x-1 bg-white/30 shadow-sm ring-1 ring-gray-900/5 text-gray-600 text-sm font-medium px-10 py-2 hover:shadow-lg active:shadow-sm transition-all"
>
<p>Deploy your own to Cloudflare</p>
<ExpandingArrow />
</Link>
<h1 className="pt-4 pb-8 bg-gradient-to-br from-black via-[#171717] to-[#575757] bg-clip-text text-center text-4xl font-medium tracking-tight text-transparent md:text-7xl">
{SITE_NAME}
</h1>
<Suspense fallback={<TablePlaceholder />}>
<Table />
</Suspense>
<p className="font-light text-gray-600 w-full max-w-lg text-center mt-6">
Postgres demo with{' '}
<Link
href="https://kysely.dev/"
className="font-medium underline underline-offset-4 hover:text-black transition-colors"
>
Kysely
</Link>{' '}
as the ORM. <br /> Built with{' '}
<Link
href="https://nextjs.org/docs"
className="font-medium underline underline-offset-4 hover:text-black transition-colors"
>
Next.js App Router
</Link>
.
</p>

<div className="flex justify-center space-x-5 pt-10 mt-10 border-t border-gray-300 w-full max-w-xl text-gray-600">
<Link
href="https://postgres-prisma.vercel.app/"
className="font-medium underline underline-offset-4 hover:text-black transition-colors"
>
Prisma
</Link>
<Link
href="https://postgres-starter.vercel.app/"
className="font-medium underline underline-offset-4 hover:text-black transition-colors"
>
Starter
</Link>
<Link
href="https://postgres-drizzle.vercel.app/"
className="font-medium underline underline-offset-4 hover:text-black transition-colors"
>
Drizzle
</Link>
</div>

<div className="sm:absolute sm:bottom-0 w-full px-20 py-10 flex justify-between">
<Link href="https://vercel.com">
<Image
src="/vercel.svg"
alt="Vercel Logo"
width={100}
height={24}
priority
/>
</Link>
<Link
href="https://github.com/vercel/examples/tree/main/storage/postgres-kysely"
className="flex items-center space-x-2"
>
<Image
src="/github.svg"
alt="GitHub Logo"
width={24}
height={24}
priority
/>
<p className="font-light">Source</p>
</Link>
</div>
</main>
)
}
6 changes: 6 additions & 0 deletions apps/web/cloudflare-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// The bindings wrangler.jsonc declares, as the Worker (and `next dev` through
// the platform proxy) sees them.
interface CloudflareEnv {
HYPERDRIVE: Hyperdrive
ASSETS: Fetcher
}
Loading
Loading