Redirecting back to starting page dynamically with nextjs-auth0

Hello, I’m trying to figure out how to redirect users dynamically after login based on the page they accessed the login form from.

In the app I’m currently trying to build, users can log in from “/” which is the home page, and from the navbar element in “/browse”. However, after logging in, it always redirects back to “/”, while I would like to redirect users to “/browse” or "/browse/[id] if that is where they began the login process from.

I’ve tried using https://community.auth0.com/t/redirecting-to-another-page-other-than-using-nextjs-auth0/66920 as a guide but this method only allows me to redirect to a pre-defined route. I would like to know how I could make the redirect URL dynamic.

SDK: nextjs-auth0
Version: “^1.6.1”
“next”: “11.1.2”

Edit: I’ve managed to find a solution for now by digging in to the req object and setting the returnTo value to “referer”.

import { handleAuth, handleLogin } from '@auth0/nextjs-auth0';

const getLoginState = (req, loginOptions) => {
    return {
        returnTo: req.headers.referer
    };
  };

export default handleAuth({
    async login(req, res) {
        try {
          await handleLogin(req, res, { getLoginState });
        } catch (err) {
            res.status(err.status ?? 500).end(err.message)
        }
      }
  });

I’m not seeing any obvious problems so far but I’m not entirely sure if this method has any drawbacks, so I would appreciate any feedback.

2 Likes

I believe from what I’m seeing in the code, if you add a returnTo value to the login link, that will be respected once the user logs in.

export default function SamplePage({ loggedIn }: Props) {

  const returnLink = `/api/auth/login?returnTo=${encodeURIComponent('/sample')}`;

  return (
    <>
      <h1>Server-side rendered page</h1>
      { loggedIn && 
      <p>
        This page is server-side rendered. The user is logged in.
      </p> }
      { !loggedIn &&
      <p>
        Please <a href={returnLink}>Login</a>.
      </p>
      }
    </>
  );
}
1 Like

Thanks for sharing that with the rest of community!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.