How to enable and disable google analytics in Next.js app?

I’ve enabled google analytics using the following script method in my _app.js.

<Script src={`https://www.googletagmanager.com/gtag/js?id=${myMeasurementId}`} strategy='afterInteractive' />
<Script id="google-analytics" strategy='afterInteractive'>
      {`
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', '${myMeasurementId}');
      `}
</Script>

I also created the following two functions:

export const pageview = (url, origin) => {
  console.log("pageView sent");
  window.gtag('config', myMeasurementId, {
      path_url: url,
  })
}

export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
  })
}

“pageview” notifies google analytics whenever a user views a page and “event” can be called along with any react event such as onClick or onSubmit.

This all works to enable google analytics but I’d like to be able to disable it if a user decides to opt out.

Referencing this https://developers.google.com/analytics/devguides/collection/gtagjs/user-opt-out I’ve tried adding {window[‘ga-disable-GA_MEASUREMENT_ID’] = true;} inside the id=”google-analytics” script tag to no avail. I still see the page_view event in my Google Analytics debugger plugin. I also still see the event registered in https://tagassistant.google.com/ and on google analytics itself. Considering privacy laws in the EU I would imagine there is a relatively simple way to disable and enable google analytics but I’ve you to find a good solution. If anyone knows, please lend a hand!