The Wayback Machine - https://web.archive.org/web/20240917061803/https://www.geeksforgeeks.org/express-js-router-use-function/
Open In App

Express.js | router.use() Function

Last Updated : 30 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The router.use() function uses the specified middleware function or functions. It basically mounts middleware for the routes which are being served by the specific router. 

Syntax:

router.use( path, function )

Parameters:

  • Path: It is the path to this middleware, if we can have /user, now this middleware is called for all API’s having /user of this router.
  • function: This function is passed as a callback, it is called when the specified path is called in this router.

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 express

After installing the express module, you can check your express version in the command prompt using the command.

npm version express

After 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.js

Project Structure:

Filename: index.js 

javascript




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:

The project structure will look like this: 

Make sure you have installed the express module using the following command:

npm install express

Run the index.js file using the below command:

node index.js

Output:

Server listening on PORT 3000

Now open your browser and go to http://localhost:3000/user, you can see the following output on your screen:

Server listening on PORT 3000
Middleware Called

And you will see the following output on your browser:

Greetings from GeeksforGeeks

Previous Article
Next Article

Similar Reads

Express express.Router() Function
The express.Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.  Syntax: express.Router( [options] )Optional Parameters: case-sensitive: This enables case sensitivity.mergeParams: It preserves the req.params values from the parent router.stric
2 min read
Purpose of the express.Router middleware in Express
express.Router() in ExpressJS is like creating a mini-app within your main app. It helps organize routes and related functionalities, making it easier to manage different parts of your web application separately. express.Router() acts as a path organizer in ExpressJS, helping to structure and manage routes efficiently within a web application. Purp
1 min read
What is the Use of Router in Express.js ?
Express.js is a powerful and flexible web application framework for Node.js. It simplifies the process of building server-side applications and APIs by providing robust features and tools. Among these tools, routers play a pivotal role in managing and organizing the routes within an application. This article delves into the concept of routers in Ex
4 min read
How to Create Custom Router with the help of React Router ?
To create a custom Router using React Router, you can define a new component that utilizes the Router's 'BrowserRouter' along with 'Route' components to handle different paths and render corresponding components. Use 'Link' components for navigation within your application, providing a seamless routing experience in your React application. What is
3 min read
Express.js router.all() Function
The router.all() function is just like the router.METHOD() methods, except that it matches all HTTP methods (verbs). It is very helpful for mapping global logic for arbitrary matches or specific path prefixes. Syntax: router.all(path, [callback, ...] callback) Parameter: The path parameter is the path of the specified URL and the callback is the fu
2 min read
Express.js router.route() Function
The router.route() function returns an instance of a single route that you can then use to handle HTTP verbs with optional middleware. You can also use the router.route() function to avoid duplicate route naming as well as typing errors. Syntax: router.route( path ) Parameter: The path parameter holds the path of the specified URL. Return Value: It
2 min read
Express.js router.METHOD() Function
The router.METHOD() method provides the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Syntax: router.METHOD(path, [callback, ...] callback) Parameter: The path parameter specifies the path on the URL and callback is the function that is executed when this path is called.
2 min read
Express.js router.param() function
The parameters of router.param() are a name and function. Where the name is the actual name of the parameter and the function is the callback function. Basically, the router.param() function triggers the callback function whenever the user routes to the parameter. This callback function will be called only a single time in the request-response cycl
2 min read
Express.js app.router Property
The Express.js app.router property was introduced in Express 4. It helps us to create modular, mountable route handlers. It provides us with many features such as it extends this routing to handle validation, handle 404 or other errors, etc. It helps us to organize our file structure for our server-side programming. What is the need to use express.
3 min read
Express.js app.router() Method
Express.js is a Node.js web flexible framework that provides a set of features for mobile and web applications. Express has various methods provided by many developers and one of the methods in Express is a Router which is used to divert the user to different pages of the website base on request. Syntax : express.Router([options]);Parameter: This f
3 min read
Express.js Router Complete Reference
Express.js is a small framework that works on top of Node.js web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. Express.js Router Methods: Methods Description Express.js router.all() Function The router.all() function is just like t
1 min read
Difference between application level and router level middleware in Express?
If you’ve used Express even a little, you know how important middleware is. Those little functions run on every request and let you do stuff like logging, authentication, file uploads, and more. In this article, we will see what is Application-level middleware and Router-level middleware and what are the key differences between them. Table of Conte
3 min read
Build Your First Router in Node.js with Express
Express.js  is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will discuss, how to use the router in the express.js server. The express.Router() function is used to create a new router object. This funct
2 min read
Express.js express.text() Function
The express.text() function is a built-in middleware function in Express. It parses the incoming request payloads into a string and is based on body-parser. Syntax: express.text( [options] ) Parameter: The options parameter contains various properties like defaultCharset, inflate, limit, verify, etc. Return Value: It returns an Object. Installation
2 min read
Express.js express.raw() Function
The express.raw() function is a built-in middleware function in Express. It parses incoming request payloads into a Buffer and is based on body-parser. Syntax: express.raw( [options] ) Parameter: The options parameter contains various properties like inflate, limit, type, etc. Return Value: It returns an Object. Installation of the express module:
2 min read
Express.js express() function Complete Reference
Express.js is a small framework that works on top of Node.js web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. Express.js express() Methods:Method Description Express.js express.json() Function The express.json() function is a buil
1 min read
Express express.static() Function
The express.static() function is a built-in middleware function in Express. It serves static files and is based on serve-static.  Syntax: express.static(root, [options])Parameters: The root parameter describes the root directory from which to serve static assets.  Return Value: It returns an Object.  Steps to create the application:Step 1: Initiali
2 min read
Express JS express.json() Function
The express.json() function is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser. It’s a critical component for handling JSON data in RESTful APIs and web applications, allowing the server to automatically parse JSON data from the request body. Syntax:express.json( [options] )Param
3 min read
Express express.urlencoded() Function
The urlencoded function is used to parse the incoming requests with URL-encoded payloads. It is a built-in middleware function in Express based on a body parser module. When there is a HTTP POST request from the client with content type application/x-www-form-urlencoded, this middleware parses the data and populates the req.body object with key-val
2 min read
Explain the purpose of the express.static middleware in Express JS
The express.static middleware in ExpressJS simplifies serving static files like HTML, CSS, and images, improving performance and enhancing user experience in web applications. Purpose of the express.static middleware in ExpressJS:Serves Static Files: express.static middleware serves static files like HTML, CSS, JavaScript, and images from a specifi
2 min read
What is the purpose of the express-validator middleware in Express JS?
The express-validator middleware is a powerful tool for validating and sanitizing incoming request data in ExpressJS applications. It helps ensure that user input meets specified criteria, preventing security vulnerabilities and data corruption. With built-in error handling and customizable rules, express-validator seamlessly integrates with Expres
2 min read
How to Expire Session After 1 Min of Inactivity in express-session of Express.js ?
To automatically expire sessions after 1 minute of inactivity in an Express.js application using express-session, configure the session settings with the cookie.maxAge and implement session touch logic to track activity. ApproachTo expire the session after 1 min of inactivity in the express-session of Express.js we use expires: 60000 in the middlew
2 min read
What is express-session middleware in Express?
In the Express web application, the express-session middleware is mainly used for managing the sessions for the user-specific data. In this article, we will see the use of express-session middleware for session management in Express with practical implementation. PrerequisitesNode JSExpress JSTable of Content What is express-session Middleware?Step
2 min read
How to use the useHistory hook in React Router?
React Router is a standard library system built on top of React and used to create routing in the React application using the React Router Package. It enables the navigation between views of various components in a React Application. React Router is useful for Single Page Applications (SPAs). To use usHistory Hook in React Router, you first need to
4 min read
What is the use of Backbone.js router ?
Backbone.js is a compact library used to organize JavaScript code. It is additionally regarded as an MVC/MV* framework. MVC is essentially an architecture paradigm for designing user interfaces, in case you are unfamiliar. It allows you to develop front-end applications in a much easier way by implementing JavaScript functions. BackboneJS provides
3 min read
What is the use of next() function in Express.js ?
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will discuss, the use of the next() function in every middleware of the express.js. There are lots of middleware functions in Express.js like
2 min read
Express app.use() Function
The app.use() function in Express.js adds middleware to the application's request-processing pipeline. It applies the specified middleware to all incoming requests or to specific routes, allowing you to modify request/response objects, perform operations, or handle errors throughout the application. Syntaxapp.use(path, callback)Parameters:path: It
3 min read
How to Dynamically Call Router Function in Node.js ?
In Node.js Dynamically calling a router function means that the function is selected at runtime based on the request parameters, instead of being explicitly defined in the code. This can be useful when you want to handle a large number of similar requests without having to define a separate function for each one. ApproachIn Express, you can use the
4 min read
How to check if email address is already in use or not using express-validator in Node.js ?
The registration or Sign Up in any website always requires a username. Most of the time we use 'email' to register on a website. The registration email is always unique and must refer to only one user otherwise conflict between the users can happen. To solve this conflict every website must have the functionality to not accept the email that alread
5 min read
How to use express in typescript ?
In this article, we will see how to use Express in TypeScript. The TypeScript is a superset of JavaScript that provides type notation with the JavaScript, so we can handle our server, and very scalable for the future. Express is web framework helps to create server-side handling with the help of Nodejs Prerequisite: Basic knowledge of NodeJS and Ex
2 min read