GrowSurf Docs
Help CenterSystem StatusContact SupportYour Dashboard →
  • Welcome
  • Getting Started for Web
    • Google Tag Manager
    • Participant Auto Authentication
  • Getting Started for Native Mobile
  • Developer Tools
    • Embeddable Elements
    • JavaScript SDK
      • Tutorials
      • Single Page Applications
      • API Reference
    • REST API
      • Tutorials
      • Objects
      • API Reference
      • API Guidelines
      • API Response Codes
    • Webhooks
      • Securing Your Webhooks (optional)
      • Examples
      • Events Reference
    • Metadata
  • Integrations
    • ActiveCampaign
      • Tutorials
    • Amplitude
    • AWeber
      • Tutorials
    • Brevo (formerly Sendinblue)
      • Tutorials
    • Cal.com
    • Calendly
    • Campaign Monitor
      • Tutorials
    • Chargebee
    • Constant Contact
      • Tutorials
    • ConvertKit
      • Tutorials
    • Customer.io
      • Tutorials
    • Drip
      • Tutorials
    • EmailOctopus
      • Tutorials
    • Fullstory
    • GetResponse
      • Tutorials
    • Google Ads
    • Google Analytics
    • Heap
    • Help Scout
    • HubSpot
      • Tutorials
    • Intercom
      • Tutorials
    • Klaviyo
      • Tutorials
    • LinkedIn Ads
    • Mailchimp
      • Tutorials
    • MailerLite
      • Tutorials
    • Mailjet
      • Tutorials
    • Make
      • Tutorials
    • Marketo
      • Tutorials
    • Meta (Facebook) Ads
    • Mixpanel
    • Pabbly Connect
      • Tutorials
    • PayPal
    • Pendo
    • PostHog
    • Recurly
    • Salesforce
      • Tutorials
    • Segment
    • SendGrid
      • Tutorials
    • Slack
    • Stripe
    • Tango Card
    • Typeform
    • X (Twitter) Ads
    • Zapier
      • Tutorials
      • Using Filters
      • Troubleshooting
Powered by GitBook
On this page
  • Example 1: Trigger a referral on qualifying action (e.g, on conversion, purchase, or upgrade)
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add the participant
  • Step 3: Trigger the referral
  • Example 2: Open GrowSurf window on button click
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add code
  • Example 3: Display a participant's unique share link and referral count inline on a webpage
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add code
  • Example 4: Redirect to another URL after a successful participant signup
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add code
  • Example 5: Add a personalized message to your Share URL for a warm welcome
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add code
  • Example 6: Only add a participant if they were referred
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add code
  • Example 7: Hide the GrowSurf Embedded Form until a GrowSurf participant is detected
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add code
  • Example 8: Add internationalization support for the GrowSurf Embedded Form and embedded invite
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add code
  • Example 9: Update pre-populated share and email invite messages to capitalize on a customer "aha moment"
  • Step 1: Make sure the GrowSurf Universal Code is installed
  • Step 2: Add code
  • Example 10: Load multiple GrowSurf campaigns on a single webpage
  • Step 1: Update each Share URL for each of your campaigns
  • Step 2: Paste this code into the <HEAD> of your website instead of the GrowSurf Universal Code
  • Example 11: Display a Referral Link on Your Login Page
  • Step 1: Install GrowSurf in Your React App
  • Step 2: Register Users and Add Them to GrowSurf
  • Step 3: Display Profile Page After Login/Registration
  • Step 4: Login and Validate the GrowSurf Participant
  • Step 5: Show the Referral Widget (Only After Logout)
  • Example 12: Display "You came through a referral link!" on Your Signup Page
  • Step 1: Install GrowSurf in Your React App
  • Step 2: Get the referralId and show the referral message on the registration page
  • Step 4: Register Users and Add Them to GrowSurf

Was this helpful?

  1. Developer Tools
  2. JavaScript SDK

Tutorials

How to implement the GrowSurf JavaScript SDK in common use-case scenarios.

Last updated 24 days ago

Was this helpful?

Table of contents

Scenario

Example 1: Trigger a referral on qualifying action (e.g, on conversion, purchase, or upgrade)

Step 2: Add the participant

your-script.js
// In this example, a new person is just signing up for a free account
const signUpFree = (user) => {
    // ...code that registers a new user...
    // Then add the new user as a participant in your GrowSurf campaign
    if (window.growsurf) {
        growsurf.addParticipant({
            email: user.email,
            firstName: user.firstName,
            lastName: user.lastName
        });
    }
};

Step 3: Trigger the referral

your-script.js
// In this example, the user upgrades to a paid plan
const upgradeToPaidPlan = (user) => {
    // ...code that upgrades the user...
    // Then trigger this action as a referral trigger
    if (window.growsurf) {
        growsurf.triggerReferral(user.email);
    }
};

Remember to set up reward fulfillment automation

Example 2: Open GrowSurf window on button click

The GrowSurf window allows your users to retrieve their referral link to share, as well track the status of their referrals and rewards. Follow this tutorial to view how to open the GrowSurf window from an element such as a button.

Step 2: Add code

Add a CSS class to your button

Add the CSS class growsurf-open-window on your button element, and clicking the element will open up the GrowSurf window.

<a class="growsurf-open-window">
   Refer and Earn
