Issue
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);
}
Solution
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 {
//...
}
}
//...
}
Answered By - adrianmanduc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.