You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS 13 App Router如何在head中添加Microsoft Clarity脚本?

在Next.js 13 App Router中正确添加Microsoft Clarity脚本

问题根源

你当前的写法错误在于在App Router的RootLayout手动将<Script>嵌套进<head>标签,Next.js 13 App Router对<head>的处理逻辑与传统pages路由不同,手动嵌套会导致脚本无法被正确注入到预期位置。另外,pages目录下的_document.js在App Router环境中完全无效,这也是你之前尝试失败的原因。

正确解决方案

使用Next.js 13的<Script>组件并指定strategy="beforeInteractive"策略,该策略会自动将脚本注入到<head>标签中,且在页面交互前加载,完全适配Clarity的运行要求。

修改后的RootLayout代码:

import Script from 'next/script';
import { inter } from '@/fonts';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      {/* Script直接放在<html>子级,无需嵌套进<head> */}
      <Script
        id="ms-clarity"
        strategy="beforeInteractive"
        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密钥");`
        }}
      />
      <head>
        {/* 这里只放元数据,比如title、meta标签等 */}
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </head>
      <body className={inter.className}>{children}</body>
    </html>
  );
}

关键说明

  • strategy="beforeInteractive":该策略仅能在App Router的RootLayout中使用,Next.js会自动将脚本注入到<head>,确保脚本在页面早期加载,符合Clarity的统计需求。
  • 无需手动管理<head>内的脚本:App Router的<head>由Next.js自动处理元数据,所有脚本都应通过<Script>组件声明,避免手动嵌套导致的注入失败。
  • 替换密钥:将代码中的你的Clarity密钥替换为你实际的Clarity项目ID。
  • 重启开发服务器:修改后重启Next.js开发服务器,避免缓存导致的脚本不更新。

验证方法

运行项目后,打开浏览器开发者工具查看页面源码,应该能在<head>标签内找到ID为ms-clarity的脚本标签。

内容的提问来源于stack exchange,提问作者ademclk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:47:19