VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/nextjs-functions-nextresponse/

⇱ Next.js Functions: NextResponse - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

Output

👁 Screenshot-2024-08-15-210426
set(name, value)

2. get(name)

This method retrieves a specific cookie from the request.

Output

👁 Screenshot-2024-08-15-210634
get(name)

3. getAll()

This method retrieves all cookies from the request.

Output

👁 Screenshot-2024-08-15-211046
getAll()

4. delete(name)

This method deletes a specific cookie from the response.

Output

👁 Screenshot-2024-08-15-205933
delete(name)

JSON Response

The json() method allows you to return a JSON response easily.

Output

{
"message": "Hello, world!"
}

Redirect

The redirect() method allows you to redirect the user to a different URL.

Output

👁 Screenshot-2024-08-20-181939
JSON Response

Rewrite

The rewrite() method rewrites the request URL to a different URL without changing the URL visible to the user.

Output

👁 Screenshot-2024-08-15-211255
Rewrite

Next

The next() method passes the request to the next middleware or route.

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

👁 Screenshot-2024-08-15-204735
Folder Struture

Example: This illustrates a Next.js middleware that redirects all requests to `/new-path`, sets a cookie, and adds a custom header.

Output

👁 Screenshot-2024-08-20-181939
Next.js Functions: NextResponse
Comment
Article Tags: