nitro icon indicating copy to clipboard operation
nitro copied to clipboard

Add option to skip middleware

Open Mokkapps opened this issue 3 months ago • 4 comments

Describe the feature

Hi, first thanks for this amazing project 💪🏻

In our Nuxt 3 app we have a core logic that heavily relies on Nitro's server middleware. For every server route we need to check if we want to render it in Nuxt or proxy the page from another system.

A simplified example:

export default defineEventHandler((event) => {
  if (event.path.startsWith('/skip')) {
    // middleware should not run for certain paths
    return;
  }

  if (event.path === '/cart') {
    console.log('First middleware redirect to cart');
    event.node.res.writeHead(302, {
      location: '/cart-redirect',
    });
    event.node.res.end();
  }

  if (event.path === '/user') {
    console.log('First middleware redirect to user');
    event.node.res.writeHead(302, {
      location: '/user-redirect',
    });
    event.node.res.end();
  }
});

As mentioned in the docs returning anything from middleware should be avoided:

Returning anything from a middleware will close the request and should be avoided! Any returned value from middleware will be the response and further code will not be executed however this is not recommended to do!

I'm wondering why Nitro does not provide something like a next() function to be able to skip certain middleware, as it is available in other frameworks like Express.

We definitely would like to avoid using an approach that is not recommended, what alternative would be available instead using server middleware with return for our requirements?

Reproduction

https://stackblitz.com/edit/github-yplgh6?file=server%2Fmiddleware%2F01.first.ts

Additional information

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

Mokkapps avatar Mar 08 '24 05:03 Mokkapps