Search code examples
typescriptreduxnext.jstypeerrorserver-side

userAgent is undefined inside _app.tsx while using getInitialProps?


I am getting userAgent as undefined in the following line of code:-

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

I am getting isMobile as undefined also as shown below

enter image description here

I want to detect the device whether it's a mobile or desktop in the server side.

Currently I am using Next.js with Typescript.

Here is my full source code:-

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);

Here is the simple version of the above code and it also returning userAgent as undefined

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

Solution

  • Here is the working answer :-

    MyApp.getInitialProps = async ({ ctx }: AppContext) => {
      const userAgent = ctx.req?.headers['user-agent'] ?? '';
      const isMobile = NextUserAgent.useUserAgent(userAgent).isMobile;
      return { isMobile };
    };