Difference Between app.use() and router.use() in Express

node.jsExpress

node.js Problem Overview


I was just reading the documentation on express and found these two terms, app.use(); and router.use();

I know app.use(); is used in node for Mounting a middleware at a path, and we often use it in most of the node apps. but what is router.use(); are they both same? if not, whats the difference ?

I read about router here. I also found similar questions on SO https://stackoverflow.com/questions/23607058/what-is-the-difference-between-express-router-and-routing-using-app-get and https://stackoverflow.com/questions/14125997/difference-between-app-all-and-app-use, but they do not really answer my question. Thanks.

node.js Solutions


Solution 1 - node.js

router.get is only for defining subpaths. Consider this example:

var router = express.Router();

app.use('/first', router); // Mount the router as middleware at path /first

router.get('/sud', smaller);

router.get('/user', bigger);
  • If you open /first/sud, then the smaller function will get called.
  • If you open /first/user, then the bigger function will get called.

In short, app.use('/first', router) mounts the middleware at path /first, then router.get sets the subpath accordingly.


But if we instead use the following:

app.use('/first', fun);

app.get('/sud', bigger);

app.get('/user', smaller);
  • If you open /first in your browser, fun will get called,
  • For /sud, bigger will get called
  • For /user, smaller will get called

But remember for /first/sud, no function will get called.

This link may also help: http://expressjs.com/api.html#router

Solution 2 - node.js

router.use(); mounts middleware for the routes served by the specific router, app.use(); mounts middleware for all routes of the app (or those matching the routes specified if you use app.use('/ANYROUTESHERE', yourMiddleware());).

Example use case could be an app with one router with standard routes and one router that handles api routes, which need a valid user.

You would then mount the authentication middleware for the api router only with router.use(yourAuthMiddleware());.

If you would have an app though that requires a valid user for all routes, mount the middleware for the app with app.use(yourAuthMiddleware());

Solution 3 - node.js

app.use() used to Mounts the middleware function or functions at the specified path,the middleware function is executed when the base of the requested path matches path.

router.use() is used to middleware function or functions, The defaults mount path to “/”.

But in app.use() you will have to give a specified path like that:

 var adsRouter = require('./adsRouter.js');
    app.use('/ads', adsRouter);

or

app.use('/ads', function(req, res, next) {

  // write your callback code here.

    });

But while using router.use() you can give only middleware, like this:

router.use(function(req, res, next) {
  console.log('%s %s %s', req.method, req.url, req.path);
  next();
});

or

router.use('/test', function(req, res, next) {
  // write your callback code here.
  next();
});

or

//in router.js

router.use('/admin', authUtil.verifySessionId, authUtil.verifyLisencee);
router.post('/admin', controllerIndex.ads.adListingAdmin);

In the above code when the end point is '/admin' then first it will call the authUtil.verifySessionId and authUtil.verifyLisencee then it will execute next line with 'admin' end point and according to controllerIndex.ads.adListingAdmin method.

Solution 4 - node.js

app.use(middleware): application-level middleware.

router.use(middleware): router-level middleware.

("middleware" refers to methods/functions/operations that are called between processing the request and sending the response.)

See https://expressjs.com/en/guide/using-middleware.html for a comparison of different types of middleware used in an Express app.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNaeem ShaikhView Question on Stackoverflow
Solution 1 - node.jsSudhanshu GaurView Answer on Stackoverflow
Solution 2 - node.jsLauraView Answer on Stackoverflow
Solution 3 - node.jsShubham VermaView Answer on Stackoverflow
Solution 4 - node.jsnCardotView Answer on Stackoverflow