How to navigate login when token expires in axios?
How to navigate login when token expires in axios?
refreshAuthLogic is a function that is called when a request fails due to an expired token. It attempts to refresh the token. If it fails to refresh the token, it removes the token from storage and redirects the user to the login page.axiosInstance.interceptors.request.use() is used to intercept requests before they are sent. You can modify the request config inside this function.const { dataCookie } = useCookie<ILoginResult>("user"); is using a custom hook useCookie to read the "user" cookie. The cookie is expected to have the shape of ILoginResult.if (dataCookie && (config as any)?.requestOptions?.withToken !== false) condition checks if the "user" cookie exists and if the request should be sent with a token. The (config as any)?.requestOptions?.withToken !== false part allows you to opt out of sending the token with a request by setting requestOptions.withToken to false in the request config.const decoded: IDecoded = jwtDecode(dataCookie.access_token); decodes the JWT token stored in dataCookie.access_token.if (decoded.exp * 1000 > Date.now()) condition checks if the token is expired. If it's not expired, it adds the token to the Authorization header of the request config.return config; returns the modified request config which will be used for the request.useCookie hook. Hooks can only be called inside of the body of a function component or a custom hook./login does not exist in your application. /login route and associate it with a login component. This can be done using the Route component from react-router-dom and placing it inside the Routes component in your main App component.LoginPage component will be rendered when the user navigates to /login. You need to replace LoginPage with your actual login component.<NavigateToResource /> component is used without a valid resource prop. This component is used to navigate to a specific resource page in your application.<NavigateToResource /> is not needed for this. You should be able to navigate to the login page directly using window.location.href = '/login' as long as the login route is defined in your application.<Route path="/login" element={<AuthPage type="login" />} /> is correctly placed within your <Routes> component and that the <BrowserRouter> is properly set up.refreshAuthLogicaxiosInstance.interceptors.request.use(
async (config: AxiosRequestConfig) => {
const { dataCookie } = useCookie<ILoginResult>("user");
if (dataCookie && (config as any)?.requestOptions?.withToken !== false) {
const decoded: IDecoded = jwtDecode(dataCookie.access_token);
if (decoded.exp * 1000 > Date.now()) {
(
config as any
).headers.Authorization = `Bearer ${dataCookie.access_token}`;
}
}
return config;
},
(error) => {
Promise.reject(error);
}
);axiosInstance.interceptors.request.use()const { dataCookie } = useCookie<ILoginResult>("user");ILoginResultif (dataCookie && (config as any)?.requestOptions?.withToken !== false)(config as any)?.requestOptions?.withToken !== falserequestOptions.withTokenconst decoded: IDecoded = jwtDecode(dataCookie.access_token);dataCookie.access_tokenif (decoded.exp * 1000 > Date.now())return config;Routereact-router-domAppLoginPageLoginPage<Route
path="/login"
element={
<AuthPage type="login" />
}
/><NavigateToResource /><NavigateToResource />window.location.href = '/login'<Route path="/login" element={<AuthPage type="login" />} /><Routes><BrowserRouter>const refreshAuthLogic = async (failedRequest: AxiosError) => {
const refreshToken = localStorage.getItem(TOKEN_REFRESH_KEY);
if (refreshToken) {
try {
const { data } = await axios
.post(`${API_BASE_URL}/token/refresh/`, {
refresh: refreshToken,
});
const { access, refresh } = data;
// save token to storage
axiosInstance.defaults.headers.common["Authorization"] = getAuthToken(access);
return Promise.resolve();
} catch {
// remove token from storage
localStorage.removeItem(TOKEN_KEY);
// redirect to login page
window.location.href = '/login';
return Promise.reject(failedRequest);
}
}
// remove token from storage
localStorage.removeItem(TOKEN_KEY);
// redirect to login page
window.location.href = '/login';
return Promise.reject(failedRequest);
};
createAuthRefreshInterceptor(
axiosInstance,
refreshAuthLogic,
{
pauseInstanceWhileRefreshing: true,
}
);axiosInstance.interceptors.response.use(
response => response,
error => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
// remove token from storage
localStorage.removeItem('token');
// redirect to login page
window.location.href = '/login';
return Promise.reject(error);
}
return Promise.reject(error);
}
);import { Refine, Authenticated } from "@refinedev/core";
import { NavigateToResource } from "@refinedev/react-router-v6";
import { Outlet, Route, Routes } from "react-router-dom";
import { LoginPage } from "./pages/login";
function App() {
return (
<Refine>
<Routes>
<Route
element={
<Authenticated fallback={<Outlet />}>
<NavigateToResource />
</Authenticated>
}
>
<Route path="/login" element={<LoginPage />} />
</Route>
</Routes>
</Refine>
);
}
export default App; import { BrowserRouter, Routes, Route } from "react-router-dom";
import { AuthPage } from "./pages/AuthPage"; // replace with your actual AuthPage import
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/login" element={<AuthPage type="login" />} />
{/* other routes... */}
</Routes>
</BrowserRouter>
);
}
export default App;