</a>

However, when your user opens the GrowSurf window, they'll see a signup form instead of their unique referral link. To ensure they always see their referral link, add them or log them in as a participant first. You can do this by adding the data-grsf-email, data-grsf-first-name , and data-grsf-last-name data attributes. Here's a code example (remember to replace the values with your logged-in user's details):

<a class="growsurf-window-open"
   data-grsf-email="gavin@hooli.com"
   data-grsf-first-name="Gavin"
   data-grsf-last-name="Belson">
  Refer and Earn
</a>

Add onclick="growsurf.open()" to your button

<a onclick="growsurf.open()">
  Refer Friends
</a>

Or use JavaScript:

<a id="refer-button">
  Refer Friends
</a>

<script>
  document.getElementById('refer-button').addEventListener('click', function() {
    growsurf.open();
  });
</script>
<a onclick="growsurf.addParticipant({
               email: 'gavin@hooli.com',
               firstName: 'gavin@hooli.com',
               lastName: 'gavin@hooli.com'
            });
            growsurf.open();">
  Refer Friends
</a>

Or use JavaScript:

<a id="refer-button">
  Refer Friends
</a>

<script>
  document.getElementById('refer-button').addEventListener('click', function() {
    growsurf.addParticipant({
      email: 'gavin@hooli.com',
      firstName: 'gavin@hooli.com',
      lastName: 'gavin@hooli.com'
    });
    growsurf.open();
  });
</script>

Example 3: Display a participant's unique share link and referral count inline on a webpage

Step 2: Add code

Just paste <div data-grsf-block-form></div> anywhere in your HTML, and the GrowSurf form will appear. If you want your participant to be already logged in and see their stats (instead of the form), you can add an attribute data-grsf-email to have the value of the participant's email.

Important Note:

If you have participant authentication enabled for your campaign, then the participant's unique share link and social buttons will only display if the participant entered your referral program from their browser (either through automatic form detection, the GrowSurf form, or the JavaScript SDK). This is because a browser cookie will be saved that identifies the participant. Otherwise, the signup form will be shown, and the participant can click the login link to get sent a one-time login email.

index.html
<!-- Providing just this code will make the GrowSurf form appear -->
<div data-grsf-block-form></div>

<!-- Add a `data-grsf-email` attribute to authenticate the participant -->
<div data-grsf-block-form
 data-grsf-email="gavin@hooli.com">
</div>

<!-- You can also completely customize the Embedded Form, shown in this example -->
<div data-grsf-block-form
 data-grsf-email="gavin@hooli.com"
 data-grsf-button-style="{'background-color': '#5890E7', 'color': '#fcfcfc', 'font-family': 'Sans', 'font-size': '12px'}"
 data-grsf-email-button-style="{'background-color': '#5890E7', 'color': '#fcfcfc', 'font-family': 'Arial', 'font-size': '12px'}"
 data-grsf-email-button-text="Share"
 data-grsf-twitter-button-style="{'background-color': '#5890E7', 'font-family': 'Arial', 'font-size': '12px'}"
 data-grsf-twitter-button-text="Share"
 data-grsf-facebook-button-style="{'background-color': '#5890E7', 'font-family': 'Courier New', 'font-size': '12px'}"
 data-grsf-facebook-button-text="Share"
 data-grsf-pinterest-button-style="{'background-color': '#5890E7', 'letter-spacing': '1.2', 'font-size': '12px'}"
 data-grsf-pinterest-button-text="Pin It"
 data-grsf-share-instructions="Share this unique link with your friends">
</div>

Call growsurf.getParticipantByEmail()

Here's an example of retrieving the participant data, then updating the #share-url and #referral-count HTML elements to show their unique referral link and referral count.

index.html
<!DOCTYPE html>
<html>
<head>
	<title>Your Referral Stats</title>
	<!-- The GrowSurf Universal Code -->
	<script type="text/javascript">
		(function(g,r,s,f){g.growsurf={};g.grsfSettings={campaignId:"REPLACE_ME_WITH_YOUR_CAMPAIGN_ID",version:"2.0.0"};s=r.getElementsByTagName("head")[0];f=r.createElement("script");f.async=1;f.src="https://growsurf.com/growsurf.js"+"?v="+g.grsfSettings.version;f.setAttribute("grsf-campaign", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):"";})(window,document);
	</script>
</head>
<body>
	<input id="share-url" type="text" disabled>
	<div id="referral-count"></div>
	
	<script>
	    // Listen and wait for Growsurf to initialize
	    window.addEventListener('grsfReady', () => {
	        const participantEmail = 'sarah@website.com'; // replace with your user's email
        	// Get the GrowSurf participant's information
		growsurf.getParticipantByEmail(participantEmail).then(participant => {
			document.getElementById("share-url").value = participant.shareUrl;
			document.getElementById("referral-count").innerHTML = participant.referralCount;			
		});
	    });	
	</script>
</body>
</html>

Example 4: Redirect to another URL after a successful participant signup

This is for when you want to redirect to another webpage after a participant successfully signs up for your referral campaign.

Step 2: Add code

Remember to replace https://replaceme.com with your redirect URL.

<div data-grsf-block-form
 data-grsf-redirect-url="https://replaceme.com">
