BFF patterns

Mobile apps and CLI tools

viaBearerAuthorization
One BFF for the browser and for clients that send Bearer tokens.

Native apps and command-line tools do not send Cookies or Origin. They send Authorization: Bearer <token>. Verify that token in verifyUser and say so with viaBearer: true; the guard then skips the same-origin check for writes.

server/auth/verify-user.ts
import { createError, getHeader } from 'h3'
import type { VerifyUser } from '@kurashina-design/nuxt-bff-guard'

export default (async (event) => {
  const authorization = getHeader(event, 'authorization')
  const bearer = /^Bearer[ \t]+(\S+)$/i.exec(authorization ?? '')?.[1]

  if (bearer) {
    event.context.user = await verifyAccessToken(bearer) // throws 401 when invalid
    return { viaBearer: true }
  }
  // Some other Authorization scheme: refuse instead of falling back to the Cookie.
  if (authorization !== undefined) throw createError({ statusCode: 401 })

  event.context.user = await verifySessionCookie(event)
  return { viaBearer: false }
}) satisfies VerifyUser
curl -X POST https://app.example.com/api/orders \
  -H 'Authorization: Bearer eyJhbGciOi...' \
  -H 'Content-Type: application/json' \
  -d '{"item":"tea","quantity":2}'

Rules

  • Return viaBearer: true only after you verified the token. The guard also checks that the header really is Bearer <one token>, so a wrong true for a Cookie request has no effect.
  • If both a Bearer token and a Cookie arrive, decide on one. The example above uses the token and ignores the Cookie.
  • Keep Bearer tokens out of URLs and query strings; the guard's logs record paths, and so do proxies.