114

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 What is the difference between "express.Router" and routing using "app.get"? and Difference between app.all('*') and app.use('/'), but they do not really answer my question. Thanks.

Community
  • 1
  • 1
Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88

5 Answers5

161

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

ruffin
  • 16,507
  • 9
  • 88
  • 138
Sudhanshu Gaur
  • 7,486
  • 9
  • 47
  • 94
  • I have edited my answer @NaeemShaikh pls have a relook. – Sudhanshu Gaur Jun 16 '15 at 17:04
  • 7
    But why use router when you can go app.use('/first/sud', smaller); and app.use('/first/user',bigger)? I mean did they create router so we don't have to type extra stuff in the first parameter? – mskw Dec 07 '15 at 02:40
  • nice question look i dont know it correctly but i think this is the thing actually routing was made to dicrecting on urls where app.use is made for middleware now you can useapp.use('/first/sud', smaller); but suppose in your app you have many routes with starting as /first/second/third/fourth now would you make every route here /first/second/third/fourth/x, no you will use router here remember both works great but router was made just for these urls purposes – Sudhanshu Gaur Dec 07 '15 at 08:41
  • So, it means we can't do nesting using `router`. We can do only by `app`. Is that correct? – Mr_Perfect Mar 28 '18 at 06:06
  • 10
    Why does the OP ask regarding `router.use` but this answer responds referring to `router.get`? – Tim Heilman Sep 30 '20 at 22:23
  • 5
    Doesn't answer the question, not sure why so many upvotes – Operator Feb 18 '21 at 12:18
  • 4
    Why is this answer even marked as correct? The one below is not only correct but also like 7 months older... It is just confusing to people who come here – Sammaye Jul 14 '21 at 08:10
95

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());

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
Laura
  • 3,233
  • 3
  • 28
  • 45
  • Can I create a new router and then `use` it in another router? Like `router1.use('/path', router2);` – CodyBugstein Jun 11 '15 at 05:25
  • 8
    This answer is clear and should be the accepted answer. Router is often misused where app would be more appropriate. – AturSams Apr 19 '17 at 10:44
3

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.

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
  • 1
    A path does not need to be provided to `app.use` if you'd like to execute the function for every request made to the app. – jacefarm Apr 20 '18 at 15:35
  • @shubham You explained very well and it was very helpful to me. In case of router with middleware we also can merge it into single line like router.delete("/:id/delete", middleware.checkToken, userController.deleteUser) – Sourabh Bhutani May 15 '19 at 06:27
1

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.

nCardot
  • 5,992
  • 6
  • 47
  • 83
1

When looking at the express js docs for Routing (https://expressjs.com/en/guide/routing.html#express-router):

Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.

A Router created with express.Router() is no different than an app created with express() in terms of functionality; it's like a logical grouping of routes/handlers/services/databases/etc. The biggest difference is the scope that it affects. A router just affects its own scope while the app is like the master/global scope for your web/app server. You could have many routers or "apps" running on one main app/web server instance. This is why you could listen to requests on an app instance via app.listen(80) but not on a router.

ryanwaite28
  • 1,804
  • 2
  • 24
  • 40