Axios - Add Bearer Token Authorization Header to HTTP Request
Below is a quick example of how to add a Bearer Token Authorization Header to an HTTP request in JavaScript using the axios
HTTP client which is available on npm.
Axios Bearer Token
This sends an HTTP POST request to the Test JSON API with the HTTP Authorization
header set to Bearer my-token
. The Test JSON API is a fake online REST API that includes that includes a /products
route that responds to POST
requests with the contents of the post body plus a new id
property and createdAt
date property.
After sending the request, the returned id
is written to the the #post-request-set-auth-header .product-id
element so it's displayed on the page.
Add Authorization Header
The auth header with bearer token is added to the request by passing a custom headers object ({ headers: { 'Authorization': 'Bearer my-token' } }
) as the third parameter to the axios.post()
method. The third param is the axios request config and it supports a bunch of different options for making HTTP requests including setting headers, a complete list is available at https://www.npmjs.com/package/axios#request-config.
// POST request using axios with bearer token authorization header
const element = document.querySelector('#post-request-set-auth-header .product-id');
const product = { name: 'Axios POST with Bearer Token' }; // request JSON body
const headers = { 'Authorization': 'Bearer my-token' }; // auth header with bearer token
axios.post('https://testapi.jasonwatmore.com/products', product, { headers })
.then(response => element.innerHTML = response.data.id);
See the Axios POST with Bearer Token on StackBlitz at https://stackblitz.com/edit/axios-post-with-bearer-token
More Axios Examples
For more Axios HTTP examples see Axios - HTTP POST Request Examples.
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Follow me on Twitter at https://twitter.com/jason_watmore
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some Axios Help?
Search fiverr to find help quickly from experienced Axios developers.