You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I created some modules for normalizing URLs in different ways (+ there are some others out there), so I would like to bundle them into a single module. This works right now:
app.use((req,res,next)=>{req.app.use((req,res,next)=>{console.log("I am called!");next();});req.app.use((req,res,next)=>{console.log("Me too!");next();});console.log("Great");next();});
Which correctly outputs:
Great
I am called!
Me too!
However I worry that this is abusing express functionality/original intent. So I'd like to ask if this is frowned upon or perfectly valid within express' API.
The text was updated successfully, but these errors were encountered:
This is not a good way to do it, you're creating a memory leak by mounting applications every single request loop which means that for each request, you have one extra set of middleware mounted (and a new function for each middleware instance too == more memory overhead).
It sounds like what you want to do is to look up how Express routers work. It allows you to do this:
constrouter=express.Router();router.use((req,res,next)=>{console.log("I am called!");next();});router.use((req,res,next)=>{console.log("Me too!");next();});app.use(router);
Basically, you can create any instance you'd like and accept (req, res, next) - inside that you can do whatever you'd like - be that routing, request management, etc. I wouldn't mess with the application instance itself as you will create a memory leak adding too many instances of middleware.
And to build on what @blakeembrey said, from a strict sense of the question "So I'd like to ask if this is frowned upon or perfectly valid within express' API.": all of that is valid use of the Express API that is public & supported, though it does seem odd.
@blakeembrey that makes total sense, of course the "base" use one is also a middleware so it'll be called each time. A flag or counter could be added to avoid leaking, but then your solution with the Router seems way better so I'll use it that way. Thanks!
I created some modules for normalizing URLs in different ways (+ there are some others out there), so I would like to bundle them into a single module. This works right now:
Which correctly outputs:
However I worry that this is abusing express functionality/original intent. So I'd like to ask if this is frowned upon or perfectly valid within express' API.
The text was updated successfully, but these errors were encountered: