How to track analytics events in NextJS without being blocked by Ad blockers

Published on

Sooner or later, most websites run into problems with ad blockers—even those that have nothing to do with ads, like SaaS platforms or utility apps.

Most services use some form of product analytics to improve their apps. Other times, all you want is to run an A/B test on your hero section title. But many ad blockers will block all events to blacklisted services.

This means A/B testing, product analytics, and many other features will stop working. When your customer contacts support, you have no idea how to help them. There is zero visibility into their actions.

Fortunately for us, Next.js has a solution for that. Next.js allows us to proxy events through their server using rewrites and make it look like we are sending them to our own backend—all in a few simple lines of config.

module.exports = {
  async rewrites() {
    return [
      {
        source: '/about',
        destination: '/',
      },
    ]
  },
}

Now let's see how to configure PostHog, Sentry, and Amplitude to circumvent ad blockers.

PostHog

This config for PostHog that will allow you to track events without being blocked:

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
  api_host: '/events',
  ui_host: 'https://eu.posthog.com', // your domain may differ, check in config
})

// next.config.js
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/events/static/:path*',
        destination: 'https://us-assets.i.posthog.com/static/:path*',
      },
      {
        source: '/events/:path*',
        destination: 'https://us.i.posthog.com/:path*',
      },
    ]
  },
  skipTrailingSlashRedirect: true,
}
module.exports = nextConfig

Amplitude

This config for Amplitude that will allow you to track events without being blocked:

amplitude.init(process.env.NEXT_PUBLIC_AMPLITUDE_KEY, {
  serverUrl: '/amplitude/2/httpapi',
})

// next.config.js
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/amplitude/:path*',
        destination: 'https://api2.amplitude.com/:path*',
      },
    ]
  },
}
module.exports = nextConfig