How to Redirect on Sign In and Sign Out with NextAuth


Suppose we have our custom, branded login page in next-auth, and we want to redirect to a protected page after logging in or to the homepage after logging out.

The code snippets in this article require NextAuth.js v4. Check out how to upgrade to version 4.

Here is our custom login page stolen from the next-auth docs.

// pages/signin.jsx
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) {
  return { props: { providers: await getProviders() } };
}

We can force a redirect after login using the second argument of signIn().

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

The same can be done with signOut().

// components/header.jsx
<button
  onClick={() =>
    signOut({
      callbackUrl: `${window.location.origin}`
    })
  }
>
  Sign out
</button>