Set the Authorization Header with Axios

Apr 1, 2020

Setting request headers with Axios is easy. Here's how you can set the Authorization header, which is typically used to send access tokens to a server.

// Send a GET request with the authorization header set to
// the string 'my secret token'
const res = await axios.get('https://httpbin.org/get', {
  headers: {
    authorization: 'my secret token'
  }
});

HTTP headers are case-insensitive, so whether you use 'authorization' or 'Authorization' doesn't matter.

// Send a GET request with the authorization header set to
// the string 'my secret token'
const res = await axios.get('https://httpbin.org/get', {
  headers: {
    'Authorization': 'my secret token'
  }
});

The actual format of the authorization header depends on what auth strategy the server uses. For example, here's how you can use Basic Auth with Axios.

With POST Requests

Setting the authorization header is a little different with post(), because the 2nd parameter to post() is the request body. You should pass the headers as the 3rd parameter to post() and put().

// Send a POST request with the authorization header set to
// the string 'my secret token'. With `post()`, the 3rd parameter
// is the request options, not the 2nd parameter like with `get()`.
const body = {};
const res = await axios.post('https://httpbin.org/post', body, {
  headers: {
    'Authorization': 'my secret token'
  }
});

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Axios Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!