Home > Mobile >  Change app settings inside Express.js request
Change app settings inside Express.js request

Time:11-27

Is it good practice to change app settings inside request Express.js handler?

app.set('title', 'My Site')
var express = require('express')
var app = express()
app.set('title', 'My Site')

app.get('/somehow', function (req, res) {
  req.app.set('title', 'New title')
  res.send('hello world')
})

app.listen(3000)

CodePudding user response:

Is it good practice to change app settings inside request Express.js handler?

It can be used just fine if what you're intending to do is to change a global server setting that could affect all future requests from all future clients. Typically, this would be done under some sort of administrative authentication (not by any random client) or just be some type of server metric you're accumulating.

It would not be the appropriate way of affecting one particular response (because it's affect is persistent and affects all future requests). For that, you should modify that one response locally, either manually or by using an HTML template. For passing data to templates, you can pass it directly or set it in res.locals and the template can render the page using that data.


If this is for business logic, then you generally do not want to make business logic dependent upon the Express framework as there's really no reason to make one dependent upon the other. Instead, you can implement a stand-alone module for your business logic that keeps track of its own state and exports an interface for getting/setting/implementing the business logic. It can then store state as module-level variables or in a database or in whatever is most appropriate.

Make this business logic a stand-alone module also makes it independently testable without Express, usable in other apps, simpler to debug, etc...

  • Related