nitro icon indicating copy to clipboard operation
nitro copied to clipboard

Allow after request middleware

Open Barbapapazes opened this issue 2 years ago • 5 comments

Describe the feature

Hello,

I was thinking about after middleware like in express.

For example, if I've a middleware like this:

export default eventHandler(() => {
	console.log('before')
	next()
	console.log('after')
})

And a route like this:

export default eventHandler(() => {
	console.log('route')
	return
})

I expect:

before
route
after

This is not an API to implement but juste an example of what I've in mind

https://github.com/nuxt/nuxt/issues/21522

Additional information

  • [ ] Would you be willing to help implement this feature?

Barbapapazes avatar Jun 11 '23 20:06 Barbapapazes

I recently came across this issue and ended up with something like (StackBlitz),

// middleware/afterware.ts
export default eventHandler((event) => {
  const start = Date.now();
  event.res.once('close', () => {
    const ms = Date.now() - start;
    console.log(`Request took ${ms}ms`);
  });
});

This was based on the node middleware helper function approach here in the h3 library. I'm not sure on the correctness of this but it would be nice if this was somehow supported.

Just noticed a recent change https://github.com/unjs/h3/pull/482 that has added the ability to add before/after hooks to h3 though. Could this be used to implement this functionality in Nitro using unjs/hookable?

gnoeley avatar Aug 02 '23 20:08 gnoeley

@gnoeley yes that's the plan! You would be able to use nitro app hooks to leverage them.

pi0 avatar Aug 02 '23 20:08 pi0

If more hooks are to be added to Nitro, is there a plan to document them more clearly either as a main-section in docs? To date, I've been grepping the code to find our what was supported. Looks like they are all listed under Plugins->Examples currently, but perhaps calling them out directly could be useful. It was a point of confusion for me personally at least 😅 Happy to raise a PR if that would be welcome?

gnoeley avatar Aug 02 '23 20:08 gnoeley

Certainly! I will make sure to at least write clear usage in PR description. You are always more than welcome to contribute and improve docs and examples ❤️

pi0 avatar Aug 02 '23 20:08 pi0

@pi0 , I've opened a draft PR with some proposed documentation changes. I've had a guess at what the final API for the addition of the new hooks could be, happy to accept comments once that is finalized and I can update. Can have any further discussion in the PR.

gnoeley avatar Aug 02 '23 23:08 gnoeley