app.get - is there any difference between res.send vs return res.send

node.jsExpress

node.js Problem Overview


I am new to node and express. I have seen app.get and app.post examples using both "res.send" and "return res.send". Are these the same?

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

app.get('/', function(req, res) {
  res.type('text/plain');
  res.send('i am a beautiful butterfly');
});

or

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

app.get('/', function(req, res) {
  res.type('text/plain');
  return res.send('i am a beautiful butterfly');
});

node.js Solutions


Solution 1 - node.js

The return keyword returns from your function, thus ending its execution. This means that any lines of code after it will not be executed.

In some circumstances, you may want to use res.send and then do other stuff.

app.get('/', function(req, res) {
  res.send('i am a beautiful butterfly');
  console.log("this gets executed");
});

app.get('/', function(req, res) {
  return res.send('i am a beautiful butterfly');
  console.log("this does NOT get executed");
});

Solution 2 - node.js

I would like to point out where it exactly made a difference in my code.

I have a middleware which authenticates a token. The code is as follows:

function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1] || null;

  if(token === null) return res.sendStatus(401); // MARKED 1
  jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
    if(err) return res.sendStatus(403); // MARKED 2
    req.user = user;
    next();
  });
}

On the // MARKED 1 line, if I did not write return, the middleware would proceed and call next() and send out a response with status of 200 instead which was not the intended behaviour.

The same goes for like // MARKED 2

If you do not use return inside those if blocks, make sure you are using the else block where next() gets called.

Hope this helps in understanding the concept and avoiding bugs right from the beginning.

Solution 3 - node.js

app.get('/', function(req, res) {
	res.type('text/plain');
	if (someTruthyConditinal) {
		return res.send(':)');
	}
	// The execution will never get here
	console.log('Some error might be happening :(');
});

app.get('/', function(req, res) {
	res.type('text/plain');
	if (someTruthyConditinal) {
		res.send(':)');
	}
	// The execution will get here
	console.log('Some error might be happening :(');
});

Solution 4 - node.js

To Add a little bit more context to the examples above. Express has layers. So if you return in your function you end the execution. If you not end that you can go further in your layered logic.

So the next function passed to each layer can be called to execute the next layer. If you don't call next the execution stops after your method excuted is executed. (Return just exits the function)

The response object is still available after sending. It is just not possible to write to it again because it has already completed after you did res.end() or res.send().

const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

// a controller handles a http request and terminat it
const controller = (req, res, next) => {
  // return http response to client
  res.send('hello world');

  // do something after you sended request
  console.log('do something else');

  // if you call next the request will go to the next layer -> afterSend,
  // if you do not call next the execution will end
  next();
};

// this middleware/layer is executed after response is send to client
const afterSend = (req, res, next) => {
  // do something after you sended request, but not send again -> readonly
  console.log(res);

  // this would throw an error
  // res.send()
  // res.end()
  // etc...
};

// we skip routers here
app.get('/hello', controller, afterSend);

app.listen(port, () => {
  console.log(`Running on ports ${port}`);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBarry MSIHView Question on Stackoverflow
Solution 1 - node.jsAJ FunkView Answer on Stackoverflow
Solution 2 - node.jsthewebjackalView Answer on Stackoverflow
Solution 3 - node.jsDiego ZoracKyView Answer on Stackoverflow
Solution 4 - node.jsMisterMonkView Answer on Stackoverflow