Next.js Discord

Discord Forum

Check User Device

Answered
Black carp posted this in #help-forum
Open in Discord
Black carpOP
Hi!, I'm using Next JS with version 14.0.0
and I'm using nextAuth with version ^4.24.5

So, my question is.. how to detect user device using NextJs?
for example when I open my application on dekstop, I can redirect the URL to be web version and vice versa with mobile device

thanks
Answered by Ray
hi, you could use userAgent from next/server
// middleware.ts
import { NextRequest, NextResponse, userAgent } from 'next/server'
 
export function middleware(request: NextRequest) {
  const url = request.nextUrl
  const { device } = userAgent(request)
  const isMobile = device.type === 'mobile' 
  if (isMobile) {
    return NextResponse.rewrite(url)
  }
}
View full answer

7 Replies

@Black carp Hi!, I'm using Next JS with version 14.0.0 and I'm using nextAuth with version ^4.24.5 So, my question is.. how to detect user device using NextJs? for example when I open my application on dekstop, I can redirect the URL to be web version and vice versa with mobile device thanks
hi, you could use userAgent from next/server
// middleware.ts
import { NextRequest, NextResponse, userAgent } from 'next/server'
 
export function middleware(request: NextRequest) {
  const url = request.nextUrl
  const { device } = userAgent(request)
  const isMobile = device.type === 'mobile' 
  if (isMobile) {
    return NextResponse.rewrite(url)
  }
}
Answer
Black carpOP
Oh Hi @Ray .. I forgot to mention router type.. I'm using pages router.. that code is applicable with pages router?
yes you can use it in middleware for page router too
Black carpOP
it works! yay.. thank you @Ray
@Black carp it works! yay.. thank you <@743561772069421169>
please mark solution if your issue is solved😀
Black carpOP
donee