Redirect on Sign In with Next Auth


When working on a Next.js application, you may want to redirect the user to a different page after they sign in.

The documentation is not clear on how to do this, so I will try to explain it here.

This is really helpful if you have Custom Sign In Page.

This is how the Next-Auth login page will look like...

import { getProviders, signIn } from "next-auth/react"

export default function SignIn({ providers }) {
  return (
    <>
      {Object.values(providers).map(provider => (
        <div key={provider.name}>
          <button onClick={() => signIn(provider.id)}>
            Sign in with {provider.name}
          </button>
        </div>
      ))}
    </>
  )
}

export async function getServerSideProps(context) {
  const providers = await getProviders()
  return {
    props: { providers },
  }
}

But we can use attach the callback function to the button onclick function and redirect the user to the page after sign in.

It should be like this. Replace the button with the below code.

<button
    onClick={() =>
        signIn(provider.id, {
        callbackUrl: `${window.location.origin}/hello`,
        })
    }
    >
Sign in with {provider.name}
</button>

Make sure to replace /hello with your page path where you want to redirect the user after sign in.