Is starting express like this "const app = require('express')()" considered bad practice? Is starting express like this "const app = require('express')()" considered bad practice? express express

Is starting express like this "const app = require('express')()" considered bad practice?


In general, your code should be the simplest and clearest way of reliably meeting your requirements. Any code that follows those simple guidelines will not be considered a bad practice in pretty much anyone's book.

There may be other influences on the desired coding style such as team style guidelines, coding style already present in the file/module/project and certain things you may want to do for testing, debugging or reuse. But, since you don't mention any of those influences, I will assume they are not present here.

So, with that first paragraph in mind, as long as you don't need access to the express module elsewhere in this module, then doing:

const app = require('express')();

is indeed the simplest and clearest way of accomplishing your goal and should not be considered a bad practice - in fact it should be considered a good practice.


On the other hand, if you were doing this:

const app = require('express')();....const mainRouter = require('express').Router();....const subRouter = require('express').Router();....app.use(require('express').static('public'));

Then, you'd have simpler and less redundant code (and perhaps a little faster since there are fewer function calls) if you loaded the express module into its own variable which you could then use everywhere else in that module:

const express = require('express');const app = express();....const mainRouter = express.Router();....const subRouter = express.Router();....app.use(express.static('public'));


Something to consider is that the express module exposes some other functionality that you might want to make use of later (e.g. express.static). In your case you would have to require express again to gain access to it:

app.use(require('express').static());

Other than that there is no reason it's "bad practise". It just depends on what you intend to leverage from the module.


Simply put, to create an identifier for reuse and better communication to readers.


More thought just about require()

Since require() takes the responsibility to load and cache modules, some argues that it should be placed before app initialization. I see many example codes follows this style. However I think it really depends on how the package/code quality is ensured in the specific project.