Looking for a solution to load my Cookies consent script as the first script in our NextJS application. The problem arises because we have Facebook pixel tracking implemented and they use parentNode.insertBefore
which places their script on top.
This is how we are using Facebook pixel, following their documentation:
const html = [
"!function(f,b,e,v,n,t,s)",
"{if(f.fbq)return;n=f.fbq=function(){n.callMethod?",
"n.callMethod.apply(n,arguments):n.queue.push(arguments)};",
"if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';",
"n.queue=[];t=b.createElement(e);t.async=!0;",
"t.src=v;s=b.getElementsByTagName(e)[0];",
"s.parentNode.insertBefore(t,s)}(window,document,'script',",
"'https://connect.facebook.net/en_US/fbevents.js');",
`fbq('init', '111222333');`,
"fbq('track', 'PageView');",
`fbq('init', '1234');`,
"fbq('track', 'PageView');",
].join("");
const DocumentFacebookPixel = () => (
<>
<script key="track-fb-pixel" dangerouslySetInnerHTML={{ __html: html }} />
</>
);
export default DocumentFacebookPixel;
Here is the OneTrust code implementation:
const DocumentOneTrust = () => {
return (
<>
<script
src="https://url.com"
type="text/javascript"
charSet="UTF-8"
data-domain-script="id-123-4"
></script>
<script type="text/javascript">{function OptanonWrapper() {}}</script>
</>
);
};
export default DocumentOneTrust;
I have loaded the OneTrust script component before the Facebook pixel like this:
class Document extends NextDocument {
render() {
return (
<Html>
<NextHead>
<DocumentOneTrust />
</NextHead>
<body>
<Main />
<NextScript />
<DocumentFacebookPixel />
</body>
</Html>
);
}
}