Adding analytics to Javascript SPAs

Panelbear is often used with Single-page applications (SPA). Once you have added your website to Panelbear, all that is left to do is integrate our analytics snippet.

It's a small piece of code that runs on your website, and it collects the metrics necessary to show you the insights in the dashboard.

Method 1: Add the script to your HTML document header

Just add the script shown in your Site Settings to your website's HTML <head> section.

You can enable the option spaMode: 'history' to automatically track navigation changes on the client.

For example (don't forget to set your Site ID in both locations):

<!-- Panelbear Analytics - We respect your privacy -->
<script async src="https://cdn.panelbear.com/analytics.js?site=YOUR_SITE_ID"></script>
<script>
    window.panelbear = window.panelbear || function() { (window.panelbear.q = window.panelbear.q || []).push(arguments); };
    panelbear('config', {
        site: 'YOUR_SITE_ID',
        spaMode: 'history',
        debug: false,
    });
</script>

Method 2: Add the script via npm or yarn

Simply install the library in your project:

npm install @panelbear/panelbear-js

# Or with yarn:
yarn add @panelbear/panelbear-js

You can now import, and use the Panelbear client on your project.

import * as Panelbear from "@panelbear/panelbear-js";

// Load the Panelbear tracker once in your app
Panelbear.load("YOUR_SITE_ID");

// This is how you record page views
Panelbear.trackPageview();

// You can also trigger custom events
Panelbear.track("NewsletterSignup");

Check your installation

After you have added our analytics script to the HTML of your website, you should be able to see pageviews show up in the dashboard within a minute of the visitors coming into your website.

If you need help, you can reach out to us at [email protected].

Tip: Check out our local development guide for some tips and tricks when testing Panelbear on your machine.