How to Redirect Page from getServerSideProps or getStaticProps in Next.js

Published Mar 6, 2022  ∙  Updated May 2, 2022

How can we redirect to another page from the server-side in Next.js?

Redirect based on a condition

Suppose we need to query a database of users within getServerSideProps() in /pages/[id].jsx.

Each user has a dogs field that is an array containing the names of all dogs the user owns.

Let’s say we want to redirect to another page if the dogs property in returned user is empty.

export async function getServerSideProps({ params }) {
  try {
    const user = await prisma.user.findUnique({
      where: { id: params.id }
    });
    if (!user.dogs) {
      // Redirect to another page
    }
    return { props: { user } };
  } catch (e) {
    console.error('uh oh');
  }
}

Perform the redirect

We can redirect from the server-side by returning a redirect key.

The destination is the path we want to route to.

The permanent field will determine whether clients/search engines should cache the redirect forever. In this case, the redirect is temporary and should not be cached.

return {
  redirect: {
    permanent: false,
    destination: `/no-dogs`
  },
};

A quick caveat: this will only work on page components that have default exports (i.e. export default function Page() {}).

Let’s update our server-side function.

export async function getServerSideProps({ params }) {
  try {
    const user = await prisma.user.findUnique({
      where: { id: params.id }
    });
    if (!user.dogs) {
      return {
        redirect: {
          permanent: false,
          destination: `/no-dogs`
        },
      };
    }
    return { props: { user } };
  } catch (e) {
    console.error('uh oh');
  }
}

Note that this will work with getStaticProps() as well.