How to Create an Affiliate Program with Svelte | AffiliateBase

Svelte is a modern JavaScript framework that compiles your code to highly efficient vanilla JavaScript. If you're looking to monetize your Svelte app 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 Svelte, from initial setup to tracking conversions using Svelte stores and SvelteKit server routes.

Whether you're building a single-page application with Svelte or a full-stack app with SvelteKit, 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 Svelte:

1

Add the Tracking Script

Add the AffiliateBase tracking script to your app. For SvelteKit, add to app.html. For Svelte, add to index.html. Using jsDelivr CDN ensures fast global delivery and automatic updates. No hosting required.
html
<!-- src/app.html (SvelteKit) or index.html (Svelte) -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <script>(function(w,r){w._abq=w._abq||[];w[r]=w[r]||function(){(w[r].q=w[r].q||[]).push(arguments)}})(window,'affiliatebase');</script>
    <script async src="https://cdn.jsdelivr.net/npm/affiliatebase-tracking@1/src/index.js" data-org-id='YOUR_ORG_ID'></script>
    %sveltekit.head%
  </head>
  <body data-sveltekit-preload-data="hover">
    <div style="display: contents">%sveltekit.body%</div>
  </body>
</html>
2

Or Install via npm

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

// In your +layout.svelte or main entry
import 'affiliatebase-tracking';
3

Create a Svelte Store

Create a store to access affiliate tracking throughout your app.
typescript
// src/lib/stores/affiliate.ts
import { writable, derived } from 'svelte/store';
import { browser } from '$app/environment';

export const affiliateReady = writable(false);
export const referralId = writable<string>('');

if (browser) {
  window.affiliatebase?.('ready', () => {
    referralId.set(window.affiliatebase_referral || '');
    affiliateReady.set(true);
  });
}

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

Create SvelteKit API Route

Pass the referral ID as client_reference_id to Stripe for accurate conversion tracking. Create a server route for checkout.
typescript
// src/routes/api/checkout/+server.ts
import { json } from '@sveltejs/kit';
import Stripe from 'stripe';
import type { RequestHandler } from './$types';

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

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

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

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

Use in Components

Use the store in your Svelte components.
svelte
<!-- src/routes/pricing/+page.svelte -->
<script lang="ts">
  import { referralId } from '$lib/stores/affiliate';

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

<button on:click={handleCheckout}>Subscribe</button>

Why Use AffiliateBase with Svelte?

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

SvelteKit Ready

Works seamlessly with SvelteKit server routes, load functions, and form actions.

Svelte Stores

Integrates naturally with Svelte's reactive store system.

Lightweight

Zero-dependency tracking script matches Svelte's minimal philosophy.

TypeScript Support

Full TypeScript support for type-safe affiliate tracking.

Frequently Asked Questions

Does AffiliateBase work with SvelteKit?
Yes! AffiliateBase works great with SvelteKit. Add the script to app.html and use stores to access the referral ID in your routes.
Can I use AffiliateBase with plain Svelte?
Yes, the tracking script works with any Svelte setup. Just add it to your index.html.
How do I handle form actions with affiliate tracking?
Use the referralId store value and include it in your form data or pass it to your API endpoint.
What tracking parameters does AffiliateBase support?
AffiliateBase automatically detects ?via=, ?ref=, ?affiliate=, and ?a= URL parameters.

Ready to Launch Your Svelte Affiliate Program?

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