Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

NodeJS / Express: what is “app.use”?

In the docs for the NodeJS express module, the example code has app.use(...).

What is the use function and where is it defined?
by

3 Answers

akshay1995
app.use() acts as a middleware in express apps. Unlike app.get() and app.post() or so, you actually can use app.use() without specifying the request URL. In such a case what it does is, it gets executed every time no matter what URL's been hit.
RoliMishra
app.use() handles all the middleware functions.
What is middleware?
Middlewares are the functions that work like a door between two all the routes.

For instance:

app.use((req, res, next) => {
console.log("middleware ran");
next();
});

app.get("/", (req, res) => {
console.log("Home route");
});

When you visit / route in your console the two message will be printed. The first message will be from middleware function. If there is no next() function passed then only middleware function runs and other routes are blocked.
pankajshivnani123
app.use(function middleware1(req, res, next){
// middleware1 logic
}, function middleware2(req, res, next){
// middleware2 logic
}, ... middlewareN);

app.use is a way to register middleware or chain of middlewares (or multiple middlewares) before executing any end route logic or intermediary route logic depending upon order of middleware registration sequence.

Middleware: forms chain of functions/middleware-functions with 3 parameters req, res, and next. next is callback which refer to next middleware-function in chain and in case of last middleware-function of chain next points to first-middleware-function of next registered middlerare-chain.

Login / Signup to Answer the Question.