In my Next.js 14 application, I have set up axios interceptors to handle errors. However, I need assistance in logging out the user and redirecting them to the '/login' page if any error occurs. Below is the code snippet for the interceptors:
axiosInstance.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config;
let session;
if (typeof window !== "undefined") {
// session for client component
session = await getSession();
} else {
// session for server component
session = await getServerSession(authOptions);
}
if (
error.response?.status === 401 ||
error.message === "Request failed with status code 401"
) {
if (session && session.refreshToken) {
try {
const refreshResponse = await axios.post(
`${BASE_URL}/v1/auth/refresh-token`,
{
refreshToken: `${session.refreshToken}avc`,
}
);
const { data } = refreshResponse;
console.log({ data });
if (data.access_token) {
if (originalRequest) {
originalRequest.headers.Authorization = `Bearer ${data.access_token}`;
return await axios(originalRequest);
}
} else {
// code to logout user
}
} catch (e) {
// code to logout user
}
} else {
// code to logout user
}
}
return Promise.reject(error);
}
);
While attempting to implement signOut
from next-auth/react
, I discovered it only works for client-component requests and not for server-component requests.