h3 icon indicating copy to clipboard operation
h3 copied to clipboard

trying to use defineEventHandler with before[] for per-route middleware

Open acidjazz opened this issue 1 year ago • 3 comments

Environment

I noticed that in this merge https://github.com/unjs/h3/pull/485 there is before: [] - i tried something like this:

const index = defineEventHandler({
  handler: async () => {
    return metapi().render(
      await prisma.user.findMany({
      }),
    )
  },
  before: [
    () => {
      console.log('we are in before[]')
      return auth.user() && auth.user().isAdmin
    },
  ],
})

Reproduction

Just run the above code in a route

Describe the bug

not sure if i'm using before: [] incorrectly?

Additional context

No response

Logs

No response

acidjazz avatar Aug 11 '24 03:08 acidjazz

Read https://h3.unjs.io/guide/event-handler#object-syntax

offizium-berndstorath avatar Aug 14 '24 14:08 offizium-berndstorath

Read https://h3.unjs.io/guide/event-handler#object-syntax

Are you saying I should use onRequest: [] instead of before: [] ?

acidjazz avatar Aug 15 '24 02:08 acidjazz

Read https://h3.unjs.io/guide/event-handler#object-syntax

I think the documentation for defineEventHandler is incomplete.

there is no example of how to apply defineEventHandler with object syntax.

what if i want to create middleware at a non-global route level. did i make defineEventHandler in another file that accepts the object event then I called it on the body defineEventHandler by inserting an event object in the route level?

alifnuryana avatar Sep 18 '24 08:09 alifnuryana

Read https://h3.unjs.io/guide/event-handler#object-syntax

I think the documentation for defineEventHandler is incomplete.

there is no example of how to apply defineEventHandler with object syntax.

what if i want to create middleware at a non-global route level. did i make defineEventHandler in another file that accepts the object event then I called it on the body defineEventHandler by inserting an event object in the route level?

true. The docs are quite cryptic to say the least.

kentntwari avatar Nov 02 '24 20:11 kentntwari

Registering middleware with h3 v2 is much clearer (I hope!) also possible to register generic middleware per route.

defineEventHandler({
  middleware: [
    // (you can add as many with any order)
    onRequest(() => {}),
    onResponse(() => {}),
    onError(() => {}),
    (event, next) => {
      next();
    },
  ],
  handler: (event) => {}
});

pi0 avatar Jun 04 '25 21:06 pi0