Express.js Middleware
Middleware 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. Middleware functions can be used to perform various tasks like logging, authentication, handling errors, etc.
Syntax
The basic syntax for using middleware in Express.js is as follows:
app.use([path], middlewareFunction)
Here,
app
is the Express instancepath
is an optional parameter representing the URL path for which the middleware function should be invokedmiddlewareFunction
is the middleware function to be executed
Example
const express = require('express')
const app = express()
// middleware function
const logger = (req, res, next) => {
console.log(`${new Date().toISOString()} ${req.method} ${req.originalUrl}`)
next()
}
// register middleware function
app.use(logger)
// route handler
app.get('/hello', (req, res) => {
res.send('Hello, World!')
})
// start the server
app.listen(3000, () => {
console.log('Server started on port 3000')
})
Output
When you visit http://localhost:3000/hello
, you should see the following output in the console:
2022-01-01T00:00:00.000Z GET /hello
Explanation
In the above example, we have defined a middleware function logger
that logs the current timestamp, HTTP method, and URL path for each incoming request. The middleware function is registered using app.use
method, which means it will be executed for every incoming request.
The middleware function takes three parameters: req
, res
, and next
. req
represents the request object, res
represents the response object, and next
is a function that should be called to pass control to the next middleware function in the chain.
After the middleware function is registered, we define a route handler for the URL path /hello
. When this URL is requested, the route handler sends the response Hello, World!
.
Use
Middleware functions can be used to perform various tasks such as processing the request body, handling errors, authentication and authorization, serving static files, etc.
You can use middleware functions to:
- Validate user input before processing a request
- Implement authentication and authorization
- Log every incoming request and response
- Compress response bodies to reduce network bandwidth
- Handle errors occurring in application code
- Serve static files
Important Points
- Middleware functions in Express.js have access to the request (
req
) and response (res
) objects, as well as the next middleware function in the chain. - Middleware functions can perform a wide range of tasks, such as data validation, authentication, logging, and error handling.
- Middleware functions can be registered using the
app.use
method in Express.js. - Middleware functions can also be registered for specific URL paths using the optional
path
parameter inapp.use
.
Summary
Middleware functions are an integral part of Express.js applications. They allow you to perform a wide range of tasks such as data validation, authentication, logging, and error handling. Middleware functions are registered using the app.use
method and can be used to process every incoming request or specific URL paths.