Using return or next after calling res.redirect

Viewed 4416

I am trying to write a code for redirecting all my Http requests to Https, now I wanted to ask I have seen below code on many different websites but some of them use return with res.redirect, some use return after res.redirect, some don't use anything and some use only next() after res.redirect.

I just want to ask what is the use of return or calling next() here. Or am I missing anything here ??

app.use(function(req,res,next) {
    if(req.headers["x-forwarded-proto"] == "http") {
        console.log('Request was HTTP');
        /* return ??*/ res.redirect("https://" + req.headers.host + req.url);
        // return or next() or nothing ??.
    } else {
        console.log('Request was not HTTP');
        return next();
    } 
});
2 Answers

In general, I do recommend to use:

return res.redirect("https://" + req.headers.host + req.url);

due to in this case you explicitly return the redirect response.

In most case just res.redirect() is enough and you do have a redirect response (HTTP 302), but an error may appear in your server log especially if you use it inside async (req, res) => {} function.

next() is a part of Express middleware. It tells to execute the next middleware function on the functions flowchart. If its not used the next middleware will not be executed.

return is used just to ensure that the execution stops after triggering the callback i.e no part of callback is processed again whether you use it with next or redirect it has same use to stop the execution of that particular function.

Related