Recipe: Next.js and Supabase
This content is not available in your language yet.
A complete setup, file by file: Vault for saved data, and Masked AI (or Sealed AI) for chat. Next.js App Router, Supabase sign-in.
Files you will touch
Section titled “Files you will touch”.env.localsupabase/trust_keys.sql (run in the Supabase SQL editor)src/lib/supabase.tssrc/lib/authorize.ts (server)src/lib/vault.tsapp/api/trust/masked-ai/[...path]/route.ts (server)app/api/trust/sealed-ai/[...path]/route.ts (server, only if you use Sealed AI)src/lib/ai.tsapp/notes/page.tsx1. Install
Section titled “1. Install”npm install @geometer/trust @supabase/supabase-js @supabase/ssr openaiUntil the package is published, your Geometer contact gives you the install command.
2. .env.local
Section titled “2. .env.local”NEXT_PUBLIC_SUPABASE_URL=https://YOUR-PROJECT.supabase.coNEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR-ANON-KEY
# Server only. No NEXT_PUBLIC_ prefix, ever.OPENAI_API_KEY=sk-...SEALED_AI_KEY=...Anything that starts with NEXT_PUBLIC_ is sent to the browser. Keep the AI keys without it.
3. supabase/trust_keys.sql
Section titled “3. supabase/trust_keys.sql”Run it once in the Supabase SQL editor. Each user can read only their own key file.
create table if not exists public.trust_keys ( app text not null, user_id uuid not null references auth.users (id) on delete cascade, key_file text not null, updated_at timestamptz not null default now(), primary key (app, user_id));
alter table public.trust_keys enable row level security;
create policy "read own key file" on public.trust_keys for select using (auth.uid() = user_id);create policy "add own key file" on public.trust_keys for insert with check (auth.uid() = user_id);create policy "change own key file" on public.trust_keys for update using (auth.uid() = user_id) with check (auth.uid() = user_id);Also create your notes table with the same style of policy (see Vault).
4. src/lib/supabase.ts
Section titled “4. src/lib/supabase.ts”import { createBrowserClient } from "@supabase/ssr";
// This client keeps the sign-in in cookies, so your server routes can see who is signed in.export const supabase = createBrowserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,);5. src/lib/authorize.ts
Section titled “5. src/lib/authorize.ts”This decides who may use your AI key. It reads the signed-in user from the request’s cookies and asks Supabase if the session is real.
import { createServerClient } from "@supabase/ssr";
export async function isSignedIn(request: Request): Promise<boolean> { const cookieHeader = request.headers.get("cookie") ?? ""; const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { getAll: () => cookieHeader .split(/;\s*/) .filter(Boolean) .map((pair) => { const i = pair.indexOf("="); return { name: pair.slice(0, i), value: decodeURIComponent(pair.slice(i + 1)) }; }), setAll: () => {}, // a route that only checks does not set cookies }, }, ); const { data } = await supabase.auth.getUser(); // asks Supabase, so a faked cookie fails return data.user !== null;}6. src/lib/vault.ts
Section titled “6. src/lib/vault.ts”"use client";
import { openVault, supabaseKeyStore, type Vault } from "@geometer/trust/vault";import { supabase } from "./supabase";
let vault: Vault | null = null;
export async function getVault(onRecoveryCode: (info: { code: string; replacesPrevious: boolean; reason: string }) => void): Promise<Vault> { if (vault) return vault; const { data } = await supabase.auth.getUser(); if (!data.user) throw new Error("Sign in first."); vault = await openVault({ app: "my-notes", // your app's name. Never change it later. user: data.user.id, keyStore: supabaseKeyStore(supabase, { app: "my-notes", user: data.user.id }), unlock: "passkey", onRecoveryCode, }); return vault;}7. app/api/trust/masked-ai/[...path]/route.ts
Section titled “7. app/api/trust/masked-ai/[...path]/route.ts”import { maskedRoute } from "@geometer/trust/masked-ai/server";import { isSignedIn } from "@/lib/authorize";
const handler = maskedRoute({ provider: "openai", apiKey: process.env.OPENAI_API_KEY!, authorize: (request) => isSignedIn(request), // required});
export const GET = handler;export const POST = handler;This route is on your app’s own origin, so it needs nothing more: it answers its own site only, and a call from another site gets 403 masked-ai/cross-origin. Only if a front end on a different origin calls this route, add allowedOrigins: ["https://other-front-end.example"] to the route and export const OPTIONS = handler; next to GET and POST, so the browser’s preflight reaches it.
For Sealed AI, make app/api/trust/sealed-ai/[...path]/route.ts the same way with sealedRoute({ provider: "tinfoil", apiKey: process.env.SEALED_AI_KEY!, authorize: (request) => isSignedIn(request) }) from @geometer/trust/sealed-ai/server.
authorize is required. A signed-out call gets 401 with masked-ai/not-authorized. Never use authorize: () => true unless you are building a public demo.
8. src/lib/ai.ts
Section titled “8. src/lib/ai.ts”"use client";
import OpenAI from "openai";import { maskedFetch } from "@geometer/trust/masked-ai";
export function makeMaskedAi(customerNames: string[] = []) { return new OpenAI({ baseURL: `${window.location.origin}/api/trust/masked-ai/v1`, apiKey: "not-used", dangerouslyAllowBrowser: true, maxRetries: 0, // the client would retry our errors, which never helps fetch: maskedFetch({ alsoMask: customerNames }), });}9. app/notes/page.tsx
Section titled “9. app/notes/page.tsx”"use client";
import { useState } from "react";import { getVault } from "@/lib/vault";import { makeMaskedAi } from "@/lib/ai";import { supabase } from "@/lib/supabase";
export default function Notes() { const [text, setText] = useState(""); const [summary, setSummary] = useState("");
async function save() { const vault = await getVault(({ code }) => window.alert(`Write this recovery code down. Keep it safe; the app may show it again until you confirm it:\n\n${code}`), ); const id = vault.newId(); const body = await vault.encrypt(text, { table: "notes", id, field: "body" }); const { error } = await supabase.from("notes").insert({ id, body }); if (error) throw error; }
async function summarise() { const ai = makeMaskedAi(); const reply = await ai.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: `Summarise: ${text}` }], }); setSummary(reply.choices[0].message.content ?? ""); }
return ( <main> <textarea value={text} onChange={(e) => setText(e.target.value)} /> <button onClick={save}>Save (encrypted)</button> <button onClick={summarise}>Summarise (masked)</button> <p>{summary}</p> </main> );}The two buttons use two modes. Each call uses exactly one.
Check it worked
Section titled “Check it worked”- The
notes.bodycolumn in Supabase holds scrambled text. - In the browser’s Network tab, the request to
/api/trust/masked-ai/...holds placeholders for emails and phone numbers. - A call while signed out returns 401.
- Your
OPENAI_API_KEYappears nowhere in the page source or the Network tab.
Errors: the openai client wraps Trust errors, so read them with findTrustError(err) from @geometer/trust/masked-ai (or /sealed-ai) and keep maxRetries: 0 on the client. See Masked AI.
If something fails, see errors.