Using middleware in Express
Middlewares are functions that do a specific task, in a specific order and hand over to the next middleware once done. How can we use this?
Middlewares are usually introduced to a developer when needing a third-party solution to be used globally with app.use(). This post is about using middlewares on a single HTTP-request method.
Middlewares are functions called between a request and your final response. The simplest form of a middleware is the arrow function that responds with "Hello World" from a GET-request:
app.get("/", (res, req) => {
res.send("Hello World")
})
// This arrow function is the middleware used above
(res, req) => { res.send("Hello World") }
Express considers every argument after the initial path-argument to be middleware. There is no limit to how many middlewares you have.
What is important to note is that each middleware hands over the request to the next middleware once done. Because Express does not know when the middleware is done with the task; it listens for next(). For the middleware to use next(), it has to add next as it's last parameter. Middleware that is last in the chain can omit the usage of next().
app.get("/", (req, res, next) => {
/* check something */
next()
}, (req, res) => {
res.send("Hello World")
})
// These arrow functions are the middleware used above
(req, res) => { /* check something */; next() }
(req, res) => { res.send("Hello World") }
A better solution is to define the functions and call them by their name instead of writing whole functions inside of our app.get parentheses.
// These functions are the middleware used below
const firstMiddleware = (req, res, next) => { /* check something */; next() }
const secondMiddleware = (req, res) => { res.send("Hello World") }
app.get("/", firstMiddleware, secondMiddleware)
27 december 2022