szymmis / vite-express

⚡ @vitejs integration module for @expressjs
MIT License
607 stars 37 forks source link

One should be able to add middlewares to static and serve routes #137

Open odahcam opened 2 months ago

odahcam commented 2 months ago

Sometimes you may want to perform some security like CSRF or other things and custom middlewares can help with that.

szymmis commented 2 months ago

Hi @odahcam, you case use custom middleware the same way as in pure express application. You can take a look at static() function, the example there should clarify how it's done. You can manipulate when static serving middleware is injected and in a result you can freely decide what middleware to run in the whole lifecycle of the request. If something isn't clear let me know and I'll do my best to answer your questions.

odahcam commented 1 month ago

At first I got a bit confused the ViteExpress class is like a global thing instead of an scoped instance. I think this would feel clearer if it was something like Remix Express adapter: https://remix.run/docs/en/main/other-api/adapter#creating-an-adapter . I would be glad to see if it was possible to implement some interface like this to factory the ViteExpress instead of the current API, just let me know.

So I just remembered my motivation for this issue: change the response body and headers. I'd like to capture the response of the ViteExpress adapter, and only this, that means my middleware would be chained to the ViteExpress adapter and would never be called unless the ViteExpress adapter runs. And I think this makes me feel like an API more similar to Remix Express adapter would make this even more flexible and powerful.

szymmis commented 1 week ago

Hi @odahcam, I admit to the mistake of writing vite-express in such a way that it is a global instance, it would be a lot better if it would work as an instance the same way you instantiate express instance for example, but right now I'm afraid that it would be a little hard to rewrite the API in such a way that it wouldn't break anything that people have written so far. I don't say it is impossible, we just need to have backwards compatibility in mind.

When it comes to having some kind of hook/functions that you can specify that run when vite-express runs it's own logic related to serving routes and files, I think it is a really solid use-case that is worthy of implementing.

Let me know if you would like to propose some solution or maybe just provide some more detailed process that you would want to cover.