BFF の設計パターン

上流の API を呼ぶ

$fetchrouteRules.proxyserver/utils
利用者のトークンはガードの後で付けます。ミドルウェアや routeRules.proxy では付けません。

BFF の要点は、ブラウザーに上流の API の資格情報を持たせないことです。ガードが利用者を確かめた後で、ハンドラーがそれを付けます。

server/utils/upstream.ts
import type { H3Event } from 'h3'

const base = process.env.UPSTREAM_API_URL!

/** 確かめた利用者として上流の API を呼ぶ。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 invoices.map(({ id, total, dueAt }) => ({ id, total, dueAt }))
})

やってはいけないこと

nuxt.config.ts
export default defineNuxtConfig({
  routeRules: {
    // ❌ どのハンドラーよりも先に転送する。ガードはこのリクエストを見ない
    '/api/invoices/**': { proxy: 'https://upstream.example.com/invoices/**' },
  },
})
server/middleware/auth-header.ts
// ❌ 認証されていないものも含め、すべてのリクエストでガードより先に動く
export default defineEventHandler((event) => {
  event.node.req.headers.authorization = `Bearer ${process.env.UPSTREAM_TOKEN}`
})