After setting up Next-Auth and Axios for my NextJs project, I utilized the getSession() method from Next-Auth to set the axios header as follows:
export const ApiAuth = () => {
const instance = axios.create({
baseURL: API_URL,
});
instance.interceptors.request.use(async (request) => {
const session = await getSession();
console.log(session);
if (session) {
request.headers["Authorization"] = `Bearer ${session.tokens.accessToken}`;
}
return request;
});
instance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
console.log(`error`, error);
if (error.response.status === 401) {
console.log("Let refresh Here");
console.log("And update Next-Auth session data");
}
}
);
return instance;
};
However, I am unsure of how to update Next-Auth session data from the axios interceptor. Can anyone guide me on this?
I am considering creating an api endpoint like /api/auth/refresh that would handle updating the new access token and refresh token for Next-Auth, while also returning the new access token for axios.