Next.js + Splitbee

How to set up Splitbee Analytics in Next.js 11

2-3 minute read

Guide ->

Splitbee is a free and open-source analytics tool that helps you understand your users and improve your website. It's a great alternative to Google Analytics and other paid analytics tools. I have been using it for a while now and I am really happy with it.

This guide is an extension and update of the Splitbee Next.js Proxy Documentation. I have added the Next.js Script Component to the guide, along with a few more quality-of-life improvements.

First, we need to make use of Next.js Rewrites to point the local payload url to the Splitbee server.

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
        source: '/bee.js',
        destination: '',
        source: '/_hive/:slug',
        destination: '',

module.exports = nextConfig

Next, we add a script tag that imports the Splitbee code. As per the original documentation:

data-api sets the endpoint for all tracking calls. We are using /_hive in this example.

src needs to point to the Splitbee JS file that is proxied through your servers. We are using /bee.js in this example. Feel free to adapt those paths & filenames.

We can abstract the logic into an Analytics component.

// components/Analytics.tsx
import Script from 'next/script'

export const Analytics: React.FC = () =>
  typeof window != 'undefined' &&
  window.location.href.includes('[site_url]') ? (
    <Script src="/bee.js" data-api="/_hive" strategy="afterInteractive" />
  ) : null

Replace [site_url] in window.location.href.includes('[site_url]') with the name of your production deployment domain. This will prevent errors from popping up in the console during development.

You can also adjust the strategy attribute according to your needs (view the documentation for the available options). However, in most cases, you should stick to "afterInteractive".

Now all that remains is to import the Analytics component into the application – ideally in _app.tsx to avoid duplication.

// pages/_app.tsx
import { Analytics } from 'components/Analytics'

import type { AppProps } from 'next/app'

const App: React.FC<AppProps> = ({ Component, pageProps }) => (
    <Analytics />
    <Component {...pageProps} />

export default App

Last Updated:

Edit on GitHub ->