NextJS - Login Redirect based on user role

Auth0 custom claims / actions flow: https://auth0.com/blog/adding-custom-claims-to-id-token-with-auth0-actions/

Basically, we have a post-login action that attaches roles to the idToken of the user who logged in. Though there are probably other ways you could go about adding roles / custom claims to the idToken of the user.

By setting a custom claim on the idToken of a user, you can access these claims in the session of an authenticated user. A bit more contrived example:

  • User lands on root URL https://my-app/ and goes through login flow
  • Upon successful authentication, user is redirected back to root URL https://my-app/
  • Using getServerSideProps in this root URL page, we are using getSession from the auth0/next-js SDK to check the custom claim.
  • Depending on the role that we checked in their session and that is available from setting the custom claims prior, we are redirecting from getServerSideProps to a different page.

The landing page is not a “dummy” page - it’s the page that hosts our login buttons and takes you through the Auth0 login flow. The user is redirected back here after successful authentication, but at this point they have a session so we can check their custom claims.

Basically the key is setting the user’s roles as custom claims in a separate flow (actions, rules, etc) and being able to check this role once they are authenticated. The rest is just Next.js.