What is Middleware?
What is Middleware?
Middleware in express.js are the functions that are invoked by the routing layer of express.js before the final request handler.
middleware is a function that appears between the requests and responses.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware
Middleware gets executed when the server receives a request and before the sending of a response
Middleware can be used for error handling.
Middleware in express.js can perform the following tasks.
Execute code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware in the stack.
To achieve the chaining in express next() function is used, which is responsible for calling the next middleware function.
Middleware functions are functions that have access to the request object (req) and the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
What is this next()?
middleware is a function that will the receive the Request(req) and Response(res) objects. The third argument is next function which you should call once your middleware code completed. This means you can wait for asynchronous database or network operations to finish before proceeding to the next step. If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function.
Types of express middleware
1. Application level middleware app.use
2. Router level middleware router.use
3. Built-in middleware express.static,express.json,express.urlencoded
4. Error handling middleware app.use(err,req,res,next)
5. Thirdparty middleware bodyparser,cookieparser
Router Level Middleware
router-level middleware by using the router.use() and router.METHOD() functions.
const express = require('express');
const app = express();
const router = express.Router()
router.use((req,res,next)=>{
console.log("Time:",new Date())
next()
})
router.get("/user/:id",(req,res,next)=>{
console.log('Request URL:', req.originalUrl)
next()
},(req,res,next)=>{
console.log('Request Type:', req.method)
next()
},(req,res)=>{
res.json({
status:true,
id:req.params.id
})
})
app.use('/',router)
Error Handing Middleware
Error Handing Middleware function with default error handling params, error-handling functions have four arguments.
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
Third-party Middlewares
1. body-parser
2. app.use(bodyParser.urlencoded({extended:false}))
3. app.use(bodyParser.json())
Example :-
The middleware function is assigned to a variable named myTutorial.
const myTutorial = function (req, res, next) {
console.log('Example of middleware function.')
next()
}
NOTE :- the call above to next(). Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.
To load the middleware function, call app.use() and specifying the middleware function name.
const express = require('express')
const app = express()
const myTutorial = function (req, res, next) {
console.log('Example of middleware function.')
next()
}
app.use(myTutorial)
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000)
The middleware function myTutorial simply prints a message, then passes on the request to the next middleware function in the stack by calling the next() function.
const express = require('express')
const app = express()
const requestTime = function (req, res, next) {
req.requestTime = Date.now()
next()
}
app.use(requestTime)
app.get('/', (req, res) => {
let responseText = 'Hello World!<br>'
responseText += `<small>Requested at: ${req.requestTime}</small>`
res.send(responseText)
})
app.listen(3000)
Middleware function validateCookies
middleware function that validates incoming cookies and sends a 400 response if cookies are invalid.
const express = require('express')
const cookieParser = require('cookie-parser')
const cookieValidator = require('./cookieValidator')
const app = express()
async function validateCookies (req, res, next) {
await cookieValidator(req.cookies)
next()
}
app.use(cookieParser())
app.use(validateCookies)
// error handler
app.use((err, req, res, next) => {
res.status(400).send(err.message)
})
app.listen(3000)
Previous
Next