Integrating Microsoft Clarity into Your Next.js Project

93 min read

Understanding user behavior is crucial for optimizing your website's performance and enhancing user experience. Microsoft Clarity offers a powerful, free tool to gain insights into how users interact with your site. In this blog post, we'll walk you through integrating Microsoft Clarity into a Next.js 14 project using the built-in <Script> component. This approach ensures that the Clarity script loads efficiently and securely across your application.

Table of Contents

  1. Prerequisites
  2. Step 1: Setting Up a Next.js 14 Project
  3. Step 2: Adding the Clarity Script
  4. Step 3: Verifying the Integration
  5. Additional Tips
  6. Conclusion

Prerequisites

Before we begin, ensure you have the following:

  • Node.js installed on your machine.
  • npm or yarn as your package manager.
  • A basic understanding of Next.js and React.

Step 1: Setting Up a Next.js 14 Project

If you haven't set up a Next.js 14 project yet, you can create one using the following commands:

npx create-next-app@latest my-nextjs-app
cd my-nextjs-app

This command initializes a new Next.js project in a directory named my-nextjs-app. Follow the on-screen prompts to complete the setup.

Step 2: Adding the Clarity Script

Next.js provides a built-in <Script> component located in next/script that optimizes the loading of third-party scripts. We'll use this component to add the Microsoft Clarity script to your application.

Method 1: Using the pages Directory Structure

If your project utilizes the pages directory (the traditional routing system in Next.js), follow these steps:

  1. Open pages/_app.js:

    This file allows you to override the default App component, enabling you to persist layouts between page changes and inject additional data or scripts.

  2. Add the Clarity Script:

    Insert the Clarity script using the <Script> component as shown below:

    // pages/_app.js
    import { useEffect } from 'react';
    import Script from 'next/script';
    import '../styles/globals.css';
    
    function MyApp({ Component, pageProps }) {
      return (
        <>
          {/* Microsoft Clarity Script */}
          <Script
            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", "YOUR_CLARITY_PROJECT_ID");
              `,
            }}
          />
          <Component {...pageProps} />
        </>
      );
    }
    
    export default MyApp;
    

    Explanation:

    • strategy="afterInteractive": Ensures the script loads after the page becomes interactive, preventing it from blocking the initial render.
    • dangerouslySetInnerHTML: Inserts the Clarity script directly into the HTML. Replace "YOUR_CLARITY_PROJECT_ID" with your actual Clarity project ID.

Method 2: Using the app Directory Structure (App Router)

For projects leveraging the app directory (introduced in Next.js 13+ with the App Router), follow these steps:

  1. Open or Create app/layout.js:

    This file defines the root layout for your application.

  2. Add the Clarity Script:

    Incorporate the Clarity script within the layout as follows:

    // app/layout.js
    import './globals.css';
    import Script from 'next/script';
    
    export const metadata = {
      title: 'My Next.js App',
      description: 'Generated by create next app',
    };
    
    export default function RootLayout({ children }) {
      return (
        <html lang="en">
          <head>
            {/* Other head elements can go here */}
          </head>
          <body>
            {/* Microsoft Clarity Script */}
            <Script
              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", "YOUR_CLARITY_PROJECT_ID");
                `,
              }}
            />
            {children}
          </body>
        </html>
      );
    }
    

    Explanation:

    • The Clarity script is placed within the <body> tag to ensure it loads after the main content.
    • Replace "YOUR_CLARITY_PROJECT_ID" with your actual Clarity project ID.

Step 3: Verifying the Integration

After adding the Clarity script, it's essential to verify that it's correctly integrated:

  1. Run Your Next.js Application:

    npm run dev
    

    or

    yarn dev
    
  2. Check the Browser:

    • Network Requests: Open your browser's developer tools, navigate to the "Network" tab, and search for clarity.ms to confirm that the script is loading.
    • Console Logs: Look for any Clarity-related errors or logs in the console.
    • Microsoft Clarity Dashboard: Log in to your Microsoft Clarity account to ensure data from your website is being received.

Additional Tips

Environment Variables

You might want to load the Clarity script only in specific environments (e.g., production) to avoid tracking during development. Here's how you can achieve this:

  1. Set Environment Variables:

    Create a .env.local file and add your Clarity project ID:

    NEXT_PUBLIC_CLARITY_ID=YOUR_CLARITY_PROJECT_ID
    
  2. Modify the Script Integration:

    Update your _app.js or layout.js to conditionally load the script based on the environment:

    // Example for pages/_app.js or app/layout.js
    {process.env.NODE_ENV === 'production' && process.env.NEXT_PUBLIC_CLARITY_ID && (
      <Script
        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", "${process.env.NEXT_PUBLIC_CLARITY_ID}");
          `,
        }}
      />
    )}
    

    Explanation:

    • The script loads only if the application is running in the production environment and the Clarity ID is provided.

Creating a Custom Clarity Component

For better code organization, consider creating a separate component for the Clarity script:

  1. Create components/Clarity.js:

    // components/Clarity.js
    import Script from 'next/script';
    
    const Clarity = () => (
      <Script
        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", "YOUR_CLARITY_PROJECT_ID");
          `,
        }}
      />
    );
    
    export default Clarity;
    
  2. Import and Use the Clarity Component:

    In your _app.js or layout.js, import and include the Clarity component:

    import Clarity from '../components/Clarity';
    
    function MyApp({ Component, pageProps }) {
      return (
        <>
          <Clarity />
          <Component {...pageProps} />
        </>
      );
    }
    
    export default MyApp;
    

    Explanation:

    • This approach promotes reusability and cleaner code by encapsulating the Clarity script within its own component.

Conclusion

Integrating Microsoft Clarity into your Next.js 14 project is a straightforward process that can provide invaluable insights into user behavior on your website. By leveraging Next.js's <Script> component, you ensure that the Clarity script loads efficiently without hindering your application's performance.

Whether you're using the traditional pages directory or the modern app directory structure, the methods outlined above will help you seamlessly incorporate Clarity into your Next.js application. Remember to verify the integration and consider using environment variables or custom components to enhance flexibility and maintainability.

If you encounter any issues or have further questions, feel free to leave a comment below or reach out for assistance!