Get User Agent in getStaticProps in NextJs

4.4k views Asked by At

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!

0

There are 0 answers