DEV Community

GreggHume
GreggHume

Posted on

Nextjs: How to check device serverside or know if mobile

I have different components that I render on Mobile vs Desktop. I like to dynamically import components depending on the device type to reduce the bundle size / unused code.

Here is a function that I use in production:

export const getServerSideProps = async (context) => {
  // util code is in the codeblock below this one
  const {isMobile} = utilServerSideDeviceDetection(context)

  return {
   isMobile,
   ...yourotherdata
  }
}
Enter fullscreen mode Exit fullscreen mode
/* 
 paste this function into a file somewhere and import it 
 into a page where you need it, as seen above
*/
export const utilServerSideDeviceDetection = (context)=> {
  const isServer = !!context.req
  const userAgent: string = isServer
    ? context.req.headers['user-agent']
    : navigator.userAgent
  const isLine = /\bLine\//i.test(userAgent) || false
  const isMobile = /(iPad|iPhone|Android|Mobile)/i.test(userAgent) || false
  const rules = [
    'WebView',
    '(iPhone|iPod|iPad)(?!.*Safari/)',
    'Android.*(wv|.0.0.0)'
  ]

  const regex = new RegExp(`(${rules.join('|')})`, 'ig')
  const isInApp = Boolean(userAgent.match(regex))

  return {
    isMobile,
    isLine,
    isInApp,
    userAgent
  }
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more