What are middleware in NodeJS?


What are middleware and what is its importance to the Node platform?

asked by anonymous 18.05.2015 / 16:41

2 answers


Middleware is all type of function that is between an HTTP request and the final response that the server sends back to the client.

For example, using Express.js, a simple GET request would have this code:

var app = express();
app.get('/', function(req, res, next) {
  res.send('Hello World!');

If you want to log a request type and url of a request you can use this simple middleware:

app.use(function(req, res, next) {
  console.log(req.method, req.url);

The middleware function has 3 parameters, request, response and callback. You can have n middleware processing an HTTP request, threaded. When a middleware has just processed, it puts itself at the end of the code next(); , thus invoking the callback and the code continues to flow to the next middleware or final response.

The middleware is therefore a functionality, functions that perform intermediate processes. The most common examples are interacting with DB, fetching static files, handling errors, or redirecting.

An example of middleware chaining might look like this:

var express = require('express'), // chamar a app e dar configurações minimas
    app = express.createServer(),                                                                                                                                                 
    port = 1337;

function middleHandler(req, res, next) {
    // tratar erros
    var err = req.body.foo == null;
    if (!err) next();
    else res.send("a variavel foo não tem dados!");

app.use(function (req, res, next) {
    // escrever na BD

app.use(function (req, res, next) {
    // outros processos                                                                                                            

app.get('/', middleHandler, function (req, res) {
    console.log(ultimo passo);
    res.send("Obrigado pelo seu registo!");

app.listen(port);  // iniciar o servidor
console.log('start server');

Note that in this example above app.get has a middleware as an argument. You can use middleware chained this way too. Here's a real example:

app.get('/', githubEvents, twitter, getLatestBlog, function(req, res){
    res.render('index', {
        title: 'MooTools',
        site: 'mootools',
        lastBlogPost: res.locals.lastBlogPost,
        tweetFeed: res.locals.twitter

This is a example we use on the MooTools website to load the post from Twitter, Blog and Github to load res with the variables that the page needs to be processed.

Note: If you use app.use this middleware will be called in all request . If you want to be more specific for example GET requests you can use as in the examples above app.get('caminho', middleware1, middlware2, etc, function(){ ...

Suggested reading

18.05.2015 / 17:36

When you create a route in your web application you release an area of your application for users to access via browser or other applications access through some http client framework. When this route is accessed, two main objects appear in the callback of this function, they are:

**request**: ele é responsável por carregar dados da requisição que esta sendo realizada, geralmente vem com dados do cliente e algums parâmetros de input, como querystrings, parâmetros de rotas e body de um formulário. Em resumo, este objeto contém diversos dados do cliente.
**response**: este objeto permite que o servidor envie uma resposta para o cliente que realizou uma requisição. Aqui você pode enviar um html, json, dados via header, redirecionar a resposta para uma outra requisição, em geral este é um objeto focado em dar uma resposta para o cliente.

The middlewares are functions that can handle the inputs and outputs of the routes before and after a route is processed, that is, you can create a middleware that intercepts and verifies if a request is sending a specific header and that if the even if it is not sending the header it returns an error screen to the user, denying the request to access a certain route of the application, in this case you have created and injured a middleware that treats a pre-requisition. You can also create a middleware that at the end of each response of a route, also return a header with response metadata, for example, data paging headers. In this case we are creating a post-requisition middleware. There are no limits when injecting middlewares, you can create and configure N middlewares in your application, however it is always good to understand what each middlewares are and especially the order that each middleware is injected affects the processing of a route, ie if you inject middlewares in the wrong order, as a side effect your application may respond or even not properly process your routes, so it is extremely important to understand what each middleware does and in what order to inject them.

18.05.2015 / 17:02