Load Google Analytics script based on user location in Next.js

When you build a site, you might want to load a script based on your users' location.

For example, you may want to only load Google Analytics in certain countries. This could be due to privacy laws amongst other reasons. Being able to load scripts based on conditions can make compliance easier.

On Vercel, you can use the x-vercel-ip-country header with a lazy loaded server component to conditionally load a script.

Example

In this example you will see how to only load a Google Analytics script for countries outside of the European Union.

app/analytics.tsx
import { headers } from 'next/headers'
import Script from 'next/script'
import { EU_COUNTRY_CODES } from '@/lib/constants' // list of EU country codes in ISO 3166-1 format
export default function Analytics() {
const countryCode = headers().get('x-vercel-ip-country') || 'US'
if (EU_COUNTRY_CODES.includes(countryCode)) {
return null
}
return (
<Script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID" />
)
}

In the code above, we use the headers() function from Next.js to read the x-vercel-ip-country header of the incoming request, determine the user's location, and render the GA script only if the user is not located in an EU country using Next.js' Script component.

You can then import this component using Suspense in your root layout:

app/layout.tsx
import { Suspense } from 'react'
import Analytics from './analytics'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<Suspense>
<Analytics />
</Suspense>
{children}
</body>
</html>
)
}

This will ensure the <Analytics/> component is imported dynamically without blocking the render of the main layout.

Check out the demo here: https://geolocation-script.vercel.app/

CleanShot 2023-10-24 at 13.16.26@2x.png

If you are located in an EU country, the script will not be loaded. This is communicated via a banner in the UI.

Couldn't find the guide you need?