Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 969
rikas Avatar asked Nov 08 '25 01:11

rikas


1 Answers

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.

like image 159
phry Avatar answered Nov 12 '25 17:11

phry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!