Creating middleware

Middleware (functions that are passed to app.use) is a fundamental concept in Express (and other web frameworks).

If we need some custom functionality (for instance, business logic related), we can create our middleware.

Let's copy the app folder from our main recipe to the custom-middleware-app and create a middleware folder with an answer.js file:

$ cp -fr app custom-middleware-app
$ cd custom-middleware-app
$ mkdir middleware
$ touch middleware/answer.js

Now we'll place the following code in middleware/answer.js:

module.exports = answer 
 
function answer () { 
  return (req, res, next) => { 
    res.setHeader('X-Answer', 42) 
    next() 
  } 
} 

Finally, we need to modify the index.js file in two places. First at the top, we add our answer middleware to the dependency loading section:

const {join} = require('path') 
const express = require('express') 
const index = require('./routes/index') 
const answer = require('./middleware/answer') 

Then we can place our answer middleware at the top of the middleware section, just underneath the port assignment:

app.use(answer()) 

Now let's start our server:

$ node index.js 

And hit the server with curl -I to make a HEAD request and view headers:

$ curl -I http://localhost:3000  

We should see output similar to the following:

HTTP/1.1 200 OK 
X-Powered-By: Express 
X-Answer: 42 
Content-Type: text/html; charset=utf-8 
Content-Length: 226 
ETag: W/"e2-olBsieaMz1W9hKepvcsDX9In8pw" 
Date: Thu, 13 Apr 2017 19:40:01 GMT 
Connection: keep-alive 

With our X-Answer present.

Middleware isn't just for setting custom headers, there's a vast range of possibilities, parsing the body of a request and session handling to implementing custom protocols on top of HTTP.