Home > Enterprise >  use router from getServerSideProps
use router from getServerSideProps

Time:01-19

what I want to achieve is to redirect the user to the login page if his token has been expired.

inside getServerSideProps I send a get request to the server to recive some data if I get the data I want to provide this data as props for my page but if it's Unauthorized I want to redirect the user to the login pagae but it seems that I can't call useRouter inside getServerSideProps when I try I get this error

React Hook "useRouter" is called in function "getServerSideProps" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".eslint

this is my code

export async function getServerSideProps({ req, params }) {
  const token = await getToken({ req });
  const userId = params.userId;
  const router = useRouter(); // the line with the error
  let result = {};

   await axiosPrivateWithToken(accessToken)
    .get(`/user/${userId}`)
    .then((res) => {
      result = res.data;
    })
    .catch((error) => {
      if(error.response.status == 401) {
      here where I want to use router.push('/login')
     }
    });

}

is it possible ? if so how ?!! thank you for your time

CodePudding user response:

you can only call hooks from function component or a custom React hook function as it is mentioned in the error, therefore there is no way to use next-router from inside getServerSidePros.

However you can achieve this by the redirect key object

 .then((res) => {
      result = res.data;
  })
  .catch((error) => {
      if(error.response.status == 401) result = 'redirection'
  });

then based on the value of result you decide what to do :

if(result === 'redirection') {
return {
 redirect: {
   destination: "/login",
   permanent: false,
 }};
}else {
// what you are used to do
}

CodePudding user response:

It's not possible to use useRouter inside getServerSideProps. Instead, you can return axiosPrivateWithToken response and receive it as props on your component and put it inside useEffect and handle your redirection logic there.

CodePudding user response:

We can direct users to the login page if "axiosPrivateWithToken" fails.

export async function authenticatedUsers(userId) {
  try {
    const response = await axiosPrivateWithToken(accessToken).get(`/user/${userId}`)
    const result = response.data;

    return result;
  } catch (error) {
    console.log(error);
    return null;
  }
  return false;
}

export const getServerSideProps: GetServerSideProps = async ({req, params}) => {
  const token = await getToken({ req });
  const userId = params.userId;

  let result = await authenticatedUsers(userId);

  if (result == null) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    };
  }
  return {
    props: {
        result
    }
  };
};
  • Related