Open In App

Next.js Functions: userAgent

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Detecting the userAgent is now very important in SSR applications using Next.js, which provides a userAgent string. Doing so can be quite helpful to optimize the rendering, find some errors that are browser-specific, or change the client experience based on the device it is accessed from. Next.js is a well-known framework for React that gives developers various powerful tools for server-side rendering, static site generation, and client-side rendering.In web development, identifying and parsing user agents can be crucial for tailoring user experiences and optimizing performance. Next.js offers a handy userAgent function to help with this. This guide will cover various aspects of userAgent, including detecting bots, browsers, devices, engines, operating systems, and CPUs.

These are the following topics that we are going to discuss:

Understanding userAgent

The userAgent function parses the user agent string and provides detailed information about the client. This includes identifying if the client is a bot, the browser they are using, the type of device, the engine powering the browser, the operating system, and the CPU architecture.

import { NextRequest, NextResponse, userAgent } from 'next/server'

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

// Log user agent information for debugging purposes
console.log('User Agent:', ua)

// Conditionally handle mobile vs. desktop requests
if (device.type === 'mobile') {
// For mobile users, redirect to a mobile-specific page
url.pathname = '/mobile'
} else {
// For desktop users, redirect to the default page
url.pathname = '/desktop'
}

// Return the updated response
return NextResponse.rewrite(url)
}

isBot

The isBot property helps in determining whether the user agent is a bot or a real user. This is particularly useful for distinguishing human users from automated scripts.

"isBot" is a true/false value that tells if the request is from a known bot.

const userAgent = require('useragent');
const agent = userAgent.parse(req.headers['user-agent']);
const isBot = agent.isBot;
console.log(`Is the user a bot? ${isBot}`);

Browser

The browser property provides information about the browser being used by the client. It includes details such as the name and version of the browser.

  • name: A text that shows the name of the browser, or it will be undefined if it can't be identified.
  • version: A text that shows the version of the browser, or it will be undefined if it can't be identified.

Example:

import { userAgent } from 'next/server'

export function middleware(request: NextRequest) {
const { browser } = userAgent(request)
const browserName = browser.name || 'Unknown Browser'
const browserVersion = browser.version || 'Unknown Version'

console.log(`Browser: ${browserName} ${browserVersion}`)

// Proceed with other middleware logic if needed
return NextResponse.next()
}

Device

The device property gives information about the device type, such as whether the user is on a mobile, tablet, or desktop device.

  • model: A text that shows the model of the device, or it will be undefined.
  • type: A text that shows the type of the device, like console, mobile, tablet, smart TV, wearable, embedded, or it will be undefined.
  • vendor : A text that shows the manufacturer of the device, or it will be undefined.

Example:

import { NextRequest, NextResponse, userAgent } from 'next/server'

export function middleware(request: NextRequest) {
const { device } = userAgent(request)

const deviceModel = device.model || 'Unknown Model'
const deviceType = device.type || 'Unknown Type'
const deviceVendor = device.vendor || 'Unknown Vendor'

console.log(`Device: ${deviceType} ${deviceModel} by ${deviceVendor}`)

// Proceed with other middleware logic if needed
return NextResponse.next()
}

Engine

The engine is an object that has details about the browser's engine.

  • name: A text that shows the name of the engine. Possible names include: Amaya, Blink, EdgeHTML, Flow , Gecko, Goanna, Webkit, or it will undefined.
  • version: A text that shows the version of the engine, or it will be undefined.

Example:

import { NextRequest, NextResponse, userAgent } from 'next/server'

export function middleware(request: NextRequest) {
const { engine } = userAgent(request)

const engineName = engine.name || 'Unknown Engine'
const engineVersion = engine.version || 'Unknown Version'

console.log(`Engine: ${engineName} ${engineVersion}`)

// Proceed with other middleware logic if needed
return NextResponse.next()
}

OS

The os property provides details about the operating system the client is using, including the name and version.

  • name: A text that shows the name of the OS, or it will be undefined.
  • version: A text that shows the version of the OS, or it will be undefined.

Example:

import { NextRequest, NextResponse, userAgent } from 'next/server'

export function middleware(request: NextRequest) {
const { os } = userAgent(request)

const osName = os.name || 'Unknown OS'
const osVersion = os.version || 'Unknown Version'

console.log(`OS: ${osName} ${osVersion}`)

// Proceed with other middleware logic if needed
return NextResponse.next()
}

CPU

The cpu property provides information about the CPU architecture of the client's device. Possible values include: 68k, amd64, arm64, avr, sparc64 or undefined.

architecture: A text that shows the architecture of the CPU. Possible values include: 68k, amd64, arm, arm64, armhf, avr, ia32 etc.

Example:

import { NextRequest, NextResponse, userAgent } from 'next/server'

export function middleware(request: NextRequest) {
const { cpu } = userAgent(request)

const cpuArchitecture = cpu.architecture || 'Unknown Architecture'
console.log(`CPU Architecture: ${cpuArchitecture}`)

// Proceed with other middleware logic if needed
return NextResponse.next()
}

Steps to Setup Project for Functions: userAgent

Step 1: Create a New Next.js Project

npx create-next-app@latest user-agent-example

Step 2: Navigate to the project

cd user-agent-example

Updated Dependencies:

dependencies: {
"react": "^18",
"react-dom": "^18",
"next": "14.2.5"
}

Folder Structure:

Screenshot-2024-08-07-151132
Project structure

Example: Create a page that uses the user agent to provide information.

JavaScript
// pages/index.js

import { NextResponse } from 'next/server';

export async function middleware(request) {
    const userAgent = request.headers.get('user-agent');
    return NextResponse.json({ userAgent });
}

export default function Home({ userAgent }) {
    return (
        <div>
            <h1>Welcome to the User Agent Example</h1>
            <p>Your User Agent: {userAgent}</p>
        </div>
    );
}

export async function getServerSideProps(context) {
    const userAgent = context.req.headers['user-agent'] || 'Unknown';

    return {
        props: {
            userAgent,
        },
    };
}

Run the development Server:

npm run dev

Output:

Screenshot
Output

Next Article

Similar Reads