Home > other >  NEXT.JS redirect not working in getServerSideProps
NEXT.JS redirect not working in getServerSideProps

Time:11-08

I'm currently developing a web application using NextJS, and in it I've created an authentication system using server-side rendering.

However it sometimes happens that in production (with the next start command) the redirect return of the function is not executed correctly and the user is not redirected to the login page when he is disconnected.

When this bug occurs, refreshing the page fixes the problem.

Here is the function in question

export const withAuthServerSideProps = (props?: WithServerSideAuthParams) => {
  return async (context: GetServerSidePropsContext) => {
    const {
      getServerSidePropsFunc,
      redirectCondition,
      requiredRole,
      route = '/signin',
    } = props || {};
    const response = await getUserData(context);
    const isAuthed = !!response?.data;
    let shouldRedirect;
    switch (redirectCondition) {
      case 'isInfluencer':
        shouldRedirect = isAuthed && response.data.role === Roles.INFLUENCER;
        break;
      case 'isAuthed':
        shouldRedirect = isAuthed;
        break;
      case 'isNotAuthed':
        shouldRedirect = !isAuthed;
        break;
      case 'noRedirect':
        shouldRedirect = false;
        break;
    }
    if (
      shouldRedirect ||
      (requiredRole && requiredRole !== response?.data?.role)
    ) {
      return {
        redirect: {
          destination: route,
          permanent: false,
        },
      };
    }
    //et on exécute la fonction du SSR s'il y en a une
    if (getServerSidePropsFunc) {
      try {
        const funcData = await getServerSidePropsFunc(context);
        return {
          props: {
            data: funcData,
            user: response?.data ?? null,
          },
        };
      } catch (e) {
        console.log(e);
        return {
          props: {
            data: null,
            user: response?.data ?? null,
          },
        };
      }
    }
    return {
      props: {
        user: response?.data ?? null,
      },
    };
  };
};

And here is how I call it in the app, so that it trigger using SSR

Exemple in a page called InfluencerPage

export const getServerSideProps = withAuthServerSideProps({
  getServerSidePropsFunc,
});

export default InfluencerPage;

The weird thing is that the network response from the service worker is wrong (it does not contain redirect)

Service Worker response image

But the other network response is correct, but the redirect is not triggered Network response

Maybe it's the cache from the service worker that is causing this but i don't know how to solve it

CodePudding user response:

The problem was indeed from the service worker cache policy, someone on Github answered me, here is the link : https://github.com/vercel/next.js/discussions/42405#discussioncomment-4046461

  • Related