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

Next.js+Typescript中,_app.tsx的getInitialProps获取userAgent为undefined

在Next.js + TypeScript中服务器端获取UserAgent为undefined的问题

我在以下代码行中获取到的userAgent为undefined:

const userAgent = context.req?.headers['user-agent'] ?? '';

同时isMobile也返回undefined(截图显示isMobile的值为undefined)。

我需要在服务器端检测设备是移动端还是桌面端,当前使用Next.js结合TypeScript开发。

以下是我的完整源代码:

MyApp.getInitialProps = wrapper.getInitialPageProps(
  (store) =>
    async (context: any): Promise<any> => {
      const userAgent = context.req?.headers['user-agent'] ?? '';
      const { isMobile } = getSelectorsByUserAgent(userAgent);
      store.dispatch(setDevice(isMobile));
      const initialProps = await App.getInitialProps(context);
      return { ...initialProps, userAgent, isMobile };
    }
);

export default wrapper.withRedux(MyApp);

以下是上述代码的简化版本,同样返回userAgent为undefined:

MyApp.getInitialProps = async ({ req }: NextPageContext) => {
  const userAgent = req
    ? req.headers['user-agent'] || ''
    : typeof window !== 'undefined'
    ? window.navigator.userAgent
    : '';
  return { userAgent };
};

内容的提问来源于stack exchange,提问作者Sumeet Kumar Paul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 12:51:36