Published on

Add Google Analytics to your Next.js app


I recently added Google Analytics to one of my personal projects that I made using Next.js app. While Next.js documentation was really helpful, I kind of got stuck with a Content-Security-Policy error that would reject loading any third-party script. I also failed to find any relevant documentation.

Considering you already have created a property on your Google Analytics account and have the script ready, we will take the following steps:

  1. Find _app.js under pages, that's where we are going to add the script.
  2. While there are many examples on the internet that suggest using <script> tag and dangerouslySetInnerHTML, for example here, I personally don't like using dangerouslySetInnerHTML. As the name suggests, using dangerouslySetInnerHTML is risky. If you are curious about why, you can read more about it here.

So we will take the better way and add Google Analytics by using the <Script> tag imported from next/script.

import Script from 'next/script'

export default function App({ Component, props }) {
  return (
      <Script src="" />
      <Script id="google-analytics">
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', 'G-YOUR_ID');
        <meta content="width=device-width, initial-scale=1" name="viewport" />
      {isDevelopment && isSocket && <ClientReload />}
        <Component {...props} />

This is all we need to do in order to add Google Analytics. There are other ways as well. Check out the docs.

After adding all of this, I ran into Content-Security-Policy error. I started to get the below error:

Content-Security-Policy: The page’s settings blocked the loading of a resource at (“script-src”).

This error meant that the script at this address is violating my CSP directive. So the first question was, where is my CSP policy in my app? After some searching, I ended up in next.config.js.

Notice the ContentSecurityPolicy, there is a comment that says, You might need to insert additional domains in script-src if you are using external services.

  1. So we do the same and add to script-src of ContentSecurityPolicy.

And yup, that's all to solve CSP error 😊