How can I combine multiple middlewares into one? #5213
-
What is the standard and suggested way to combine multiple middlewares into one? method 1 using
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Usually if you need to use multiple middleware functions in Express, they can be passed as an array or a sequence of functions (or both). For example here I have 3 middleware functions, 2 of which are passed as an array, in case I'd like to reuse the same set on another route without listing them all again: import express from "express";
function m1(req, res, next) {
console.log("middleware 1");
next();
}
function m2(req, res, next) {
console.log("middleware 2");
next();
}
function m3(req, res, next) {
console.log("middleware 3");
next();
}
const combined = [m1, m2];
const app = express();
app.get("/", combined, m3, (req, res) => res.send("Hello world!"));
const server = app.listen(0, async () => {
const uri = `http://127.0.0.1:${server.address().port}/`;
const r = await fetch(uri);
console.log(await r.text());
server.close();
}); The Using middleware guide also contains similar examples, which I recommend checking out. |
Beta Was this translation helpful? Give feedback.
Your usage of
connect
is very similar to creating aRouter
or evenexpress()
app, sinceconnect
also is an extensible HTTP server framework, so you could probably use that if you don't want additional dependencies.You could also use
next('route')
ornext('router')
to (conditionally) skip some middleware or whole router. This however won't let you run it inside other middleware - only before or after.