Last Updated : 23 Jul, 2025
In Next.js, particularly with the introduction of Next.js 13 and the new App Router, NextRequest is part of the API used in the new routing system. It is designed to provide a simple and more powerful way to handle HTTP requests within Next.js applications, especially in API routes and middleware functions.
This article will give an overview of NextRequest, its use cases, and how to work with it effectively.
What is NextRequest?NextRequest is an abstraction provided by Next.js that represents an incoming HTTP request. It offers a consistent API for accessing request details and manipulating requests within middleware and API routes. This class is a part of the new experimental features that improve the developer experience and provide enhanced functionality for handling HTTP requests.
Syntax:
import { NextRequest, NextResponse } from 'next/server';export function middleware(request) {
request.cookies.set('key', 'value'); // Set cookie
const value = request.cookies.get('key'); // Get cookie
const exists = request.cookies.has('key'); // Check cookie
request.cookies.delete('key'); // Delete cookie
const path = request.nextUrl.pathname; // Access pathname
return NextResponse.next(); // Continue request
}
// Example: Setting a cookie to hide a banner\
request.cookies.set('show-banner', 'false'); // Sets `Set-Cookie: show-banner=false; path=/home`
// Example: Retrieving the 'show-banner' cookie
const bannerStatus = request.cookies.get('show-banner'); // Returns 'false'
// Example: Getting all 'experiments' cookies
const experiments = request.cookies.getAll('experiments'); // Returns an array of cookies
// Example: Deleting the 'experiments' cookie
request.cookies.delete('experiments'); // Returns true if deleted
// Example: Checking if the 'experiments' cookie exists
const hasExperiments = request.cookies.has('experiments'); // Returns true or false
// Example: Clearing all cookies2. nextUrl Property:
request.cookies.clear();
// Example: Accessing pathname and search parameters
const path = request.nextUrl.pathname; // e.g., '/home'
const params = request.nextUrl.searchParams; // e.g., { 'name': 'lee' }
Middleware functions in Next.js 13+ can use NextRequest to handle requests before they reach the actual route handlers. Here’s an example of how to use NextRequest in middleware:
// middleware.tsimport { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;// Example: Redirect requests to `/old-page` to `/new-page`
if (pathname === '/old-page') {
const url = request.nextUrl.clone();
url.pathname = '/new-page';
return NextResponse.redirect(url);
}return NextResponse.next();
}export const config = {
matcher: '/:path*',
};
In this example:
You can also use NextRequest in API routes to process incoming requests. Here’s a basic example:
// app/api/hello/route.tsimport { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
const userAgent = request.headers.get('user-agent');
const url = request.nextUrl;
const name = url.searchParams.get('name') || 'World';return NextResponse.json({
message: `Hello, ${name}!`,
userAgent,
});
}
In this example:
NextRequest allows you to handle different HTTP methods within your routes. You can use the request.method property to determine the method of the incoming request:
// app/api/data/route.tsSteps To Implement Next.js Functions: NextRequest Step 1: Create a New Next.js Applicationimport { NextRequest, NextResponse } from "next/server";
export async function handler(request: NextRequest) {
switch (request.method) {
case "GET":
return NextResponse.json({ message: "GET request received" });
case "POST":
const data = await request.json();
return NextResponse.json({ message: "POST request received", data });
default:
return NextResponse.json(
{ error: "Method not allowed" },
{ status: 405 }
);
}
}
Use the create-next-app command to bootstrap a new Next.js project:
npx create-next-app@latest my-next-appCreate Next.js application Folder Structure Folder Structure Dependencies
cd my-next-app
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.11"
}
Example: Create a middleware file to demonstrate the usage of NextRequest for handling cookies and URL manipulations.
JavaScript
//src/middleware.js
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request) {
const path = request.nextUrl.pathname;
const query = request.nextUrl.searchParams.get('name') || 'guest';
if (path === '/dashboard' && query === 'guest') {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: '/:path*',
};
JavaScript
//app/login/page.js
"use client";
export default function LoginPage() {
const handleSubmit = (e) => {
e.preventDefault();
alert("Logged in successfully!");
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="bg-white p-8 rounded shadow-md w-80">
<h2 className="text-2xl font-bold mb-6">Login</h2>
<form onSubmit={handleSubmit}>
<div className="mb-4">
<label
htmlFor="username"
className="block text-sm font-medium text-gray-700"
>
Username
</label>
<input
type="text"
id="username"
className="mt-1 p-2 border border-gray-300 rounded w-full"
required
/>
</div>
<div className="mb-6">
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700"
>
Password
</label>
<input
type="password"
id="password"
className="mt-1 p-2 border border-gray-300 rounded w-full"
required
/>
</div>
<button
type="submit"
className="w-full bg-blue-500 text-white py-2 rounded hover:bg-blue-600"
>
Login
</button>
</form>
</div>
</div>
);
}
To start the application run the following command.
npm run devOutput
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4