Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express: composing middleware

I want to move a series of app.use() calls into its own module. The easiest way to encapsulate this is to expose a function(app) in the exports, but I feel that handing over the app object is too much of an opaque interface.

I would like to expose a middleware to be app.use()'d from outside the module. I need to chain/compose the middlewares used internally.

Is there a stylish way of doing this, or an alternative? What's the easiest way of going about it? Anything I should avoid?

like image 547
slezica Avatar asked Oct 13 '13 02:10

slezica


People also ask

What is Expressjs middleware?

Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the HTTP request and response for each route (or path) it's attached to. In fact, Express itself is compromised wholly of middleware functions.

Does Express supports middleware?

Express provides a built in middleware function express. static . Static files are those files that a client downloads from a server. It is the only middleware function that comes with Express framework and we can use it directly in our application.

How many types of middleware are in Express?

Here we have two middleware functions attached to the route with route path /products .

Is Express router a middleware?

Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.


1 Answers

This answer is a little late, but here it goes anyway...

// composedMiddleware.js
const express = require('express')
const ware1 = (req, res, next)=>{...}
const ware2 = (req, res, next)=>{...}
const router = express.Router()
router.use(ware1)
router.use(ware2)
export default router

// app.js
const composedMiddleWare = require('./composedMiddleware.js')
app.get('/something', (req, res, next)=>{...})
app.get('/something', composedMiddleWare)

If the code isn't self-explanatory, then just note that routers are also middleware. Or, to put it more precisely, "a router behaves like middleware itself, so you can use it as an argument to app.use()" ref.

like image 183
Bijou Trouvaille Avatar answered Oct 12 '22 13:10

Bijou Trouvaille