Device-aware routing
Rewrite requests differently for mobile and desktop clients.
Next.js 16+ · Function
userAgent parses a request's user-agent data into bot, browser, device, engine, and operating-system details. It is imported from next/server and is commonly used with NextRequest in Proxy logic.
Import userAgent from next/server and pass it a NextRequest in Proxy or another request-aware server context. The returned object exposes parsed bot, browser, device, engine, and operating-system details; individual values can be undefined when the user agent cannot identify them.
userAgent(request)| Name | Type | Description |
|---|---|---|
request | NextRequest | The incoming request whose user-agent information should be parsed. |
An object containing isBot and parsed browser, device, engine, and operating-system information.
import { NextRequest, NextResponse, userAgent } from 'next/server'
export function proxy(request: NextRequest) {
const { device, isBot } = userAgent(request)
const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
request.nextUrl.searchParams.set('viewport', viewport)
request.nextUrl.searchParams.set('bot', String(isBot))
return NextResponse.rewrite(request.nextUrl)
}This proxy classifies the incoming request using parsed device and bot information, then rewrites the URL with those values.
Rewrite requests differently for mobile and desktop clients.
Detect recognized crawlers before applying request handling rules.
Collect browser, engine, or operating-system metadata for server-side decisions.
userAgent parses the incoming request and returns structured information about the user agent. The result includes isBot plus browser, device, engine, and operating-system objects.
Follow-up: How should device-dependent routing handle unknown clients? Use a conservative default when device.type is undefined rather than assuming mobile or desktop.
Call userAgent with the request object, commonly a NextRequest received by Proxy. For example, userAgent(request) can provide device.type for a rewrite decision.
Follow-up: Why use NextRequest instead of constructing a new Request? NextRequest supplies Next.js request context such as nextUrl, which is useful when applying the parsed result to a rewrite.
The isBot property is a boolean that indicates whether the request comes from a known bot. Browser, device, engine, and operating-system fields provide parsed metadata, with some fields possibly undefined.
Follow-up: What should code do with uncertain browser metadata? Treat absent names, versions, models, and types as unknown and avoid relying on them as mandatory values.
NextRequestNextResponseproxyProxyrequest.nextUrldevicebrowserengine