Search code examples
reduxreact-reduxrtk-query

disable RTK Query prepareHeaders on specific endpoint


how to disable prepareHeaders on specific endpoint?, for example, i dont need authorization header on login or register endpoint, but on some endpoint i need authorization headers.

  export const backendService = createApi({
  reducerPath: 'backend',
  baseQuery: fetchBaseQuery({
    baseUrl: `${Endpoint}`,
    prepareHeaders: (headers, {getState}) => {
      const token = getState().auth.token;
      if (token) {
        headers.set('authorization', `Bearer ${token}`);
      }
      headers.set('Access-Control-Allow-Origin', '*');
      return headers;
    },
  }),
  tagTypes: ['Question', 'Questions'],
  endpoints: build => ({
    registerUser: build.mutation({ <------ skip prepareHeaders in register
      query: body => ({
        url: 'auth/local/register',
        method: 'POST',
        body,
      }),
    }),
    login: build.mutation({ <------- skip prepareHeaders on login
      query: body => ({
        url: 'auth/local',
        method: 'POST',
        body,
      }),
    }),
    getCategories: build.query({ <------ apply prepareHeaders 
      query: () => {
        return {
          url: 'categories'
        };
      },
    }),
    
  }),
});

Solution

  • The current beta for RTK 1.7 passes the endpointname to prepareHeaders, so if you try that you should be able to work around that.

    The BaseQueryApi and prepareheaders args now include fields for endpoint name, type to indicate if it's a query or mutation, and forced to indicate a re-fetch even if there was already a cache entry. These can be used to help determine headers like Cache-Control: no-cache.