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 @@
# algolia-search

[Vercel's Algolia Integration Example](https://github.com/algolia/algolia-supabase-vercel-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).
Vercel's [Algolia Integration Example](https://github.com/algolia/algolia-supabase-vercel-starter)
(Algolia's Algolia × Supabase × Vercel starter) — instant, typo-tolerant
search over a Postgres `products` table, with InstantSearch's facets and a
product page that shows what only the database holds — 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 and the template's
demo products 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 (AL2).

The template's code is the code. What the port changes is what the Workers
runtime, a fresh unattended deployment and Orun's rule that no SaaS key is
ever in a build force: upstream's lazy module-level `pg.Pool` becomes one `pg`
client per request over the Hyperdrive binding (`lib/db.ts`, its `query()`
unchanged at every call site); the Algolia application id and search-only key
are the Worker's secrets, read when the page renders and handed to
InstantSearch as props, instead of `NEXT_PUBLIC_` variables inlined at build;
and `demo/seed.sql`, which upstream had you paste into Supabase's SQL Editor,
is two migrations (the table, then its twenty demo products) applied before
the app serves. Until the owner connects Algolia, the home page keeps the
template's "search activates once…" notice and lists the catalogue straight
from Postgres under it. Every table in `public` has row-level security, so
Supabase's Data API serves none of it — the internal-only cost prices,
suppliers and notes above all. See [`specs/epics/algolia-search`](specs/epics/algolia-search/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 title) | `apps/web/lib/site.ts` |
| The home page: the hero, InstantSearch, the catalogue while search is not connected | `apps/web/app/page.tsx`, `apps/web/components/search/`, `apps/web/components/catalogue.tsx` |
| The product page, with the database-only fields | `apps/web/app/products/[id]/page.tsx`, `apps/web/lib/products.ts` |
| The per-request pg client (Hyperdrive first, `POSTGRES_URL` fallback) | `apps/web/lib/db.ts` |
| The Algolia config the page hands the browser, read from the Worker | `apps/web/lib/algolia.ts` |
| The connector's transformation (pasted into Algolia's dashboard) | `apps/web/demo/transform.js` |
| The database check the deploy smoke-tests | `apps/web/app/api/health/route.ts` |
| Workers build, bindings and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc` (committed), `component.yaml`; the Algolia secrets pushed after the build by `tooling/wire/worker-secrets.mjs` |
| The schema and the demo products 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 |
| The Supabase project, the Hyperdrive config, the migration step | `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive`, `infra/db-migrate` |
| Tests | `tests/web` (vitest; InstantSearch rendered in jsdom against an in-process Algolia stand-in), `tests/db` (vitest; 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 and no Algolia account. Running it locally — a
Postgres on `localhost:54322` (`supabase start`), `pnpm --filter @app/web
db:migrate`, then `next dev` or `wrangler dev`, with Algolia's keys in
`apps/web/.dev.vars` if you have them — 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 |
| The Supabase integration's `POSTGRES_URL`, a lazy module-level `pg.Pool` (with an `ssl` override for Supabase's pooler) | The Supabase project's Postgres through Hyperdrive: `query()` is still upstream's, run on one `pg` client per request from `env.HYPERDRIVE.connectionString` (no `ssl` override: the Worker talks to Hyperdrive); `POSTGRES_URL` is for local work without wrangler, through upstream's own pool |
| The Algolia integration's `NEXT_PUBLIC_ALGOLIA_APP_ID` / `NEXT_PUBLIC_ALGOLIA_SEARCH_API_KEY`, inlined into the browser bundle at build (`next.config` `env`) | Orun secrets `ALGOLIA_APP_ID` / `ALGOLIA_SEARCH_API_KEY`, pushed to the Worker as secrets after the build (`tooling/wire/worker-secrets.mjs`) and read per request (`lib/algolia.ts`); the page hands them to InstantSearch as props. The write key, never read upstream either, is not used at all |
| Paste `demo/seed.sql` into the Supabase SQL Editor | `infra/db-migrate` applies `packages/db/src/migrations` per environment — the table (010), row-level security (020), the twenty demo products (030, upstream's rows byte for byte) — after the project and the Hyperdrive config exist, before the Worker deploys |
| The Algolia connector, set up in Algolia's dashboard | The same, as the owner's one-time step (the product's README, "Connect Algolia"), with the same `demo/transform.js` |
| Until the integration's env vars are pulled, the page shows a notice | The same notice (naming the Orun secrets), and the catalogue listed from Postgres under it |
| `next/font/google` (Geist) | The `geist` package (next/font/local): Google's font download fails on GitHub's runners |
| The Supabase and Algolia integrations "Deploy with Vercel" installs | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (one config per environment), ids and credentials as orun secrets; Algolia connected by the owner |
| "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 |
17 changes: 17 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Local development only — the Worker never reads this file; its database is
# the HYPERDRIVE binding (wrangler.jsonc's localConnectionString locally) and
# its Algolia keys are Worker secrets (`.dev.vars` locally, below).
#
# A Postgres connection string for `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
#
# The Algolia application and its search-only key go in apps/web/.dev.vars
# (wrangler dev and `next dev` read it as the Worker's secrets), never here:
# ALGOLIA_APP_ID=…
# ALGOLIA_SEARCH_API_KEY=…
# Without them the home page says search is not connected and lists the
# catalogue from Postgres. The write/admin key is never needed: the connector
# indexes from Algolia's dashboard.
41 changes: 41 additions & 0 deletions apps/web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# @app/web — Algolia search over Supabase, on Cloudflare Workers

Vercel's [Algolia Integration Example](https://github.com/algolia/algolia-supabase-vercel-starter)
([demo](https://algolia-supabase-vercel-starter.vercel.app)): a search page
built on Algolia's [InstantSearch](https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/react/)
— a search box, category, price and rating facets, a "hide out of stock"
toggle, highlighted hits — over a `products` table Algolia's Supabase
connector indexes, and a product page served from Postgres that shows the
fields the index never gets. 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 `<title>` |
| `app/page.tsx` | The template's home page, rendered per request: InstantSearch when the Algolia secrets are set, else the template's notice and the catalogue |
| `components/search/search-experience.tsx`, `product-hit.tsx` | The template's InstantSearch UI; its lite client is built from the props the page hands it |
| `components/catalogue.tsx` | Not upstream's: the products from Postgres, in the hits' cards, while search is not connected |
| `app/products/[id]/page.tsx`, `lib/products.ts` | The template's product page and its query, and the catalogue's (searchable fields only) |
| `lib/db.ts` | Upstream's `query()`: one `pg` client per request over the `HYPERDRIVE` binding's connection string on the Worker, upstream's own `pg.Pool` over `POSTGRES_URL` without a Cloudflare context |
| `lib/algolia.ts` | The application id and search-only key (and an optional search host), read from the Worker per request — never at build |
| `demo/transform.js` | The connector's transformation, pasted into Algolia's dashboard as upstream's is |
| `app/api/health/route.ts` | 200 only when the database answers through the binding and the table exists with row-level security; says whether search is connected |
| `scripts/migrate.mjs`, `scripts/app-migrations.mjs` | `pnpm db:migrate`: `packages/db`'s migrations applied to a local database (POSTGRES_URL), its ledger in schema `local_migrations`; 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 Algolia keys are the Worker's secrets (`.dev.vars` locally), not
`NEXT_PUBLIC_` variables: the template inlined them into the browser bundle
at build time, and here no build ever sees one. The search key is Algolia's
search-only key, which the page hands the browser as upstream's bundle did.

`pg` resolves its Cloudflare socket (`pg-cloudflare`'s `workerd` export) on the
Worker; `next.config.ts` ships that package whole, because the build traces it
for Node.

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

// 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 `products` table exists, with row-level security on. `search` says
// whether the Algolia secrets reached the Worker (never their values); a
// product goes live without them, so it is not part of `ok`.
export const dynamic = "force-dynamic";

export async function GET() {
const headers = { "cache-control": "no-store" };
const search = searchConfig() ? "connected" : "not connected";
try {
const [row] = await query<{ products: string | null; rls: boolean }>(
`select to_regclass('public.products')::text as products,
coalesce((select relrowsecurity from pg_class
where oid = to_regclass('public.products')), false) as rls`,
);
const ok = Boolean(row?.products) && row?.rls === true;
return Response.json(
{ ok, database: "reachable", schema: ok ? "migrated" : "missing", search },
{ status: ok ? 200 : 503, headers },
);
} catch (error) {
console.error("health: database check failed", error);
return Response.json({ ok: false, database: "unreachable", search }, { status: 503, headers });
}
}
Binary file added apps/web/app/favicon.ico
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 48 additions & 0 deletions apps/web/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* The sources named, not detected: Tailwind 4's automatic detection reads
.gitignore only inside a git checkout, so in a CI job tree with no .git it
would also scan .next and .open-next build output. */
@import "tailwindcss" source(none);
@source "./";
@source "../components";

@theme {
--color-supabase: #3ecf8e;
--color-algolia: #003dff;
/* Text-safe Algolia blue: #003dff fails WCAG AA on the dark surface. */
--color-algolia-text: #4d7cff;
--color-surface: #0a0a0a;
--color-card: #141414;
--color-border-subtle: #262626;
}

@theme inline {
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}

:root {
color-scheme: dark;
}

::selection {
background: var(--color-algolia);
color: #fff;
}

body {
background: var(--color-surface);
color: #ededed;
font-family: var(--font-sans), Arial, Helvetica, sans-serif;
}

/* InstantSearch highlight marks (default CSS is not imported). */
.ais-Highlight-highlighted,
.ais-Snippet-highlighted {
background: transparent;
color: var(--color-supabase);
font-weight: 600;
}

.facet-checkbox {
accent-color: var(--color-supabase);
}
34 changes: 34 additions & 0 deletions apps/web/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { GeistSans } from "geist/font/sans";
import { GeistMono } from "geist/font/mono";
import { SITE_NAME } from "@/lib/site";
import "./globals.css";

// Geist, self-hosted: the `geist` package ships the font files and loads them
// with next/font/local (the same --font-geist-sans and --font-geist-mono
// variables). next/font/google fetches them from Google at build time, which
// fails on GitHub's runners.
const geistSans = GeistSans;
const geistMono = GeistMono;

export const metadata: Metadata = {
metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000"),
title: SITE_NAME,
description:
"Algolia finds it. Supabase stores it. Cloudflare wires them. An open-source search starter.",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="flex min-h-full flex-col">{children}</body>
</html>
);
}
64 changes: 64 additions & 0 deletions apps/web/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { SearchExperience } from "@/components/search/search-experience";
import { Catalogue } from "@/components/catalogue";
import { searchConfig } from "@/lib/algolia";

// Per request: the Algolia secrets are the Worker's, read at render (a
// build-time prerender would freeze the build's answer in), and the catalogue
// is read from Postgres while search is not connected.
export const dynamic = "force-dynamic";

export default function Home() {
const config = searchConfig();
return (
<div className="flex min-h-full flex-col">
<header className="mx-auto flex w-full max-w-6xl items-center justify-between px-6 py-5">
<span className="font-mono text-sm">
<span className="text-algolia-text">algolia</span>
<span className="mx-0.5 text-zinc-500">×</span>
<span className="text-supabase">supabase</span>
<span className="mx-0.5 text-zinc-500">×</span>
<span className="text-zinc-300">cloudflare</span>
</span>
</header>

<main className="mx-auto w-full max-w-6xl flex-1 px-6 pb-24">
<section className="py-14 text-center sm:py-20">
<p className="mb-5 inline-flex items-center gap-2 rounded-full border border-border-subtle bg-card px-3 py-1 text-xs font-medium text-zinc-400">
<span className="size-1.5 rounded-full bg-supabase" />
Open-source search starter
</p>
<h1 className="mx-auto max-w-3xl text-balance text-4xl font-semibold leading-tight tracking-tight text-zinc-400 sm:text-5xl">
<span className="text-algolia-text font-bold">Algolia</span> finds it.{" "}
<span className="text-supabase font-bold">Supabase</span> stores
it. <span className="font-bold text-zinc-50">Cloudflare</span>{' '}
wires them.
</h1>
<p className="mx-auto mt-5 max-w-xl text-balance text-base leading-relaxed text-zinc-400">
A production-ready template for typo-tolerant, instant search over
your Postgres data, indexed to{" "}
<span className="text-algolia-text">Algolia</span>, deployed on
Cloudflare.
</p>
</section>

<div data-search={config ? "connected" : "not-connected"}>
<SearchExperience config={config} />
{!config && <Catalogue />}
</div>
</main>

<footer className="border-t border-border-subtle">
<div className="mx-auto flex w-full max-w-6xl flex-col items-center justify-between gap-2 px-6 py-6 text-xs text-zinc-500 sm:flex-row">
<span className="font-mono">
<span className="text-algolia-text">Algolia</span>{" "}
<span className="text-zinc-600">·</span>{" "}
<span className="text-supabase">Supabase</span>{" "}
<span className="text-zinc-600">·</span>{" "}
<span className="text-zinc-300">Cloudflare</span>
</span>
<span>Built as an open-source starter template.</span>
</div>
</footer>
</div>
);
}
Loading
Loading