Next.js Functions: NextResponse
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.
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.
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
{
"message": "Hello, world!"
}
Redirect
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 ResponseRewrite
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
RewriteNext
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-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
Folder StrutureExample: 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
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
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
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read