4

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'
        };
      },
    }),
    
  }),
});

1 Answers1

4

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.

phry
  • 35,762
  • 5
  • 67
  • 81
  • Thanks @phry, but is there any documentation? – Nur Ilham Iskandar Nov 16 '21 at 21:53
  • That part of the new docs seems to still be missing, but you can take a look at the PR, is should be pretty straightforward what was added: https://github.com/reduxjs/redux-toolkit/pull/1656/files – phry Nov 17 '21 at 08:10