1

I am using react-device-detect package to detect whether the request is from a mobile or desktop device, it uses user agent of course to do that.

In my NextJS project I want to use it on SSG pages.

Imported the package

import { isMobile, getUA, getSelectorsByUserAgent } from 'react-device-detect';

And using the getStaticProps like this

export async function getStaticProps(context) {

  // Device React
  const deviceIsMobile = isMobile;

  const deviceType = deviceIsMobile ? 'Yes, I am a mobile' : 'Nope, Desktop!';

  return {
    props: {
       mobileDevice: deviceType
    }, // will be passed to the page component as props
  }
}

And finally in my page's function

function AwesomePage( { mobileDevice } ) {
    return(
         <h1>{ mobileDevice }</h1>
    )
}

No matter what I always see 'Nope, Desktop!'.

In some examples of react-device-detect I noticed that we may use the userAgent from the req param, but does getStaticProps even provide that, I checked and it seems it don't? What's the way around this? I simply want to get user agent on an SSG page through getStaticProps.

Thanks!

Deepak Kamat
  • 1,880
  • 4
  • 23
  • 38
  • 1
    [`getStaticProps`](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) runs once at build time, and therefore doesn't have access to request-specific information. You'll have to do the detection on the client-side, _OR_ use [`getServerSideProps`](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) if you want it server-side. – juliomalves Oct 10 '21 at 16:21

0 Answers0