N
Nuxt3mo ago
dankell.

Nuxt Auth Utils and external bearer tokens

We are currently in the process of moving an internal site from Vue 2 to Vue 3 and are likely using Nuxt as the final destination. I'm currently looking at how the Nuxt application will communicate with the existing API server (Hapi.js), and more importantly how that server will authenticate requests once users have been authenticated on the frontend I am at the point where nuxt-auth-utils is retrieving an authenticated user and displaying the { user } details on the front-end using useUserSession I can also confirm that the backend auth route is receiving a Bearer token from the Microsoft server. What I don't understand is how I use that with $fetch when making calls to out API server
5 Replies
kapa.ai
kapa.ai3mo ago
Hi @dankell.. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To send the Bearer token (retrieved via nuxt-auth-utils and available in your user session) with $fetch requests to your external API server, you should attach the token to the Authorization header of your requests. A recommended approach in Nuxt is to create a custom $fetch instance via a Nuxt plugin. This allows you to automatically include the Bearer token from your session in all outgoing API requests. Here’s how you can do it: 1. Create a Nuxt plugin for your custom $fetch instance:
// plugins/api.ts
export default defineNuxtPlugin((nuxtApp) => {
const { session } = useUserSession()

const api = $fetch.create({
baseURL: '<https://your-api-server.com',> // Replace with your API base URL
onRequest({ options }) {
if (session.value?.token) {
options.headers = {
...options.headers,
Authorization: `Bearer ${session.value.token}`
}
}
}
})

return {
provide: {
api
}
}
})
// plugins/api.ts
export default defineNuxtPlugin((nuxtApp) => {
const { session } = useUserSession()

const api = $fetch.create({
baseURL: '<https://your-api-server.com',> // Replace with your API base URL
onRequest({ options }) {
if (session.value?.token) {
options.headers = {
...options.headers,
Authorization: `Bearer ${session.value.token}`
}
}
}
})

return {
provide: {
api
}
}
})
2. Use your custom $api in components or composables:
<script setup>
const { $api } = useNuxtApp()
const { data } = await useAsyncData('userData', () => $api('/your-endpoint'))
</script>
<script setup>
const { $api } = useNuxtApp()
const { data } = await useAsyncData('userData', () => $api('/your-endpoint'))
</script>
This setup ensures that every request made with $api will include the Bearer token from your authenticated session in the Authorization header, allowing your Hapi.js backend to authenticate the user properly. For more details and examples, see the official Nuxt documentation on Custom useFetch in Nuxt and Use Custom Fetch Composable. If you want to use this logic with useFetch or useAsyncData, you can also create a composable that injects your custom $fetch instance, as shown in the docs.
In summary:
- Retrieve the token from your session (e.g., via useUserSession). - Attach it to the Authorization header in your custom $fetch instance. - Use this instance for all API calls to ensure the token is sent automatically.
If you need to handle token refresh or 401 errors, you can also add an onResponseError handler in your plugin to manage those scenarios as shown in the documentation. Custom useFetch in Nuxt ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@602890303753682944> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
dankell.
dankell.OP3mo ago
@kapa.ai It's not clear how the token is attached to the session object
kapa.ai
kapa.ai3mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I'm sorry, but the knowledge sources do not explicitly describe how the Bearer token is attached to the session object when using nuxt-auth-utils. The documentation and examples show how to use useUserSession to access the session and user data, and how to send the token in the Authorization header for API requests, but they do not detail the internal mechanism for how the token is stored in the session. What is clear from the Sessions and Authentication recipe is that session data (such as user information) is set on the server using helpers like setUserSession, and then accessed on the client with useUserSession. However, the specific process for storing external tokens (like a Microsoft Bearer token) in the session is not documented in the provided sources. If you need to ensure the token is available in the session, you may need to customize your login API route to explicitly store the token in the session object when authenticating the user, but the exact implementation details are not covered in the current documentation or examples provided in the knowledge sources. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3mo ago
<@602890303753682944> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?