Middleware in Express refers to functions that process requests before reaching the route handlers. These functions can modify the request and response objects, end the request-response cycle, or call the next middleware function. Middleware functions are executed in the order they are defined. They can perform tasks like authentication, logging, or error handling. Middleware helps separate concerns and manage complex routes efficiently.
Middleware workingSyntax
app.use((req, res, next) => {
console.log('Middleware executed');
next();
});
- (req, res, next) => {}: This is the middleware function where you can perform actions on the request and response objects before the final handler is executed.
- next(): This function is called to pass control to the next middleware in the stack if the current one doesn't end the request-response cycle.
What Middleware Does in Express.js
Middleware functions in Express.js can perform several important tasks:
- Execute Code: Middleware can run any code when a request is received.
- Modify Request and Response: Middleware can modify both the request (req) and response (res) objects.
- End the Request-Response Cycle: Middleware can send a response to the client, ending the cycle.
- Call the Next Middleware: Middleware can call next() to pass control to the next function in the middleware stack.
How Middleware Works in Express.js?
In Express.js, middleware functions are executed sequentially in the order they are added to the application. Here’s how the typical flow works:
- Request arrives at the server.
- Middleware functions are applied to the request, one by one.
- Each middleware can either:
- Send a response and end the request-response cycle.
- Call next() to pass control to the next middleware.
- If no middleware ends the cycle, the route handler is reached, and a final response is sent.
Types of Middleware
ExpressJS offers different types of middleware and you should choose the middleware based on functionality required.
1. Application-level Middleware
Application-level middleware is bound to the entire Express application using app.use() or app.METHOD(). It executes for all routes in the application, regardless of the specific path or HTTP method.
This type of middleware is commonly used for tasks like logging, body parsing, authentication checks, or setting headers for every incoming request.
app.use(express.json()); // Parses JSON data for every incoming request
app.use((req, res, next) => {
console.log('Request received:', req.method, req.url);
next();
});
2. Router-level Middleware
Router-level middleware is applied to a specific router instance using router.use() or router.METHOD(). It only applies to routes defined within that particular router, making it perfect for modular applications where middleware is only relevant to specific groups of routes.
This type of middleware is often used to group related routes (e.g., all routes related to authentication or user management) and apply middleware logic to them.
const router = express.Router();
// Apply middleware to only this router's routes
router.use((req, res, next) => {
console.log('Router-specific middleware');
next();
});
router.get('/dashboard', (req, res) => {
res.send('Dashboard Page');
});
app.use('/user', router); // The middleware applies only to routes under "/user"
3. Error-handling Middleware
Error-handling middleware is a special type of middleware used to catch and respond to errors during the request-response cycle. It is defined with four parameters: err, req, res, next.
This middleware is essential for sending a consistent error response and avoiding unhandled exceptions that might crash the server.
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error stack
res.status(500).send('Something went wrong!');
});
4. Built-in Middleware
Express provides built-in middleware to help with common tasks, like serving static files or parsing data.
For example, express.static() serves files like images, and express.json() helps parse incoming JSON data.
app.use(express.static('public')); // Serves static files from the "public" folder
app.use(express.json()); // Parses JSON payloads in incoming requests
5. Third-party Middleware
Third-party middleware is developed by external developers and packaged as npm modules. These middleware packages add additional functionality to your application, such as request logging, security features, or data validation.
For example, the morgan middleware logs HTTP requests, and body-parser helps parse incoming request bodies for easier handling of form data.
const morgan = require('morgan');
app.use(morgan('dev')); // Logs HTTP requests using the "dev" format
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true })); // Parses URL-encoded bodies
Steps to Implement Middleware in Express
Step 1: Initialize the Node.js Project
npm init -y
Step 2: Install the required dependencies.
npm install express
Step 3: Set Up the Express Application
JavaScript
// Filename: index.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('<div><h2>Welcome to GeeksforGeeks</h2><h5>Tutorial on Middleware</h5></div>');
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Step 4: Start the Application:
node index.js
Output:
When you navigate to http://localhost:3000/, you will see:
Welcome to GeeksforGeeksTutorial on Middleware
Middleware Chaining
Middleware can be chained from one to another, Hence creating a chain of functions that are executed in order. The last function sends the response back to the browser. So, before sending the response back to the browser the different middleware processes the request.
The next() function in the express is responsible for calling the next middleware function if there is one.
Modified requests will be available to each middleware via the next function
Middleware chaining example
JavaScript
const express = require('express');
const app = express();
// Middleware 1: Log request method and URL
app.use((req, res, next) => {
console.log(`${req.method} request to ${req.url}`);
next();
});
// Middleware 2: Add a custom header
app.use((req, res, next) => {
res.setHeader('X-Custom-Header', 'Middleware Chaining Example');
next();
});
// Route handler
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
- Middleware 1: Logs the HTTP method and URL of the incoming request.
- Middleware 2: Sets a custom header X-Custom-Header in the response.
- Route Handler: Sends a "Hello, World!" message as the response.
Output
When a client makes a GET request to http://localhost:3000/, the server responds with:
Hello, World!
Advantages of using Middleware
- Modularity: Breaks down complex tasks into smaller, manageable functions.
- Reusability: Middleware functions can be reused across different routes or applications.
- Maintainability: Organizes code logically, making it easier to manage and update.
- Error Handling: Centralizes error handling, improving the application's robustness.
- Performance Optimization: Allows for tasks like caching, compression, and security checks to be handled efficiently.
Best Practices for Middleware in ExpressJS
- Always call next() to pass control to the next middleware unless you are ending the request-response cycle.
- Use specific middleware for different tasks (e.g., authentication, logging) to keep the code modular and clean.
- Place error-handling middleware at the end of the middleware stack to catch any unhandled errors.
- Avoid using synchronous code in middleware to prevent blocking the event loop.
Similar Reads
Express.js Tutorial Express.js is a minimal and flexible Node.js web application framework that provides a list of features for building web and mobile applications easily. It simplifies the development of server-side applications by offering an easy-to-use API for routing, middleware, and HTTP utilities.Built on Node.
4 min read
Top 50+ ExpressJS Interview Questions and Answers ExpressJS is a fast, unopinionated, and minimalist web framework for NodeJS, widely used for building scalable and efficient server-side applications. It simplifies the development of APIs and web applications by providing powerful features like middleware support, routing, and template engines.In t
15+ min read
Express Basics
Basic Express Guide
Routing Path for ExpressJSWhat and Why ? Routing in ExpressJS is used to subdivide and organize the web application into multiple mini-applications each having its own functionality. It provides more functionality by subdividing the web application rather than including all of the functionality on a single page. These mini-a
3 min read
Explain the use of req and res objects in Express JSExpress JS is used to build RESTful APIs with Node.js. We have a 'req' (request) object in Express JS which is used to represent the incoming HTTP request that consists of data like parameters, query strings, and also the request body. Along with this, we have 'res' (response) which is used to send
4 min read
Error Handling in ExpressError handling in Express ensures that your application runs smoothly by catching and managing errors before they cause issues. It allows developers to log errors, fix problems faster, and send clear responses to users, preventing technical error messages from appearing.What is Error Handling in Exp
5 min read
How to do Templating using ExpressJS in Node.js ?Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side. Templating Engine Examples: EJS (Embedded JavaScript Templating) Pug Mustache In this article w
2 min read
How To Serve Static Files in ExpressJS?ExpressJS is a popular web framework for NodeJS that allows developers to build robust web applications. One of its core functionalities is serving static files such as images, CSS, JavaScript, and HTML files.Syntaxapp.use(express.static(path.join(__dirname, 'public')));Serves Static Files: This lin
2 min read
How to enable debugging in Express App ?In express, there is a module present called DEBUG that gives log information. It tells about middleware functions, application mode, their status, and also about the requests and responses made to the server. To use this module while running the express app, set the DEBUG environment variable to ex
3 min read
Express.js express() Methods
ExpressJS express.json() FunctionThe express.json() function is a built-in middleware in Express that is used for parsing incoming requests with JSON payload. The express.json middleware is important for parsing incoming JSON payloads and making that data available in the req.body or further processing within the routes. Without us
4 min read
Express.js express.raw() FunctionThe 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
2 min read
Express express.Router() FunctionThe express.Router() function in Express.js creates a new router object that can handle requests in a modular and organized way. It serves as a mini-application with middleware and routes but is limited to specific segments of your application. By using express.Router(), you can organize your Expres
3 min read
Express express.static() FunctionIn Express.js, serving static files like images, CSS, and JavaScript used to require custom routes. With the express.static() function, you can serve static content directly from a folder, making it easier and faster. Let's explore how this function works and how you can use it in your web applicati
4 min read
Express.js express.text() FunctionThe express.text() function is a built-in middleware in Express.js that parses incoming HTTP request bodies with a text/plain content type. It allows you to easily handle raw text data sent in the body of a request, making it suitable for handling non-JSON, non-URL-encoded, or non-multipart data.The
5 min read
Express express.urlencoded() FunctionThe express.urlencoded() middleware in Express.js is used to parse URL-encoded form data, making it accessible as a JavaScript object in req.body. It's essential for handling form submissions in application/x-www-form-urlencoded format.Syntaxapp.use( express.urlencoded({ extended: true, inflate: tru
3 min read
Express.js express() function Complete ReferenceExpress.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.jso
1 min read
Express Application Methods
Express app.delete() FunctionThe `app.delete()` function is utilized to handle HTTP DELETE requests for a specified path. It takes the path as a parameter and also accepts callback functions as parameters to handle the request.Syntax: app.delete(path, callback)Parameters: path: It is the path for which the middleware function i
2 min read
Express.js | app.disable() FunctionThe app.disable() function is used to set the boolean setting name to false. It is basically the shorthand for the app.set(name, false). So instead we can use app.disable(name) function to set the false boolean value to some system Express.js settings. Syntax: app.disable(name) Installation of the
1 min read
Express.js | app.disabled() FunctionThe app.disabled() function is used to return the bool values of the setting name. It returns true if the setting name is disabled and returns false if the setting name is not disabled. Syntax: app.disabled(name) Installation of the express module: You can visit the link to Install the express modu
1 min read
Express.js | app.enable() FunctionThe app.enable() function is used to set the boolean value i.e. name to true. It is basically the shorthand for the app.set(name, true) or app.set(name, false). So instead we can use app.enable(name) function to set boolean values to some system Express.js settings. Syntax: app.enable(name) Installa
1 min read
Express.js | app.enabled() FunctionThe app.enabled() function is used to return the bool values of the setting name. It returns true if the setting name is enabled and returns false if the setting name is not enabled. Syntax: app.enabled(name) Installation of the express module: You can visit the link to Install the express module.
1 min read
Express.js app.mountpath PropertyThe app.mountpath property contains one or more path patterns on which a sub-app was mounted. Syntax: app.mountpath Parameter: No parameters. Return Value: String. Installation of the express module: You can visit the link to Install the express module. You can install this package by using this
2 min read
Express.js Mount EventThe mount event is fired on a sub-app when it is mounted on a parent app and the parent app is basically passed to the callback function. Syntax: app.on('mount', callback(parent)) Parameter: It is an event named 'mount', and the callback function is called when this event is called. Return Value:
2 min read
Express.js | app.all() FunctionThe app.all() function is used to route all types of HTTP requests. Like if we have POST, GET, PUT, DELETE, etc, requests made to any specific route, let's say /user, so instead of defining different APIs like app.post('/user'), app.get('/user'), etc, we can define single API app.all('/user') which
2 min read
Express.js Application Complete ReferenceExpress.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 Application Properties:Properties Description Express.js ap
4 min read
Express Request Methods
Express Response methods
Express.js res.app PropertyThe res.app property holds a reference to the instance of the Express application that is using the middleware. Syntax: res.app Parameter: No parameters. Return Value: Object Installation of the express module: You can visit the link to Install the express module. You can install this package by
2 min read
Express.js res.headersSent PropertyThe res.headersSent property is a boolean property that indicates if the app sent HTTP headers for the response. Syntax: res.headersSent Parameter: No parameters. Return Value: This property returns a Boolean value either True or False. Installation of the express module: You can visit the link t
2 min read
Express res.locals PropertyThe `res.locals` property is an object that holds response local variables specific to the current request. It has a scope limited to the request and is accessible only to the view(s) rendered during that particular request/response cycle, if any. Syntax:res.localsParameter: No parameters. Return Va
2 min read
Express.js res.append() FunctionThe res.append() function appends the specified value to the HTTP response header field and if the header is not already set then it creates the header with the specified value. Syntax: res.append(field [, value])Parameter: The field parameter describes the name of the field that need to be appended
2 min read
Express.js res.attachment() FunctionThe res.attachment() function is used to set the HTTP response Content-Disposition header field to 'attachment'. If the name of the file is given as a filename, then it sets the Content-Type based on the extension name through the res.type() function and finally sets the Content-Disposition 'filenam
2 min read
Express res.cookie() FunctionThe res.cookie() function is used to set a cookie in the client's browser. It allows you to assign a cookie by providing a name and a value. The value can be a simple string or an object, which will be automatically converted to JSON.Syntax:res.cookie(name, value [, options])name: The name of the co
2 min read
Express.js res.clearCookie() FunctionThe res.clearCookie() function is used to clear the cookie specified by name. This function is called for clearing the cookies which as already been set. For example, if a user cookie is set, then it can be cleared using this function. Syntax:res.clearCookie(name, [ options ])Parameters:Name: It is
2 min read
Express.js res.download() FunctionThe res.download() function transfers the file at the path as an 'attachment'. Typically, browsers will prompt the user to download.Syntax:res.download(path [, filename] [, options] [, fn])Parameters: The filename is the name of the file which is to be downloaded as an attachment and fn is a callbac
2 min read
Express res.end() FunctionThe res.end() function concludes the response process and is derived from the HTTP.ServerResponse's response.end() method in the Node core. It is employed to promptly conclude the response without including any data.Syntax: res.end([data] [, encoding])Parameters: The default encoding is 'utf8' and t
2 min read
Express.js Response Complete ReferenceExpress.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 Response Properties:Properties Description Express.js res.a
4 min read
Express Router Methods
Express.js router.all() FunctionThe 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
2 min read
Express.js router.METHOD() FunctionThe 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 f
2 min read
Express.js router.param() functionThe 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 call
2 min read
Express.js router.route() FunctionThe 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
2 min read
Express.js | router.use() FunctionThe 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
2 min read
Express.js Router Complete ReferenceExpress.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()
1 min read
Express Middleware
How to create custom middleware in express ?Express.js is the most powerful framework of the node.js. Express.js is a routing and Middleware framework for handling the different routing of the webpage, and it works between the request and response cycle. Express.js use different kinds of middleware functions in order to complete the different
2 min read
What is middleware chaining in Express JS, and how is it useful?In Express JS there is the process of Middleware chaining by which multiple middleware functions sequentially can be processed and also can be able to modify the incoming requests before they reach the final route handler. In this article, we will see the concept of Middleware Chaining in Express JS
3 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
2 min read
How to use third-party middleware in Express JS?Express JS is a robust web application framework of Node JS which has the capabilities to build web and mobile applications. Middleware is the integral part of the framework. By using the third party middleware we can add additional features in our application.PrerequisitesNode JSExpress JSPostmanTa
2 min read
Difference between app-level and route-level middleware in ExpressMiddleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next middleware function in the application's request-response cycle. In this article, we will go through app-level and route-level middleware and also see the key differences betw
3 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
2 min read