#NextJS, external Optimizely script, isOptOut

1 messages · Page 1 of 1 (latest)

tidal merlin
#

I'm running a static Next.js v12.3 app which has the OneTrust cookie consent tool running through a Google Tag Manager script and Optimizely set as an external script. How can I configure my app to wait for a OneTrust cookie to be set on the client, get the value of Functionality Cookie acceptance, and use that result to set an Optimizely isOptOut event?

naive tendonBOT
#

Hi @tidal merlin. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To configure your Next.js app to wait for a OneTrust cookie to be set on the client, get the value of Functionality Cookie acceptance, and use that result to set an Optimizely isOptOut event, you can follow these steps:

  1. Ensure OneTrust and Google Tag Manager are properly integrated: Make sure that OneTrust is set up to manage your cookies and that Google Tag Manager is correctly configured to load the necessary scripts.

  2. Check for OneTrust Cookie Consent: You need to check if the OneTrust cookie consent has been given for Functionality Cookies. This can be done by checking the OneTrust cookies.

  3. Set Optimizely isOptOut based on Cookie Consent: Use the value of the OneTrust cookie to determine whether to set the Optimizely isOptOut flag.

Here is an example of how you might implement this in your Next.js app:

import { useEffect } from 'react';
import Script from 'next/script';

export default function MyApp({ Component, pageProps }) {
  useEffect(() => {
    // Function to check OneTrust cookie consent
    const checkOneTrustConsent = () => {
      const functionalityConsent = document.cookie
        .split('; ')
        .find(row => row.startsWith('OptanonConsent'))
        ?.split('=')[1];

      if (functionalityConsent) {
        const consentData = decodeURIComponent(functionalityConsent);
        const hasConsent = consentData.includes('groups.functional:true');
        return hasConsent;
      }
      return false;
    };

    // Set Optimizely isOptOut based on OneTrust consent
    const setOptimizelyOptOut = () => {
      const hasConsent = checkOneTrustConsent();
      window.optimizely = window.optimizely || [];
      window.optimizely.push({
        type: 'setOptOut',
        isOptOut: !hasConsent,
      });
    };
#

// Wait for OneTrust to be ready
const onOneTrustReady = () => {
if (window.OneTrust) {
window.OneTrust.OnConsentChanged(() => {
setOptimizelyOptOut();
});
}
};

// Check if OneTrust is already loaded
if (window.OneTrust) {
  onOneTrustReady();
} else {
  // If not, wait for it to load
  window.addEventListener('OneTrustLoaded', onOneTrustReady);
}

}, []);

return (
<>
<Script
src="https://cdn.cookielaw.org/consent/XXXX/otSDKStub.js"
strategy="beforeInteractive"
/>
<Component {...pageProps} />
</>
);
}


### Explanation:
1. **Check OneTrust Consent**: The `checkOneTrustConsent` function checks the OneTrust cookie to see if the user has given consent for Functionality Cookies.
2. **Set Optimizely `isOptOut`**: The `setOptimizelyOptOut` function sets the Optimizely `isOptOut` flag based on the consent status.
3. **Wait for OneTrust to be Ready**: The `onOneTrustReady` function ensures that the consent check and Optimizely configuration happen after OneTrust has loaded.

### Notes:
- Replace `XXXX` in the script URL with your actual OneTrust domain script ID.
- Ensure that the OneTrust script is loaded before any other scripts that depend on it.

