The Unexpected Benefits of Express Middleware

If you’ve developed web apps using Javascript on the server side, you’ve seen the Express framework. It simplifies Node’s basic http handler significantly, and makes it easy to write simple servers that look pretty, like this one:

const express = require('express');
var app = express();
app.listen(1337);
app.get('/hello', function (req, res, next) {
res.send('hello world!');
});
app.post('/hello', function (req, res, next) {
res.send({ "hello" : "world });
});
app.get('/world', teachToSing, save);

That cleanliness comes from middleware. Clean code is easier-to-read and, most importantly, easier-to-follow when a new developer needs to fix a bug in two years. But cleanliness is middleware’s expected benefit.

Communicative Middleware

Middleware isn’t just clean, it’s communicative as well. Middleware can save diverse data in the request object and pass that saved data down the stack to later request handlers, like this:

// Middleware 1
const request = require('request');
oauthController.getNewToken = function (req, res, next) {
'use strict';
  let client = request.createClient('https://provider.prov/api');
  client.get(oauthAccessUrl, function (err, res, body) {
    if (err) console.log('err', err);
    if (body) {
req.oauthToken = body.access_token;
next();
}
}
}
// Middleware 2
const request = require('express.json()');
postController.makePost = function (req, res, next) {
'use strict';
  let userToken = req.oauthToken
  let request = { 
host: 'https://provider.prov/api/v2/post-blog',
port: 80,
path: '/login',
method: 'POST'
}
  let userdata = {
"token" : userToken,
"post" : "hello world"
}
  let doPost = http.request(request, function (rq, rs) {
rs.send(userdata);
}

next();
}
// Call it this way
app.get('/post-blog-to-provider'
, oauthController.getNewToken
, postController.makePost);

This makes middleware very well-behaved helpers.

Middleware as Promises

You’ll notice I used an asynchronous GET request in that code and didn’t have to wrap it in a promise — that’s right, one of the great, and often-overlooked, things Express middleware gives developers for free is easy synchronous handling of asynchronous code.

If you make the next(); call within any given middleware script itself respect asynchronous calls within that script, you’ll get what is effectively a promise: next() won’t be called until the asynchronous process is complete.

You can use this as a quick trick to handle short-lived asynchronous calls on the server side. Or, now that you know it, you can know to use other tools, such as Promises, to make sure that you don’t halt server execution while you wait for an asynchronous call to resolve.

But middleware doesn’t just give us clean code — it gives us a free gift: fake promises.

Show your support

Clapping shows how much you appreciated Wade Armstrong’s story.