Search code examples
reactjsexpressfetch-api

Setting authorization header in Fetch API


I have a Node/Express backend and I'm consuming the API with a React Client. I want to be able to set the authorization header after a user is signed up. This ensures that subsequent requests are sent with the authorization header.

I can see how it's done in Axios here and how to retrieve the authorization header in Fetch here

Is it possible to do this with Fetch API and how?


Solution

  • As far as I know, there's no way to use default options/headers with fetch. You can use this third party library to get it to work, or set up some default options that you then use with every request:

    // defaultOptions.js
    const defaultOptions = {
      headers: {
        'Authorization': getTokenFromStore(),
      },
    };
    
    export default defaultOptions;
    

    Then use the default options like:

    import defaultOptions from './defaultOptions';
    
    // With default options:
    fetch('/auth', defaultOptions);
    
    // With additional (non-default) options:
    fetch('/auth', { ...defaultOptions, body: JSON.stringify(additionalData) });