Skip to content
Will Fox
LinkedInGitHubHomepage

Add Microsoft Clarity to your NextJS App

Monitoring2 min read

I recently tried to add Microsoft Clarity to a website and came across an unexpected (and hard-to-diagnose) issue. We will get to that in a minute, but let me start by walking though the process.

Microsoft Clarity is a cool monitoring tool that embeds scripts in your sites to track detailed user behaviors, like how a user moved their mouse across the screen. In order to use it, you first need to sign up for an account and set up a property by following these instructions.

Once you have your account set up, you then need to embed their tracking scripts in your app. To get your tracking script, you need to select your project and then click into Settings -> Setup.

There, you will see two alternatives. Clarity offers simple integrations with popular web hosting platforms, but for NextJS you have to go the manual route.

Adding Clarity

Under the "Install manuall" heading, select the "Get tracking code" button, and on the following screen click "Copy to clipboard." If you drop this script directly into your app, you should see some syntax errors, so we will make a few small changes to the implementation. The first is to use the NextJS "Script" component rather than vanilla HTML script.

Since we want the tag to run on every page, we will work inside the app/layout.tsx page. However, you can move this code around if you only want Clarity to run on a subset of your site.

We start by importing the "Script" component from "next/script" into app/layout.tsx.

app/layout.tsx
1import Script from "next/script";

Next, we create a new Script component right below our </body> tag with the following structure, modifying the script we copied earlier from the Clarity dashboard.

app/layout.tsx
1<Script id="microsoft-clarity-analytics">
2 {`
3 (function(c,l,a,r,i,t,y){
4 c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
5 t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
6 y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
7 })(window, document, "clarity", "script", "[YOUR-ID-HERE]");
8 `}
9</Script>

Note that we replaced the <script> tag with our own <Script> and added the id microsoft-clarity-analytics to the tag. Otherwise, we copied the tag content as children of our script component, surrounding it with {``}. Once you have this code embedded, redeploy your website and Clarity should be up and running!

The Mystery Error

But what was the mystery error I referred to at the beginning? The first time I deployed, I used the id clarity for the Script component and was not seeing any new data coming in. This ended up conflicting with an element that my script was trying to create, which also had the id of clarity. For that reason, when setting up this script, do not use the id clarity for your "Script" element.