Integration Guide

Add referral attribution to your app

This guide shows you how to capture the ?ref parameter your partners share, persist it across your site, and record it when a user signs up or converts. The whole integration is three steps and less than 20 lines of code.

How it works

  1. 1.You assign a referral code (e.g. ALICE) to a partner inside Referrall, then give them a link like yourapp.com/signup?ref=ALICE — or a Referrall short link that already forwards to it.
  2. 2.When a visitor clicks the link, your site reads the ref query param and saves it in a cookie so it survives navigation and page refreshes.
  3. 3.At signup (or purchase), your server reads the cookie and stores the referral code alongside the new user record. Now you can query which codes are converting.
1

Create your partner links in Referrall

In your Referrall organization, go to Campaigns → Referral codes and assign a unique code to each partner. The code can be anything — a name, a slug, a partner ID from your own system.

Your partner's inbound link just needs ?ref=THEIR_CODE appended to any URL on your domain:

# The simplest possible partner link — no Referrall short link needed
https://yourapp.com/signup?ref=ALICE

# Or attach the code to any landing page
https://yourapp.com/pricing?ref=PARTNER2024

# You can also create a Referrall short link that redirects to the URL above,
# so partners share a clean branded URL instead of a raw query string.
# Example: ref.al/alice → https://yourapp.com/signup?ref=ALICE

Referrall tracks every click on short links automatically. The steps below handle attribution inside your own app.

2

Capture ?ref on your site

Add a small script that reads the query param on page load, writes it to a 30-day cookie, and cleans the URL. This runs client-side so it works on any framework or plain HTML.

Vanilla JS — any site or framework

Paste before </body>
<script>
  (function () {
    var ref = new URLSearchParams(window.location.search).get("ref");
    if (ref) {
      // Store for 30 days; path=/ makes it available site-wide
      document.cookie =
        "referral=" + encodeURIComponent(ref) +
        "; path=/; max-age=2592000; SameSite=Lax";

      // Remove ?ref from the URL without a page reload
      window.history.replaceState({}, "", window.location.pathname);
    }
  })();
</script>

React / Next.js — component approach

Create a client component that runs the same logic inside useEffect, then mount it once in your root layout. This is exactly how Referrall itself handles attribution.

components/referral-param-tracker.tsx
"use client";

import { useSearchParams } from "next/navigation";
import { useEffect } from "react";

export function ReferralParamTracker() {
  const searchParams = useSearchParams();

  useEffect(() => {
    const ref = searchParams.get("ref");
    if (ref) {
      document.cookie =
        `referral=${encodeURIComponent(ref)}; path=/; max-age=2592000; SameSite=Lax`;
      // Clean the param from the URL bar without a page reload
      window.history.replaceState({}, "", window.location.pathname);
    }
  }, [searchParams]);

  return null; // renders nothing — pure side-effect
}
app/layout.tsx
import { Suspense } from "react";
import { ReferralParamTracker } from "@/components/referral-param-tracker";

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}

        {/*
          Wrap in Suspense — useSearchParams() needs it when the component
          is rendered during static generation (Next.js 13+).
        */}
        <Suspense fallback={null}>
          <ReferralParamTracker />
        </Suspense>
      </body>
    </html>
  );
}
3

Read the code at conversion

On your signup or purchase handler, read the referral cookie from the incoming request and save it alongside the new user record. You can then join it back to your Referrall data by code.

Next.js — Server Action

Use next/headers to read cookies server-side. This is exactly how Referrall records which partner code referred each new account.

app/actions.ts
"use server";

import { cookies } from "next/headers";

export async function signUpAction(formData: FormData) {
  const cookieStore = await cookies();
  const referralCookie = cookieStore.get("referral");
  const referralCode = referralCookie
    ? decodeURIComponent(referralCookie.value)
    : null;

  await db.insert(users).values({
    email:        formData.get("email") as string,
    referralCode, // null if no ?ref was present
  });
}

Node.js / Express

routes/signup.js
// Requires cookie-parser middleware: app.use(require("cookie-parser")())

app.post("/signup", async (req, res) => {
  const referralCode = req.cookies.referral
    ? decodeURIComponent(req.cookies.referral)
    : null;

  await db.users.create({
    email:        req.body.email,
    referralCode, // null if no ?ref was present
  });

  res.json({ ok: true });
});

Python / Flask

routes.py
from urllib.parse import unquote
from flask import request

@app.route("/signup", methods=["POST"])
def signup():
    raw = request.cookies.get("referral")
    referral_code = unquote(raw) if raw else None

    user = User(
        email=request.json["email"],
        referral_code=referral_code,  # None if no ?ref was present
    )
    db.session.add(user)
    db.session.commit()

    return {"ok": True}

Notes & tips

  • Cookie lifetime. The examples use 30 days (max-age=2592000). Adjust to match how long your typical signup funnel takes.
  • Case sensitivity. Referral codes in Referrall are case-sensitive. Normalize to lowercase on both ends if your codes might be shared in mixed case.
  • Don't overwrite on repeat visits. If you want first-touch attribution, check whether the cookie already exists before writing it. If you want last-touch, always overwrite.
  • Stripe metadata. When creating a Stripe customer at signup, pass the referral code as a metadata field. This links attribution all the way to revenue without a separate query.
  • Short links are optional. You can give partners a raw URL with ?ref= appended directly — Referrall short links just make it cleaner to share and add click analytics on top.

Ready to track your partners?

Create your free account, set up an organization, assign codes to your partners, and you'll have attribution data in minutes.

Questions? support@referrall.app