dev-resources.site
for different kinds of informations.
Nextjs: How to check device serverside or know if mobile
Published at
7/17/2023
Categories
nextjs
serverside
device
detectio
Author
GreggHume
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
}
}
Articles
12 articles in total
AWS S3 Change Url, Proxy Url, Map to Domain in 2024
read article
Prevent body from scrolling when a modal is open : css solution
read article
Svelte 5: Slot / children example
read article
Whatsapp Webhook Setup and Nodejs Code Example
read article
Vite: How to bundle / group chunks together
read article
Payfast API: Easy Nodejs signature and headers function
read article
CSS: Fix a div center on the page
read article
Strapi: Update user via api
read article
Strapi: Create user via api
read article
Anyone else get bored of coding? How do you stay excited?
read article
Nextjs: How to check device serverside or know if mobile
currently reading
Nextjs: How to get url in getInitialProps
read article
Featured ones: