Middleware explained with a basic NodeJs & Express authentication.

David Joos
2 min readFeb 21, 2019

While scrolling through Stackoverflow, watching my tags, i have noticed that the most of the beginners struggle with the middleware pattern and how to apply this to their app — event though they have used it before with bodyparser and/or other tools.

Javascript — a love.

It’s no rocket science to understand middleware and to use them effective. Let’s build a very basic authentication middleware and apply it to our routes.

First of all: Authentication means that we should have some source of truth e.g. a database. This will not be part of this little example, but i assume there are plenty database tutorials out there.

A middleware is just a function, which can applied to another function which executes the middleware function with it’s own parameters and passes the outcome of it to itself. Easy right? So let’s define our middleware function:

const authenticate = (req, res, next) => {
// parse the user - or anything else -
// out of the request body.
let user = req.body.user
// do some checking
if (user === database.user) {
// user successfully authenticated -> call next, which
// terminates the middleware-function and the parent
// continues.
next()
)
// user didn't match any we know? Respond with authentication
// failure.
res.status(401);
}

Very easy. Now we can apply this middleware to every route of our back-end. Because we are handling req and res objects it makes no sense to apply it to other functions.

We have now to decide whether to apply it to all of our routes or just to some certain ones.

// apply it to all routes
app.use(authenticate)
// apply it to a certain route
app.get('/sensibledata', authenticate, (req, res) => {
// only authenticated user will have access to the
// following code - everyone else received a status
// 401 to their request.
res.send({ data: sensibleData })
}

Done.

--

--

David Joos

Works at Bosch.IO as a Software Engineer. Thrilled about coding, beer and other technical stuff ;).