Reputation: 2165
I basically have a back end api that I'm hitting with a React SPA. I have a username password auth that assigns a key to the user when the client is authenticated. The key needs to be passed as a header on every http request.
I want to be able to pass this authentication header on EVERY api request.
Is there an easy way to do this? I.e. someway to have a top level React component that handles passing this on every page request?
I assume this is a common problem for SPA and the solution is out there. Any guidance would be much appreciated.
Upvotes: 0
Views: 1862
Reputation: 16246
Actually, it's not related with React or react-router. It depends on the HTTP request library -- after authenticated, all you need to do is config the library and make it send the key
header every time.
If jQuery is used to send the API request, the code would be:
// get key from successful authentication response
$(document).ajaxSend(function(event, jqxhr) {
jqxhr.setRequestHeader('KEY', key);
});
If axios is used to send the API request, the code would be:
axios.defaults.headers.common['KEY'] = key;
If something else is used to send the API request, you can check the library's document and make the same config operation.
Upvotes: 0
Reputation: 406
The way I do this is to store the key in localStorage
. So, when you get the key, do something like:
localStorage.setItem('key', key);
Then, you can retrieve it:
localStorage.getItem('key');
Upvotes: 1