Adding analytics to Next.js web apps

We've also written a dedicated guide to analytics and monitoring for Next.js apps - feel free to check it out!

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.

Install the analytics script

Installing the analytics script on your Next.js based website is super simple.

We're going to be using the official Panelbear Next.js integration. It includes a React hook that will automatically track navigation changes for Next.js apps.

First, install the library in your project:

npm install @panelbear/panelbear-nextjs

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

Basic usage

You can now import, and use the Panelbear hook on your project. Don't forget to replace YOUR_SITE_ID with the Site ID you got from Panelbear.

// ./pages/_app.js

import { usePanelbear } from '@panelbear/panelbear-nextjs';

function CustomApp({ Component, pageProps }) {

  // Load Panelbear only once during the app lifecycle
  usePanelbear('YOUR_SITE_ID');

  return <Component {...pageProps} />;
}

export default CustomApp;

Debug-mode

When developing in localhost, Panelbear does not send events to avoid using your quota.

You can enable debug mode to send events when testing things locally. It will also log messages to console.

// ./pages/_app.js

import { usePanelbear } from '@panelbear/panelbear-nextjs';

function CustomApp({ Component, pageProps }) {
  
  usePanelbear('YOUR_SITE_ID', {
    debug: true
  });

  return <Component {...pageProps} />;
}

export default CustomApp;

That's all you need to add analytics to your NextJS project.

Recording custom events

By default, Panelbear automatically tracks pageviews when your Next.js router comples a navigation change. But you can also record custom events for pretty much anything.

For example, here's how you can record a SignupNewsletter event:

import * as Panelbear from "@panelbear/panelbear-js";
import { useState } from "react";

export function SignupForm(props) {
  const [email, setEmail] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();

    // Handle form submit
    alert(`Handling newsletter signup: ${email}`);

    // Record custom event on submit
    Panelbear.track("SignupNewsletter");
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email:
        <input
          type="text"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

As these events get triggered, they should show up on your analytics dashboard under the "Custom events" section.

Custom events example dashboard

Serving the analytics script from your own domain

While the analytics script and API calls are handled by Panelbear's servers, you can point all requests to first pass through your own server.

Using Next.js it's super simple. You just need to configure rewrites in your next.config.js (this only works in Node mode, if you export your site as static-only, there's no server to perform the rewrites):

module.exports = {
  async rewrites() {
    return [
      {
        source: "/bear.js",
        destination: "https://cdn.panelbear.com/analytics.js",
      },
    ];
  },
};

Then when loading the Panelbear script, simply override the scriptSrc URL:

Panelbear.load("YOUR_SITE_ID", { scriptSrc: "/bear.js" });

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.