DEV Community

Cover image for Saving a missing referral
Caio Jhonny
Caio Jhonny

Posted on

Saving a missing referral


After the GDPR, we can no longer enable cookies without user consent. This means that we can no longer save the user's session on their first visit, losing your reference.

Alt Text

How can I save the referral?

We can save the referral using the localStorage property at the first access.

Before saving, we need to check if there is a referral to be saved and if the referral is different from our document.location.origin to avoid saving your website as a referral (This also prevents cases where the user goes to another page of your website).

if(document.referrer.length > 0 
&& document.referrer.indexOf(document.location.origin) !== 0){
    localStorage.setItem("referral", document.referrer);
Enter fullscreen mode Exit fullscreen mode

After that, we can retrieve our referral when it's necessary to call our cookie function.

// Get the referral saved on localStorage
var referral = localStorage.getItem("referral");

// Verify if exists
if(referral !== null 
&& typeof referral !== "undefined")
    // Define your saved referral into document.referrer
    Object.defineProperty(document, "referrer", {
        get : function(){ return referral; }

// After that you can call your cookies function, analytics,  facebook pixel, etc...
Enter fullscreen mode Exit fullscreen mode

Hope it's helpful some of you 🙂

Top comments (1)

alessio_marcone profile image
Alessio Marcone

So much helpful sir!