Webhooks
Webhooks come from another server, with no user, no Cookie, and no Origin or Sec-Fetch-Site header. The guard's same-origin check applies to every POST it wraps, public or not, so a webhook under server/api would always get 403.
Put webhooks in server/routes/, which the default route check does not cover, and verify the sender's signature before doing anything.
import { createHmac, timingSafeEqual } from 'node:crypto'
const secret = process.env.PAYMENTS_WEBHOOK_SECRET!
export default defineEventHandler(async (event) => {
const body = await readRawBody(event, 'utf8') ?? ''
const signature = getHeader(event, 'x-signature') ?? ''
const expected = createHmac('sha256', secret).update(body).digest('hex')
const valid = signature.length === expected.length
&& timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
if (!valid) throw createError({ statusCode: 401 })
await handlePaymentEvent(JSON.parse(body))
return { received: true }
})
The route is served at /webhooks/payments. Use the verification helper of your provider's SDK when it has one (Stripe's constructEvent, for example); it also checks timestamps against replays.
Keep the folder small
Everything in server/routes/webhooks/ is reachable without a user. Keep only signature-checked handlers there, and review additions to it as carefully as public routes. If you also check other folders with routePatterns, list them explicitly instead of server/routes/**:
bffGuard: {
verifyUser: './server/auth/verify-user.ts',
routePatterns: ['server/api/**', 'server/routes/account/**'],
}
Security middleware on the same path
Module middleware still runs for /webhooks/**, before your handler. Two settings need care:
- nuxt-security's
xssValidatorchecks POST bodies by default and can reject payloads that contain HTML, such as an email body, with 400. - nuxt-csurf rejects requests without its token with 403.
Turn both off for webhooks, and keep the rate limiter and size limit:
export default defineNuxtConfig({
routeRules: {
'/webhooks/**': {
security: { xssValidator: false },
csurf: false, // only if you use nuxt-csurf
},
},
})