Home > Enterprise >  Next.js: redirect loads the site, but doesn't redirect the user
Next.js: redirect loads the site, but doesn't redirect the user

Time:12-01

I have a Next.js serverless logout function:

import magic from './magic';
import { withSessionRoute } from './sessions';

export default withSessionRoute(async function logoutHandler(
  request,
  response,
) {
  try {
    if (request.method === 'GET') {
      if (request.session.user) {
        await magic.users.logoutByIssuer(request.session.user.issuer);
      }

      request.session.destroy();

      return response.redirect(302, '/').end();
    }

    const message = 'This endpoint only supports the GET method.';
    return response.status(405).json({ message });
  } catch (error) {
    console.log(error);
  }
});

The important part is response.redirect(302, '/').end();.

I trigger this in a button's onClick handler:

const logoutRoute = '/api/logout';

const logoutRequest = () => axios.get(logoutRoute);

async function handleLogoutClick() {
  return await logoutRequest();
}

// ... later

<button onClick={handleLogoutClick}>
  {t('user-authentication:logout')}
</button>

However, when the request resolves, Next.js loads /, but it doesn't redirect in the browser.

$ yarn dev
yarn run v1.22.17
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from /Users/janhesters/dev/my-proj/.env.local
event - compiled client and server successfully in 943 ms (217 modules)
wait  - compiling /home (client and server)...
event - compiled client and server successfully in 173 ms (594 modules)
wait  - compiling /api/logout...
event - compiled client and server successfully in 96 ms (612 modules)
wait  - compiling / (client and server)...
event - compiled client and server successfully in 56 ms (620 modules)
wait  - compiling...
event - compiled successfully in 76 ms (58 modules)

enter image description here

What is missing so that the frontend actually redirects to /?

CodePudding user response:

So in my specific case Router.push was successfully happening.

Something in getServerSideProps was causing the instant redirect back to login.

export const getServerSideProps = withIronSessionSsr(
  async function getServerSideProps({ req, locale }) {
    const user = req.session.user;

    if (!user) {
      return {
        redirect: {
          destination: '/login',
          permanent: false,
        },
      };
    }

    return {
      props: {
        user: mapUserSessionToUserProfile(user),
        ...(await serverSideTranslations(locale, [
          'common',
          'home',
          'user-authentication',
        ])),
      },
    };
  },
  sessionOptions,
);

My issue is that request.session.user is undefined, but that's a separate issue.

  • Related