The router.use() function is used to mount middleware functions on an Express Router instance. The middleware can be applied to all requests handled by the router or only to requests that match a specified path.

Syntax:
router.use([path], callback [, callback ...])Parameters:
- path: An optional path at which the middleware is mounted. If omitted, the middleware runs for all requests handled by the router.
- callback: A middleware function or multiple middleware functions that are executed when the request matches the specified path. Each middleware function receives req, res, and next arguments.
Installation of the express module:
You can visit the link to Install the express module. You can install this package by using this command.
npm install expressAfter installing the express module, you can check your express version in the command prompt using the command.
npm version expressAfter that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.
node index.jsProject Structure:

Filename: index.js
const express = require('express');
const app = express();
const router = express.Router();
const PORT = 3000;
// All requests to this router will
// first hit this middleware
router.use(function (req, res, next) {
console.log("Middleware Called");
next();
})
// Always invoked
router.use(function (req, res, next) {
res.send("Greetings from GeeksforGeeks");
})
app.use('/user', router);
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Steps to run the program:
Run the index.js file using the below command:
node index.jsOutput:
Server listening on PORT 3000Now open your browser and go to http://localhost:3000/user, you can see the following output on your screen:

And you will see the following output on your browser:

Working of router.use()
- An Express Router instance is created using express.Router().
- Middleware is registered using router.use().
- When a request reaches the router, Express checks whether it matches the middleware's path.
- The matching middleware function is executed in the order in which it was registered.
- The middleware can process the request and response objects.
- Calling next() passes control to the next middleware or route handler.
- A middleware function can end the request-response cycle by sending a response.
Use Cases of router.use()
- Applying middleware to all routes handled by a router.
- Applying middleware to a specific path.
- Implementing authentication and authorization.
- Logging incoming requests.
- Validating request data before route handlers execute.
- Organizing middleware in modular Express applications.