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.
Need Some Axios Help?
Search fiverr for freelance Axios developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!