Search code examples
javascriptreactjsnext.jsserver-side-rendering

Return redirect not working in GetServerSideProps


I want to redirect the user to home page if '_SYS_USER_AUTH' toke is not present and also if it is not valid. If I am deleting the token and refreshing the page, redirect is working fine whereas while I am checking if the token is valid (i.e., api response is 200) its not working. I want to redirect if the repsonse is anything other than 200. I have tried console.log inside if condition and it's completely fine.

export async function getServerSideProps({ req }) {
  if (!req?.cookies?._SYS_USER_AUTH) {
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  } else {
    const etoken = req.cookies._SYS_USER_AUTH;
    const token = atob(etoken);

    fetch("http://api.abc.com/customers/me", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    }).then((response) => {
      if (response.status !== 200) {
        console.log(response.status !== 200, reponse.status) //Prints true, 401
        return {
          redirect: {
            permanent: false,
            destination: "/",
          },
        };
      }
    });
  }

  return {
    props: {}, // will be passed to the page component as props
  };
}

Solution

  • Try to execute the code sequentially with await:

    export async function getServerSideProps({ req }) {
      if (!req?.cookies?._SYS_USER_AUTH) {
        return {
          redirect: {
            destination: '/',
            permanent: false,
          },
        };
      }
    
      const etoken = req.cookies._SYS_USER_AUTH;
      const token = atob(etoken);
    
      const response = await fetch('http://api.abc.com/customers/me', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (response.status !== 200) {
        return {
          redirect: {
            permanent: false,
            destination: '/',
          },
        };
      }
    
      return {
        props: {}, // will be passed to the page component as props
      };
    }