Next.js Functions: NextResponse
NextResponse is a utility function provided by Next.js, used within middleware to create responses for HTTP requests. Middleware in Next.js allows you to run code before a request is completed, enabling you to handle things like authentication, redirects, and more. NextResponse makes it easy to construct responses with various configurations, such as setting headers, cookies, or redirecting requests.
Cookies
Cookies are a way to store small amounts of data on the client side, allowing for persistent state across requests. NextResponse provides several methods to interact with cookies easily.
1. set(name, value)
This method sets a cookie in the response.
import { NextResponse } from 'next/server';
export function middleware(req) {
const response = NextResponse.next();
response.cookies.set('userToken', 'abc123');
return response;
}
Output

2. get(name)
This method retrieves a specific cookie from the request.
import { NextResponse } from 'next/server';
export function middleware(req) {
const userToken = req.cookies.get('userToken');
console.log('userToken:', userToken);
return NextResponse.next();
}
Output

3. getAll()
This method retrieves all cookies from the request.
import { NextResponse } from 'next/server';
export function middleware(req) {
const allCookies = req.cookies.getAll();
console.log('All Cookies:', allCookies);
return NextResponse.next();
}
Output

4. delete(name)
This method deletes a specific cookie from the response.
import { NextResponse } from 'next/server';
export function middleware(req) {
const response = NextResponse.next();
response.cookies.delete('userToken');
return response;
}
Output

JSON Response
The json() method allows you to return a JSON response easily.
import { NextResponse } from 'next/server';
export function middleware(req) {
return NextResponse.json({ message: 'Hello, world!' });
}
Output
{
"message": "Hello, world!"
}
Redirect
The redirect() method allows you to redirect the user to a different URL.
import { NextResponse } from 'next/server';
export function middleware(req) {
return NextResponse.redirect('/new-path');
}
Output

Rewrite
The rewrite() method rewrites the request URL to a different URL without changing the URL visible to the user.
import { NextResponse } from 'next/server';
export function middleware(req) {
return NextResponse.rewrite('/another-path');
}
Output

Next
The next() method passes the request to the next middleware or route.
import { NextResponse } from 'next/server';
export function middleware(req) {
// Some middleware logic
return NextResponse.next();
}
Steps to Create Application
Step 1: Initialize a Next.js Application
npx create-next-app@latest next-response-example
cd next-response-example
Step 2: Create Middleware File
Create a _middleware.js file in the pages directory.
pages/_middleware.js
Step 3: Install Additional Dependencies (if needed)
Next.js comes with all necessary dependencies for using NextResponse. If you need additional packages for your middleware, you can install them using npm or yarn.
npm install some package
or
yarn add some package
Dependencies
Ensure your package.json file reflects the necessary dependencies for your project. Here is an example:
"dependencies": {
"next": "14.2.5",
"package": "^1.0.1",
"react": "^18",
"react-dom": "^18",
"some": "^0.1.1"
}
Folder Structure

Example: This illustrates a Next.js middleware that redirects all requests to `/new-path`, sets a cookie, and adds a custom header.
//pages/_app.js
export default function NewPath() {
return (
<div>
<h1>Welcome to New Path</h1>
</div>
);
}
//pages/index.js
export default function Home() {
return (
<div>
<h1>Welcome to Next.js!</h1>
</div>
);
}
//pages/_middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
const response = NextResponse.redirect('/new-path');
response.cookies.set('user', 'nikunj sonigara');
response.headers.set('X-Custom-Header', 'example-value');
return response;
}
Output
