BFF patterns
Testing the protection
@nuxt/test-utilsvitest
An end-to-end test that every protected route refuses anonymous calls.
The build already fails when a route forgets defineBffHandler. A short end-to-end test checks the rest: that verifyUser really rejects anonymous calls and that public routes stay public.
test/bff.test.ts
import { fileURLToPath } from 'node:url'
import { $fetch, fetch, setup } from '@nuxt/test-utils/e2e'
import { describe, expect, test } from 'vitest'
await setup({ rootDir: fileURLToPath(new URL('..', import.meta.url)) })
const protectedRoutes = ['/api/orders', '/api/me', '/api/invoices']
const publicRoutes = ['/api/health', '/api/catalog']
describe('anonymous requests', () => {
test.each(protectedRoutes)('%s answers 401', async (path) => {
const response = await fetch(path)
expect(response.status).toBe(401)
expect(response.headers.get('cache-control')).toBe('private, no-store')
})
test.each(publicRoutes)('%s stays public', async (path) => {
expect((await fetch(path)).status).toBe(200)
})
})
test('Cookie writes from another site are refused', async () => {
const response = await fetch('/api/orders', {
method: 'POST',
headers: { 'cookie': 'session=test-user', 'sec-fetch-site': 'cross-site' },
})
expect(response.status).toBe(403)
})
test('a signed-in user gets data', async () => {
const orders = await $fetch('/api/orders', { headers: { cookie: 'session=test-user' } })
expect(orders).toBeInstanceOf(Array)
})
For the signed-in case, let a test-only verifyUser accept a fixed Cookie. Point the option at it only in the test build:
nuxt.config.ts
bffGuard: {
verifyUser: process.env.VITEST ? './test/verify-user.ts' : './server/auth/verify-user.ts',
}
Make sure VITEST is never set when you build for production, or use a separate Nuxt config for tests.