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
Next.js Functions: NextRequest
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 fu
5 min read
Next.js Functions: notFound
Next.js is a React framework that is used to build full-stack web applications. It is used both for front-end and back-end development, simplifying React development with powerful features. In this article, we will explore the notFound function, which is used to handle cases where a requested resour
3 min read
Next.js Functions: userAgent
Detecting the userAgent is now very important in SSR applications using Next.js, which provides a userAgent string. Doing so can be quite helpful to optimize the rendering, find some errors that are browser-specific, or change the client experience based on the device it is accessed from. Next.js is
5 min read
Next.js Functions: redirect
Next.js is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is redirect Function. In this article, we will learn abou
2 min read
Next.js Functions: usePathname
Next.js is a JavaScript framework library used to build fast and scalable web applications with server-side rendering and static site generation capabilities. One of the useful hooks provided by Next.js is usePathname, which allows developers to easily access and manipulate the current pathname of t
3 min read
Next.js Functions: useParams
Next.js is known for its ability to create dynamic and highly optimized web applications. Among them, useParams allows you to access route parameters and enhance the interactivity and functionality of the applications. In this article, we will explore what useParams is and how it works. What is useP
4 min read
Underscore.js _.result() Function
Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects. The _.result() function is an inbuilt function in Underscore.js library of JavaScript. Here, if the state
2 min read
Underscore.js _.last() Function
Underscore.js _.last() is used to display the last element of the array. It is usually applied to separate the elements of an array by making it into 2 arrays. One which contains only the last element and the other which contains all the elements except the last one. Syntax:_.last( array, [n] ) Para
3 min read
Next.js Functions: useSearchParams
The Next.js useSearchParams hook gives the functional component access to the query parameters from the URL and the ability to manipulate them. This is pretty useful in cases where you need to get, parse, or change search parameters directly within the component, without manually parsing the URL. Sy
5 min read
Underscore.js _.lastindexOf() Function
_.lastIndexOf() function: It finds the index of an element in an array. If the element is repeated then it gives the index of that element which is closest to the end. It is used when we have a number of repeated elements in the array and we want to find the index of that repeated element which is n
3 min read