How to add headers to endpoints in RTK-Query Plugin?
Asked Answered
P

5

8

Trying to follow the rather sparse tutorial on the official page doesn't get me far.

I'm essentially trying to add a certain header based on the params of an api call, but am clueless how to configure the endpoints to do so.

Paviour answered 28/7, 2021 at 13:54 Comment(0)
E
14

Everything you return from you endpoint's query function will be passed as the first argument to your baseQuery. So if you are using fetchBaseQuery, you need to take a look at that.

Generally, a baseQuery created by fetchBaseQuery takes all the options that a normal fetch call would take - including a headers field.

So you would have something like

myEndpoint: build.query({
  query(args) {
    return {
      url: "foo",
      headers: { myHeader: args.blup }
    }
  }
})

should do the trick.

Generally, besides the "sparse tutorial", there are about 25 more documentation pages when you scroll down - but even then it's difficult to cover everythin, as RTK-Query is rather flexible.

You can read more on fetchBaseQuery in the docs here: https://redux-toolkit.js.org/rtk-query/api/fetchBaseQuery#using-fetchbasequery

Estellaestelle answered 29/7, 2021 at 8:19 Comment(0)
M
10

@phry response not working on my case. Checking docs, this make the trick, in my case to resolve a CORS problem:

baseQuery: fetchBaseQuery({ 
        baseUrl: '.....',
        prepareHeaders: (headers, { getState }) => {
            headers.set('Access-Control-Allow-Origin', '*')
            return headers
        }
    }),
Mcgaw answered 6/11, 2021 at 20:50 Comment(0)
A
2

You can use prepareHeaders. This worked for me.

createYourEndPoint: builder.mutation({
    query: (body) => ({
      url: `youEndPoint`,
      method: "POST",
      body,
      prepareHeaders: (headers) => {
        headers.set("Content-Type", "multipart/form-data")
          return headers
      },
    }),
    invalidatesTags: ["YourEndPointTag"],
}),
Adenectomy answered 19/1, 2023 at 6:20 Comment(0)
C
1

You can use prepareHeaders which is the second arg of fetchBaseQuery to customize the header as you need:

 `
  const baseQuery = fetchBaseQuery({
  baseUrl: "",
  prepareHeaders: (headers) => {
    headers.set("Content-type", "appliation/json"),
      headers.set("businessUnit", "EUS,MPS"),
      headers.set("auth-token", tokenService.getLocalAccessToken());
    return headers;
  },
});


 `
Chromatin answered 21/1, 2023 at 7:45 Comment(0)
R
1

Here is my own example assuming your query is getUserProfile and you are pulling the values for token, userId and your custom header keys from the query params.

getUserProfile: builder.query({
    query: (params) => ({
        url: `user/${params.userId}`,
        method: "GET",
        headers: {
            Authorization: `Bearer ${params.token}`,
            "your-custom-header": params.customKey
        },
    }),
}),
Rizas answered 16/9, 2023 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.