</div>
<script>
    // Listen and wait for the Growsurf Universal Code to initialize
    window.addEventListener('grsfReady', () => {
        console.log('GrowSurf is Ready!');
        // Your redirect code goes here....
        growsurf.subscribe('signup', (participant) => {
          window.location.replace("http://replaceme.com");
        });
    });
</script>

Please note that if the redirect is not working, it is most likely because the form submission is failing. If this is the case, please check your browser console for errors.

Example 5: Add a personalized message to your Share URL for a warm welcome

Step 2: Add code

<html>
	<body>
		<h1 id="header">Pet puppies on-demand</h1>
	</body>
	<script>
		window.addEventListener('grsfReady', () => {
			const referrerId = growsurf.getReferrerId();	
			if (referrerId) {
				growsurf.getParticipantById(referrerId).then(participant => {
					if (participant) {
						const { firstName, lastName = '' } = participant;
						const lastNameAsString = (lastName).toString();
						const newHeader = `${firstName && lastName ? firstName + ' ' + lastNameAsString.charAt(0) + '. invited you to pet puppies on-demand' : 'Pet puppies on-demand'}`;
						const headerEl = document.getElementById('header');
						headerEl.innerHTML = newHeader;
					}
				});
			}
		});
	</script>
</html>

Example 6: Only add a participant if they were referred

Step 2: Add code

This code is for demonstration purposes only. You may need to modify it to work on your website.

<html>
	<body>
		<h1 id="header">Pet puppies on-demand</h1>
		<!-- Example form only, this must be replaced with your actual form -->
		<form id="form">
	  		<label>Email: <input name="email" type="text"></label>
  			<button type="submit">Submit form</button>
		</form>
	</body>
	<script>
		// Listen for the GrowSurf Ready Event
		window.addEventListener('grsfReady', () => {
			// Add an event listener to the example form to listen for submissions
			const form = document.getElementById('form');
			form.addEventListener('submit', onFormSubmit);
		});
		
		// Callback function that is invoked when a new visitor has just submitted a form on your website
		const onFormSubmit = (event) => {
		    // Get the value of the email - Update this depending on your form
		    const userEmail = event.target.email.value;
		    // Check to see if the submitter was referred
		    if (window.growsurf && !!window.growsurf.getReferrerId()) {
		        // Only Add the participant if they were referrered
		        window.growsurf.addParticipant({ email: userEmail });
		    }
		    event.preventDefault();
		};
	</script>
</html>

Example 7: Hide the GrowSurf Embedded Form until a GrowSurf participant is detected

Step 2: Add code

<div data-grsf-block-form
  data-grsf-email="sarah@smith.com"
  class="hide-until-grsf-auth"></div>
.show-after-grsf-auth { display: initial }
.hide-until-grsf-auth { display: none }
// Check if a participant is logged-in, and display auth views based on if there is a participant
function showGrsf() {
	var participantAuth = growsurf.getParticipantId();
	if (participantAuth) {
		$('.hide-until-grsf-auth').addClass('show-after-grsf-auth');
	} else {
		// Subscribe to a 'GrowSurf signup' event listener
		growsurf.subscribe('signup', function(participant) {
		  $('.hide-until-grsf-auth').addClass('show-after-grsf-auth');
		});
	}
}

// See if GrowSurf is available
if(!window.growsurf) {
	// Listen and wait for the Growsurf Universal Code to initialize
	window.addEventListener('grsfReady', function() {
		showGrsf();
	});
} else {
	showGrsf();
}

Example 8: Add internationalization support for the GrowSurf Embedded Form and embedded invite

Step 2: Add code

In English:

<div data-grsf-block-form
 data-grsf-field-first-name-label="First name"
 data-grsf-field-first-name-placeholder="First name"
 data-grsf-field-first-name-label="Last name"
 data-grsf-field-first-name-placeholder="Last name" 
 data-grsf-field-phone-number-label="Phone number"
 data-grsf-field-phone-number-placeholder="Phone number"
 data-grsf-share-instructions="Share this unique link with your friends"
 data-grsf-copy-link-button-text="Copy Link"
 data-grsf-email-button-text="Share"
 data-grsf-email-button-message="I just saved $X,XXX by using this service! {{shareUrl}}"
 data-grsf-email-button-subject="Check this out friend"
 data-grsf-facebook-button-text="Share"
 data-grsf-facebook-button-message="I just saved $X,XXX by using this service! {{shareUrl}}"
 data-grsf-twitter-button-text="Share"
 data-grsf-twitter-button-message="I just saved $X,XXX by using this service! {{shareUrl}}">
</div>

In Spanish:

<div data-grsf-block-form
 data-grsf-field-first-name-label="Primer nombre"
 data-grsf-field-first-name-placeholder="Primer nombre"
 data-grsf-field-first-name-label="Apellido"
 data-grsf-field-first-name-placeholder="Apellido" 
 data-grsf-field-phone-number-label="Número de teléfono"
 data-grsf-field-phone-number-placeholder="Número de teléfono"
 data-grsf-share-instructions="Comparte este enlace único con tus amigos"
 data-grsf-copy-link-button-text="Copiar link"
 data-grsf-email-button-text="Cuota"
 data-grsf-email-button-message="¡Acabo de ahorrar $X,XXX al usar este servicio! {{shareUrl}}"
 data-grsf-email-button-subject="Mira esto amigo"
 data-grsf-facebook-button-text="Cuota"
 data-grsf-facebook-button-message="¡Acabo de ahorrar $X,XXX al usar este servicio! {{shareUrl}}"
 data-grsf-twitter-button-text="Cuota"
 data-grsf-twitter-button-message="¡Acabo de ahorrar $X,XXX al usar este servicio! {{shareUrl}}">
