Next.js Functions: NextResponse (original) (raw)

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

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 (

Welcome to New Path

); }

JavaScript

//pages/index.js export default function Home() { return (

Welcome to Next.js!

); }

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