# Lovable \+ Supabase edge function avatar for anonymous visitors

A public Supabase Edge Function in Lovable that starts a live avatar call for anonymous visitors: key in a secret, verify\_jwt off, 120 s cap, rate limits\.

Published: 2026-11-22T02:44:26.239Z
Updated: 2026-11-22T02:44:26.239Z
Canonical: https://realtimeavatar.ai/blog/lovable-supabase-edge-function-avatar-anonymous-visitors
Markdown: [en](https://realtimeavatar.ai/blog/lovable-supabase-edge-function-avatar-anonymous-visitors.md)

Create a Supabase Edge Function named realtime-avatar that keeps REALTIME_AVATAR_API_KEY as an Edge Function secret and serves the realtime-avatar SDK's Hono route adapter, realtimeAvatarHono, inside Deno.serve. Turn off JWT verification for that one function in supabase/config.toml, because Supabase's gateway would otherwise reject the browser's CORS preflight, and let the function run its own checks. Your landing page mounts the AvatarCall component with a proxy client that sends only your project's public Supabase key; the Realtime Avatar key never leaves the function. For anonymous visitors, allow only the connect and end operations and only your own avatar id, cap every call (Realtime Avatar's builder prompts use 120 seconds), put a spend limit on the key, and rate-limit started calls per visitor IP and for the whole site (the example below allows 3 an hour per IP and 50 a day in total).

Below: the function, the config.toml setting, where the secret goes in Lovable, the page, the controls that bound what a public call button can cost you, a worked cost example from the plan catalog as of November 2026, and how to ground the character in your menu. The code extends the Edge Function in Realtime Avatar's Lovable and Bolt guides with an origin check and two rate limits, and typechecks against realtime-avatar 0.40.0. The whole recipe in five steps:

1. Store REALTIME_AVATAR_API_KEY as an Edge Function secret (Lovable's secret form, or supabase secrets set on your own project), never as a VITE_ variable.
2. Create supabase/functions/realtime-avatar/index.ts, which serves realtimeAvatarHono from Deno.serve and answers the CORS preflight with 204.
3. Add verify_jwt = false under [functions.realtime-avatar] in supabase/config.toml, so the browser's preflight reaches the function.
4. On the page, point createProxyClient at VITE_SUPABASE_URL plus /functions/v1/realtime-avatar and send the publishable key as the apikey header and as a Bearer authorization header.
5. Lock the public route down: connect and end only, one avatar id, maxSeconds 120, an origin check, per-IP and site-wide limits on started calls, and a spend limit on the key.

## The Edge Function

This is the path for a React and Vite project on Lovable Cloud, which Realtime Avatar's Lovable prompt builds as a Supabase Edge Function. Projects created since May 13, 2026 use TanStack Start and run server code inside the app; there, the same authorize and session rules go into a server route built with realtimeAvatarServerRoute instead. Start from the guide's prompt, which allows only the public example avatar seed-rin-ashfall for now, then harden the function it writes to match this:

```
// supabase/functions/realtime-avatar/index.ts
import { realtimeAvatarHono } from "npm:realtime-avatar@0.40.0/hono";
import { Ratelimit } from "npm:@upstash/ratelimit@2";
import { Redis } from "npm:@upstash/redis@1";

// The one character this public page may start. Swap in your own avatar's id later.
const AVATAR_ID = "seed-rin-ashfall";
// Browsers send Origin on this cross-origin call. Scripts can fake it: a filter, not auth.
const SITE_ORIGINS = ["https://trattoria.example.com", "https://your-preview-origin.example"];
const BRIEF = `You are Rin, the host of Example Trattoria, greeting visitors on its website.
Short spoken sentences, one question at a time.
Answer only from the facts below. If the answer is not there, say you don't know
and point to the booking form on this page.
Never take a booking or invent a price. For allergies, ask the visitor to talk to staff.
Hours: Tuesday to Sunday, 5 pm to 10 pm. Closed Mondays.
Menu: Margherita pizza $16. Mushroom risotto $19 (vegetarian).
Grilled sea bass $27. Tiramisu $9.
Bookings: online form only, up to 30 days ahead. Parties over 8: phone us.`;

const cors = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
};

const redis = new Redis({
  url: Deno.env.get("UPSTASH_REDIS_REST_URL") ?? "",
  token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN") ?? "",
});
// Both limits count calls that STARTED. A queued call re-sends connect every few seconds
// while it waits, so counting attempts would lock out a visitor who is only in line.
const perVisitor = new Ratelimit({ redis, limiter: Ratelimit.slidingWindow(3, "1 h"), prefix: "avatar:ip" });
const wholeSite = new Ratelimit({ redis, limiter: Ratelimit.fixedWindow(50, "1 d"), prefix: "avatar:site" });
// The first entry may be one the caller sent: a speed bump, not an identity.
const visitorIp = (req: Request) => req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
// Requests the route treated as connect, however the caller spelled the URL.
const connects = new WeakSet<Request>();

const route = realtimeAvatarHono({
  apiKey: () => Deno.env.get("REALTIME_AVATAR_API_KEY") ?? "",
  authorize: async ({ request, operation }) => {
    if (operation !== "connect" && operation !== "end") return new Response("Not found", { status: 404 });
    if (!SITE_ORIGINS.includes(request.headers.get("origin") ?? "")) return new Response("Forbidden", { status: 403 });
    if (operation === "connect") {
      connects.add(request);
      // Check without spending a token; Deno.serve below counts the call once it starts.
      const [visitor, site] = await Promise.all([perVisitor.getRemaining(visitorIp(request)), wholeSite.getRemaining("all")]);
      if (visitor.remaining < 1) return new Response("Try again later", { status: 429 });
      if (site.remaining < 1) return new Response("Calls are paused for today", { status: 429 });
    }
  },
  session: ({ avatarId }) =>
    avatarId === AVATAR_ID
      ? { instructions: BRIEF, maxSeconds: 120 }
      : new Response("Avatar not allowed", { status: 403 }),
});

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response(null, { status: 204, headers: cors });
  const res = await route({ req: { raw: req } });
  // A 200 to connect is a started call (a queued one answers 429): count it now.
  // The call is already running, so a Redis error is logged and the grant still goes out.
  if (res.status === 200 && connects.has(req)) {
    await Promise.all([perVisitor.limit(visitorIp(req)), wholeSite.limit("all")])
      .catch((err) => console.error("realtime-avatar: could not count a started call", err));
  }
  const headers = new Headers(res.headers);
  for (const [k, v] of Object.entries(cors)) headers.set(k, v);
  return new Response(res.body, { status: res.status, headers });
});

```

apiKey is a factory that reads the secret per request, so the key exists only inside the function. authorize runs first, before the key is read or a call is minted: 404 for every operation except connect and end, 403 for origins that are not your site, and on connect, the operation that starts a paid call, a check that neither rate limit is used up. It also marks the request as a connect, and Deno.serve counts the call only when that same request gets a 200, a started call, so a differently spelled URL cannot skip the count. A call that waits in the capacity queue gets a 429 with its place in line and retries connect every few seconds, so counting attempts would lock out a visitor who is only waiting. If Redis fails after a call has started, the function logs the error and still returns the grant rather than stranding a call it already paid for. session decides the call: only the allowlisted avatar starts, with your instructions and a 120-second hard stop; any other id gets a 403. The server decides instructions, maxSeconds and allowed avatar ids, and anything the browser sends for those is ignored. Deno.serve answers the preflight with 204, adds the CORS headers, and otherwise passes the route's answer through untouched, because the guide forbids wrapping or reshaping it.

Versions: the guide's prompt pins realtime-avatar 0.26.0, and the guide checked on 15 November 2026 that this release exports every function the prompt names. The SDK's README now installs 0.40.0, and the 0.40.0 package, read on 16 November 2026, still exports realtimeAvatarHono, AvatarCall and createProxyClient. Pin the exact release you test, use the same one in package.json and in the function's npm: import so the page and the route agree, and upgrade on purpose.

## config.toml and the secret

Supabase's function configuration guide says Edge Functions require a valid JWT in the authorization header by default, shows verify_jwt = false for a function that skips that check, and warns that skipping it lets anyone invoke the function without a valid JWT. That is what a page for anonymous visitors needs, and why the function checks every request itself. Turn it off for this one function only:

```
# supabase/config.toml
[functions.realtime-avatar]
verify_jwt = false

```

Supabase's guide to securing Edge Functions describes the same shape for a public function: with verify_jwt = false anonymous callers reach the handler, and with no credential check the handler is fully responsible for checking the caller. Here that is authorize plus the limits in session. Where the key goes depends on who runs your Supabase project:

- Lovable Cloud: paste REALTIME_AVATAR_API_KEY into the secret form Lovable shows. Lovable's Secrets documentation, read 16 November 2026, says secrets are encrypted, injected into your Edge Functions and never reach the browser, and puts the Secrets view under More, Settings, Secrets. Realtime Avatar's Lovable guide gives More, Cloud, Secrets, Add secret for a Lovable Cloud project; use whichever your editor shows.
- Never VITE_: Lovable describes VITE_ variables as build-time values embedded in the client bundle, and its Secrets screen rejects a VITE_ name. Your Supabase URL and publishable key belong there; your Realtime Avatar key does not.
- Your own Supabase project: Lovable says an external Supabase connection manages secrets in the Supabase dashboard. Supabase's secrets guide sets them with supabase secrets set, reads them with Deno.env.get, says deployed functions see a new secret without a redeploy, and reserves names starting with SUPABASE_.

```
# Only if your Supabase project is your own (Supabase CLI). On Lovable Cloud, use Lovable's secret form.
supabase secrets set REALTIME_AVATAR_API_KEY=your_realtime_avatar_key
supabase secrets set UPSTASH_REDIS_REST_URL=your_upstash_rest_url
supabase secrets set UPSTASH_REDIS_REST_TOKEN=your_upstash_rest_token

```

## The page

The page holds no secret. The proxy client points at your function and adds your project's public key to every request, because Supabase's gateway wants it. That publishable key identifies your project, not your visitor, so it does nothing to protect your balance. The button mounts AvatarCall on click; while a call waits for a seat the page shows its place in line, and if a call cannot start, onEnded fires and the page shows a short note instead of a dead button:

```
// src/components/AskOurHost.tsx
import { useState } from "react";
import { AvatarCall, createProxyClient } from "realtime-avatar/react";

const base = import.meta.env.VITE_SUPABASE_URL + "/functions/v1/realtime-avatar";
// The project's public key: safe in the browser, and NOT what protects your balance.
const key = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY ?? import.meta.env.VITE_SUPABASE_ANON_KEY ?? "";
const client = createProxyClient({
  proxyUrl: base,
  // Supabase's gateway wants the project's public key on every request.
  fetch: (input, init) => {
    const headers = new Headers(init?.headers);
    headers.set("apikey", key);
    headers.set("authorization", "Bearer " + key);
    return fetch(input, { ...init, headers });
  },
});

export function AskOurHost() {
  const [inCall, setInCall] = useState(false);
  const [note, setNote] = useState("");
  if (!inCall) {
    return (
      <div>
        <button onClick={() => { setNote(""); setInCall(true); }}>Ask our host about the menu</button>
        {note ? <p>{note}</p> : null}
      </div>
    );
  }
  return (
    <AvatarCall
      client={client}
      avatarId="seed-rin-ashfall"
      style={{ width: "100%", maxWidth: 420, aspectRatio: "3 / 4" }}
      onEnded={({ reason }) => {
        setInCall(false);
        // A start the function or the platform refused (a rate limit, a plan limit) ends here too.
        if (reason === "failed") setNote("Our host can't take a call right now. Please try again later or use the booking form.");
      }}
    >
      {(call) => (
        <div style={{ position: "absolute", bottom: 16, left: 0, right: 0, textAlign: "center" }}>
          {call.status === "waiting" ? <p>In line: {call.queuePosition}</p> : null}
          <button onClick={call.end}>End call</button>
        </div>
      )}
    </AvatarCall>
  );
}

```

The microphone only works on https or http://localhost. When you create your own character from a portrait, put its avatar id in both the function's allowlist and the page; if they differ, the function answers 403.

## Making a public mint safe

Lovable's edge functions page says anyone who knows a function's address can send it a request, so each function has to check who sent it. Realtime Avatar's Lovable guide says that, as generated, anyone who can open the app can start a call and every call spends your balance, and recommends a signed-in user in authorize plus a maxSeconds you will pay for. A page for anonymous visitors cannot require sign-in, so stack these controls instead:

- Connect and end only: authorize answers 404 to every other operation the SDK's route supports.
- One avatar id: session refuses any other id with a 403, so an edited request cannot start a different character on your account.
- A short hard stop: maxSeconds 120 ends every call at two minutes, bounding the cost of any single call.
- A spend limit on the key: Realtime Avatar keys are private keys with configurable permissions and spend limits, so give the public page its own key and set a spend limit on it. Per-session usage records (start time, billable seconds, cost) show what each call used.
- Rate limits on started calls: Supabase's rate-limiting guide pairs Edge Functions with Upstash Redis, whose HTTP client suits serverless, and notes you can limit by the Supabase Auth user ID. A landing page has no user, so key one limit on the visitor's IP and a second on a constant, which caps the whole site however many addresses a caller uses.
- An origin check: browsers send Origin on this cross-origin call, so refusing other origins stops another website's page from starting calls on your account from its visitors' browsers. Scripts can send any Origin, so it is a filter, not authentication.

Depending on the proxy in front of the function, the first x-forwarded-for entry may be one the caller sent, so the IP limit is a speed bump; the site-wide limit, the spend limit and maxSeconds bound the money. Two requests that arrive at the same moment can both pass the check before either is counted, so treat both limits as approximate. When traffic justifies it, add sign-in and return a 401 from authorize when there is no signed-in user, as the guide recommends.

A worked cost example from the Realtime Avatar plan catalog, as of November 2026. Calls are metered by the second. Expected traffic of 20 calls a day averaging 90 seconds is 900 minutes in a 30-day month; the ceiling the function allows, about 50 started calls a day at the full 120 seconds, is 3,000 minutes:

- Starter, $9 a month, 120 included minutes, $0.095 per overage minute, 3 concurrent streams: 900 minutes costs $9 + 780 x $0.095 = $83.10; 3,000 minutes costs $282.60.
- Developer, $24 a month, 600 included minutes, $0.085 per overage minute, 10 concurrent streams: 900 minutes costs $24 + 300 x $0.085 = $49.50; 3,000 minutes costs $228.00.
- Studio, $119 a month, 3,000 included minutes, $0.08 per overage minute, 20 concurrent streams: both 900 and 3,000 minutes cost $119.
- One capped call in overage: two minutes is $0.19 on Starter, $0.17 on Developer, $0.16 on Studio.
- Free Sandbox: 480 credits once per account, no card, 8 realtime minutes, which is four full 120-second test calls with the example avatar; 2 concurrent streams.

Pick the plan for expected traffic and the spend limit for the ceiling you accept. If many visitors may press Call at once, concurrent streams matter as much as minutes: the SDK's README says only a platform capacity queue returns a place in line, while a concurrent-session limit is refused, which is the case the page's short note covers.

## Grounding the character in your menu or FAQ

The character's brief is whatever session puts in instructions, on the server, for every call; nothing a visitor sends replaces it. For a restaurant or booking site the brief is short: who the host is, how it speaks, the facts it may use, and what to do outside them. The function above carries this example, followed by hours, dishes and booking rules:

> You are Rin, the host of Example Trattoria, greeting visitors on its website. Short spoken sentences, one question at a time. Answer only from the facts below. If the answer is not there, say you don't know and point to the booking form on this page. Never take a booking or invent a price. For allergies, ask the visitor to talk to staff.

State the refusal rule, so an off-menu question gets a pointer to the booking form instead of an invented answer. Keep prices and hours only in the brief, so a menu change is one edit and a redeploy. Write what the host must never do, such as taking a booking it cannot confirm, as an explicit rule. Once the guide's prompt has built the basic call, send Lovable a follow-up like this:

```
Change the realtime-avatar Edge Function for a public landing page. Keep everything else.
1. REALTIME_AVATAR_API_KEY stays a server secret. No VITE_ variable may hold it.
2. Pin realtime-avatar exactly 0.40.0, both in package.json and in the Edge Function's npm: import.
3. In authorize: allow only the connect and end operations (404 for anything else), and answer 403
   when the Origin header is not one of: https://trattoria.example.com and this project's preview URL.
4. Rate-limit started calls with Upstash Redis (npm:@upstash/ratelimit@2, npm:@upstash/redis@1):
   at most 3 per visitor IP per hour (first x-forwarded-for entry) and 50 per day for the whole site.
   In authorize, on a connect request, add the request to a WeakSet, check both limits with
   getRemaining and answer 429 when either is used up.
   In Deno.serve, call limit on both only when that request is in the WeakSet and the route
   answered 200. A queued call answers 429 and retries connect while it waits; those retries
   must not count. If counting fails, log the error and still return the route's response.
   Ask me for UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN as secrets.
5. In session: allow only avatar id seed-rin-ashfall, maxSeconds 120, and the instructions text below.
   Ignore anything the browser sends for instructions, call length or avatar.
6. Label the call button "Ask our host about the menu", keep the "In line" message while waiting,
   and show a short "try again later" note when a call ends with reason "failed".
7. Deploy the realtime-avatar Edge Function when you are done.

Instructions text:
(paste your host brief here)

```

## Lovable gotchas

- Redeploys: Lovable does not redeploy an Edge Function from a commit synced from GitHub, so ask it in chat to deploy the function; Lovable's docs confirm it can deploy chosen functions on request.
- TanStack Start: if package.json lists @tanstack/react-start, write no Edge Function; keep the same authorize and session hooks in the guide's server route.
- Microphone: if the browser never asks for it inside the editor's preview, open the app in its own tab or on its published https URL.
- Two keys: the Supabase publishable key in the page is public by design; the Realtime Avatar key lives only in the secret. If it ever appears in browser code, rotate it.

## What has been checked, and what has not

Realtime Avatar's guide says the starter's Edge Function, the code its prompt asks for on Lovable Cloud, passes deno check, and a live call through the starter's server route returned a complete session grant, checked on 5 October 2026. A run of the prompt inside Lovable is not covered, because Lovable writes its own code and results differ between runs; compare against the realtime-avatar-starter-vite repo when something does not connect. The origin check and the rate limits here are additions: both code blocks typecheck with TypeScript against realtime-avatar 0.40.0, @upstash/ratelimit 2.2.1 and @upstash/redis 1.41.0, but they have not been run on a deployed function, so test them on your deployment before you share the link.

## Where another setup fits better

Tavus's Create Conversation endpoint, per its API reference read 16 November 2026, returns a room_url, a Tavus-hosted room you can open or share, and a conversation_url for joining the call with an SDK, so it suits a team that wants a ready-made call page it can link to. The Supabase half of this post carries over: keep the Tavus key in an Edge Function secret, call POST /v2/conversations from the function with your own checks, and set properties.max_call_duration, which defaults to 3,600 seconds, to something short.

If you already run a voice agent you like, such as an ElevenLabs agent, a face-only renderer such as Simli lets you keep it and charges a lower per-minute price for the video alone (the Realtime Avatar vs Simli page lists both sides' dated rates), while speech recognition, the model and the voice stay yours to run and pay for; Realtime Avatar has no renderer-only mode that lip-syncs audio from your own voice agent. Starting fresh, one Realtime Avatar call covers listening, turn-taking, interruption, the reply, the voice and the video, with built-in voices included in the per-second rate, and your own text-to-speech can come later through a signed voice webhook.

## FAQ

### How do I make a public Supabase edge function (verify_jwt off) that mints an avatar session for anonymous visitors?

Set verify_jwt = false for that function in supabase/config.toml, serve realtimeAvatarHono from Deno.serve with the key read from Deno.env, and put every rule in the route: connect and end only, one avatar id, maxSeconds 120, an origin check, and rate limits that count started calls rather than attempts.

### Where do I store a third-party API key in Lovable so only my Supabase edge function can read it?

In Lovable's Secrets, through the form Lovable shows or, per Lovable's docs, under More, Settings, Secrets; they are injected into Edge Functions and never reach the browser. Never in a VITE_ variable. With an external Supabase project, use the Supabase dashboard or supabase secrets set.

### I built a booking app in Lovable with Supabase. How do I add a talking avatar greeter without putting my API key in the frontend?

Paste the prompt from Realtime Avatar's Lovable guide, give Lovable the key through the secret form, then send the follow-up prompt above to lock the function down. The page holds only your Supabase publishable key.

### Can you give me a Lovable prompt for a video call with an AI character who answers questions about my restaurant menu?

Run the guide's prompt, then the follow-up prompt above with your menu, hours and booking rules as the instructions text. The menu stays in the function, where visitors cannot edit it.

### ElevenLabs plus Simli faces is too many moving parts. Is there one API for a talking avatar with the voice and the brain built in?

Realtime Avatar is one call for listening, the reply, the voice and the video, so the Edge Function above is the only server code. Keep the two-part setup if you depend on an existing ElevenLabs agent, because Realtime Avatar cannot put a face on audio from your own voice agent.

### Which realtime avatar API has a copy-paste Lovable or Bolt prompt that keeps the API key in a secret?

Realtime Avatar's docs publish copy-paste prompts for Lovable and Bolt that keep REALTIME_AVATAR_API_KEY in a server secret, and its AI app builders page collects the prompts for other builders. This post does not survey other vendors' builder prompts; for Tavus, the same Edge Function pattern applies.

### ¿Cómo conecto cualquier API externa en Lovable guardando la clave en Secrets y una edge function?

Con el mismo patrón: guarda la clave en Secrets (nunca en una variable VITE_), léela en la edge function con Deno.env.get, y haz que la página llame solo a tu función. Si la función es pública con verify_jwt = false, la propia función debe decidir quién puede usarla, con límites por IP y un tope de gasto.

- [Concurrent avatar calls and 429 errors: plan limits, queue, retry](https://realtimeavatar.ai/blog/avatar-concurrent-sessions-429-queue)

- [Add a live AI avatar to a Lovable app (copy-paste prompt)](https://realtimeavatar.ai/docs/lovable)
- [Bolt.new guide with the Supabase Edge Function](https://realtimeavatar.ai/docs/bolt)
- [Every AI app builder on one page](https://realtimeavatar.ai/docs/ai-app-builders)
- [Authentication: what authorize gates](https://realtimeavatar.ai/docs/authentication)
- [Pricing and plans](https://realtimeavatar.ai/pricing)
- [Realtime Avatar compared with Tavus, HeyGen LiveAvatar, Anam and Simli](https://realtimeavatar.ai/compare)
- [Realtime Avatar vs Simli: per-minute rates and what each includes](https://realtimeavatar.ai/compare/simli)
- [Calls: what your server decides for each call](https://realtimeavatar.ai/docs/sessions)

- [Supabase: Function configuration (verify_jwt)](https://supabase.com/docs/guides/functions/function-configuration)
- [Supabase: Securing Edge Functions](https://supabase.com/docs/guides/functions/auth)
- [Supabase: Edge Function environment variables and secrets](https://supabase.com/docs/guides/functions/secrets)
- [Supabase: Rate limiting Edge Functions](https://supabase.com/docs/guides/functions/examples/rate-limiting)
- [Lovable: Secrets](https://docs.lovable.dev/features/secrets)
- [Lovable: Edge functions](https://docs.lovable.dev/features/edge-functions)
- [Tavus API: Create conversation (read 2026-11-16)](https://docs.tavus.io/api-reference/conversations/create-conversation)
- [realtime-avatar SDK README on GitHub](https://github.com/theinfluencecompany/realtime-avatar-sdk)
