Last Updated : 21 Aug, 2024
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.
CookiesCookies 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.
JavaScript
import { NextResponse } from 'next/server';
export function middleware(req) {
const response = NextResponse.next();
response.cookies.set('userToken', 'abc123');
return response;
}
Output set(name, value) 2. get(name)
This method retrieves a specific cookie from the request.
JavaScript
import { NextResponse } from 'next/server';
export function middleware(req) {
const userToken = req.cookies.get('userToken');
console.log('userToken:', userToken);
return NextResponse.next();
}
Output get(name) 3. getAll()
This method retrieves all cookies from the request.
JavaScript
import { NextResponse } from 'next/server';
export function middleware(req) {
const allCookies = req.cookies.getAll();
console.log('All Cookies:', allCookies);
return NextResponse.next();
}
Output getAll() 4. delete(name)
This method deletes a specific cookie from the response.
JavaScript
import { NextResponse } from 'next/server';
export function middleware(req) {
const response = NextResponse.next();
response.cookies.delete('userToken');
return response;
}
Output delete(name) JSON Response
The json() method allows you to return a JSON response easily.
JavaScript
import { NextResponse } from 'next/server';
export function middleware(req) {
return NextResponse.json({ message: 'Hello, world!' });
}
Output
{Redirect
"message": "Hello, world!"
}
The redirect() method allows you to redirect the user to a different URL.
JavaScript
import { NextResponse } from 'next/server';
export function middleware(req) {
return NextResponse.redirect('/new-path');
}
Output JSON Response Rewrite
The rewrite() method rewrites the request URL to a different URL without changing the URL visible to the user.
JavaScript
import { NextResponse } from 'next/server';
export function middleware(req) {
return NextResponse.rewrite('/another-path');
}
Output Rewrite Next
The next() method passes the request to the next middleware or route.
JavaScript
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-exampleStep 2: Create Middleware File
Create a _middleware.js file in the pages directory.
pages/_middleware.jsStep 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 packageDependencies
Ensure your package.json file reflects the necessary dependencies for your project. Here is an example:
"dependencies": {Folder Structure Folder Struture
"next": "14.2.5",
"package": "^1.0.1",
"react": "^18",
"react-dom": "^18",
"some": "^0.1.1"
}
Example: This illustrates a Next.js middleware that redirects all requests to `/new-path`, sets a cookie, and adds a custom header.
JavaScript
//pages/_app.js
export default function NewPath() {
return (
<div>
<h1>Welcome to New Path</h1>
</div>
);
}
JavaScript
//pages/index.js
export default function Home() {
return (
<div>
<h1>Welcome to Next.js!</h1>
</div>
);
}
JavaScript
//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 Next.js Functions: NextResponse
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