nitrojs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.build
MIT License
6.23k stars 513 forks source link

Allow after request middleware #1301

Open Barbapapazes opened 1 year ago

Barbapapazes commented 1 year ago

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

gnoeley commented 1 year ago

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?

pi0 commented 1 year ago

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

gnoeley commented 1 year ago

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?

pi0 commented 1 year ago

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 ❤️

gnoeley commented 1 year ago

@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.