'Next.js Redirects: redirects key in next.config.js vs. redirect object in getServerSideProps()

Let's just say I want to redirect my index page to the about page in Next.js. It seems like I have 2 options:

1. Adding the redirects key in next.config.js

module.exports = {
  async redirects() {
    return [
      {
        source: '/',
        destination: '/about',
        permanent: true,
      },
    ]
  },
}

2. Returning the redirect object inside the getServerSideProps() function

// pages/index.js
export async function getServerSideProps() {
  return {
    redirect: {
      destination: '/about',
      permanent: true,
    },
  };
};

What is the difference between these 2 options?



Solution 1:[1]

According to your logic, they're the same in terms of functionality, but redirect on your page pages/index.js will have more flexibility and more customization. For example, you want to redirect to another page conditionally like below

// pages/index.js
export async function getServerSideProps() {
  const value = true; //receive data from APIs

  //if value is true, redirect to `/help` instead of `/about`
  if(value) {
    return {
      redirect: {
        destination: '/help',
        permanent: true,
      },
    };
  }

  //TODO: You can add your logic here before redirection

  return {
    redirect: {
      destination: '/about',
      permanent: true,
    },
  };
};

You cannot achieve that logic with redirects() under next.config.js. You can imagine that it's like configurations being only applied once without the complicated logic requirement.

You can consider these use cases:

  • If you don't want to have complicated routing logic and just use them as one-time setups - Use redirects() in next.config.js
  • If you have some logic to handle routings in pages and it's relied on external resources - Use redirect in pages themselves

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1