'RTK Query not passing headers

I have an RTK Query api like below

export const wireguardApi = createApi({
    reducerPath: 'wireguardApi',
    baseQuery: fetchBaseQuery({
        baseUrl: '/api/',
        prepareHeaders: (headers, { getState }) => {
            const token = (getState()).auth.access?.token;
            if (token)
                headers.set('authorization', `Bearer ${token}`);
            return headers;
        },
    }),
    endpoints: (builder) => ({
        getAllServers: builder.query({
            query: () => `wg/servers/`,
        }),
        obtainRefreshToken: builder.mutation({
            query: (formData) => ({
                url: `auth/token/obtain/`,
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: formData,
            }),
        }),
    }),
});

And call it on my page using

const { data: servers, error, isLoading, refetch, isFetching } = useGetAllServersQuery();

Yet, when the page loads, executing the query, it doesn't pass the authorization header. Why?



Solution 1:[1]

I also faced the same issue

The problem is that access token is unavailable when the query starts Make sure that adding the token executes before making queries. (You can check the sequence in Redux DevTools)

ScreenShot of ReduxDevTools

Here addFromLocalStorage executes before starting the query

Earlier I was using react useEffect to dispatch the action. Then the query started before adding the token

What then I did was

store.dispatch(addFromLocalStorage())

in main.js or index.js where you've rendered your App.

This makes sure that access token is added before executing any query in your React App.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1