How to use multiple query management functions with Node.js Express?


I need to do a repetitive auth process in most routes in my app. I decided to give some structure to it and get that repetitive work in a middleware function.

If the auth process isn't valid, I should response and avoid second function to execute, terminating the request.

So, instead of:


I tried something like:


In particular this is the dummy example I got:


function sum (request,response,next) {

    if (5>1) {
        return next();

function test (request,response,next) {
    response.send('Still alive');

However, when I try to do a GET to /rutas I'm not even getting a response. What am I doing wrong?

At server side I can see the following when I try it:

Error: Can't set headers after they are sent.

You can't call next() after ending a response, next() is meant to be called to pass the request/response to the next middleware in the stack. Consider this example:

var app = require('express')();
app.route('/rutas').get(sum, test);
app.listen(function () { console.log(this.address()); });
var i = 0;

function sum (request, response, next) {
    i += 1;
    if (i % 2 === 0) {
        return response.status(200).end('Fin');
    return next();

function test (request, response, next) {
    response.send('Still alive');