Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
Next.js Functions: NextResponse
Next article icon

Next.js Functions: NextResponse

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Screenshot-2024-08-15-210426
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

Screenshot-2024-08-15-210634
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

Screenshot-2024-08-15-211046
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

Screenshot-2024-08-15-205933
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

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.

JavaScript
import { NextResponse } from 'next/server';  export function middleware(req) {     return NextResponse.rewrite('/another-path'); } 

Output

Screenshot-2024-08-15-211255
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-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.

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

Screenshot-2024-08-20-181939
Next.js Functions: NextResponse

Next Article
Next.js Functions: NextResponse

N

nikunj_sonigara
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Next.js

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: 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: 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 usePa
    4 min read
    Next.js Functions: permanentRedirect
    Next.js is a React framework that is used to build full-stack web applications. It comes with a powerful set of features to simplify the development of React applications. One of its features is permanentRedirect Function. In this article, we will learn about permanentRedirect Function.What is perma
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences