BFF patterns
Caching public data
defineCachedFunctionaccess: 'public'
Cache what is the same for everyone on a separate public route.
Protected routes must not be cached (see Scope and caching). Data that is the same for every visitor, like a product catalog, can still be cached: cache the data in a server function, not the response of a protected route.
server/utils/catalog.ts
export const getCatalog = defineCachedFunction(async () => {
return await $fetch<Product[]>(`${process.env.UPSTREAM_API_URL}/products`)
}, { maxAge: 60 * 10, name: 'catalog', getKey: () => 'all' })
server/api/catalog.get.ts
import { defineBffHandler } from '#bff-guard'
// Public and identical for everyone.
export default defineBffHandler(() => getCatalog(), { access: 'public' })
server/api/recommendations.get.ts
import { defineBffHandler } from '#bff-guard'
// Protected: the same cached catalog, filtered per user on every request.
export default defineBffHandler(async (event) => {
const catalog = await getCatalog()
return recommendFor(event.context.user!, catalog)
})
The guard still sends Cache-Control: private, no-store on the public route. If browsers or a CDN should cache it, set your own header in the handler; for public data that is safe.
export default defineBffHandler((event) => {
setResponseHeader(event, 'cache-control', 'public, max-age=600')
return getCatalog()
}, { access: 'public' })
Never do that on a protected route.