Skip to content

Idiomatic way to create a reusable auth middleware that supports both app.use() and per-route handler wrapping in H3 v2 #1374

Description

@targetlucked69

Describe the change

Not really a documentation issue, but I'm having a hard time understanding something.

I'm building a reusable middleware library with H3 v2 and want to support two usage patterns from a single function:

// Pattern A: app-wide via app.use()
app.use(withAuth({ role: 'user' }))

// Pattern B: per-route handler wrapping (e.g. Nitro/Nuxt file routes)
export default withAuth({ role: 'user' }, async (event) => {
  return event.context.authCtx
})

My current implementation returns defineMiddleware(...) for pattern A and defineEventHandler({ middleware: [m], handler }) for pattern B.

Two questions:

  1. 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?

  2. For Nuxt's server/middleware/ files, the convention is export default defineEventHandler(...) but pattern A returns a Middleware type. Is it safe/correct to export a Middleware directly from a Nitro server middleware file, or should it always be wrapped in defineEventHandler?

URLs

No response

Additional information

  • Would you be willing to help?

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions