DEV Community

Chun
Chun

Posted on

Conditionally load scripts in NextJS using environment variables

Introduction

Recently I added Google Analytics to my NextJS project, but it caused some errors when running the Cypress tests during the CI/CD workflow.

Therefore, I wanted to only include the scripts during the production build, but not include them during the Cypress tests.

Here is my _app.tsx:

/** _app.tsx **/

import Head from 'next/head';
import Script from 'next/script';

function MyApp() {
  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </Head>
      <header>
        {process.env.NEXT_PUBLIC_LOAD_SCRIPTS &&
          process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID && (
            <Script id="google-analytics" strategy="afterInteractive">
              {`
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID}');
              `}
            </Script>
          )}
        {process.env.NEXT_PUBLIC_LOAD_SCRIPTS &&
          process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID && (
            <Script
              src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID}`}
              strategy="afterInteractive"
            />
          )}
      </header>
      <main>{/* content */}</main>
    </>
  );
}

export default MyApp;

Enter fullscreen mode Exit fullscreen mode

Explained

process.env.NEXT_PUBLIC_LOAD_SCRIPTS refers to the environment variable NEXT_PUBLIC_LOAD_SCRIPTS.

Notice the prefix "NEXT_PUBLIC_", this is the NextJS convention to expose the environment variable to the browser.

Without "NEXT_PUBLIC_", the environment variable will be undefined in the browser and not load the script.

process.env.NEXT_PUBLIC_LOAD_SCRIPTS will be controlled during the CI/CD workflow.

{process.env.NEXT_PUBLIC_LOAD_SCRIPTS &&
  process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID && (
    <Script id="google-analytics" strategy="afterInteractive">
      {`
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID}');
      `}
    </Script>
)}
Enter fullscreen mode Exit fullscreen mode

Conclusion

As you can see, it is quite simple to conditionally load scripts in NextJS using environment variables.

Feel free to comment if you have any questions or suggestions.

Top comments (0)