How to Create an Affiliate Program with Next.js | AffiliateBase

Next.js is a popular React framework that makes it easy to build fast, scalable web applications. If you're looking to monetize your Next.js SaaS or membership site through an affiliate program, you've come to the right place.

This comprehensive guide will walk you through everything you need to know about setting up an affiliate program with Next.js, from initial setup to tracking conversions and managing payouts.

Whether you're building a SaaS product, membership platform, or subscription service with Stripe, an affiliate program can help you grow your user base and increase revenue.

Follow these steps to get your affiliate program up and running in Next.js:

1

Add the Tracking Script

Add the AffiliateBase tracking script to your Next.js app. Add this to your app/layout.tsx or pages/_document.tsx. Using jsDelivr CDN ensures fast global delivery and automatic updates. No hosting required.
typescript
// app/layout.tsx
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        <Script id="affiliatebase-queue" strategy="beforeInteractive">
          {`(function(w,r){w._abq=w._abq||[];w[r]=w[r]||function(){(w[r].q=w[r].q||[]).push(arguments)}})(window,'affiliatebase');`}
        </Script>
        <Script
          src="https://cdn.jsdelivr.net/npm/affiliatebase-tracking@1/src/index.js"
          data-org-id="YOUR_ORG_ID"
          strategy="afterInteractive"
        />
      </head>
      <body>{children}</body>
    </html>
  );
}
2

Or Install via npm

Install via npm for TypeScript support and bundler integration.
bash
npm install affiliatebase-tracking

// Import in your app entry
import 'affiliatebase-tracking';
3

Access Referral ID in Components

Create a hook to access the referral ID in your Next.js components.
typescript
// hooks/useAffiliateTracking.ts
'use client';

import { useState, useEffect } from 'react';

export const useAffiliateTracking = () => {
  const [referralId, setReferralId] = useState<string>('');
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    if (typeof window !== 'undefined' && window.affiliatebase) {
      window.affiliatebase('ready', () => {
        setReferralId(window.affiliatebase_referral || '');
        setIsReady(true);
      });
    }
  }, []);

  const trackConversion = (email: string) => {
    window.affiliatebase?.('convert', { email });
  };

  return { referralId, isReady, trackConversion };
};
4

Pass Referral ID to Stripe

Pass the referral ID as client_reference_id to Stripe for accurate conversion tracking. Here's how to pass it when creating a Checkout Session in your API route.
typescript
// app/api/checkout/route.ts
import { NextResponse } from 'next/server';
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(request: Request) {
  const { referralId, priceId } = await request.json();

  const session = await stripe.checkout.sessions.create({
    success_url: `${process.env.NEXT_PUBLIC_URL}/success`,
    cancel_url: `${process.env.NEXT_PUBLIC_URL}/cancel`,
    customer_creation: 'always',
    ...(referralId && { client_reference_id: referralId }),
    line_items: [{ price: priceId, quantity: 1 }],
    mode: 'subscription',
  });

  return NextResponse.json({ url: session.url });
}
5

Create Checkout Button Component

Use the hook in your checkout component to pass the referral ID.
typescript
// components/CheckoutButton.tsx
'use client';

import { useAffiliateTracking } from '@/hooks/useAffiliateTracking';

export function CheckoutButton({ priceId }: { priceId: string }) {
  const { referralId } = useAffiliateTracking();

  const handleCheckout = async () => {
    const response = await fetch('/api/checkout', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ referralId, priceId }),
    });
    const { url } = await response.json();
    window.location.href = url;
  };

  return <button onClick={handleCheckout}>Subscribe</button>;
}

Why Use AffiliateBase with Next.js?

AffiliateBase is the perfect solution for Next.js developers who want to launch an affiliate program quickly and efficiently.

App Router Ready

Works seamlessly with Next.js App Router, Server Components, and API routes.

TypeScript Support

Full TypeScript definitions included for type-safe affiliate tracking.

Automatic Stripe Integration

Tracks Stripe Checkout, Payment Links, and Pricing Tables automatically.

Zero Configuration

Drop in the script tag and start tracking. No API keys or complex setup.

Frequently Asked Questions

Does AffiliateBase work with Next.js App Router?
Yes! AffiliateBase fully supports both the Pages Router and App Router in Next.js. Use the next/script component for optimal loading.
How do I access the referral ID in Server Components?
The tracking script runs client-side, so pass the referral ID from a Client Component to your API routes when needed.
Can I use AffiliateBase with Next.js middleware?
The tracking uses cookies that are set client-side. For middleware, you can read the affiliate cookie and forward it to your backend.
What tracking parameters does AffiliateBase support?
AffiliateBase automatically detects ?via=, ?ref=, ?affiliate=, and ?a= URL parameters for attribution.

Ready to Launch Your Next.js Affiliate Program?

Get started with AffiliateBase today and start growing your business with affiliate marketing.