In express.js I get into situations in which I am dealing with more than one instance of an express app object. This is helpful, and to some extent necessary as it helps break things down into more manageable smaller components that are each responsible for a certain task, such as rendering, or grabbing settings from a yaml or json file.
In this post I will be writing about req.app, res.app which are both just reference the instance of app that is using the express middleware. This can be used as a way to not use require to get a reference to my main app instance from another file, but that is another way of pulling it off. In other words this post is about instances of the app object in express, and how to manage a bunch of theme when starting to make something a little complicated.
This is a post on working with app objects in express.js using req.app, and res.app properies, it is not a getting started post on express.js, or any additional skills required before hand. If you are new to express, or you just want to check out my main post on express that might be a good starting point.
For this demo I just need to install express.
Here in the main app.js file I create an instance of an app object, and set some app settings with app.set. I then just require a single middleware function called otherapp.js that will do the rendering, but it needs some values that I have set here. There are a few ways to do it, but in this demo I will be using res.app.
This is the single middleware method that the main app is using with app.use. In here I am using res.app to gain a reference to the main app object instance in app.js. I am then setting the settings of another instance of the app object in the middleware to the settings in the main app.js file.
Finally I have a single index.ejs file in the view folder that will be rendered by the middleware method.
There is no difference that I am aware of at least when it comes to req.app, and req.app they both should be references to the same express app at least from my experience thus far that has been the case. The main thing about this here is that the property is a way to make use of value of a main express app. This is one of the reasons why I have got into the habit of using the app.get and app.set methods as a way to set values that I intend to use across the whole of a project.