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 } }
/* 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 } }
Top comments (0)