Next.js Server Side Redirect

Using getServerSideProps() to redirect user on server side in Next.js.

Routing and redirecting in Next.js can be trivial on the client side, but doing this on the server side may not be as straight forward. Previously you would need to determine if the request was client side or server side in getInitialProps then manage the response by setting the correct headers and manually writing out the http response object. Now as of Next.js 10+ they have introduced an easy way to do this.

Redirecting Server Side with Next.js

The idea is to return an object with a redirect key in getServerSideProps:

// HelloWorld.js
export default function HelloWorld() {
  return <p>Hello World</p>
}

export async function getServerSideProps(ctx) {
  // Custom function to determine user authentication
  const isAuthenticated = await getUser(ctx)

  if (!isAuthenticated) {
    return {
      redirect: {
        permanent: false, // determines 308/307 status response code
        destination: "/", // where to redirect user
      },
    }
  }
  return {}
}

This redirect object allows you to set a destination and whether it is a permanent redirect or not. destination is the new route that the user will be redirected to. permanent will determine if the redirect will use a 308 status response code or 307 status response code.

Have some feedback on this post? .