Microsoft clarity not working with Next js/React Js project

12.8k views Asked by At

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.

6

There are 6 answers

3
Vaulstein On BEST ANSWER

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.

2
Muhammad Usama Ehsan On

I am using native script tag

<script type="text/javascript" >
      {`(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");`}
    </script>
0
fatemeh kazemi On

you should to set this code like this syntax in nextJs For Nextjs version 10 and below:

<script
   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", "XXXXXXXXX");`,
   }}
 />;
0
Diego González Cruz On

For all of you using nextjs with app router, you should put the Clarity Script inside a 'use client' component. If you check the code, you will notice working with the window object.

'use client'

<Script
        id="ms-clarity"
        strategy="afterInteractive"
        onLoad={() => console.log('clarity onload')}
        onReady={() => console.log('clarity onready')}
        onError={() => console.log('clarity onerror')}
      >
        {typeof window !== 'undefined' &&
          (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', 'XXXXXXXXXX')}
</Script>

1
Piotr Szcześniak On

Here are the resources I found helpful - useful for Next.js ver. 13.4.9:

  • Clarity GitHub issue here
  • Next.js docs about Script component here
*_app.tsx*

import Script from 'next/script';

const clairtyCode = `
(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", "xxxxxxxxxxx");

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <Script id="ms-clarity" strategy="afterInteractive">
        {clairtyCode}
      </Script>
    </>
  );
}

2
BackCoder On

You can use react-microsoft-clarity package

npm install react-microsoft-clarity --save

and then for example import it in _app.js

import { clarity } from 'react-microsoft-clarity';

and use it in a useEffet hook in the _app.js component with your id

clarity.init(id);