Fetch - 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 fetch()
which comes built into all modern browsers.
Fetch Bearer Token
This sends an HTTP GET request to the Test JSON API with the HTTP Authorization
header set to a bearer token. The Test JSON API is a fake online REST API that includes a product details route (/products/{id}
), the returned product includes an id
and name
.
After the JSON data is fetched from the API the product name is written to the the #product-name
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 (e.g. { headers: { 'Authorization': 'Bearer my-token' } }
) as the second parameter to the fetch()
function. The second param contains the fetch request options and it supports a bunch of different options for making HTTP requests including setting headers, a complete list is available at https://developer.mozilla.org/docs/Web/API/fetch.
// GET request using fetch with bearer token authorization header
const element = document.querySelector('#product-name');
const headers = { 'Authorization': 'Bearer my-token' }; // auth header with bearer token
fetch('https://testapi.jasonwatmore.com/products/1', { headers })
.then(response => response.json())
.then(data => element.innerHTML = data.name);
See the Fetch Request with Bearer Token on StackBlitz at https://stackblitz.com/edit/fetch-request-with-bearer-token
More Fetch Examples
For more Fetch HTTP examples see Fetch - HTTP GET Request Examples.
Need Some Fetch Help?
Search fiverr for freelance Fetch 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!