verifyUser
verifyUser is a server file with a default export. The guard calls it for every protected request, before your handler.
type VerifyUser = (event: H3Event) => { viaBearer: boolean } | Promise<{ viaBearer: boolean }>
Return value
Return { viaBearer: true } only when you actually verified the user's own Bearer token from the Authorization header. Return { viaBearer: false } for Cookie sessions.
A verified Bearer request skips the same-origin check, because another site cannot make a browser attach your token. A Cookie is attached automatically, so Cookie-based writes are always checked.
Any other return value, for example undefined, is treated as a failed check.
Failures
How you fail decides the status code. The guard hides the error details from the client.
verifyUser throws | The guard answers |
|---|---|
an error with statusCode: 403 (a known user who may not use the app) | 403 |
an error with a 4xx statusCode, such as 401 (missing, invalid or expired credentials) | 401 |
an error without statusCode, or with a 5xx one (the auth backend is down) | 503 |
Throw createError({ statusCode: 401 }) for bad credentials, and let infrastructure errors through. If you turn an outage into a 401, a client that signs out on 401 will sign out every user whenever your auth provider has a bad minute.
import { createError, getCookie } from 'h3'
import type { VerifyUser } from '@kurashina-design/nuxt-bff-guard'
export default (async (event) => {
const token = getCookie(event, 'session')
if (!token) throw createError({ statusCode: 401 })
const session = await sessions.find(token) // a network error here becomes 503
if (!session) throw createError({ statusCode: 401 })
if (session.user.suspended) throw createError({ statusCode: 403 })
return { viaBearer: false }
}) satisfies VerifyUser
Storing the user for the handler
verifyUser may put what it learned on event.context, so handlers do not verify twice.
event.context.user = session.user
return { viaBearer: false }
import { defineBffHandler } from '#bff-guard'
export default defineBffHandler(event => event.context.user)
Type it once with a declaration file:
declare module 'h3' {
interface H3EventContext {
user?: { id: string, role: 'member' | 'admin' }
}
}
export {}
What belongs elsewhere
- App-wide access (is this user allowed to use the app at all?) belongs in
verifyUseras a 403. - Per-record access (may this user read order 42?) belongs in the handler.
- Development: without
verifyUser, protected routes answer 401. In production the build and the server refuse to start without it.