</div>

These examples used Google as the enabled address book. If you have other address books enabled, make sure to account for them.

In English:

<div data-grsf-block-invite
 data-grsf-input-placeholder-text="Enter email addresses here"
 data-grsf-preview-link-text="Preview your message"
 data-grsf-preview-subject-label="Email Subject"
 data-grsf-preview-subject-placeholder="Check this out friend"
 data-grsf-preview-subject="Check this out friend"
 data-grsf-preview-message-label="Email Message"
 data-grsf-preview-message-placeholder="I just saved $X,XXX by using this service! {{shareUrl}}"
 data-grsf-preview-message="I just saved $X,XXX by using this service! {{shareUrl}}" 
 data-grsf-submit-button-text="Send Invites"
 data-grsf-google-button-text="Import Google Contacts"
 data-grsf-contact-picker-search-text="Search"
 data-grsf-contact-picker-suggestions-text="Suggestions"
 data-grsf-contact-picker-results-text="Results"
 data-grsf-contact-picker-load-more-button-text="Load More">
</div>

In Spanish:

<div data-grsf-block-invite
 data-grsf-input-placeholder-text="Ingrese las direcciones de correo electrónico aquí"
 data-grsf-preview-link-text="Vista previa de su mensaje"
 data-grsf-preview-subject-label="Asunto del email"
 data-grsf-preview-subject-placeholder="Mira esto amigo"
 data-grsf-preview-subject="Mira esto amigo"
 data-grsf-preview-message-label="Mensaje de correo electrónico"
 data-grsf-preview-message-placeholder="¡Acabo de ahorrar $X,XXX al usar este servicio! {{shareUrl}}"
 data-grsf-preview-message="¡Acabo de ahorrar $X,XXX al usar este servicio! {{shareUrl}}" 
 data-grsf-submit-button-text="Enviar invitaciones"
 data-grsf-google-button-text="Importar contactos de Google"
 data-grsf-contact-picker-search-text="Buscar"
 data-grsf-contact-picker-suggestions-text="Sugerencias"
 data-grsf-contact-picker-results-text="Resultados"
 data-grsf-contact-picker-load-more-button-text="Carga más">
</div>

Example 9: Update pre-populated share and email invite messages to capitalize on a customer "aha moment"

Step 2: Add code

To better illustrate this use-case, consider the following scenarios:

Let's say you're a SaaS company that helps social media users gain more followers. You could ask for referrals once a user gains 100 followers.

Add the following HTML code (e.g, in a popup on your webpage):

<div>
    <h2>💯 Alert!</h2>
    <p>Amazing, you just hit 100 followers this past week.</p>
    <div data-grsf-block-form
         data-grsf-share-instructions="Get your next month on us when you refer a friend"
         data-grsf-copy-link-container-style="{'display': 'none'}"></div>
    <div data-grsf-block-invite></div>
</div>

Add the following JavaScript code:

// Sign up (or log in) your user as a GrowSurf participant
const userEmail = 'bob@boblaw.com'; // Replace with the user's email address
growsurf.addParticipant({email: userEmail});

// Set the initial message and subject line
const message = "I've just gained 100 followers by using this tool! {{shareUrl}}";
const subjectLine = "Check this out!";

// Update the social share messages
growsurf.updateSocialShareMessage('email', message, subjectLine);
growsurf.updateSocialShareMessage('facebook', message);
growsurf.updateSocialShareMessage('twitter', message);
growsurf.updateSocialShareMessage('pinterest', message);
growsurf.updateSocialShareMessage('sms', message);
growsurf.updateSocialShareMessage('whatsapp', message);

// Update the pre-populated email invite message and subject line
growsurf.updateEmailInviteMessage(message, subjectLine);

Let's say you're a messaging SaaS (e.g, Slack). You could ask for referrals once a team sends 2,000 messages in a workspace.

Add the following HTML code (e.g, in a popup on your webpage):

<div>
    <h2>Woohoo, you've just sent 2,000 messages!</h2>
    <p>That's 6 days worth of time saved in productivity.</p>
    <div data-grsf-block-form
         data-grsf-share-instructions="Share your victory:"
         data-grsf-copy-link-container-style="{'display': 'none'}"></div>
    <div data-grsf-block-invite></div>
</div>

Add the following JavaScript code:

// Sign up (or log in) your user as a GrowSurf participant
const userEmail = 'bob@boblaw.com'; // Replace with the user's email address
growsurf.addParticipant(userEmail);

// Set the initial message and subject line
const message = "We've just sent 2,000 messages using this service and have saved 6 days of productivity. Love this service! {{shareUrl}}";
const subjectLine = "Check this out!";

// Update the social share messages
growsurf.updateSocialShareMessage('email', message, subjectLine);
growsurf.updateSocialShareMessage('facebook', message);
growsurf.updateSocialShareMessage('twitter', message);
growsurf.updateSocialShareMessage('pinterest', message);
growsurf.updateSocialShareMessage('sms', message);
growsurf.updateSocialShareMessage('whatsapp', message);

