Using Express Middlewares with Zero

Express.js has lots of great middleware plugins. There are multiple ways to use them with Zero.

Exporting an Express App

One way to solve this is to just export your express app. Here is one API with two logging middlewares.

// ./user.js
const app = require('express')()
var logOriginalUrl = function (req, res, next) {
console.log('url', req.originalUrl)
next()
}
var logMethod = function (req, res, next) {
console.log('method', req.method)
next()
}
app.use([logOriginalUrl, logMethod])
app.use((req, res)=>{
res.send("User Info")
})
module.exports = app

This method is great if you only want to use a middleware in a few handlers. But it's not much feasible when you want to add a middleware for all endpoints.

Wrapping Method

Another workaround is to wrap your API handler with the middleware, below are two middlewares, one is to log the HTTP method of each request and another to enable CORS (cross-origin resource sharing). We keep them in a separate file so we can import them to each handler:

// ./common/middlewares.js
// MIDDLEWARES
var enableCORS = (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
};
var logMethod = function(req, res, next) {
console.log("method", req.method);
next();
};
// Call each middleware and then our handler
module.exports = (req, res, handler) => {
logMethod(req, res, () => {
enableCORS(req, res, () => {
handler(req, res);
});
});
};

We then use these middlewares in our handler:

// ./user.js
const middlewares = require("./common/middlewares");
module.exports = (rq, rs) =>
middlewares(rq, rs, (req, res) => {
res.send("Some User Info");
});

Copyright © 2019 Remote Interview, Inc. All rights reserved.