// context/auth.js
axios.interceptors.response.use(
function (response) {
// Do something before request is sent
return response;
},
function (error) {
// Do something with request error
let res = error.response;
if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
setAuth({
user: null,
token: "",
});
localStorage.removeItem("auth");
router.push("/signin");
console.log("LOGOUT FORCECULLY ======> ");
}
}
);
Now try generating jwt that expires in few seconds in signin controller. Try login, and go to admin dashboard. It will fail. Bring back your token expiry to '7d'
to make sure user can stay logged in for 7 day.
Move code from useAxios
hook to context/auth
It's easier to config axios in context and easily use axios anywhere rather than using useAxios
hook. So let's refactor code.
// context/auth.js
if (process.server) {
axios.defaults.baseURL = process.env.API;
axios.defaults.headers.common["Authorization"] = `Bearer ${auth.token}`;
} else {
axios.defaults.baseURL = process.env.NEXT_PUBLIC_API;
axios.defaults.headers.common["Authorization"] = `Bearer ${auth.token}`;
}
Now you can simply import and use axios in any page/component without using useAxios
hook we created earlier.