// Update the pre-populated email invite message and subject line
growsurf.updateEmailInviteMessage(message, subjectLine);

Let's say you're a food delivery service company (e.g, Doordash). You could ask for referrals once the user leaves a positive review after a delivery.

Add the following HTML code (e.g, in a popup on your webpage):

<div>
    <h2>Loving Doordash?</h2>
    <div data-grsf-block-form
         data-grsf-share-instructions="Get your next meal on us, up to $20 when you refer a friend."
         data-grsf-copy-link-container-style="{'display': 'none'}"></div>
    <div data-grsf-block-invite></div>
</div>

Add the following JavaScript code:

// Sign up (or log in) your user as a GrowSurf participant
const userEmail = 'bob@boblaw.com'; // Replace with the user's email address
growsurf.addParticipant(userEmail);

// Set the initial message and subject line
const message = "I just ordered delicious Wing's spicy noodle soup with DoorDash. 5/5 experience! Get $20 off your first order: {{shareUrl}}";
const subjectLine = "Check this out!";

// Update the social share messages
growsurf.updateSocialShareMessage('email', message, subjectLine);
growsurf.updateSocialShareMessage('facebook', message);
growsurf.updateSocialShareMessage('twitter', message);
growsurf.updateSocialShareMessage('pinterest', message);
growsurf.updateSocialShareMessage('sms', message);
growsurf.updateSocialShareMessage('whatsapp', message);

// Update the pre-populated email invite message and subject line
growsurf.updateEmailInviteMessage(message, subjectLine);

Example 10: Load multiple GrowSurf campaigns on a single webpage

If you have multiple GrowSurf campaigns and want to use the same landing page and/or signup pages, here's how you can load the right campaign depending on where the traffic is coming from.

Step 1: Update each Share URL for each of your campaigns

For each of your campaigns, navigate to Campaign Editor > 5. Installation and update the Share URL to include a ?growsurf_campaign parameter.

  • Grab the campaign ID in the address bar of your browser.

  • See an example in the image below:

Step 2: Paste this code into the <HEAD> of your website instead of the GrowSurf Universal Code

Instead of pasting the GrowSurf Universal Code into the <HEAD> of your webpage(s), add the following code below. Make sure to update the DEFAULT_GROWSURF_CAMPAIGN_ID value at line 3 to your own default campaign ID.

<script type="text/javascript">
   // Update these parameters
   const DEFAULT_GROWSURF_CAMPAIGN_ID = 'abc123'; // (Optional) Replace with your default campaign ID. This will be used as a fallback if provided.
   
   // Additional configurable parameters
   const GROWSURF_CAMPAIGN_ID_URL_PARAM = 'growsurf_campaign';
   const GROWSURF_CAMPAIGN_ID_COOKIE_NAME = 'growsurf_campaign'; // Make it the same name as the URL param for simplicity

    function getBaseDomain() {
      const hostname = window.location.hostname;
      const parts = hostname.split('.');
      if (parts.length > 1) { return '.' + parts.slice(-2).join('.'); }
      return hostname;
   }

   function getQueryParam(name) {
      const urlParams = new URLSearchParams(window.location.search);
      const value = urlParams.get(name);
      if (value && value.includes('?')) {
         return value.split('?')[0];
      }
      return value;
   }

   function setCookie(name, value, days) {
      let expires = "";
      if (days) {
         const date = new Date();
         date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
         expires = "; expires=" + date.toUTCString();
      }
      const domain = getBaseDomain();
      document.cookie = `${name}=${value}; domain=${domain}; path=/;${expires}`;
   }   

   function getCookie(name) {
      const nameEQ = `${name}=`;
      const ca = document.cookie.split(';');
      for (let i = 0; i < ca.length; i++) {
         let c = ca[i];
         while (c.charAt(0) === ' ') c = c.substring(1, c.length);   
         if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
      }
      return null;
   }

   const growsurfCampaignIdInUrlParam = getQueryParam(GROWSURF_CAMPAIGN_ID_URL_PARAM);
   if (growsurfCampaignIdInUrlParam) {
      setCookie(GROWSURF_CAMPAIGN_ID_COOKIE_NAME, growsurfCampaignIdInUrlParam, 365); // Stores campaign ID in cookie for 365 days
   }   
   const growsurfCampaignId = getCookie(GROWSURF_CAMPAIGN_ID_COOKIE_NAME) || DEFAULT_GROWSURF_CAMPAIGN_ID;
   if (growsurfCampaignId) {
      console.log('Loading GrowSurf Universal Code with campaign ID:', growsurfCampaignId);
      // Call the GrowSurf Universal Code
      (function(g,r,s,f){g.grsfSettings={campaignId:growsurfCampaignId,version:"2.0.0"};s=r.getElementsByTagName("head")[0];f=r.createElement("script");f.async=1;f.src="https://app.growsurf.com/growsurf.js"+"?v="+g.grsfSettings.version;f.setAttribute("grsf-campaign", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):"";})(window,document);            
   }
</script>

