Supabase Auth
Attribute Supabase email and OAuth signups, with optional SQL creation receipts for OAuth.
The RefRef recipe for Supabase Auth connects each new account to the browser's referral click. Email signups use one file that you copy into your application, with no database changes. OAuth signups additionally require the optional SQL installation and server callback below.
Set up
- Add the landing script to the pages where a referral link can land. It keeps the browser's referral handle in the
refref_handlecookie. - Copy the recipe file into your application as
refref.ts. SetREFREF_API_URL,REFREF_API_KEY, andREFREF_PROJECT_IDon your server. - On the server, add the RefRef data to each sign-up:
import { cookies } from "next/headers";
import { refrefSignupData } from "./refref";
const data = refrefSignupData((await cookies()).get("refref_handle")?.value);
await supabase.auth.signUp({
email,
password,
options: { data, emailRedirectTo },
});
await supabase.auth.signInWithOtp({
email,
options: { data, emailRedirectTo },
});- Where the user is confirmed, send the signup:
import { trackSignup } from "./refref";
const { data } = await supabase.auth.verifyOtp({ token_hash, type });
if (data.user) await trackSignup(data.user);- To make links work in any browser, change the Confirm signup and Magic link email templates to link to your confirm route with the token hash:
<a href="{{ .RedirectTo }}?token_hash={{ .TokenHash }}&type=email">Confirm</a>Build emailRedirectTo from your configured site URL, never from the request's Host header. Keep the API key on your server.
What it does
- A new account: Supabase writes the RefRef data into the user's metadata only when it creates the user. When the email is confirmed, the recipe sends the signup with the browser's handle. The signup counts at the confirmation.
- A link opened on another device: the handle travels in the user's metadata, so the click counts in any browser.
- Nothing else: a sign-in or a sign-up for an existing email does not change the metadata. A user that existed before you added RefRef has no RefRef data and sends nothing. If such a user adds RefRef data to its own metadata, RefRef refuses it only when the account is older than your RefRef Project: then its signup does not count and identifies no browser. An account created after the Project and before you added RefRef is not refused.
- OAuth: the optional extension sends a signup only for a creation receipt tied to the exact OAuth flow. Existing logins and account linking send nothing. It snapshots the starting browser's handle and requires that browser to complete PKCE.
Failures
A RefRef failure never fails a sign-in. The recipe logs it. Send the same call again later: a repeated signup returns the first result.
The recipe file
/**
* The RefRef recipe for Supabase Auth. Copy this file into a
* Supabase application. Email flows need no table or referral storage.
* OAuth additionally needs oauth.ts and the optional SQL migration:
*
* - `refrefSignupData(handle)` goes into `options.data` of `signUp` and
* `signInWithOtp`. Supabase writes it into the user's metadata only when it
* creates the user, so it marks a user that a sign-up of this app created,
* with the handle of the browser that started it. A sign-in or a sign-up
* for an existing email never changes it.
* - `trackSignup(user)` runs where the user is confirmed: `/auth/confirm` and
* the email code check. It sends the signup with that handle.
*/
import type { User } from "@supabase/supabase-js";
/** The `options.data` of a sign-up that this app starts. */
export function refrefSignupData(handle: string | undefined) {
return { refref_signup: true, ...(handle && { refref_handle: handle }) };
}
async function call(path: string, body: object) {
const response = await fetch(
`${(process.env.REFREF_API_URL ?? "").replace(/\/$/, "")}${path}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Api-Key": process.env.REFREF_API_KEY ?? "",
},
body: JSON.stringify({
projectId: process.env.REFREF_PROJECT_ID,
...body,
}),
},
);
if (!response.ok)
throw new Error(`RefRef ${path} failed with status ${response.status}`);
}
/**
* Sends the signup of a user that a sign-up of this app created. A user with
* no `refref_signup` mark (created before the integration, by an admin, or by
* another app) sends nothing. A later sign-in sends the same signup again,
* which RefRef takes once. The time is the account creation: a user created
* before the RefRef Project never qualifies.
*/
export async function trackSignup(user: User) {
const metadata = user.user_metadata as Record<string, unknown>;
if (metadata.refref_signup !== true) return;
const handle =
typeof metadata.refref_handle === "string"
? metadata.refref_handle
: undefined;
try {
await call("/v1/track/events", {
type: "signup",
participant: { kind: "individual", externalId: user.id },
occurredAt: new Date(user.created_at).toISOString(),
...(handle && { identify: { handle } }),
});
} catch (error) {
// Sign-in never fails for RefRef. Log, and send the same call again
// later: a repeated signup returns the first result.
console.error(error);
}
}
/** The optional OAuth extension calls this ONLY with a verified creation
* receipt. Throws on delivery failure so the receipt remains pending. */
export async function trackOAuthSignup(
userId: string,
createdAt: string,
handle: string | null,
) {
await call("/v1/track/events", {
type: "signup",
participant: { kind: "individual", externalId: userId },
occurredAt: new Date(createdAt).toISOString(),
...(handle && { identify: { handle } }),
});
}Optional OAuth installation
This extension uses an AFTER INSERT trigger on auth.users, following Supabase's user-data trigger pattern. A second trigger ties creation to the exact OAuth flow. The callback exchanges the PKCE code, then claims that receipt as the authenticated user. The RPC gets the user ID from auth.uid(), never from a request parameter. Keep the private schema out of the exposed API schemas.
Why the flow check is required: an unclaimed user-creation row alone is not sufficient. A user can close the browser after Supabase creates the account but before the app callback. A later login must not claim that creation with a new referral click. Comparing created_at and last_sign_in_at, or adding a time window, does not establish which flow created the account.
Compatibility boundary: the SQL depends on Supabase Auth's internal flow_state schema and its transaction ordering. It targets Auth v2.197.0: insertion of the new user and assignment of the PKCE flow's user_id occur in the same transaction. Check the integration journey against your Auth version before installation or upgrade. Supabase can change these internals. A failing Auth trigger can block account creation. This is an optional installation requirement for OAuth; email flows still need no SQL.
- Apply the SQL below to the Supabase project's database before enabling the OAuth callback. It creates private receipts and two narrowly granted authenticated RPCs. It does not backfill existing accounts. Do not expose
refref_privateor grant browser roles table access. - Copy
oauth.tsbesiderefref.ts. Both run only on the server.REFREF_API_KEYalso signs the short-lived attempt cookie; rotation invalidates in-flight attempts. No service-role key is required by the app. - Configure the OAuth provider in Supabase and allow your application's
/auth/callbackredirect URL, including itsattemptquery parameter. For GitHub, the provider's callback is Supabase's/auth/v1/callback, not the app callback. See Supabase's GitHub setup. - Add the server action and callback below. The example chooses GitHub; the receipt and callback logic work with other Supabase OAuth providers. Set
SITE_URLto the app's trusted origin. Use HTTPS outside local development.
OAuth SQL
-- Optional OAuth installation. Email signups do not need this migration.
-- Compatibility boundary: Supabase Auth v2.197.0 creates auth.users and
-- assigns auth.flow_state.user_id in the SAME transaction for a new OAuth user.
-- Re-run the local OAuth journey before upgrading Auth. No backfill.
create schema refref_private;
revoke all on schema refref_private from public, anon, authenticated;
create table refref_private.oauth_signup (
user_id uuid primary key references auth.users(id) on delete cascade,
created_at timestamptz not null,
provider text not null,
creation_transaction xid8 not null,
code_hash bytea unique,
handle text,
claimed_at timestamptz,
delivered_at timestamptz
);
alter table refref_private.oauth_signup enable row level security;
revoke all on refref_private.oauth_signup from public, anon, authenticated;
create function refref_private.record_user_creation()
returns trigger language plpgsql security definer set search_path = '' as $$
begin
-- Admin-created OAuth-looking users can leave a row, but only an OAuth
-- flow in this same transaction can qualify it. Ordinary admins create
-- email users, which leave no row at all.
if new.raw_app_meta_data ->> 'provider' not in ('email', 'phone', 'anonymous') then
insert into refref_private.oauth_signup
(user_id, created_at, provider, creation_transaction)
values (new.id, new.created_at, new.raw_app_meta_data ->> 'provider', pg_current_xact_id());
end if;
return new;
end;
$$;
revoke all on function refref_private.record_user_creation() from public, anon, authenticated;
create trigger refref_record_user_creation after insert on auth.users
for each row execute function refref_private.record_user_creation();
create function refref_private.qualify_oauth_creation()
returns trigger language plpgsql security definer set search_path = '' as $$
begin
if old.user_id is null and new.user_id is not null
and new.authentication_method = 'oauth'
and new.code_challenge is not null and new.auth_code is not null
and new.linking_target_id is null and new.invite_token is null then
update refref_private.oauth_signup
set code_hash = sha256(convert_to(new.auth_code, 'UTF8'))
where user_id = new.user_id
and creation_transaction = pg_current_xact_id()
and provider = new.provider_type and code_hash is null;
end if;
return new;
end;
$$;
revoke all on function refref_private.qualify_oauth_creation() from public, anon, authenticated;
create trigger refref_qualify_oauth_creation after update on auth.flow_state
for each row execute function refref_private.qualify_oauth_creation();
-- A claim fixes the handle once. Repeating the SAME receipt returns the
-- original payload for delivery retry; a later login code cannot claim it.
-- This RPC is callable by authenticated users, not only the app backend.
-- The user ID comes only from auth.uid(); knowing another user's code is
-- insufficient. Only the trusted app backend can send Events to RefRef.
create function public.refref_claim_oauth_signup(code text, signup_handle text)
returns jsonb language plpgsql security definer set search_path = '' as $$
declare receipt refref_private.oauth_signup;
begin
select * into receipt from refref_private.oauth_signup
where user_id = auth.uid() and code_hash = sha256(convert_to(code, 'UTF8'))
for update;
if not found then return null; end if;
if receipt.claimed_at is null then
update refref_private.oauth_signup
set handle = nullif(signup_handle, ''), claimed_at = now()
where user_id = receipt.user_id returning * into receipt;
end if;
return jsonb_build_object('user_id', receipt.user_id,
'created_at', receipt.created_at, 'handle', receipt.handle);
end;
$$;
revoke all on function public.refref_claim_oauth_signup(text, text) from public, anon, authenticated;
grant execute on function public.refref_claim_oauth_signup(text, text) to authenticated;
create function public.refref_ack_oauth_signup(code text)
returns void language sql security definer set search_path = '' as $$
update refref_private.oauth_signup set delivered_at = coalesce(delivered_at, now())
where user_id = auth.uid() and code_hash = sha256(convert_to(code, 'UTF8'))
and claimed_at is not null;
$$;
revoke all on function public.refref_ack_oauth_signup(text) from public, anon, authenticated;
grant execute on function public.refref_ack_oauth_signup(text) to authenticated;OAuth server helpers
/** Optional server-only OAuth extension. Install the accompanying SQL first. */
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
import type { User } from "@supabase/supabase-js";
import { trackOAuthSignup } from "./refref";
export const oauthCookie = "refref_oauth";
export const oauthMaxAge = 600;
interface Attempt {
id: string;
handle: string | null;
expires: number;
}
function signature(value: string) {
const key = process.env.REFREF_API_KEY;
if (!key) throw new Error("REFREF_API_KEY is required for OAuth attribution");
return createHmac("sha256", key).update(`supabase-oauth:${value}`).digest();
}
/** Snapshot the starting handle, without closing it for an existing login. */
export function startOAuthAttempt(handle: string | undefined) {
const attempt: Attempt = {
id: randomUUID(),
handle: handle ?? null,
expires: Date.now() + oauthMaxAge * 1000,
};
const value = Buffer.from(JSON.stringify(attempt)).toString("base64url");
return {
id: attempt.id,
cookie: `${value}.${signature(value).toString("base64url")}`,
};
}
/** Never accept a handle or attempt ID directly from the callback query. */
export function readOAuthAttempt(
cookie: string | undefined,
id: string | null,
): Attempt | null {
if (!cookie || !id) return null;
try {
const [value, mac, extra] = cookie.split(".");
if (!value || !mac || extra) return null;
const received = Buffer.from(mac, "base64url");
const expected = signature(value);
if (
received.length !== expected.length ||
!timingSafeEqual(received, expected)
)
return null;
const attempt: unknown = JSON.parse(
Buffer.from(value, "base64url").toString(),
);
if (
typeof attempt !== "object" ||
attempt === null ||
!("id" in attempt) ||
attempt.id !== id ||
!("expires" in attempt) ||
typeof attempt.expires !== "number" ||
attempt.expires <= Date.now() ||
!("handle" in attempt) ||
(attempt.handle !== null && typeof attempt.handle !== "string")
)
return null;
return { id, handle: attempt.handle, expires: attempt.expires };
} catch {
return null;
}
}
interface Receipt {
user_id: string;
created_at: string;
handle: string | null;
}
/** Fail closed on missing/malformed evidence or another user's receipt. */
export function oauthSignupReceipt(
value: unknown,
user: Pick<User, "id" | "created_at">,
): Receipt | null {
if (
typeof value !== "object" ||
value === null ||
!("user_id" in value) ||
value.user_id !== user.id ||
!("created_at" in value) ||
typeof value.created_at !== "string" ||
!Number.isFinite(Date.parse(value.created_at)) ||
Date.parse(value.created_at) !== Date.parse(user.created_at) ||
!("handle" in value) ||
(value.handle !== null && typeof value.handle !== "string")
)
return null;
return {
user_id: user.id,
created_at: value.created_at,
handle: value.handle,
};
}
interface OAuthClient {
auth: {
exchangeCodeForSession(code: string): PromiseLike<{
data: { user: User | null };
error: unknown;
}>;
};
rpc(
name: string,
args: Record<string, string | null>,
): PromiseLike<{ data: unknown; error: unknown }>;
}
/** No session fallback: a consumed code, missing verifier, or provider error
* cannot turn a later login into signup. RefRef failures do not fail login. */
export async function completeOAuth(
client: OAuthClient,
code: string | null,
attempt: Attempt | null,
) {
if (!code || !attempt) return false;
const { data, error } = await client.auth.exchangeCodeForSession(code);
if (error || !data.user) return false;
try {
const claim = await client.rpc("refref_claim_oauth_signup", {
code,
signup_handle: attempt.handle,
});
if (claim.error) throw new Error("OAuth creation receipt lookup failed");
const receipt = oauthSignupReceipt(claim.data, data.user);
if (!receipt) return true;
await trackOAuthSignup(receipt.user_id, receipt.created_at, receipt.handle);
const ack = await client.rpc("refref_ack_oauth_signup", { code });
if (ack.error) throw new Error("OAuth signup acknowledgement failed");
} catch {
// Do not log codes, tokens, handles or provider responses. The private
// receipt retains the original payload for a backend delivery retry.
console.error(
"OAuth signup delivery incomplete; inspect pending creation receipts",
);
}
return true;
}Start OAuth on the server
Use your request-scoped Supabase SSR client, which reads and writes the PKCE/session cookies. The browser submits a form whose action is signInWithGitHub.
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { oauthCookie, oauthMaxAge, startOAuthAttempt } from "@/lib/oauth";
import { supabaseServer } from "@/lib/supabase-server";
/** The example selects GitHub; the recipe and callback are provider-agnostic. */
export async function signInWithGitHub() {
const store = await cookies();
const attempt = startOAuthAttempt(store.get("refref_handle")?.value);
const callback = new URL(
"/auth/callback",
process.env.SITE_URL ?? "http://localhost:3006",
);
callback.searchParams.set("attempt", attempt.id);
store.set(oauthCookie, attempt.cookie, {
httpOnly: true,
secure: callback.protocol === "https:",
sameSite: "lax",
path: "/",
maxAge: oauthMaxAge,
});
const { data, error } = await (
await supabaseServer()
).auth.signInWithOAuth({
provider: "github",
options: { redirectTo: callback.toString() },
});
if (error || !data.url) redirect("/oauth?error=provider");
redirect(data.url);
}Complete OAuth on the server
import { cookies } from "next/headers";
import { NextResponse, type NextRequest } from "next/server";
import { completeOAuth, oauthCookie, readOAuthAttempt } from "@/lib/oauth";
import { supabaseServer } from "@/lib/supabase-server";
export async function GET(request: NextRequest) {
const query = request.nextUrl.searchParams;
const store = await cookies();
const attempt = readOAuthAttempt(
store.get(oauthCookie)?.value,
query.get("attempt"),
);
const success =
!query.has("error") &&
(await completeOAuth(await supabaseServer(), query.get("code"), attempt));
// Do not clear a different tab's newer attempt.
if (attempt) store.delete(oauthCookie);
const origin = process.env.SITE_URL ?? "http://localhost:3006";
return NextResponse.redirect(
new URL(success ? "/dashboard" : "/oauth?error=callback", origin),
);
}OAuth behavior and recovery
- Existing users and linking: no new
auth.usersinsertion in the OAuth transaction, so no receipt for that flow. A normal admin-created email user has no receipt. Even an admin-created user marked with an OAuth provider cannot qualify in a later OAuth transaction. - Abandoned or concurrent flows: only the transaction that creates the user qualifies. A later login cannot claim an abandoned creation. One browser supports one active attempt; starting another replaces the attempt and PKCE cookies, so the older callback fails closed.
- Another browser: the attempt cookie and PKCE verifier stay in the starting browser. A copied callback URL cannot complete sign-in or identify in another browser. Unlike email token-hash links, OAuth does not provide cross-device completion here. A RefRef reference cannot replace PKCE verification.
- No referral cookie: a verified new account still sends its signup, without
identify. - Retries: the first receipt claim fixes its handle. Repeating that claim with the original code and authenticated user returns the same payload; other users and later login codes get nothing. RefRef deduplicates signup by Participant. A replayed HTTP callback fails because its PKCE code is consumed; it never falls back to the current session.
- Delivery failure: authentication succeeds. A claimed receipt with
delivered_at IS NULLretainsuser_id,created_at, andhandle. A trusted backend recovery task can resend that exact payload withtrackOAuthSignupand mark delivery after success. The example does not run a background retry worker. Do not retry with the browser's current handle. A failure before the claim may lose attribution because the handle was not persisted; do not recover it from a later sign-in. - Trust boundary: authenticated clients can call the claim RPC for their own receipt if they know its original code, and can acknowledge it. This is not an authorization or fraud-proof record. They cannot access other users' receipts or send RefRef Events without the server's Workspace API key. Keep the same Supabase project and RefRef Project mapping when recovering a pending payload.
Check your integration
| Test | Expected result |
|---|---|
| A shares a link; B follows it, signs up, and confirms | B's signup has a referral from A |
| B signs up but never confirms | No signup and no referral |
| B asks for a magic link on a laptop and opens it on a phone | B's signup has a referral from A |
| An existing user follows another referral link and signs in | The first referral stays |
| New GitHub user follows a referral and completes OAuth | One signup with the starting click | | Existing email or OAuth user signs in through GitHub | No signup or identification | | Original OAuth callback is abandoned, then the user signs in again | No signup or identification from the later flow | | OAuth callback is copied to another browser or replayed | Callback fails; no new signup |