I am trying to add clarity to a Next JS project. I have followed some online resources which have shown that scripts for Google tag manager/Clarity can be added in the below way.
File: app.tsx
<Script
id="clarity"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", '${CLARITY_KEY}');`,
}}
/>
This code triggers successfully and is fetching another script file which throws error while execution. Below is the script which is called by Clarity and throws an error:
!function(c, l, a, r, i, t, y) {
if (a[c].v || a[c].t)
return a[c]("event", c, "dup." + i.projectId);
a[c].t = !0,
(t = l.createElement(r)).async = !0,
t.src = "https://www.clarity.ms/eus2-f/s/0.6.34/clarity.js",
(y = l.getElementsByTagName(r)[0]).parentNode.insertBefore(t, y),
a[c]("start", i),
a[c].q.unshift(a[c].q.pop())
}("clarity", document, window, "script", {
"projectId": "XmaskedX",
"upload": "https://www.clarity.ms/eus2-f/collect",
"expire": 365,
"cookies": ["_uetmsclkid", "_uetvid"],
"track": true,
"lean": false,
"content": true,
"extract": [0, 501, "window.navigator.hardwareConcurrency", 0, 502, "window.navigator.deviceMemory", 0, 503, "window.navigator.platform", 0, 504, "window.navigator.maxTouchPoints", 0, 505, "window.devicePixelRatio", 0, 510, "screen.isExtended", 0, 511, "navigator.cookieEnabled", 0, 512, "navigator.onLine", 0, 513, "navigator.doNotTrack", 0, 514, "navigator.connection", 0, 515, "navigator.vendor", 0, 516, "navigator.product", 0, 517, "navigator.productSub", 0, 518, "navigator.pdfViewerEnabled"],
"fraud": [[1, "input[type=\u0027email\u0027]"]],
"report": "https://www.clarity.ms/report/eus2f"
});
Error thrown is as below:
line 8 Uncaught TypeError: a[c] is not a function a[c]("start", i) // throws error on this line
Have debugged a is window and c is a string "clarity".
The code works fine in a React project but is not working in Next JS.
Problem was assigning id="clarity" to the script tag.
It seems clarity tries to insert an element with id="clarity" which might be the problem. Changing id to something else works.