How to add headers to endpoints in RTK-Query Plugin?

Viewed 9268

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.

2 Answers

@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
        }
    }),

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

Related