BFF patterns
SSR and server functions
useFetchuseRequestFetchserver/utils
Call your own API during server rendering, or skip HTTP entirely.
During server rendering, useFetch('/api/orders') calls your API inside the same server. That call goes through the guard like any other, so it needs the user's Cookie.
Forward the Cookie
useFetch forwards the incoming request's headers for you. For a plain $fetch in a component, use useRequestFetch():
pages/orders.vue
<script setup lang="ts">
// useFetch forwards the user's Cookie during SSR.
const { data: orders } = await useFetch('/api/orders')
// For a manual call, take the request-bound fetch.
const requestFetch = useRequestFetch()
const { data: profile } = await useAsyncData('profile', () => requestFetch('/api/me'))
</script>
A bare $fetch('/api/me') during SSR does not carry the Cookie, and the guard answers 401.
Skip HTTP inside the server
When server code needs data, call a function instead of your own HTTP route. There is no second trip through the guard, and no internal route that could be called from outside.
server/utils/orders.ts
export async function listOrders(userId: string) {
return await db.order.findMany({ where: { userId } })
}
server/api/orders.get.ts
import { defineBffHandler } from '#bff-guard'
export default defineBffHandler(event => listOrders(event.context.user!.id))
server/tasks/send-reminders.ts
// A Nitro task: no user, no HTTP, no guard needed.
export default defineTask({
meta: { description: 'Send order reminders' },
async run() {
for (const user of await usersWithOpenOrders()) {
await sendReminder(user, await listOrders(user.id))
}
return { result: 'ok' }
},
})
Do not create "internal" HTTP routes that skip the user check because only your server calls them. Anything under server/api is reachable from the internet.