BrandChamp Referral Code Capture Scripts
Overview
BrandChamp provides two lightweight JavaScript utilities for capturing referral codes from URL parameters: a Cookie version and a localStorage version. Both scripts automatically detect referral codes and store them for later use during checkout, form submission, or any conversion event.
Both scripts expose the same API: BrandChamp.referrals.captureReferralCode() - you simply choose which script to include based on your needs.
Which Version Should I Use?
| Feature | Cookie Version | localStorage Version |
|---|---|---|
| Storage Method | Browser cookies | Browser localStorage |
| Cookie Consent Required | Yes (in most jurisdictions) | Usually not required* |
| Auto-sent to Server | ✅ Yes, with every request | ❌ No, manual retrieval needed |
| Cross-subdomain Support | ✅ Yes (with domain config) | ❌ No (same-origin only) |
| Server-side Access | ✅ Direct cookie access | ❌ Must pass via request body |
*Consult with your legal/compliance team regarding your specific privacy requirements.
Choose Cookie Version if:
- You need automatic server-side access to the referral code
- You need cross-subdomain tracking
- You already manage cookie consent or are not legally required to do so
- You acknowledge that tracking depends on the user’s consent settings and local regulations
Choose localStorage Version if:
- You want to avoid cookie consent requirements
- You're comfortable manually retrieving and sending the referral code
- Your site operates on a single domain
How It Works
- User clicks a referral link → Navigates to your store with a referral code in the URL (e.g.,
https://yourstore.com/?r=AMBASSADOR123) - Script detects the code → Automatically extracts the referral code from the URL parameter
- Data is stored → Stores the code in a cookie or localStorage (depending on which script you use)
- Conversion tracking → During checkout or form submission, read the stored code and send it to the BrandChamp API to track the referral
Installation
Cookie Version
<script src="https://assets.brandchamp.io/scripts/capture_referral_code.cookie.min.js"></script> <script> BrandChamp.referrals.captureReferralCode(); </script>
localStorage Version
<script src="https://assets.brandchamp.io/scripts/capture_referral_code.localstorage.min.js"></script> <script> BrandChamp.referrals.captureReferralCode(); </script>
Self-Hosted Option (Recommended)
- Download the appropriate minified script from the links above
- Host it on your server or CDN
- Include it on every page of your store
Important: The script must be loaded on every page of your store to ensure referral codes are captured regardless of which page the visitor lands on.
Configuration Options
Both scripts accept the same configuration object:
BrandChamp.referrals.captureReferralCode({
queryParam: 'r', // URL parameter to look for
attribution: 'last-touch', // Attribution model
expiryDays: 30, // Days until expiration
name: 'bc_referral_code', // Cookie/localStorage key name
domain: null, // Cookie domain scope (cookie version only)
onCapture: null, // Callback function
logger: null // Debug logger function
});
| Option | Type | Default | Description |
|---|---|---|---|
queryParam |
string |
'r' |
The URL query parameter key that contains the referral code. |
attribution |
string |
'last-touch' |
Attribution model: 'first-touch' or 'last-touch' |
expiryDays |
number |
30 |
Number of days until the stored value expires. |
name |
string |
'bc_referral_code' |
The name/key used to store the referral code (cookie name or localStorage key). |
domain |
string |
null |
Cookie domain scope for cross-subdomain access (e.g., .yourstore.com ). Cookie version only. |
onCapture |
function |
null |
Callback function invoked when a referral code is successfully captured. |
logger |
function |
null |
Debug logger function for troubleshooting. |
Note: The domain option is only available in the cookie version. It is ignored by the localStorage version.
Attribution Models
The attribution option determines how the script handles scenarios where a visitor arrives via multiple referral links.
Last-Touch Attribution (Default)
BrandChamp.referrals.captureReferralCode({
attribution: 'last-touch'
});
- Behavior: Always overwrites the existing referral code with the new one
- Use case: Credit the most recent ambassador who drove the conversion
- Example: Visitor clicks Ambassador A's link, then later clicks Ambassador B's link → Ambassador B gets credit
First-Touch Attribution
BrandChamp.referrals.captureReferralCode({
attribution: 'first-touch'
});
- Behavior: Preserves the original referral code, ignores subsequent referral visits
- Use case: Credit the first ambassador who introduced the customer
- Example: Visitor clicks Ambassador A's link, then later clicks Ambassador B's link → Ambassador A keeps credit
Cookie Consent Considerations
Cookie Version
The cookie version creates a browser cookie (bc_referral_code ) to store the referral code. Depending on your jurisdiction and privacy requirements (GDPR, CCPA, etc.), you may need to obtain cookie consent before calling the capture function.
// Example: Only capture after consent is granted
if (cookieConsentGranted) {
BrandChamp.referrals.captureReferralCode();
}
⚠️ Warning: If cookie consent is required but not granted, referral codes will not be captured and referrals will not be tracked. This can lead to missed referral attributions.
localStorage Version
The localStorage version stores data locally in the browser and does not send it with HTTP requests. In many jurisdictions, localStorage is treated differently under privacy regulations since the data stays local. However, you should consult with your legal/compliance team to determine the requirements for your specific situation.
Reading the Referral Code
Cookie Version - Server-Side Access
The bc_referral_code cookie is automatically sent with requests to your server. For traditional form submissions and page navigations, the browser includes cookies automatically. However, for AJAX requests, you need to explicitly enable credentials:
Fetch API:
fetch('/api/checkout', {
method: 'POST',
credentials: 'same-origin', // or 'include' for cross-origin
// ...
});
Axios:
axios.post('/api/checkout', data, {
withCredentials: true
});
Node.js / Express Example:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.post('/api/checkout', (req, res) => {
// Read the referral code from the cookie
const referralCode = req.cookies.bc_referral_code || null;
if (referralCode) {
console.log('Referral code:', referralCode);
// Include referralCode when sending order data to BrandChamp API
}
// Process checkout...
});
localStorage Version - Client-Side Retrieval
Since localStorage data is not automatically sent to the server, you need to manually retrieve the referral code and include it in your API requests.
Using the built-in helper function:
Both versions provide a utility function to retrieve the stored referral code:
// Get the referral code
const referralCode = BrandChamp.referrals.getReferralCode();
// Or with a custom name
const referralCode = BrandChamp.referrals.getReferralCode('my_custom_name');
Including in checkout/form submission:
const referralCode = BrandChamp.referrals.getReferralCode();
fetch('/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// ... your checkout data
referralCode: referralCode
})
});
Server-side handling (Node.js / Express):
app.post('/api/checkout', (req, res) => {
// Read the referral code from the request body
const referralCode = req.body.referralCode || null;
if (referralCode) {
console.log('Referral code:', referralCode);
// Include referralCode when sending order data to BrandChamp API
}
// Process checkout...
});
Usage Examples
Basic Usage
// Use all defaults BrandChamp.referrals.captureReferralCode();
Custom Expiration
// Extend expiration to 60 days
BrandChamp.referrals.captureReferralCode({
expiryDays: 60
});
Cross-Subdomain Tracking (Cookie Version Only)
// Share cookie across all subdomains
BrandChamp.referrals.captureReferralCode({
domain: '.yourstore.com'
});
With Capture Callback
BrandChamp.referrals.captureReferralCode({
onCapture: function(data) {
console.log('Referral captured:', data.referralCode);
// Optional: Track in analytics
if (window.gtag) {
gtag('event', 'referral_captured', {
referral_code: data.referralCode
});
}
// For last-touch attribution, check if a code was overwritten
if (data.previousReferralCode) {
console.log('Previous code replaced:', data.previousReferralCode);
}
}
});
Debug Mode with Logger
BrandChamp.referrals.captureReferralCode({
logger: function(event, data) {
console.log('[BrandChamp]', event, data);
}
});
Logger Events:
| Event | Description |
|---|---|
INITIALIZED |
Script initialized with configuration |
NO_CODE_DETECTED |
No referral code found in URL |
CODE_DETECTED |
Referral code found in URL |
CODE_INVALID |
Referral code failed validation (must be 1-25 characters) |
FIRST_TOUCH_SKIP |
Code not saved due to first-touch attribution |
COOKIE_SET |
Cookie successfully set (cookie version only) |
STORAGE_SET |
localStorage value successfully set (localStorage version only) |
Full Configuration Example
BrandChamp.referrals.captureReferralCode({
queryParam: 'r',
attribution: 'last-touch',
expiryDays: 45,
name: 'bc_referral_code',
domain: '.yourstore.com', // Cookie version only
onCapture: function(data) {
console.log('Captured referral:', data.referralCode);
},
logger: function(event, data) {
console.log('[BrandChamp Debug]', event, data);
}
});
Security Features
Both scripts implement security best practices:
- URL encoding - Properly encodes/decodes values
- Input validation - Referral codes must be 1-25 characters
Cookie version additional security:
- SameSite=Lax - Prevents CSRF attacks while allowing top-level navigation
- Secure flag - Automatically added when served over HTTPS
Browser Support
Both scripts use modern JavaScript features with broad browser support:
- Chrome 49+
- Firefox 52+
- Safari 10+
- Edge 17+
- Opera 36+
Troubleshooting
Referral code not being captured
- Check the URL parameter - Ensure the referral link uses the correct parameter (default:
r) - Enable debug logging - Add a logger function to see what's happening
- Check for existing stored value - If using first-touch attribution, an existing code won't be overwritten
- Validate code length - Codes must be between 1 and 25 characters
Cookie not accessible (Cookie Version)
- Cross-subdomain issues - Set the
domainoption to.yoursite.com - Secure context - On HTTPS sites, cookies with the Secure flag won't be accessible over HTTP
- Browser privacy settings - Some browsers block third-party cookies
- Cookie consent - Ensure consent was granted before capturing
localStorage not working (localStorage Version)
- Private/Incognito mode - Some browsers restrict localStorage in private browsing
- Storage quota - Browser may have reached storage limit
- Browser settings - User may have disabled localStorage
Debug Example
BrandChamp.referrals.captureReferralCode({
logger: function(event, data) {
console.log('[BrandChamp Debug]', event, JSON.stringify(data, null, 2));
}
});
FAQ
Q: Does the script need to be on every page?
A: Yes. Since you don't know which page a visitor will land on from a referral link, the script should be present on all pages.
Q: What happens if the visitor clears their cookies/localStorage?
A: The referral code will be lost. If they click another referral link, a new code will be captured.
Q: Can I use a different URL parameter than r ?
A: The default ?r= parameter works with referral links generated in the BrandChamp portal. If you need a different parameter for custom integrations, set the queryParam option to your preferred parameter name.
Q: How do I test if the script is working?
A: Add ?r=TEST123 to any page URL, then check your browser's cookies (for cookie version) or localStorage (for localStorage version) for bc_referral_code .
Q: Why would I choose localStorage over cookies?
A: The main reasons are: (1) avoiding cookie consent requirements in some jurisdictions, and (2) if you don't need automatic server-side access. The trade-off is that you must manually retrieve and send the referral code with your API requests.
Q: Can I switch from cookies to localStorage (or vice versa)?
A: Yes, but existing stored codes won't transfer automatically. You may want to implement migration logic during the transition period.
Support
For additional help or questions about integrating with the BrandChamp API, contact BrandChamp support or refer to the BrandChamp API Documentation.