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:
Add the Tracking Script
// 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>
);
}
Or Install via npm
npm install affiliatebase-tracking
// Import in your app entry
import 'affiliatebase-tracking';
Access Referral ID in Components
// 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 };
};
Pass Referral ID to Stripe
// 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 });
}
Create Checkout Button Component
// 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?
How do I access the referral ID in Server Components?
Can I use AffiliateBase with Next.js middleware?
What tracking parameters does AffiliateBase support?
Related Platform Guides
Create an Affiliate Program with React
Complete guide to setting up an affiliate program in React. Step-by-step integration with React hooks, context, and components for React developers.
Create an Affiliate Program with Vue
Complete guide to setting up an affiliate program in Vue. Step-by-step integration with Vue 3, composables, and plugins for Vue developers.
Create an Affiliate Program with Svelte
Complete guide to setting up an affiliate program in Svelte. Step-by-step integration with SvelteKit, stores, and components for Svelte developers.
Create an Affiliate Program with Remix
Complete guide to setting up an affiliate program in Remix. Step-by-step integration with Remix loaders, actions, and forms for full-stack React developers.
Create an Affiliate Program with Astro
Complete guide to setting up an affiliate program in Astro. Step-by-step integration with Astro API routes, islands, and components for content-focused sites.
Ready to Launch Your Next.js Affiliate Program?
Get started with AffiliateBase today and start growing your business with affiliate marketing.