Install Userpilot on Single Page Application Frameworks

If your web app is running on a Single Page Application framework, such as Angular or React, and is characterized by very few page refreshes, then installing Userpilot will be slightly different.

Normally, Userpilot would depend on page reloads (refresh) to update and trigger new Flows.

Since Single Page Applications do not reload after URL changes, you must call userpilot.reload() after each URL change. This is typically done in your application’s router and is handled after a successful page (URL) change. 

Here is what we recommend you do.

Initialization 

First, include the Userpilot script in your HTML code as the first item inside your  <head> tag as you normally would. This will most probably be inside your index.html  file. Alternatively, you can use our NPM package here to install Userpilot as a node module.

Importing SDK script

<script>
window.userpilotSettings = {token: "appToken"};
</script>
<script src="https://js.userpilot.io/sdk/latest.js"></script>

Using NPM package

npm install userpilot --save

Then place this code in your main entry file: 

import { Userpilot } from 'userpilot';

//Initialize Userpilot
Userpilot.initialize('appToken'); //`appToken` should be replaced with your userpilot appToken.

Identifying and Tracking users

React

Identify users to Userpilot

To send Userpilot information about the current user, you must call Userpilot's identify function and pass the user's attributes inside it. Userpilot will then be able to create a session for that user and track them. You only have to call this function once, upon a successful user authentication.

The following is an example of how Userpilot's  identify function is called only when the user is successfully authenticated. Note that in this example, isAuthenticated is an authentication state that is used as a dependency to call identify

Let's assume that you always check for user authentication inside  App.jsx file, so you should place the following code inside that component

import react from 'react';
import Userpilot from 'userpilot';

const App = (props) => {
    // ...component code
    const location = useLocation();

    React.useEffect(() => {
        if (isAuthenticated) {
            Userpilot.identify(
                user.id,
                {
                    name: user.name,
                    email: user.email,
                    created_at: user.created_at, // ISO8601 Date,
                    company:  // optional 
                    {
                        id: company.id, // Company Unique ID
                        created_at: company.created_at // ISO8601 Date
                    }
                    // Additional user properties
                    // plan: user.plan,
                    // trialEnds: user.trial_ends ISO8601 Date
                }
            )
        }
    }, [isAuthenticated]);
    // ... rest of component code

    return (
        <div>
            // component return JSX syntax
        </div>
    );
};

Note: You must pass a unique user id as the first parameter in the identify method to help Userpilot identify each user (same applies for company).

Note: You can identify anonymous users (users that do not require authentication) through Userpilot.anonymous()

Note: Date attributes must be passed in ISO8601 format (YYYY-MM-DD).

Reload Userpilot on a Page Change

Userpilot must be reloaded on every route change through Userpilot's  reload function. In order to do so, please add this code to your App.jsx file:

import react from 'react';
import { useLocation } from 'react-router';
import Userpilot from 'userpilot';

const App = (props) => {
    // ...component code
    const location = useLocation();

    React.useEffect(() => {
        Userpilot.reload();
    }, [location]);
    // ... rest of component code
    
    return (
        <div>
            // component return JSX syntax
        </div>
    );
};
		

Angular

Identify users to Userpilot
To send Userpilot information about the current user, you must call Userpilot's  identify function and pass the user's attributes inside it. Userpilot will then be able to create a session for that user and track them. You only have to call this function once, upon a successful user authentication.

The following is an example of how Userpilot's  identify function is called in the app's entry point only when the user is successfully authenticated. Note that localStorage.get("token") is an example method of authentication.

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {

    constructor(
        private userService: AuthService
    ) {
        const token = localStorage.getItem('token');
        if (token) {
            this.userService.getUser().subscribe((user) => {
                if (user.id) {
            		Userpilot.identify(
                		user.id,
                		{
                    			name: user.name,
                    			email: user.email,
                    			created_at: user.created_at, // ISO8601 Date,
                    			company:  // optional 
                    			{
                        			id: company.id, // Company Unique ID
                        			created_at: company.created_at // ISO8601 Date
                    			}
                    			// Additional user properties
                    			// plan: user.plan,
                    			// trialEnds: user.trial_ends ISO8601 Date
                		}
            		)
                }

            });
        }

    }
}

Note: You must pass a unique user id as the first parameter in the identify method to help Userpilot identify each user (same applies for company).

Note: You can identify anonymous users (users that do not require authentication) through Userpilot.anonymous()

Note: Date attributes must be passed in ISO8601 format (YYYY-MM-DD).

Reload Userpilot on page change

Userpilot must be reloaded on every route change through Userpilot's  reload function. In the following example, we call the reload function in the route change watcher file (in our case it is auth.guard.ts):

@Injectable()
export class AuthGuard implements CanActivate {
    public routers: typeof routes = routes;

    constructor(private router: Router) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        const token = localStorage.getItem('token');

        if (token) {
            Userpilot.reload();
            return true;
        } else {
            this.router.navigate([this.routers.LOGIN]);
        }
    }
}

Note: If you want to trigger experiences on anonymous users, call  Userpilot.reload() without checking for authentication on every page change.

VueJS

Identify users to Userpilot
To send Userpilot information about the current user, you must call Userpilot's  identify function and pass the user's attributes inside it. Userpilot will then be able to create a session for that user and track them. You only have to call this function once, upon a successful user authentication.

To install the Userpilot identify method, you can either add it as a script in your  head section inside the app template which renders after authentication, which would make sure that the method is called after the user is authenticated. Or, for a cleaner approach in VueJS 3.0 and above, if you have an authentication service that handles authentication routes, it’s easier to call the identify method in the Authentication guard:

export const authenticationGuard = (to, from, next) => {
    const authService = getAuthService();

    const guardAction = () => {
        if (authService.isAuthenticated) {
            const user = authService.getUser();
            const company = getUserCompany(user.id);

            Userpilot.identify(
                user.id,
                {
                    name: user.name,
                    email: user.email,
                    created_at: user.created_at, // ISO8601 Date
                    company:  // optional 
                    {
                        id: company.id, // Company Unique ID
                        created_at: company.created_at // ISO8601 Date
                    }
                    // Additional user properties
                    // plan: user.plan,
                    // trialEnds: user.trial_ends ISO8601 Date
                }
            )

            return next();
        }

        authService.loginWithRedirect({ appState: { targetUrl: to.fullPath } });
    };
}
	

Note: You must pass a unique user id as the first parameter in the identify method to help Userpilot identify each user (same applies for company).

Note: You can identify anonymous users (users that do not require authentication) through Userpilot.anonymous()

Note: Date attributes must be passed in ISO8601 format (YYYY-MM-DD).

Reload Userpilot on page change

Userpilot must be reloaded on every route change through Userpilot's  reload function. In order to do so, please add this code to your route watcher:

router.afterEach((route) => {
 userpilot.reload();
});
	

Or for older versions than Vue 3.0, in your main App component, add a route watch handler that calls the  reload function:

new Vue({
    el: "#app",
    router,
    watch: {
        $route: {
            handler: () => Userpilot.reload(),
            deep: true,
            immediate: true
        }
    },
    template: "<App/>",
    components: { App }
});
			
Note : If you want to trigger experiences on anonymous users, call  Userpilot.reload() without checking for authentication on every page change.
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.