Next.js Functions: NextRequest
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
}
- request.cookies.set('key', 'value'): Sets a cookie with a specified key and value.
- request.cookies.get('key'): Retrieves the value of a cookie by its key.
- request.cookies.has('key'): Checks if a cookie with the specified key exists.
- request.cookies.delete('key'): Deletes a cookie by its key.
- request.nextUrl.pathname: Accesses the path of the request URL.
- NextResponse.next(): Continues processing the request.
Key Features of NextRequest
1. Enhanced Cookies Management:
- Set a Cookie: You can set cookies on a request using request.cookies.set(name, value). This sets a Set-Cookie header on the request.
// Example: Setting a cookie to hide a banner\
request.cookies.set('show-banner', 'false'); // Sets `Set-Cookie: show-banner=false; path=/home`
- Get a Cookie: Retrieve the value of a cookie by name using request.cookies.get(name). If the cookie is not found, it returns undefined.
// Example: Retrieving the 'show-banner' cookie
const bannerStatus = request.cookies.get('show-banner'); // Returns 'false'
- Get All Cookies: Use request.cookies.getAll(name) to get all values of a specific cookie or all cookies if no name is provided.
// Example: Getting all 'experiments' cookies
const experiments = request.cookies.getAll('experiments'); // Returns an array of cookies
- Delete a Cookie: Remove a cookie using request.cookies.delete(name), which returns true if the cookie is deleted or false if it wasn't found.
// Example: Deleting the 'experiments' cookie
request.cookies.delete('experiments'); // Returns true if deleted
- Check for a Cookie: Use request.cookies.has(name) to check if a cookie exists on the request.
// Example: Checking if the 'experiments' cookie exists
const hasExperiments = request.cookies.has('experiments'); // Returns true or false
- Clear Cookies: Use request.cookies.clear() to remove all Set-Cookie headers from the request.
// Example: Clearing all cookies
request.cookies.clear();
2. nextUrl Property:
- nextUrl extends the native URL API with additional Next.js-specific properties, allowing detailed handling of request URLs within the app.
// Example: Accessing pathname and search parameters
const path = request.nextUrl.pathname; // e.g., '/home'
const params = request.nextUrl.searchParams; // e.g., { 'name': 'lee' }
- Properties:
- basePath: The base path of the URL.
- buildId: The unique build identifier of the Next.js application.
- pathname: The path part of the URL.
- searchParams: An object representing the search parameters of the URL.
How to Use NextRequest?
1. Using Middleware Functions
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.ts
import { 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:
- request.nextUrl provides access to the URL of the incoming request.
- NextResponse.redirect creates a redirect response if the requested path matches /old-page.
- NextResponse.next allows the request to continue to the next middleware or route handler if no action is taken.
2. Using API Route
You can also use NextRequest in API routes to process incoming requests. Here’s a basic example:
// app/api/hello/route.ts
import { 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:
- request.headers.get('user-agent') retrieves the User-Agent header from the request.
- request.nextUrl provides access to the URL and its query parameters.
- NextResponse.json sends a JSON response with the greeting message and user agent.
3. Handling Different Request Methods
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.ts
import { 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 }
);
}
}
Steps To Implement Next.js Functions: NextRequest
Step 1: Create a New Next.js Application
Use the create-next-app command to bootstrap a new Next.js project:
npx create-next-app@latest my-next-app
cd my-next-app
Create Next.js applicationFolder Structure
Folder StructureDependencies
"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 dev
Output
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects