François Richard François Richard - 3 months ago 11
Node.js Question

What happens if you overload the same route with express js?

I would like to know what happens if I write that in expressjs ( we assume app is an expressjs app).

app.get.use('/here' , function(req, res) {
// EXECUTE SET OF ACTION NUMBER 1
});

app.get.use('/here' , function(req, res) {
// EXECUTE SET OF ACTION NUMBER 2
})


We write the same route twice but with different set of actions. Will the second declaration overload the first one ?

Answer

It depends on what's happening inside the callback function. Consider three different examples:

a)

const express = require('express');
const app = express();

app.get('/', (req, res, next) => {
  console.log('1!');
  res.json(true);
});

app.get('/', (req, res) => {
  console.log('2!');
  res.json(true);
});

app.listen(3000);

b)

const express = require('express');
const app = express();

app.get('/', (req, res, next) => {
  console.log('1!');
});

app.get('/', (req, res) => {
  console.log('2!');
  res.json(true);
});

app.listen(3000);

c)

const express = require('express');
const app = express();

app.get('/', (req, res, next) => {
  console.log('1!');
  next();
});

app.get('/', (req, res) => {
  console.log('2!');
  res.json(true);
});

app.listen(3000);

In the (a) case, the workflow is top-to-bottom. The first route handler kicks in, console.logs "1!" and responds with true. Since the complete response has been sent, the following route handler will never be reached.

In the (b) case, the execution stalls at the first route handler. It neither responds or allows execution to go further. If you curl this app, you'll end up with request timeout, although you'll see "1!" on the console.

Finally, in the (c) case, you can see next function call. This is what makes Express proceed with execution and go to the next route handler, if any. Since there's another route handler, it is executed, so you end up with both "1!" and "2!" printed on the console, as well as the response sent correctly.

A few points here:

  • always call next if you expect another route handler to run after current one, and it is especially important when you're writing a middleware or, as in your case, a "middleware-like" app that you are possibly going to add to another app,
  • it's okay to build up response in more than one handler, for example, when the first one declares headers and/or body, and the next one adds something to headers and/or body (which is weird and I'd strongly discourage you from doing so), and
  • once the response has been sent, the execution stops, and none of the further route handlers can be reached (which isn't guaranteed when you use conditional blocks, for example).
Comments