title: How to properly store access token in memory react
body: <p>I'm searching for a clean way to store my access token in React.</p>
  <ul>
  <li>First thing: I don't want to use local storage. I don't need to make my access token persistent since I can always refresh it.</li>
  <li>I also excluded a cookie since I want to prevent CSRF attacks. By storing the access token only in memory, in fact, the page needs to be loaded to get the token and authenticate requests (refresh token can be used only to refresh)</li>
  <li>I thought of using redux/context, however, the function calling the API is not a child of a component so I can't access the token from that. Furthermore, I don't want to pass the token as a parameter, since I want to keep decoupled the HTTP logic. Maybe there is a clean way to use it?</li>
  </ul>
  <p>After a bit of research, I found that using a global variable is a working &quot;cheat&quot; to obtain what I want. However, I was guessing if there was a clearer way to get the same result.</p>
  <pre><code>//token.js
  
  const access_token= &quot;&quot;;
  
  export const setAccessToken(token){
   access_token=token;
  }
  
  export const getAccessToken(){
   return access_token;
  }
  
  //NOTICE:
  // -ON LOGIN/REFRESH: I set the access token
  // -ON API CALLS: I get the access token and I add it to the header
  </code></pre>
  <pre><code>api.js
  
  const baseURL= &quot;http://my_base_url&quot;;
  
  const generateApiInterface = ()=&gt;{
      let headers : any= {
         
      };
      
      token=getAccessToken(); //HERE I NEED TO RETRIEVE MY ACCESS TOKEN
  
      if(token){
          headers={
              'Authorization': 'Token '+ token,
              ...headers //append other basic proprieties
          }
      }
  
      return axios.create({
          baseURL: baseURL,
          headers: headers
      });
  }
  
  const api = generateApiInterface();
  
  </code></pre>