Created
May 27, 2020 06:36
-
-
Save buddalee/d3d7a46cfab71e072fb6c3bed074bc58 to your computer and use it in GitHub Desktop.
Nextjs in server side to detect device with user agent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Nextjs in server side to detect device with user agent |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static async getInitialProps ({ Component, ctx }) { | |
const isServer = !!ctx.req | |
const userAgent = isServer | |
? ctx.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)) | |
console.log('=================') | |
console.log('userAgent: ', userAgent) | |
console.log('isLine: ', isLine) | |
console.log('isMobile: ', isMobile) | |
console.log('isInApp: ', isInApp) | |
console.log('=================') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For app router:
I wanted to pre-render a page conditionally based on the device type on React/NextJS/SSR. I was able to do it by storing the user-agent in a context and reading it from a hook
useIsMobile()
which returned true or false based on the parsed user-agent header on the server side.We create a context to store the parsed user-agent header.
We create a hook to consume the context and check device type.
We can use a sever component as the layout (app router) to get the user agent from request headers
We can then pass the user agent to a client component that will provide the initial value for the context. Since client components with
"use client"
directive are still rendered once on the server with initial values then hydrated on the client.Now when this page is rendered for the first time on the server with initial values, useIsMobile() should accurately return a value based on the user-agent device type.