Idiomatic way to create a reusable auth middleware that supports both app.use() and per-route handler wrapping in H3 v2 #1373
Replies: 2 comments
|
At the H3 level, the reusable primitive should be the middleware, and the per-route case should adapt that middleware through the handler object form. So this shape is the one I would keep: const auth = withAuth({ role: "user" })
export default defineHandler({
middleware: [auth],
handler: async (event) => event.context.authCtx,
})H3 v2 documents route-level For Nuxt/Nitro |
|
Yes, import { defineMiddleware, defineHandler, HTTPError, type EventHandler } from 'h3'
export function withAuth(opts: { role: string }, handler?: EventHandler) {
const auth = defineMiddleware(async (event) => {
const user = await getUser(event) // your logic
if (user?.role !== opts.role) throw new HTTPError({ status: 401 })
event.context.authCtx = { user }
})
return handler ? defineHandler({ middleware: [auth], handler }) : auth
}
app.use('/admin/**', withAuth({ role: 'admin' })) // pattern A
app.get('/me', withAuth({ role: 'user' }, (e) => e.context.authCtx)) // pattern BI tested this on h3 2.0.8. Both forms return 401 for the wrong role and pass On the Nuxt question: Docs: https://h3.dev/guide/basics/middleware and https://h3.dev/guide/basics/handler#handler-object-syntax |
Uh oh!
There was an error while loading. Please reload this page.
I'm building a reusable middleware library with H3 v2 and want to support two usage patterns from a single function:
My current implementation returns
defineMiddleware(...)for pattern A anddefineEventHandler({ middleware: [m], handler })for pattern B.Two questions:
For pattern B, is
defineEventHandler({ middleware, handler })the right approach, or is there a more idiomatic way to compose a pre-handler middleware with a route handler?For Nuxt's
server/middleware/files, the convention isexport default defineEventHandler(...)but pattern A returns aMiddlewaretype. Is it safe/correct to export aMiddlewaredirectly from a Nitro server middleware file, or should it always be wrapped indefineEventHandler?Thanks!
All reactions