For more information on integrating third-party scripts in Next.js, you can refer to the **Next.js Script Optimization documentation** (<https://nextjs.org/docs/app/building-your-application/optimizing/scripts#api-reference>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@tidal merlin kapa.ai is still learning and improving, please let us know how it did by reacting below

tidal merlin
#

@naive tendon Would this be the _app.js file?

naive tendonBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, the code provided would typically be placed in the _app.js file in a Next.js project. The _app.js file is used to initialize pages and can be used to include global CSS, JavaScript, and other configurations that need to be applied across all pages.

Here is the complete _app.js file with the provided code:

import { useEffect } from 'react';
import Script from 'next/script';

export default function MyApp({ Component, pageProps }) {
  useEffect(() => {
    // Function to check OneTrust cookie consent
    const checkOneTrustConsent = () => {
      const functionalityConsent = document.cookie
        .split('; ')
        .find(row => row.startsWith('OptanonConsent'))
        ?.split('=')[1];

      if (functionalityConsent) {
        const consentData = decodeURIComponent(functionalityConsent);
        const hasConsent = consentData.includes('groups.functional:true');
        return hasConsent;
      }
      return false;
    };

    // Set Optimizely isOptOut based on OneTrust consent
    const setOptimizelyOptOut = () => {
      const hasConsent = checkOneTrustConsent();
      window.optimizely = window.optimizely || [];
      window.optimizely.push({
        type: 'setOptOut',
        isOptOut: !hasConsent,
      });
    };

    // Wait for OneTrust to be ready
    const onOneTrustReady = () => {
      if (window.OneTrust) {
        window.OneTrust.OnConsentChanged(() => {
          setOptimizelyOptOut();
        });
      }
    };

    // Check if OneTrust is already loaded
    if (window.OneTrust) {
      onOneTrustReady();
    } else {
      // If not, wait for it to load
      window.addEventListener('OneTrustLoaded', onOneTrustReady);
    }
  }, []);
#

return (
<>
<Script
src="https://cdn.cookielaw.org/consent/XXXX/otSDKStub.js"
strategy="beforeInteractive"
/>
<Component {...pageProps} />
</>
);
}


### Explanation:
- **Global Initialization**: The `_app.js` file is used to initialize global settings and configurations for your Next.js application.
- **Script Loading**: The `Script` component from Next.js is used to load the OneTrust script before any other scripts (`strategy="beforeInteractive"`).
- **Effect Hook**: The `useEffect` hook is used to run the consent check and Optimizely configuration after the component mounts.

For more information on `_app.js` and its usage, you can refer to the **Next.js Custom App documentation** (<https://nextjs.org/docs/pages/building-your-application/routing/custom-app>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@tidal merlin kapa.ai is still learning and improving, please let us know how it did by reacting below

tidal merlin
#

@naive tendon The OneTrust Cookielaw script is already set by an existing Google Tag Manager script in a LayoutWrapper component. Is this the optimal place to put the Google Tag Manager script? and how would the overall Optimizely configuration change, if not?

naive tendonBOT
#

Let me check the knowledge base for you. One moment! :books:

#

If the OneTrust Cookielaw script is already set by an existing Google Tag Manager script in a LayoutWrapper component, you should ensure that the Google Tag Manager script is placed in an optimal location to load early enough for your consent management to work correctly. Typically, this would be in the <head> of your document or as early as possible in the body.

Given that the OneTrust script is already managed by Google Tag Manager, you don't need to include it again in your _app.js or any other component. Instead, you should focus on checking the consent status and configuring Optimizely based on that.

Here’s how you can adjust your LayoutWrapper component to handle the Optimizely configuration:

  1. Ensure Google Tag Manager is loaded early: Make sure your Google Tag Manager script is placed in the <head> or at the top of the <body> in your LayoutWrapper component.

  2. Check OneTrust Consent and Configure Optimizely: Use the same logic to check for OneTrust consent and configure Optimizely based on that.

Here is an example of how you might implement this in your LayoutWrapper component:

import { useEffect } from 'react';

export default function LayoutWrapper({ children }) {
  useEffect(() => {
    // Function to check OneTrust cookie consent
    const checkOneTrustConsent = () => {
      const functionalityConsent = document.cookie
        .split('; ')
        .find(row => row.startsWith('OptanonConsent'))
        ?.split('=')[1];

      if (functionalityConsent) {
        const consentData = decodeURIComponent(functionalityConsent);
        const hasConsent = consentData.includes('groups.functional:true');
        return hasConsent;
      }
      return false;
    };
#

// Set Optimizely isOptOut based on OneTrust consent
const setOptimizelyOptOut = () => {
const hasConsent = checkOneTrustConsent();
window.optimizely = window.optimizely || [];
window.optimizely.push({
type: 'setOptOut',
isOptOut: !hasConsent,
});
};

// Wait for OneTrust to be ready
const onOneTrustReady = () => {
  if (window.OneTrust) {
    window.OneTrust.OnConsentChanged(() => {
      setOptimizelyOptOut();
    });
  }
};

// Check if OneTrust is already loaded
if (window.OneTrust) {
  onOneTrustReady();
} else {
  // If not, wait for it to load
  window.addEventListener('OneTrustLoaded', onOneTrustReady);
}

}, []);

return (
<>
{/* Ensure Google Tag Manager script is loaded early */}
<script
async
src={<https://www.googletagmanager.com/gtm.js?id=GTM-XXXX}>
></script>
{children}
</>
);
}


### Explanation:
- **Google Tag Manager Script**: Ensure the Google Tag Manager script is loaded early in the `LayoutWrapper` component.
- **Effect Hook**: The `useEffect` hook is used to run the consent check and Optimizely configuration after the component mounts.
- **Check Consent and Configure Optimizely**: The same logic is used to check for OneTrust consent and configure Optimizely based on that.

### Notes:
- Replace `GTM-XXXX` with your actual Google Tag Manager container ID.
- Ensure that the OneTrust script is correctly configured within your Google Tag Manager setup.

For more information on integrating third-party scripts in Next.js, you can refer to the [Next.js Script Optimization documentation](<https://nextjs>
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------