Vue 3 - 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 Vue 3 using fetch()
which comes built into all modern browsers.
Vue 3 Bearer Token
This sends an HTTP GET request to the Test JSON API with a couple of headers, the HTTP Authorization
header with a bearer token and a custom header My-Custom-Header
. 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 it is assigned to the product
ref variable and rendered in the component template.
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.
<script setup>
import { ref } from 'vue';
const product = ref(null);
// GET request using fetch with set headers
const headers = {
'Authorization': 'Bearer my-token',
'My-Custom-Header': 'foobar'
};
fetch('https://testapi.jasonwatmore.com/products/3', { headers })
.then(response => response.json())
.then(data => product.value = data);
</script>
<template>
<div class="card text-center m-3">
<h5 class="card-header">GET Request with Set Headers</h5>
<div class="card-body">Product name: {{product?.name}}</div>
</div>
</template>
See the Vue 3 request with bearer token on StackBlitz at https://stackblitz.com/edit/vue-3-http-get-request-examples?file=src%2FGetRequestSetHeaders.vue
More Vue 3 Examples
For more Vue 3 HTTP examples see Vue 3 - HTTP GET 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 Vue 3 Help?
Search fiverr to find help quickly from experienced Vue 3 developers.