How to Redirect on Sign In and Sign Out with NextAuth

Published Apr 13, 2021

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.

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

// pages/signin.jsx
import { providers, signIn } from "next-auth/client";
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 providers() } };
}

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>

More JS Articles