Here's what this code does:

  • Referral links will now look something like this: https://mysite.com?growsurf_campaign=abc123&grsf=xyz789 . The campaign ID is abc123 and will be saved as a cookie for 365 days. So when a referred friend lands on a referral link, the appropriate campaign ID will first be loaded. (The referrer ID xyz789 is also automatically saved as a cookie).

  • If that referred friend revisits or returns to your site (e.g, mysite.com) even without using a referral link, the appropriate campaign will still be loaded b/c the campaign ID was saved as a cookie.

  • Once the referred friend signs up, the campaign that they originally came through a referral link from will be the one they get added to.

  • If a website visitor did not use a referral link to land on your website and sign ups, the fallback campaign abc123 will be the one used.

Example 11: Display a Referral Link on Your Login Page

In this tutorial, you'll learn how to display referral links to users on your login page. The typical use-case for this is to remind returning users of your referral program and conveniently provide their referral link that they can share.

This tutorial uses React, Firebase Authentication, and the GrowSurf JavaScript SDK.

Step 1: Install GrowSurf in Your React App

Inside your App.js, add the following function and use it in a useEffect:

const GROWSURF_CAMPAIGN_ID = "x8yi1l" // Replace with your own campaign ID

const addGrsfScript = () => {
  if (document.querySelector('script[src*="growsurf.js"]')) return;
  const script = document.createElement("script");
  script.src = "https://app.growsurf.com/growsurf.js?v=2.0.0";
  script.setAttribute("grsf-campaign", GROWSURF_CAMPAIGN_ID);
  script.async = true;
  document.head.appendChild(script);
};

useEffect(() => {
  onAuthStateChanged(auth, (user) => {
    setCurrentUser(user);
  });

  if (document.readyState === "complete") {
    addGrsfScript();
  } else {
    window.addEventListener("load", addGrsfScript);
    return () => window.removeEventListener("load", addGrsfScript);
  }
}, []);

Important: Make sure to replace x8yi1l at line 1 with your own campaign ID.

This ensures GrowSurf loads once when the app starts.

Step 2: Register Users and Add Them to GrowSurf

For the purpose of this demo, this is the logic that we'll have when a new user registers:

  1. Create the user in Firebase

  2. Redirect them to the Profile page

This is what the register() function in the Register.js file looks like:

const register = (e) => {
  e.preventDefault();
  createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      const user = userCredential.user;
      
      // Add user to GrowSurf
      if (window.growsurf?.addParticipant) {
        window.growsurf.addParticipant(user.email);
      }
      navigate("/"); // Redirect to profile
    })
    .catch((err) => setError(err.message));
};

Step 3: Display Profile Page After Login/Registration

In the Profile.js file, we'll show the user’s email and display a Logout button:

<h2>Welcome, {currentUser.email}</h2>
<button onClick={logout}>Logout</button>

When the user logs out, they’re redirected back to the Login page.

Step 4: Login and Validate the GrowSurf Participant

When a user logs in, we'll have the following logic be executed:

Here's what we have in the Login.js file:

const login = (e) => {
  e.preventDefault();
  setError("");

  signInWithEmailAndPassword(auth, email, password)
    .then(() => {
      if (window.growsurf?.getParticipantByEmail) {
        window.growsurf.getParticipantByEmail(email, (participant) => {
          if (participant) {
            // Initialize GrowSurf participant session
            window.growsurf.addParticipant(email, () => {
              localStorage.setItem("hasLoggedIn", "true");
              setShowReferral(true);
              navigate("/");
            });
          }
        });
      } else {
        setError("GrowSurf is not ready. Please try again shortly.");
      }
    })
    .catch((err) => setError(err.message));
};

Step 5: Show the Referral Widget (Only After Logout)

{showReferral && (
  <div className="referral-sidebar">
    <div
      data-grsf-block-form
      data-grsf-share-instructions="<h3 style='text-align: center;'>Refer a friend</h3>"
      data-grsf-social-buttons-layout-theme="3"
      data-grsf-copy-link-button-layout-theme="3"
    ></div>
  </div>
)}

Important note on authentication: This tutorial focuses on integrating GrowSurf referral tracking in a React app using Firebase for authentication. However, the same concepts apply no matter what auth system you’re using (Supabase, Auth0, a custom backend, etc).

For simplicity, the tutorial assumes that returning users already exist in both your authentication system and your GrowSurf campaign.

This tutorial doesn’t cover all security details, and you'll want to adapt the logic to fit your own authentication flow and app structure.

Example 12: Display "You came through a referral link!" on Your Signup Page

In this tutorial, you'll learn how to display a message like “You came through a referral link!” on your signup page using the GrowSurf JavaScript SDK using the following two methods:

The use-case for this scenario is for verifying to referred visitors that they came through a referral link.

This tutorial uses React, Firebase Authentication, and the GrowSurf JavaScript SDK.

Demo:

From this tutorial, the following can be assumed:

  • The GrowSurf Universal Code will be dynamically injected in App.js

  • User authentication is via Firebase Auth and Firebase Realtime Database

  • growsurf.addParticipant(email) will be called after user signup to track referrals

  • The login state is managed using a custom AuthContext.js

Step 1: Install GrowSurf in Your React App

Inside your App.js, add the following function and use it in a useEffect:

const GROWSURF_CAMPAIGN_ID = "x8yi1l" // Replace with your own campaign ID

