Add a referral program to your Firebase Studio app

Firebase Studio builds Next.js apps that run on Firebase App Hosting with Firebase Auth. Google is retiring Firebase Studio: new prototyping workspaces stopped in June 2026, and it shuts down on 22 March 2027. Your exported app keeps running on App Hosting, so the same integration applies after you move it to Google AI Studio or another editor.

01The stackFirebase Studio

What Firebase Studio builds, and where the signup call goes

Frontend
Next.js on Firebase App Hosting
Accounts
Firebase Authentication
Server code
Next.js route handlers and server actions on App Hosting
Secrets
Cloud Secret Manager, referenced from apphosting.yaml

Signup boundary: A route handler, called once after createUserWithEmailAndPassword or a first Google sign-in, verifies the Firebase ID token and sends the signup with the cookie of the request.

Before you start, create a Project and a referral Program in RefRef, and keep the API key, Project ID, and Program ID ready. The integration reference has each step. Store them as server secrets: firebase apphosting:secrets:set, then env entries with secret: in apphosting.yaml.

02PromptsPaste in order

1. Capture referral clicks

Paste into the agent first.

1. Capture referral clicks
Add the RefRef landing script to the <head> of every page where a referral link can land, with the URLs from configuration: <script src="https://assets.refref.ai/attribution.v1.js" data-api-url="https://api.refref.ai" defer></script>. Before the signup form submits, wait for window.RefRefAttribution?.capture() for at most 3 seconds, then continue the signup even if capture fails. Do not create, change, or delete the refref_handle cookie. Do not store referral data in localStorage. Use next/script in the root layout.

2. Send each new account to RefRef

Store REFREF_API_KEY, REFREF_PROJECT_ID, and REFREF_PROGRAM_ID with firebase apphosting:secrets:set and reference them in apphosting.yaml.

2. Send each new account to RefRef
Connect each new account to the referral click. Create a route handler at app/api/refref/signup/route.ts. It reads the Firebase ID token from the Authorization header and verifies it with the Admin SDK (verifyIdToken), then loads the user with getUser(uid), and sends nothing when user.metadata.creationTime is more than 10 minutes ago. Otherwise it sends POST {REFREF_API_URL}/v1/track/events with the X-Api-Key header and { projectId, type: "signup", participant: { kind: "individual", externalId: uid }, occurredAt: <user.metadata.creationTime as ISO>, identify: { handle } } with the refref_handle cookie of the request; leave out identify without one. On the client, call this route only when getAdditionalUserInfo(credential)?.isNewUser is true, with the ID token. Read REFREF_API_KEY, REFREF_PROJECT_ID, and REFREF_PROGRAM_ID from secrets in apphosting.yaml, never as NEXT_PUBLIC_ variables. A RefRef failure must never fail the signup.

3. Show each user their invite link

Optional.

3. Show each user their invite link
Add an "Invite friends" card to the account page. In a route handler that verifies the Firebase ID token, for the signed-in user only, call POST https://api.refref.ai/v1/enrollments and then POST https://api.refref.ai/v1/referral-codes, each with { projectId, programId: REFREF_PROGRAM_ID, participant: { kind: "individual", externalId: <user ID> } } and the X-Api-Key header. Show the link https://r.refref.ai/<code> with a Copy button that announces "Copied". Show three states: loading, ready, and "We could not load your invite link" with a Try again button. Never show a placeholder link, a made-up count, or made-up earnings.
03Backend codeReview

The route handler that prompt 2 should produce

Compare the generated code with this reference before you publish. The user must come from the verified session, the key from a secret, and a RefRef failure must not block the user.

app/api/refref/signup/route.ts
app/api/refref/signup/route.ts
import { cookies } from "next/headers";
import { getAuth } from "firebase-admin/auth";
import "@/lib/firebase-admin"; // initializeApp() once

export async function POST(request: Request) {
  const token = request.headers.get("Authorization")?.replace(/^Bearer /, "");
  if (!token) return Response.json({ error: "Unauthorized" }, { status: 401 });
  const { uid } = await getAuth().verifyIdToken(token);
  const user = await getAuth().getUser(uid);
  // Only a new account sends a signup: the client cannot attribute an old one later.
  if (Date.now() - new Date(user.metadata.creationTime).getTime() > 10 * 60_000)
    return Response.json({ sent: false });
  const handle = (await cookies()).get("refref_handle")?.value;
  const response = await fetch(`${process.env.REFREF_API_URL ?? "https://api.refref.ai"}/v1/track/events`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-Api-Key": process.env.REFREF_API_KEY! },
    body: JSON.stringify({
      projectId: process.env.REFREF_PROJECT_ID,
      type: "signup",
      participant: { kind: "individual", externalId: uid },
      occurredAt: new Date(user.metadata.creationTime).toISOString(),
      ...(handle && { identify: { handle } }),
    }),
  });
  return Response.json({ sent: response.ok });
}

Watch for

  • Firebase Studio shuts down on 22 March 2027. Export the project and keep the app on App Hosting; the RefRef code does not change.
  • An App Hosting rollout serves a new domain only after the custom domain is connected. Test referrals there, not on the workspace preview.
  • isNewUser comes from the client, so the route itself refuses accounts older than 10 minutes, and sends occurredAt: RefRef refuses a signup for an account older than the RefRef Project.
04ResultRendered mock

What you get

For the program, start from the SaaS referral program template. Apps on App Hosting are often subscription products, where a reward after the first payment fits best.

your-app.com/account · built with Firebase Studio

Study planner

Invite friends

Share your link. You both get a reward when your friend signs up.

https://r.refref.ai/k3x9m2p7qaCopy

RefRef Console · Referrals

Referrer
user-a (your user ID)
Referee
user-b (your user ID)
Touch
click → signup
Program
Invite friends
Reward
earned, waiting for delivery
Rendered mock with example values: the invite card that prompt 3 builds, and the referral that RefRef records when B signs up through A's link.
05Rehearsal recordChecks open

What we ran, and what happened

Some checks have not run yet. Treat the open steps as a guide to verify yourself, and record your own results.

pendingThe prompts produce the integration in Firebase Studio
Not run: it needs a signed-in Firebase Studio account and an existing workspace, because Firebase Studio no longer creates new prototyping workspaces, and generation uses builder credits. Paste prompts 1 and 2 into a test app, then compare the generated code with the reference code.
pendingTwo-user journey on the published app
Not run. On the published app at its final domain: follow A's link as B, sign up, and check the referral in the Console; sign in again as B and check that no second signup arrives; search the browser bundle for the API key.
passed · 2026-10-20The request of the reference code matches the RefRef API
The reference code sends the same signup body (projectId, type, participant, identify) that the rehearsal journey of the coding-agent guides sent to a disposable RefRef stack, where it created the referral. The function itself has not run on the builder.
06QuestionsFAQ
01

Does this give me Firebase Studio credits?

No. It adds a referral program to the app that you build with Firebase Studio, so that your users can invite their friends and you can reward them. Credits for inviting people to Firebase Studio itself are a separate offer of Firebase Studio.

02

Firebase Studio is closing. Should I still use this?

Yes, if your app runs on Firebase App Hosting with Firebase Auth. The integration is app code in Next.js, so it keeps working after you export the project to Google AI Studio, Antigravity, or another editor.

Official references

Start with a Sandbox Project

Create a RefRef account, add a Project, and get the keys that the Firebase Studio prompts need. Sandbox data never mixes with live data.

Get Started