How can I override the callback handler's redirect?


I’m trying to redirect the user to his previous page. To do that, I set a cookie before the login handler runs and read the cookie in the callback handler’s afterCallback. (see code below)

However, I always get redirected to the root of the page.

Note: nookies.destroy({ res: res2 }, 'authReturnUrl'); doesn’t work as well. It seems like the handleCallback blocks altering the response.

So, how can I redirect the user properly?

Thank you in advance, any help would be appreciated. :slight_smile:


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

export default handleAuth({
  login(req, res) {
    const returnUrl = req.query.returnUrl;

    if (returnUrl) {
      nookies.set({ res }, 'authReturnUrl', returnUrl, {
        maxAge: 3600,
        path: '/',

    return handleLogin(req, res);
  callback(req, res) {
    const { authReturnUrl } = nookies.get({ req });

    const returnUrl = authReturnUrl || '/';

    return handleCallback(req, res, {
      afterCallback(_, res2, session) {
        res2.setHeader('Location', returnUrl);

        nookies.destroy({ res: res2 }, 'authReturnUrl');

        // res2.redirect(returnUrl);
        // ^ doesn't work either

        return session;


  • SDK: @auth0/nextjs-auth0
  • SDK Version: 1.9.1
  • Next.js Version: 12.2.5

In the meantime, I’ve figured it out. There’s actually a handler option I’ve overlooked.

My current, working approach:

const getLoginState = (req: NextApiRequest, loginOptions: LoginOptions) => {
  const returnTo = req.query.returnTo;

  return { ...loginOptions, returnTo };

export default withSentry(
    login(req, res) {
      return handleLogin(req, res, { getLoginState });
    logout(req, res, options) {
      const returnTo = req.query.returnTo;

      return handleLogout(req, res, { ...options, returnTo });

@michaelschufi I’m glad you solved it.

I’m here trying to implement you approach, and I"m not making any headway.
Even the returnTo variable in logout is always returning null. Is there something that is missing from your post that could be helpful, maybe the middleware file.