Skip to content

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.

.env.local
supabase/trust_keys.sql (run in the Supabase SQL editor)
src/lib/supabase.ts
src/lib/authorize.ts (server)
src/lib/vault.ts
app/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.ts
app/notes/page.tsx
Terminal window
npm install @geometer/trust @supabase/supabase-js @supabase/ssr openai

Until the package is published, your Geometer contact gives you the install command.

Terminal window
NEXT_PUBLIC_SUPABASE_URL=https://YOUR-PROJECT.supabase.co
NEXT_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.

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).

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!,
);

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;
}
"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.

"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 }),
});
}
"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.

  • The notes.body column 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_KEY appears 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.