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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay