Security modules
A frontend on another origin
nuxt-securitycorsHandlerviaBearer
CORS with nuxt-security for a separate app that calls the BFF with Bearer tokens.
A BFF is usually called by its own pages. When a second frontend on another origin (say https://admin.example.com) must call it, use Bearer tokens and CORS. Cookie-based writes from another origin are rejected by the same-origin check, by design.
nuxt.config.ts
export default defineNuxtConfig({
modules: ['nuxt-security', '@kurashina-design/nuxt-bff-guard'],
bffGuard: {
verifyUser: './server/auth/verify-user.ts',
},
security: {
corsHandler: false, // off for the whole app…
},
routeRules: {
// …and on only for the API that the other origin uses.
'/api/admin/**': {
security: {
corsHandler: {
origin: ['https://admin.example.com'],
methods: ['GET', 'POST', 'PATCH', 'DELETE'],
allowHeaders: ['authorization', 'content-type'],
credentials: false, // no Cookies across origins
},
},
},
},
})
server/auth/verify-user.ts
import { createError, getHeader } from 'h3'
import type { VerifyUser } from '@kurashina-design/nuxt-bff-guard'
export default (async (event) => {
const bearer = /^Bearer[ \t]+(\S+)$/i.exec(getHeader(event, 'authorization') ?? '')?.[1]
if (bearer) {
event.context.user = await verifyAccessToken(bearer) // throws 401 on bad tokens
return { viaBearer: true }
}
event.context.user = await verifySessionCookie(event) // your own pages
return { viaBearer: false }
}) satisfies VerifyUser
The CORS preflight (OPTIONS) is answered by nuxt-security's middleware before the router, so it never reaches verifyUser. The real request then carries the Bearer token; once verifyUser reports viaBearer: true, the guard skips the origin check, because the other site could not have attached your token on its own.