Next.js - NextRequest



The NextRequest

The Next.js NextRequest class extends the native Web Request API to provide additional functionality and methods to handle HTTP requests in Next.js applications.

Syntax

Following is the syntax of NextRequest class:

class NextRequest extends Request {
  constructor(input: RequestInfo | URL, init?: RequestInit)
}

Parameters

The NextRequest class takes two parameters:

  • input Either a URL string, Request object, or URL object representing the request URL
  • init (optional): An object containing custom configurations

Return Value

The NextRequest method will return a new NextRequest instance with the following additional methods:

  • cookies Access to request cookies
  • nextUrl Parsed URL with additional utility methods
  • geo Geographic information about the request
  • ip Client's IP address

Key Points

  • NextRequest is only available in Edge Runtime
  • Provides enhanced functionality over standard Request object
  • Cannot be used in API Routes (pages/api), only in App Router
  • Useful for handling cookies, URL manipulation, and geolocation data
  • Commonly used with NextResponse for complete request/response handling

Example 1

In the code below, we demonstrate how to use the NextRequest class to access request cookies, query parameters, and geolocation data in a Next.js application.

// app/api/hello/route.ts

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

export async function GET(request: NextRequest) {
    const searchParams = request.nextUrl.searchParams
    const query = searchParams.get('query')
    const cookies = request.cookies.get('user-token')

    return NextResponse.json({
        query: query,
        cookieExists: !!cookies,
        clientCountry: request.geo?.country
    })
}

Example 2

In the code below, we demonstrate how to use the NextRequest class to access the client's IP address and perform URL manipulation in a Next.js application.

// app/api/hello/route.ts
import { NextRequest, NextResponse } from 'next/server'

export async function GET(request: NextRequest) {
    const clientIp = request.ip
    const nextUrl = request.nextUrl
    const path = nextUrl.pathname
    
    // Get query parameters
    const searchParams = nextUrl.searchParams
    const queryExample = searchParams.get('example') || 'no query provided'
    
    // Get headers
    const userAgent = request.headers.get('user-agent')
    const host = request.headers.get('host')
    
    // Get cookies
    const cookies = request.cookies
    const cookieExample = cookies.get('example')?.value
    
    // Get geo information
    const geo = request.geo || {
        country: undefined,
        region: undefined,
        city: undefined
    }

    return NextResponse.json({
        clientIp: clientIp,
        path: path,
        fullUrl: nextUrl.href,
        searchParams: Object.fromEntries(searchParams.entries()),
        headers: {
            userAgent,
            host
        },
        cookies: {
            example: cookieExample
        },
        geo: {
            country: geo.country,
            region: geo.region,
            city: geo.city
        }
    }, {
        status: 200,
        headers: {
            'Cache-Control': 'no-store',
            'Content-Type': 'application/json'
        }
    })
}

// Add OPTIONS handler for CORS if needed
export async function OPTIONS(request: NextRequest) {
    return NextResponse.json({}, {
        status: 200,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization'
        }
    })
}
Advertisements