Access app settings
A reusable middleware needs an application setting without importing the application module.
Express.js · Pipe
req.app is a reference to the Express application instance that is using the middleware. Reusable middleware can use it to access application settings and other app-level APIs.
Inside middleware, req.app points to the Express application instance handling the current request. This lets reusable middleware access application settings and other app-level APIs without importing the app module.
req.appconst express = require('express');
const app = express();
app.set('featureName', 'reports');
app.use((req, res) => {
res.json({
applicationSetting: req.app.get('featureName'),
sameApplication: req.app === app
});
});
app.listen(3000);Run the server and request any path to read an application setting through req.app and verify that it references the same Express application.
A reusable middleware needs an application setting without importing the application module.
Middleware must use an app-level API while remaining usable across applications.
req.app is a reference to the Express application instance that is using the middleware. Middleware can use it to access app-level APIs such as settings.
Follow-up: How can middleware read an application setting? Use req.app.get with the setting name, for example req.app.get('views').
A reusable middleware module can export a middleware function and access the application through the request object. This avoids requiring the application instance directly in that module.
Follow-up: Why is this useful for reusable middleware? It keeps the middleware decoupled from a specific app module while still allowing access to the active application.
The property has the Application type and identifies the app instance associated with the current middleware execution. It is available through the request object as req.app.
Follow-up: What related property exposes the application through the response? Express also exposes the same application through res.app.
res.appapp.get()Application ObjectRequest Object