How to create and use Middleware for Express.js
Introduces how to create and use middleware for Express.js. The code is also posted on Git Hub, so please refer to it.
On this page
overview
Express is a framework with the ability to perform processing between requests and responses using middleware. Middleware provides access to request objects, response objects, and the following middleware functions: Middleware is used within Express route handlers.
Here, I’ll show you how to create middleware in Express, using the following versions:
- Express v4.17.1
- nodejs v19.7.0
In addition, all the code created this time is posted on GitHub.
How to define middleware
In Express.js there are five main ways to use middleware.
- Application level middleware
Middleware that applies to the entire application. Define using
app.use()
orapp.METHOD()
.
const express = require('express');
const app = express();
app. use((req, res, next) => {
console.log('This is an application-level middleware');
next();
});
- Router level middleware
Middleware applied to a specific route or route group. Define using
router.use()
orrouter.METHOD()
.
const express = require('express');
const router = express.Router();
router. use((req, res, next) => {
console.log('This is a router-level middleware');
next();
});
app. use('/api', router);
- Embedded middleware
It’s a middleware function built into Express. For example,
express.static
,express.json
,express.urlencoded
, etc.
app.use(express.json()); // for parsing application/json
app.use(express.static('public')); // to serve static files
- THIRD PARTY MIDDLEWARE
Middleware provided by a third party. Apply with
app.use()
orrouter.use()
. For example,cookie-parser
for parsing cookies andmorgan
for creating HTTP request logs.
const cookieParser = require('cookie-parser');
app. use(cookieParser());
- Error handling middleware other middleware functions
Middleware for handling errors that occur in It usually has four arguments (err
, req
, res
, next
).
app. use((err, req, res, next) => {
console. error(err. stack);
res.status(500).send('Something broke!');
});
These middlewares help perform functions at specific points as individual requests pass through your application. Each middleware function either completes the request-response cycle or passes the request and response objects to the next middleware function in the stack.
How to create application level middleware
The example below creates an application-level middleware named myMiddleware
.
application.js
const express = require('express');
const app = express();
function myMiddleware(req, res, next) {
// middleware processing
console.log('run middleware');
next();
}
app. use(myMiddleware);
app.get('/', (req, res) => {
res.send({ message: 'Hello, World!' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Commentary
- Create Express instance
const express = require('express');
const app = express();
Import an Express module and create an instance of it.
- Define middleware functions
function myMiddleware(req, res, next) {
// middleware processing
console.log('run middleware');
next();
}
Define a middleware function named myMiddleware
. This function takes the request and response objects and calls the next
function to pass processing to the next middleware or route handler.
- Add middleware
app. use(myMiddleware);
Add middleware to your Express application. Register the myMiddleware
function as middleware using the app.use
method. This middleware is called before all route handlers are executed.
- Defining route handlers
app.get('/', (req, res) => {
res.send({ message: 'Hello, World!' });
});
Define a route handler to handle GET requests to the path /
. When a request comes in, it returns an object { message: 'Hello, World!' }
as a response.
- Start server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.
test
curl -X GET http://localhost:3000
How to create router level middleware
The example below creates a router-level middleware named myMiddleware
.
routeMiddleware.js
function myMiddleware(req, res, next) {
// middleware processing
console.log('run middleware');
next();
}
module.exports = myMiddleware;
Commentary
- Define middleware functions
function myMiddleware(req, res, next) {
// middleware processing
console.log('run middleware');
next();
}
Define a middleware function named myMiddleware
. This function takes the request and response objects and calls the next
function to pass processing to the next middleware or route handler.
- Export middleware functions
module.exports = myMiddleware;
Export the myMiddleware
function. This allows you to import and use this middleware function from other files.
routeMain.js
const express = require('express');
const app = express();
const myMiddleware = require('./myMiddleware');
app. use(myMiddleware);
app.get('/', (req, res) => {
res.send({ message: 'Hello, World!' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Commentary
- Create Express instance
const express = require('express');
const app = express();
Import an Express module and create an instance of it.
- import middleware
const myMiddleware = require('./myMiddleware');
Import a middleware function named myMiddleware
from another file.
- register middleware
app. use(myMiddleware);
Register the imported middleware function in your Express application using the app.use()
method. This will cause this middleware function to run for all routes in your application.
- Defining route handlers
app.get('/', (req, res) => {
res.send({ message: 'Hello, World!' });
});
Define a route handler to handle GET requests to the path /
. When a request comes in, it returns a JSON response with { message: 'Hello, World!' }
.
- Start server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.
test
curl -X GET http://localhost:3000
How to use built-in middleware
The Express framework has built-in middleware, these provide specific functionality. For example, you can serve static files with code like this:
builtin.js
const express = require('express');
const app = express();
// Serve static files using express.static middleware
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Commentary
- Create Express instance
const express = require('express');
const app = express();
Import an Express module and create an instance of it.
- Serve static files
app.use(express.static('public'));
Use the express.static
middleware to serve static files in the public
directory. This allows files in the public
directory to be accessed directly using their file names as paths. For example, if you have a file called sample.txt
in the public
directory, you can access the image with the URL http://localhost:3000/sample.txt
.
- Start server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.
test
curl -X GET http://localhost:3000/sample.txt
This code serves static files in the public
directory. For example, if you access http://localhost:3000/sample.txt
in your browser, you will see public/sample.txt
.
How to use 3rd party middleware
Express can take advantage of third-party middleware available through NPM. For example, you can use morgan
middleware for log output with the following code.
First, install the morgan
package into your project.
npm install morgan
Now write the code to incorporate this package into your application.
thirdparty.js
const express = require('express');
const morgan = require('morgan');
const app = express();
// output logs using morgan middleware
app. use(morgan('dev'));
app.get('/', (req, res) => {
res.send({ message: 'Hello, World!' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Commentary
- Creating instances of Express and Morgan
const express = require('express');
const morgan = require('morgan');
const app = express();
Import Express and Morgan modules. And create an instance of Express.
- log output settings
app. use(morgan('dev'));
Use Morgan middleware to output logs. Here we are using the ‘dev’ format. This will print a short response message to the console for each request.
- Defining route handlers
app.get('/', (req, res) => {
res.send({ message: 'Hello, World!' });
});
Handles GET requests to the root (’/’). When a request comes in, it responds with a JSON object containing the message ‘Hello, World!’.
- Start server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.
test
curl -X GET http://localhost:3000
This code runs the morgan
middleware for every request, which prints the details of the HTTP request to the console.
How to create error handling middleware
Error handling middleware handles errors passed to it by other middleware. Error handling middleware takes four arguments (err
, req
, res
, next
) unlike other middleware. Below is an example of creating an error handling middleware.
errorhandling.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('Something went wrong');
});
// error handling middleware
app. use((err, req, res, next) => {
console. error(err. message);
res.status(500).send('Something went wrong');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Commentary
- Create Express instance
const express = require('express');
const app = express();
Import an Express module and create an instance of it.
- Defining route handlers
app.get('/', (req, res) => {
throw new Error('Something went wrong');
});
Handles GET requests to the root (’/’). It throws an error when a request comes in.
- Define error handling middleware
app. use((err, req, res, next) => {
console. error(err. message);
res.status(500).send('Something went wrong');
});
Define error handling middleware. This middleware will be executed if an error is thrown. Prints an error message to the console and sends the error message as a response with status code 500.
- Start server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.
test
curl -X GET http://localhost:3000/
This code throws an error when a GET request comes to the ‘/’ route. This error is caught by the error handling middleware and an error message is printed to the console. Also, an error message is returned to the client with a 500 error (Internal Server Error).