Next.js Redirects
Last Updated :
02 Feb, 2023
Next.js Redirects means changing the incoming source request to the destination request and redirecting the user to that path only. When the original web application is under maintenance, the users browse or access the web application, and we want to redirect the user to another web page or application for a limited amount of time.
Setting up Project: Follow the below steps to create the project:
Step 1: Create a project folder, and move into that directory.
mkdir foldername
cd foldername
Step 2: In that folder, create your project by using the below command in the terminal:
npx create-next-app project
Project Structure: This project should look like this:
Project Structure
Run the Project: To run the project use the following command:
npm run dev
Note: By default, it will start the server on port 3000.
Syntax: next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = {
redirects: async () => {
return [
{
// Source Path ( from )
source: '/',
// Destination Path ( to )
destination: '/',
permanent: true,
},
]
},
}
redirects() Async function: It anticipates receiving an array of objects with source, destination, and permanent properties:
Parameters:
- Source: The source is the path from which you want to redirect. The source is the location, if users will search for this location they will redirect to another location.
- Destination: The path where you want to redirect is the destination. The location where the users will reach when they will search for the source location.
- Permanent: It takes a boolean value. If true, search engines will cache the redirect otherwise the redirect is not cached.Â
Example 1: Redirect User to /contact page from /home page:
Create a new JavaScript file contact.js in the Pages section. We want when the user searches for /home, the user should reach the /contact page where the GeeksforGeeks official contact details will be displayed.
Write the following lines of code inside the contact.js file to display when the redirect happens:
Javascript
export default function Contact() {
return (
<div>
<h1 style={{ color: "green;" }}>GeeksforGeeks</h1>
<h3>Contact Details</h3>
<p>A-143, 9th Floor, Sovereign Corporate Tower, <br></br>
Sector- 136, Noida, Uttar Pradesh (201305) <br></br>
+91-7838223507 (Course related Queries)</p>
</div>
);
}
|
Now we have to update our next.config.js file. Update the source to ‘/home’ and destination to ‘/contact’.
The following changes are necessary:
Javascript
const nextConfig = {
reactStrictMode: true ,
}
module.exports = {
redirects: async () => {
return [
{
source: '/home' ,
destination: '/contact' ,
permanent: true ,
},
]
},
}
|
That’s it. If the user will search for /home then the user will automatically redirect to /contact page.
Example 2: Using the has object and redirecting the user based on the type, key, and value in the has object:
Syntax: The has object uses the following syntax to redirect a particular user request:
Valid `has` object shape is
{
"type": "header, cookie, query, host",
"key": "the key to check for",
"value": "undefined or a value string to match against"
}
We will use the type: host and key: localhost.
Javascript
const nextConfig = {
reactStrictMode: true ,
}
module.exports = {
redirects: async () => {
return [
{
source: '/home' ,
has: [
{
type: 'host' ,
key: 'localhost' ,
value: '' ,
},
],
permanent: false ,
destination: '/contact' ,
},
]
},
}
|
Output:
Â
Example 3: When a user enters the wrong route and the redirect fails ( 404 – page not found ):
Step 1: Create the 404.js file inside the pages directory. When redirect will fail and the user reaches a 404 page, we want the user should redirect to  /contact page only:
Step 2: Insert the following code in the 404.js file:
Javascript
import { useEffect } from "react"
import { useRouter } from "next/router"
export default function Error() {
const router = useRouter()
useEffect(() => {
router.replace( "/contact" )
});
};
|
In the above code, we are using the Router and useEffect hook. whenever redirection will fail or the user will reach to 404 page automatically redirect to the /contact page.
Output:
Error Redirection
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...