const addGrsfScript = () => {
  if (document.querySelector('script[src*="growsurf.js"]')) return;
  const script = document.createElement("script");
  script.src = "https://app.growsurf.com/growsurf.js?v=2.0.0";
  script.setAttribute("grsf-campaign", GROWSURF_CAMPAIGN_ID);
  script.async = true;
  document.head.appendChild(script);
};

useEffect(() => {
  onAuthStateChanged(auth, (user) => {
    setCurrentUser(user);
  });

  if (document.readyState === "complete") {
    addGrsfScript();
  } else {
    window.addEventListener("load", addGrsfScript);
    return () => window.removeEventListener("load", addGrsfScript);
  }
}, []);

Important: Make sure to replace x8yi1l at line 1 with your own campaign ID.

This ensures GrowSurf loads once when the app starts.

Step 2: Get the referralId and show the referral message on the registration page

useEffect(() => {
  if (window.growsurf?.getReferrerId) {
    const referrerId = window.growsurf.getReferrerId();
  
    if (referrerId) {
      setShowReferralBanner(true);
  
      if (window.growsurf?.getCampaign) {
        window.growsurf.getCampaign((campaign) => {
          const reward = campaign?.rewards?.[0];
          const rewardValue = reward?.metadata?.rewardForReferred;
  
          if (rewardValue !== undefined) {
            setRewardAmount(rewardValue);
          }
        });
      }
    }
  }
}, []);

This code does two things:

  1. Shows a referral banner only if a referrer ID is stored. The growsurf.getReferrerId() method checks if there is a referral cookie stored (which would be present if the visitor initially came from a referral link).

Then render the message inside your JSX:

{showReferralBanner && rewardAmount !== null && rewardAmount !== undefined && (
  <div style={{
    backgroundColor: "#fff3cd",
    padding: "12px",
    borderRadius: "6px",
    marginBottom: "15px",
    border: "1px solid #ffeeba",
    color: "#856404",
    fontWeight: "bold",
  }}>
    You came through a referral link! <strong>${rewardAmount} discount</strong> will automatically be applied to your account.
  </div>
)}

Step 4: Register Users and Add Them to GrowSurf

if (response?.user?.email) {
  window.growsurf.addParticipant(response.user.email, () => {
    // Mark that this user is part of GrowSurf
    localStorage.setItem("isGrowSurfParticipant", "true");
  });
}

Important note on applying the $50 discount upfront:

Important Note: If your campaign is configured to add participants automatically through a form on your website (), skip this step.

First, in the code where you capture the referred friend's email address, add them to your GrowSurf campaign as a participant with . Let's say you have a signup function called signUpFree(), here's what that looks like:

Behind the scenes, the GrowSurf Universal Code will associate the referrer (if they exist) with the new participant. At any future date , if this new participant triggers a referral, GrowSurf will provide credit to the referrer.

Then, in the code where the action takes place, trigger the referral with . Let's say you have a function called upgradeToPaidPlan(), here's what that looks like:

Important Note: Make sure your campaign's referral trigger is set to Sign Up + Qualifying Action (). If the referral trigger is set to Sign Up, triggering referrals will not work since referral credit has already been provided.

Make sure you have or set up so that rewards automatically get fulfilled to the participant once they reach a reward goal.

Add onclick="" to your button, and clicking it will open the GrowSurf window.

