DEV Community

Cover image for Next.js + Splitbee
Nico Bachner
Nico Bachner

Posted on • Originally published at nicobachner.com

Next.js + Splitbee

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.

Table of Contents

  • Next.js Config Setup
  • Creating the Analytics Component
  • Using the Analytics Component

Next.js Config Setup

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: 'https://cdn.splitbee.io/sb.js',
      },
      {
        source: '/_hive/:slug',
        destination: 'https://hive.splitbee.io/:slug',
      },
    ]
  },
}

module.exports = nextConfig
Enter fullscreen mode Exit fullscreen mode

Creating the Analytics Component

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.VFC = () =>
  typeof window != 'undefined' &&
  window.location.href.includes('[site_url]') ? (
    <Script src="/bee.js" data-api="/_hive" strategy="afterInteractive" />
  ) : null
Enter fullscreen mode Exit fullscreen mode

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".

Using the Analytics Component

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.VFC<AppProps> = ({ Component, pageProps }) => (
  <>
    <Analytics />
    <Component {...pageProps} />
  </>
)

export default App
Enter fullscreen mode Exit fullscreen mode

Top comments (0)