Next.js - userAgent() Function



The userAgent() Function

The Next.js userAgent() function extents the Web Request API, to provide additional properties and methods to interact with the user agent object from the request. This is useful for getting information about the user's device, operating system, and browser.

Syntax

Following is syntax of userAgent() function:

import { userAgent } from 'next/server'

export function middleware(request: NextRequest) {
    const { device, engine, browser, os, cpu } = userAgent(request)
}

Parameters

The userAgent() function takes a request object as its parameter. This object will provide information about the incoming request, such as headers, cookies, query parameters, etc.

Return Value

The function returns an object containing the following properties:

  • device: The type of device (e.g., desktop, mobile, tablet, etc.)
  • engine: The rendering engine of the browser (e.g., Blink, WebKit, Gecko, etc.)
  • browser: The name of the browser
  • os: The operating system of the device
  • cpu: The architecture of the device's CPU (e.g., x86, ARM, etc.)

Key Points

  • The userAgent() function is middleware-specific, means it can be used only in middleware functions.
  • The function will execute before page rendering
  • The function is useful for customizing the content based on the user's device, browser, or operating system.

Example 1

The example below shows how to use the userAgent function in a middleware to add device information to the URL parameters.

// app/middleware.ts
import { NextRequest, NextResponse, userAgent } from 'next/server'

export function middleware(request: NextRequest) {
    const ua = userAgent(request)
    const url = request.nextUrl

    // Add device info to URL params
    url.searchParams.set('device', ua.device.type)
    url.searchParams.set('browser', ua.browser.name)
    url.searchParams.set('os', ua.os.name)
    url.searchParams.set('engine', ua.engine.name)
    url.searchParams.set('cpu', ua.cpu.architecture)

    return NextResponse.rewrite(url)
}

Output

When a user visits the page, the URL will be modified to include the device, browser, OS, engine, and CPU information as query parameters.

Next.js userAgent Example 1

Example 2

The example below shows how to use the userAgent function in a middleware to add viewport information to the URL parameters based on the user's device type.

import { NextRequest, NextResponse, userAgent } from 'next/server'
 
export function middleware(request: NextRequest) {
    const url = request.nextUrl
    const { device } = userAgent(request)
    const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
    url.searchParams.set('viewport', viewport)
    return NextResponse.rewrite(url)
}
Advertisements