Thecodeblocks Com Middleware in Expressjs
Thecodeblocks Com Middleware in Expressjs
NODEJS
A Gentle Introduction of
Middleware in Expressjs
Kevin Durant
Feb 16, 2023 5 min
What is Middleware?
Middleware is a function that receives a request and a response object, and
optionally a third argument, usually called next. The middleware function can then
modify the request and/or response objects, and call the next function to pass
control to the next middleware in the chain.
Middleware functions can be used to perform a wide range of tasks, such as:
Logging
Authentication
Authorization
Error handling
Request parsing
Response formatting
Caching
Application-level Middleware
Application-level middleware functions are executed for every incoming request to
the application. They can be defined using the app.use() method or any of its aliases,
such as app.all(), app.get(), app.post(), etc.
Here's an example of a simple application-level middleware that logs the URL and
HTTP method of each incoming request:
app.listen(3000, () => {
console.log('Server started on port 3000')
})
In this example, the app.use() method is used to define the middleware function. The
middleware function logs the URL and HTTP method of each incoming request using
console.log(), and then calls the next function to pass control to the next
middleware in the chain.
Router-level Middleware
Router-level middleware functions are executed for every incoming request to a
specific router. They can be defined using the router.use() method or any of its
aliases, such as router.all(), router.get(), router.post(), etc.
router.use(isAuthenticated)
app.use('/api', router)
app.listen(3000, () => {
console.log('Server started on port 3000')
});
In this example, the router.use() method is used to define the middleware function.
The middleware function checks if the user is authenticated by checking if the
req.user property is set, and then either calls the next function to pass control to
the next middleware in the chain, or sends a 401 Unauthorized response if the user
is not authenticated.
Route-level Middleware
Route-level middleware functions are executed for a specific route. They can be
defined using the router.METHOD() method, where METHOD is the HTTP method of
the request, such as router.get(), router.post(), etc.
Here's an example of a route-level middleware that logs the IP address of the client
making the request:
app.use('/api', router)
app.listen(3000, () => {
console.log('Server started on port 3000')
});
In this example, the router.get() method is used to define the route and the route-
level middleware function. The middleware function logs the IP address of the client
making the request using console.log(), and then calls the next function to pass
control to the route handler, which sends the response "Hello, world!".
Built-in Middleware
Express.js comes with a number of built-in middleware functions that can be used
out of the box. Here are some examples:
app.use(express.static('public'))
app.listen(3000, () => {
console.log('Server started on port 3000')
});
Third-Party Middleware
In addition to built-in middleware functions, Express.js supports the use of third-
party middleware functions. There are many third-party middleware functions
available for Express.js, and they can be installed using npm.
app.use(bodyParser.json());
app.listen(3000, () => {
console.log('Server started on port 3000')
});
In this example, the app.use() method is used to define the body-parser middleware
function, which parses incoming JSON payloads and makes them available on the
req.body property. The parsed JSON payload is then logged to the console, and a
response of "User created" is sent back to the client.
Conclusion
In this blog, we have explored the world of middleware in Express.js. We have
learned what middleware is, how it works, and how it can be used to perform a wide
range of tasks. We have also looked at the different types of middleware that are
available in Express.js, including built-in middleware functions and third-party
middleware functions.
We have seen how to define middleware functions at the application level and at the
route level, and we have looked at some examples of how middleware functions can
be used to perform tasks such as logging, parsing request bodies, and serving static
files.
In addition to the middleware functions that we have discussed, there are many
other middleware functions available in the Express.js ecosystem. Some of these
middleware functions are designed to handle specific tasks, such as authentication
or validation, while others are more general-purpose and can be used for a wide
range of tasks.
If you are building an application with Express.js, it is worth taking the time to
explore the different middleware functions that are available, and to choose the
functions that are best suited to your needs.
READ NEXT
COMMENTS (0)
Sign up now
Subscribe to thecodeblocks
Don't miss out on the latest news and tutorials
Subscribe now
Copyright by @ thecodeblocks