However, when your user opens the GrowSurf window, they'll see a signup form instead of their unique referral link. To ensure they always see their referral link, add them or log them in as a participant first. You can do this by first calling . Here's a code example (remember to replace the values with your logged-in user's details):

Add the anywhere in your HTML

Fetch a participant's information using .

If you are using the , you can add the following HTML attribute: data-grsf-redirect-url.

If you are using your own form via automatic form detection or JavaScript Web API, then include the following snippet of code within the <HEAD> of the HTML source code. This should be the same page(s) where you have included the . Remember to replace https://replaceme.com at line 7 with your redirect URL.

When a new visitor lands on your site using their friend's unique link, you can personalize a message for them with and . In this example, we have a simple page with a h1#header that will display as "Emily S. invited you to pet puppies on-demand" if a referrer exists, otherwise it will display as "Pet puppies on-demand".

In this example, we will only add a participant if they were referred by another participant within your campaign. We will utilize the GrowSurf functions and to do this.

Here we are only adding the participant but if you wish to trigger a referral replace the method with in the example below. The example code also assumes that you have set up a submit listener on your form which will listen for submission events and invoke the callback function described below. If you are not sure how to add a form submission listener .

A few things to notice here are the window.addEventListener and the form.addEventListener snippets of code. The window.addEventListener listens for the GrowSurf script grsfReady event which is emitted when the . Once the GrowSurf script is ready we are adding a submit event listener to our form form.addEventListener to listen for submission events. You will need to get the form element using document.getElementById using the id of your form for this to work - this is just an example. The next piece of code we will look at is the onFormSubmit function that is called when our form is submitted. The function provided by the GrowSurf JavaScript API is used to determine if the submitter of the form was referred. If this function returns a value we then continue to add the participant using the function. You will need to get the value of theuserEmail input using the id or name of the input element of your form - this is just an example. Please note that this example will attempt to add a participant on all form submissions regardless if the form is valid or not. If you wish to perform some validation before adding the participant that will require some extra coding to do so but is out of scope for this example.

Let's say you are using the and passing an email address as a data attribute so that a participant gets created. Because GrowSurf needs to wait for a network request to finish, the signup form may be shown for a few seconds or less. To change this behavior to hide the signup form, you can use the following HTML, CSS, and JS (jQuery) code as an example below.

In this example, we'll walk through how to use GrowSurf embeddable elements to support multiple languages on your website. We will use the and elements, customizing data attributes to display text in both English and Spanish.

These examples only use facebook and twitter as the enabled social share buttons. If you have other social share options enabled, make sure to account for them. These examples also assume that you have a custom signup field called "Phone Number" (). Custom fields are supported via (see example usage of phone-number at lines 6 and 7 in the code snippets below).

If your product has an "", this is a great time to ask for referrals. On your webpage or web app, display the and elements to provoke the participant to share.

In this example, we will use two methods and to update pre-populated social share messages so that the default text is more relevant to your user.

If you need to call this on immediate page load, wrap the JavaScript code in a .

If you need to call this on immediate page load, wrap the JavaScript code in a .

If you need to call this on immediate page load, wrap the JavaScript code in a .

Demo: To view a working demo and to access the full code, .

The first step is to install the by dynamically injecting it into your React app.

Add the user to GrowSurf using

After a successful Firebase login, check if the user exists in your GrowSurf campaign using .

If the user exists in the campaign, call to log them in as a GrowSurf participant.

After tracking the user login state, we can now conditionally display the (aka the referral link) on the Login page — but only after logout.

to fetch the referrer ID (aka the referral code)

to fetch custom reward metadata (for displaying the 50 in "$50 discount will automatically be applied to your account.")

to add new user signups to your GrowSurf campaign

To view a working demo, and navigate to the signup page.

To access the full code, .

The first step is to install the by dynamically injecting it into your React app.

Now switch to Register.js. Inside a useEffect, check if a referral ID is stored by calling .

If there is a referrer ID, then show a banner that says "You came through a referral link! $50 discount will automatically be applied to your account." Get the 50 by fetching the reward amount from your GrowSurf campaign's reward metadata by calling :

Uses growsurf.getCampaign() to fetch the metadata of your campaign's first reward. Note, you'll need to have .

When a new user signs up, you’re already registering them with Firebase Auth. After that, use to add them to your GrowSurf campaign:

This tutorial does not cover how to apply the $50 discount the new user who just signed up. To view how to apply the actual discount, .

see image
within the referral credit window
growsurf.triggerReferral()
see image
Webhooks
Zapier
growsurf.addParticipant()
Embedded Form
Embedded Form
GrowSurf Universal Code
growsurf.getReferrerId()
growsurf.getParticipantById()
growsurf.getReferrerId()
growsurf.addParticipant()
growsurf.addParticipant()
growsurf.triggerReferral()
here is an example
GrowSurf script is ready
getReferrerId()
addParticipant()
Embedded Form
Embedded Form
Embedded Invite
see image
kebab-case
aha moment
Embedded Form
Embedded Invite
growsurf.updateSocialShareMessage()
growsurf.updateEmailInviteMessage()
grsfReady Event Listener
grsfReady Event Listener
grsfReady Event Listener
click here
GrowSurf Universal Code
growsurf.getParticipantByEmail(email)
GrowSurf Embedded Form
growsurf.getReferrerId()
growsurf.addParticipant()
click here
click here
GrowSurf Universal Code
growsurf.getReferrerId()
growsurf.getCampaign()
set the reward metadata
growsurf.addParticipant()
view this article
Example 1: Trigger a referral on qualifying action (e.g, on conversion, purchase or upgrade)
Example 2: Open the GrowSurf window on button click
Example 3: Display a participant's unique share link and referral count inline on a webpage
Example 4: Redirect to another URL after a successful participant signup
Example 5: Add a personalized message to your Share URL for a warm welcome
Example 6: Only add a participant if they were referred
Example 7: Hide the GrowSurf Embedded Form until a GrowSurf participant is detected
Example 8: Add internationalization support for the GrowSurf Embedded Form and Embedded Invite
Example 9: Update pre-populated share and email invite messages to capitalize on a customer "aha moment"
Example 10: Load multiple GrowSurf campaigns on a single webpage
Example 11: Display a referral link on your login page
Example 12: Display "You came through a referral link!" on your signup page
growsurf.addParticipant()
growsurf.open()
growsurf.getParticipantByEmail()
growsurf.addParticipant()
growsurf.addParticipant(email)
growsurf.getCampaign()
Step 1: Make sure the GrowSurf Universal Code is installed
Step 1: Make sure the GrowSurf Universal Code is installed
Step 1: Make sure the GrowSurf Universal Code is installed
Step 1: Make sure the GrowSurf Universal Code is installed
Step 1: Make sure the GrowSurf Universal Code is installed
Step 1: Make sure the GrowSurf Universal Code is installed
Step 1: Make sure the GrowSurf Universal Code is installed
Step 1: Make sure the GrowSurf Universal Code is installed
Step 1: Make sure the GrowSurf Universal Code is installed
Update your Share URL with a ?growsurf_campaign parameter
Display a referral link to returning users on your login page
Display "You came through a referral link!" on your signup page