Skip to content

Recipe: Vite, React and Supabase Edge Functions

This content is not available in your language yet.

This is the default stack of Lovable and Bolt: a Vite React app, Supabase for sign-in and data. The app has no server of its own, so the AI route runs as a Supabase Edge Function. The function holds the AI key.

supabase/trust_keys.sql (run in the Supabase SQL editor)
supabase/functions/_shared/authorize.ts (server, Deno)
supabase/functions/masked-ai/index.ts (server, Deno)
supabase/functions/sealed-ai/index.ts (server, only if you use Sealed AI)
src/lib/supabase.ts
src/lib/vault.ts
src/lib/ai.ts
.env (browser values only)
Terminal window
npm install @geometer/trust @supabase/supabase-js openai

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

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

3. The check: supabase/functions/_shared/authorize.ts

Section titled “3. The check: supabase/functions/_shared/authorize.ts”

This decides who may use your AI key. The browser sends the signed-in user’s access token as the client’s apiKey. The function asks Supabase if the token is real.

import { createClient } from "npm:@supabase/supabase-js@2";
// Supabase sets these two for every Edge Function.
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
);
export async function isSignedIn(request: Request): Promise<boolean> {
const token = request.headers.get("authorization")?.replace(/^Bearer /i, "");
if (!token) return false;
const { data, error } = await supabase.auth.getUser(token);
return !error && data.user !== null;
}

4. The Edge Function: supabase/functions/masked-ai/index.ts

Section titled “4. The Edge Function: supabase/functions/masked-ai/index.ts”
import { maskedRoute } from "npm:@geometer/trust/masked-ai/server";
import { isSignedIn } from "../_shared/authorize.ts";
const handler = maskedRoute({
provider: "openai",
apiKey: Deno.env.get("OPENAI_API_KEY")!,
authorize: isSignedIn, // required
// The function address (https://<project>.supabase.co) is another origin than your app's page, so
// a route that answers its own site only would refuse your own app with 403 `masked-ai/cross-origin`.
allowedOrigins: [Deno.env.get("APP_ORIGIN")!], // for example https://my-app.example.com
});
// Deno.serve gives the handler every request, OPTIONS included. The browser sends an OPTIONS "preflight"
// before the real call (the Authorization header makes it one); the route answers it for the origins
// listed above and adds the CORS headers to its answers. Do not add your own CORS code on top.
Deno.serve(handler);

For Sealed AI, supabase/functions/sealed-ai/index.ts:

import { sealedRoute } from "npm:@geometer/trust/sealed-ai/server";
import { isSignedIn } from "../_shared/authorize.ts";
const handler = sealedRoute({
provider: "tinfoil",
apiKey: Deno.env.get("SEALED_AI_KEY")!,
authorize: isSignedIn, // required
allowedOrigins: [Deno.env.get("APP_ORIGIN")!],
});
Deno.serve(handler); // OPTIONS reaches the handler, which answers the preflight

Set the secrets and deploy:

Terminal window
supabase secrets set OPENAI_API_KEY=sk-... APP_ORIGIN=https://my-app.example.com
supabase functions deploy masked-ai

While you develop, the app runs on another address (for example http://localhost:5173): set APP_ORIGIN to that, or list both: allowedOrigins: Deno.env.get("APP_ORIGIN")!.split(",") with APP_ORIGIN=https://my-app.example.com,http://localhost:5173. Write each origin in full, without a path.

Leave JWT verification on (the default) as a second lock. authorize is the check that counts: a call without a real user token gets 401 with masked-ai/not-authorized. Never use authorize: () => true unless you are building a public demo.

Terminal window
VITE_SUPABASE_URL=https://YOUR-PROJECT.supabase.co
VITE_SUPABASE_ANON_KEY=YOUR-ANON-KEY

Never add the AI key here. Anything starting with VITE_ is sent to the browser.

import { createClient } from "@supabase/supabase-js";
export const supabase = createClient(
import.meta.env.VITE_SUPABASE_URL,
import.meta.env.VITE_SUPABASE_ANON_KEY,
);
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;
}

The function lives at your Supabase address, not at your app’s address. Point baseURL there. Pass the signed-in user’s token as apiKey: Supabase lets the call in, and authorize checks it. This is a token for Supabase, not an AI key.

import OpenAI from "openai";
import { maskedFetch } from "@geometer/trust/masked-ai";
import { supabase } from "./supabase";
export async function makeMaskedAi(customerNames: string[] = []) {
const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
if (!token) throw new Error("Sign in first.");
return new OpenAI({
baseURL: `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/masked-ai/v1`,
apiKey: token, // the user's Supabase token. The AI key stays in the function.
dangerouslyAllowBrowser: true,
maxRetries: 0, // the client would retry our errors, which never helps
fetch: maskedFetch({ alsoMask: customerNames }),
});
}
export async function summarise(text: string) {
const ai = await makeMaskedAi();
const reply = await ai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: `Summarise: ${text}` }],
});
return reply.choices[0].message.content ?? "";
}

For Sealed AI, use sealedFetch() from @geometer/trust/sealed-ai and the base URL ${import.meta.env.VITE_SUPABASE_URL}/functions/v1/sealed-ai/v1.

  • supabase functions list shows masked-ai as active.
  • A call from the signed-in app returns an answer. A call with no token returns 401.
  • A call from another site gets 403 masked-ai/cross-origin (only the origins in APP_ORIGIN may call the function from a browser).
  • The Network tab shows placeholders in the request body, and your AI key nowhere.

The standard address is /api/trust/masked-ai/* on your app’s own origin. The route works under any address that contains /masked-ai/, so the direct function address above is correct. On a host that supports rewrites (Vercel, Netlify, Cloudflare), you can map /api/trust/masked-ai/* to the function and use ${window.location.origin}/api/trust/masked-ai/v1 instead. Lovable and Bolt hosting may not let you add a rewrite. The direct address above works everywhere.

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.