title: How can I store a JWT in cookies using Axios?
body: <p>I am using JWT in my React application and Axios to handle API calls. I am looking for a way to store the token in cookies so that I am not redirected to login again every time the browser is refreshed. </p>
  
  <p>Here is my setup for Axios and my login call:</p>
  
  <pre><code>let authToken = null; 
  
  const axios = axiosAPI.create({
      baseURL: baseURL
  });
  
  // User login
  export const loginUser = (data) =&gt; {
      return new Promise((resolve, reject) =&gt; {
          axios.post(`${baseURL}/jwt-auth/v1/token`, data)
              .then((res) =&gt; {
                  authToken = res.data.token;
  
                  // Adds the token to the header
                  axios.defaults.headers.common.Authorization = `Bearer ${authToken}`;
  
                  resolve(res.data);
              })
              .catch((error) =&gt; {
                  reject(error);
              });
      });
  };
  </code></pre>
  
  <p>I am not certain where I should be setting the cookie and how to set it?</p>
  
  <p>EDIT:</p>
  
  <p>I have rewritten my code using js-cookie so it looks like the comment.</p>
  
  <pre><code>import axiosAPI from 'axios';
  import Cookies from 'js-cookie';
  
  let authToken = null;
  
  const axios = axiosAPI.create({
      baseURL: `${baseURL}`
  });
  
  // Check if user is logged in.
  (function () {
      if (Cookies.get('token') === null) {
          // This means that there's no JWT and no user is logged in.
          axios.defaults.headers.common.Authorization = null;
      } else {
          // This means that there's a JWT so someone must be logged in.
          axios.defaults.headers.common.Authorization = `Bearer ${authToken}`;
      }
  }());
  
  // User login
  export const loginUser = (data) =&gt; {
      return new Promise((resolve, reject) =&gt; {
          axios.post(`${baseURL}/jwt-auth/v1/token`, data)
              .then((res) =&gt; {
                  authToken = res.data.token;
  
                  Cookies.setToken('token', authToken);
  
                  // Adds the token to the header
                  axios.defaults.headers.common.Authorization = `Bearer ${authToken}`;
  
                  resolve(res.data);
              })
              .catch((error) =&gt; {
                  reject(error);
              });
      });
  };
  </code></pre>
  
  <p>However this prevents me from logging in at all and I get the error 'wrong number of segments'. Any idea why this isn't working?</p>