nuxt icon indicating copy to clipboard operation
nuxt copied to clipboard

Add a possibility of setting up added dynamic route middleware so that it would be executed before any global middleware from /middleware dir

Open nicky1038 opened this issue 1 year ago • 2 comments
trafficstars

Describe the feature

Hi everyone!

I have found out that:

  • addRouteMiddleware function adds the specified mw to nuxtApp._middleware.global list
  • The strict order in which mws are being executed on each route is [...globalMiddleware, ...nuxtApp._middleware.global], where globalMiddleware is a list of scanned mw files from /middleware dir.

That is, mw added by addRouteMiddleware will always be executed after mws from /middleware dir.

I am authoring a module that adds an mw to all projects that use it, and I would like my mw to be always running before any other. It would be great to achieve that in some easy way, e. g. by providing some new argument to addRouteMiddleware. (in this particular case new calls of addRouteMiddleware should not change the fact that a firstly added mw will always be executed first)

  • Is it possible to add to nuxt any functionality that would allow achieving my goal, i. e. to easily programmatically add some new mw that will be always executed before any other?
  • Or is there any existing way to easily achieve what I am trying to do?
  • Is addRouteMiddleware ever the best option to use for my purposes? Another option seems to be adding my mw to middleware array inside app:resolve hook, but working with it is not trivial (there I should specify mw as a path to a file with it, but I need to use compile-time options while creating mw, so I need to generate a proper mw file at first) and I am not sure if this was ever meant to be used by developers.

Additional information

  • [ ] Would you be willing to help implement this feature?
  • [ ] Could this feature be implemented as a module?

Final checks

nicky1038 avatar Mar 06 '24 09:03 nicky1038

We think it would be a good idea to allow passing an option to addRouteMiddleware (as with addPlugin) to allow adding middleware to the beginning of the middleware array rather than the end.

In general I'd advise against strict middleware ordering dependencies.

danielroe avatar Aug 09 '24 09:08 danielroe

@nicky1038 Here it is https://github.com/nuxt/nuxt/pull/28496

trandaison avatar Aug 15 '24 02:08 trandaison

Looks like this may have been resolved in https://github.com/nuxt/nuxt/pull/28496 with the prepend option. https://nuxt.com/docs/api/kit/pages#addroutemiddleware

davidstackio avatar May 20 '25 16:05 davidstackio