Open In App

Next.js Redirects

Last Updated : 02 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Contact Page Redirection
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




/** @type {import('next').NextConfig} */
const nextConfig = {
    reactStrictMode: true,
}
  
module.exports = {
    redirects: async () => {
        return [
            {
                source: '/home',           // source path /home
                destination: '/contact',    // destination path
                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




/** @type {import('next').NextConfig} */
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




// Importing the useEffect Hook.
import { useEffect } from "react"
  
// Importing the Router.
import { useRouter } from "next/router"
  
// Error function
export default function Error() {
  
    // route object.
    const router = useRouter()
  
    // runs after every rendering.
    useEffect(() => {
  
        // Change the route /404 to /contact.
        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
Previous
Next
Share your thoughts in the comments

Similar Reads