BFF patterns
Handling 401, 403 and 503 in the app
$fetch.createonResponseError
Sign out on 401, explain 403, retry on 503.
The guard gives each failure its own status, so the client can react correctly:
| Status | Meaning | Client reaction |
|---|---|---|
| 401 | no valid session | go to sign-in |
| 403 | signed in, but not allowed (or a cross-site write) | show a message, stay signed in |
| 503 | the auth backend failed | keep the session, retry later |
app/plugins/api.ts
export default defineNuxtPlugin(() => {
const api = $fetch.create({
retry: 2,
retryStatusCodes: [503],
retryDelay: 500,
async onResponseError({ response }) {
if (response.status === 401 && import.meta.client) {
await navigateTo('/signin')
}
},
})
return { provide: { api } }
})
pages/orders.vue
<script setup lang="ts">
const { $api } = useNuxtApp()
const { data: orders, error } = await useAsyncData('orders', () => $api('/api/orders'))
</script>
<template>
<p v-if="error?.statusCode === 503">The service is busy. Your data is safe; try again in a moment.</p>
<p v-else-if="error?.statusCode === 403">You do not have access to orders.</p>
<OrderList v-else :orders="orders" />
</template>
If your verifyUser turned every failure into 401, an outage of the auth provider would send every user to the sign-in page at once. That is why the guard answers 503 for unexpected errors.