Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Next.js, How to Redirect page in axios interceptor?

I want to redirect page in axios interceptor.

However, when server-side rendering, I can't access to server side context in axios interceptor. So I try to use next/router. but it only works in client side.

How can I this?

Below is the function executed in the axios interceptor.

// customAxios.ts
const customAxios = axios.create();

customAxios.interceptors.response.use((response) => response, responseErrorHandler);
// responseErrorHandler.ts
const responseErrorHandler = (error: AxiosError): Promise<AxiosError> => {
  if (error.response) {
    if (error.message === TIMEOUT_MESSAGE) {
      if (typeof window === 'undefined') {
         // Redirect to /503 page in server side rendering
      } else {
        window.location.href = '/503';
      }
    }
  }

  return Promise.reject(error);
}
like image 613
Reynor Avatar asked Sep 20 '25 00:09

Reynor


1 Answers

It is hard to give an answer without seeing your actual implementation of getServerSideProps or getStaticProps, but this might help. Your interceptor should probably throw a custom error you can identify in those methods and then use Next.js redirects

// responseErrorHandler.ts
const responseErrorHandler = (error: AxiosError): Promise<AxiosError> => {
  if (error.response) {
    if (error.message === TIMEOUT_MESSAGE) {
      if (typeof window === 'undefined') {
         throw new CustomError(); //Throw custom error here
      } else {
        window.location.href = '/503';
      }
    }
  }

  return Promise.reject(error);
}

And then, in the data fetching methods (needs to be adapted to Typesctipt):

export async function getServerSideProps(context) {

  try {
    await customAxios.get(...)
  } catch(e) {
    if (e instanceof CustomError){
      return {
        redirect: {
          destination: '/503'
        }
      };
    } else { 
        //...
    }
  }

  //...
}
like image 64
adrianmanduc Avatar answered Sep 22 '25 13:09

adrianmanduc