How to use Next Response In Next.js
This approach is used in a middleware. Middleware allows you to run code before a request is completed. based on the incoming request we can redirect to a different route or URL using NextResponse.redirect() method. We can use this to redirect a user based on a conditions such as Session exist, authentication etc..
Example: The below example demonstrate the use of Next Response
//page.js (gfg directory)
export default function Page() {
return (
<>
<h1>Welcome to w3wiki</h1>
</>
)
}
//middleware.js (src directory)
import { NextResponse } from "next/server"
export async function middleware(req) {
return NextResponse.redirect(new URL('/gfg', req.url))
}
export const config = {
matcher: '/',
}
Output:
How to Redirect in Next.js ?
NextJS 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. In this article, we will learn about How to Redirect in NextJS with different approaches.
We will discuss different approaches to Redirect in NextJS:
Table of Content
- Using Redirect method
- Using Configuration setting
- Using Router Push method
- Using Next Response
Contact Us