Question

For example, say you use winston for logging, and instead of having each middleware to require the logger, you may have one (upstream) middleware that adds it to the request object, so that other middleware can just do:

request.logger.log(...)

Is this good or bad practice?

Was it helpful?

Solution

In my opinion, it's not really good practice to do so.

First of all, you clutter the req object with things you hope do not exist yet and will not exist in the future. If they do, you break things, perhaps even without noticing it. Even worse, when a property name you are using today is being used in a future version of any middleware you use, you have a problem. And for sure you do not check this every single time for every single minor update.

Then, it introduces dependencies between the middleware modules. But these dependencies are not explicit, they are implicit: It only works if middleware B is run after middleware A, but that's expressed nowhere in code. If you change the order, you may only end up with a little helpful undefined is not a function error.

These are my two main issues why I consider this a bad practice. Sure, there's no rule without exception, but if you ask for a rule of thumb, I'd try to avoid that.

By the way, when you take a look at the Migrating Express 3.x to 4.x guide, you can read the following paragraph:

Connect patched node's prototypes globally. This is considered bad behaviour and has been removed in Connect 3.

As this explicitly refers to the res object, this also perfectly answers that you should not do this, and that doing so should be considered bad practice.

This essentially says the same as I wrote here.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top