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

Next.js(TypeScript)接入Azure Application Insights报错求解决方案

Next.js 14 + TypeScript 接入Azure Application Insights 报错解决方案

错误原因分析

你遇到的window is not defined错误,核心原因是:

  1. Next.js 14 App Router默认使用服务器组件,服务器端渲染阶段不存在window对象,直接访问会报错
  2. 原代码中typeof window !== undefined是语法错误,正确判断应为typeof window !== 'undefined'(typeof返回值是字符串类型)
  3. AppInsightsContext未定义,直接使用会导致上下文报错
  4. 直接解构window.history的方式不符合API规范,history对象的属性多为只读,无法直接覆盖

完整解决方案

1. 修改AppInsightService.tsx(客户端组件化+修正逻辑)

添加'use client'指令将其转为客户端组件,确保仅在浏览器端执行初始化逻辑:

'use client';

import { createContext } from 'react';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ReactPlugin } from '@microsoft/applicationinsights-react-js';

// 创建AppInsights上下文(原代码缺失)
export const AppInsightsContext = createContext<ReactPlugin | null>(null);

let reactPlugin: ReactPlugin;
let appInsights: ApplicationInsights;

// 仅在浏览器环境初始化
if (typeof window !== 'undefined') {
  reactPlugin = new ReactPlugin();
  appInsights = new ApplicationInsights({
    config: {
      instrumentationKey: "<你的instrumentationKey>",
      extensions: [reactPlugin],
      extensionConfig: {
        [reactPlugin.identifier]: { 
          // 适配Next.js路由的history配置
          history: {
            location: window.location,
            // 可选:结合Next.js useRouter监听路由变化
            listen: (callback: () => void) => {
              return () => {};
            }
          }
        },
      },
      enableAutoRouteTracking: true,
      disableTelemetry: false,
    }
  });

  appInsights.loadAppInsights();
}

export { reactPlugin, appInsights };

2. 修改layout.tsx(适配客户端组件+上下文注入)

同样添加'use client'指令,确保上下文Provider在客户端生效:

'use client';

import { AppInsightsContext, reactPlugin } from './AppInsightService';
import { Inter } from 'next/font/google';

const inter = Inter({ subsets: ['latin'] });

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>
        {/* 兜底处理reactPlugin未初始化的情况 */}
        <AppInsightsContext.Provider value={reactPlugin || null}>
          {children}
        </AppInsightsContext.Provider>
      </body>
    </html>
  );
}

关键修改说明

  • 'use client'指令:强制组件转为客户端组件,避免服务器端执行时访问浏览器API报错
  • 修正window判断:用typeof window !== 'undefined'准确判断浏览器环境
  • 上下文定义:补充AppInsightsContext的创建,确保组件间可以正确共享实例
  • history配置优化:避免直接解构window.history,改用符合规范的方式传入路由信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:42:21