Search code examples
redux-toolkitrtk-query

RTK Query - how to access headers?


I have a working RTK Query api, reading from a backend that after a successful login was sending the token in the payload.

The backend API changed and now the token comes in the response's Authorization header and I can't figure out how to read it.

This is what I had before, on my reducer. I used a matcher for when the request was fulfilled and stored the token in the payload:

// reducer.js
const authReducer = createSlice({
  // ...
  extraReducers: (builder) => {
    builder.addMatcher(backendApi.endpoints.login.matchFulfilled, (state, { payload }) => {
      // save the payload.token in localstorage
    }
  }
});

It seems like getting the headers is not straightforward, and I actually can't find the Authorization header when trying to get the headers from the request:

// reducer.js
const authReducer = createSlice({
  // ...
  extraReducers: (builder) => {
    builder.addMatcher(backendApi.endpoints.login.matchFulfilled, (state, { meta }) => {
      const headers = meta.baseQueryMeta.response.headers; // this is a Headers {} object
      console.log(headers.get('content-type')); // prints application/json; charset=utf-8
      console.log(headers.get('authorization')); // prints undefined
    }
  }
});

When I try to debug and print all headers with console.log(Array.from(headers)) this is what I get:

[
  [
    "cache-control",
    "max-age=0, private, must-revalidate"
  ],
  [
    "content-type",
    "application/json; charset=utf-8"
  ]
]

It's super strange because the response has many more headers, but I can't access them.

Any guidance here? Maybe it's not possible to read the headers this way?

Thanks in advance!


Solution

  • You are doing everything right there. If headers.get('authorization') comes back as undefined I would assume it is a CORS issue preventing your JavaScript from accessing that.

    So your server would need to set the correct CORS headers, nothing to do on the client side.