BFF patterns
Calling an upstream API
$fetchrouteRules.proxyserver/utils
Attach the user's token after the guard, never in middleware or routeRules.proxy.
The point of a BFF is that the browser never holds the upstream API's credentials. The handler adds them, after the guard has checked the user.
server/utils/upstream.ts
import type { H3Event } from 'h3'
const base = process.env.UPSTREAM_API_URL!
/** Call the upstream API as the verified user. Only use inside defineBffHandler. */
export function upstreamFetch<T>(event: H3Event, path: string, options: Parameters<typeof $fetch>[1] = {}) {
const user = event.context.user
if (!user) throw createError({ statusCode: 500, statusMessage: 'upstreamFetch outside the guard' })
return $fetch<T>(path, {
...options,
baseURL: base,
headers: { ...options.headers, authorization: `Bearer ${user.accessToken}` },
})
}
server/api/invoices.get.ts
import { defineBffHandler } from '#bff-guard'
export default defineBffHandler(async (event) => {
const invoices = await upstreamFetch<Invoice[]>(event, '/invoices', {
query: { status: getQuery(event).status },
})
// Return only what the page needs.
return invoices.map(({ id, total, dueAt }) => ({ id, total, dueAt }))
})
What not to do
nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
// ❌ Forwards the request before any handler runs. The guard never sees it.
'/api/invoices/**': { proxy: 'https://upstream.example.com/invoices/**' },
},
})
server/middleware/auth-header.ts
// ❌ Runs for every request, before the guard, including unauthenticated ones.
export default defineEventHandler((event) => {
event.node.req.headers.authorization = `Bearer ${process.env.UPSTREAM_TOKEN}`
})