Can't figure out how to switch from access_token
to refresh_token
in fetchBaseQuery
馃槥
#4180
-
Following the example in docs, I've customized it to follow my needs, the thing is that no matter what I do the headers I send via RTK Query keeps using the const mutex = new Mutex();
const baseQuery = fetchBaseQuery({
baseUrl: `${process.env.NEXT_PUBLIC_BACKEND_URL}`,
credentials: "include",
prepareHeaders: (headers, { getState, endpoint }) => {
const state = getState() as RootState;
const token = state.auth.access_token;
if (token) {
headers.set("Authorization", `Bearer ${token}`);
}
return headers;
},
});
const baseQueryWithReauth: BaseQueryFn<
string | FetchArgs,
unknown,
FetchBaseQueryError
> = async (args, api, extraOptions) => {
await mutex.waitForUnlock();
let result = await baseQuery(args, api, extraOptions);
if (result.error && result.error.status === 401) {
// checking whether the mutex is locked
if (!mutex.isLocked()) {
const release = await mutex.acquire();
try {
const state = api.getState() as RootState;
const refreshResult = await baseQuery({
url: "/auth/refresh",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${state.auth.refresh_token}`,
},
}, api, extraOptions);
if (refreshResult.data) {
// const state = api.getState() as RootState;
api.dispatch(setAuth({ ...refreshResult.data }));
// retry the initial query
result = await baseQuery(args, api, extraOptions);
} else {
// api.dispatch(logout());
}
} finally {
// release must be (called once the mutex should be released again.
release();
}
} else {
// wait until the mutex is available without locking it
await mutex.waitForUnlock();
result = await baseQuery(args, api, extraOptions);
}
}
return result;
}; I even tryed to swap the token inside const baseQuery = fetchBaseQuery({
baseUrl: `${process.env.NEXT_PUBLIC_BACKEND_URL}`,
credentials: "include",
prepareHeaders: (headers, { getState, endpoint }) => {
const state = getState() as RootState;
const token =
endpoint === "/auth/refresh"
? state.auth.refresh_token
: state.auth.access_token;
if (token) {
headers.set("Authorization", `Bearer ${token}`);
}
return headers;
},
}); I also read this discussion but it is not applicable to my use case because he sent the token via I thought of not customize the Please help me out because I am not able to figure it out. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Maybe add something like |
Beta Was this translation helpful? Give feedback.
Your
baseQueryWithReauth
calls the otherbaseQuery
, which then sets theAuthorization
header.Maybe add something like
if (!headers.has("Authorization"))
before setting it?