How to redirect a user from the server or using the getServerSideProps() function in Next.js?

Published April 23, 2021

To redirect a user from the server-side or using the getServerSideProps() function in Next.js, you can use the redirect key with an object containing the destination property set to the path you want to redirect the user to and a permanent property with a boolean value in the return object from the getServerSideProps() function.

It can be done like this,

export async function getServerSideProps() {
  return {
    redirect: {
      destination: "/login",
      permanent: false,
    },
    props: {},
  };
}

For example, let's consider a Next.js page called /app, and we want to redirect the user to the page /login route if the user visits the /app page.

For that First let's create a Next.js Page called app.jsx like this,

// Next.js Page: /app
export default function App() {
  return <div>Hello World!</div>;
}

Then we can create the getServerSideProps() function which will be called whenever the user visits the /app route or page.

It can be done like this,

// Next.js Page: /app
export default function App() {
  return <div>Hello World!</div>;
}

// getServerSideProps() function
export function getServerSideProps() {
  // redirect logic here
}

Inside the function, we can redirect the user to a particular route using the redirect key with an object containing the destination property set to the path you want to redirect the user to, in our case, it is the /login route and the permanent property set to the boolean value false in the return object.

it can be done like this,

// Next.js Page: /app
export default function App() {
  return <div>Hello World!</div>;
}

// getServerSideProps() function
export function getServerSideProps() {
  return {
    redirect: {
      destination: "/login",
      permanent: false,
    },
    props: {},
  };
}

Now whenever the user visits the /app page or route, he will be redirected to the /login page.

NOTE: It is important to return the props object from the getServerSideProps() function even if you don't want any props to be passed to the page component.

This feature is only available in Next.js version 10 and up.

That's it! 😃

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter