Justin Elkow
Justin Elkow

Reputation: 2943

Node js - Express js code is executing after redirect

I have an express web app. And within the app, I have a route that makes several calls to the database. During each call, if it fails, then I am redirecting the browser to a page /temporarily-unavailable (basically a generic error page that doesn't freak the user out, just says try back later).

PORTION OF PSEUDO-CODE

app.get('/sign-in/twitter', function(req, res, next){
    request({
        'method' : 'GET',
        // BLAH BLAH BLAH CALL TO DATABASE
        // DATABASE CALLBACK
        function (error, response, body){
            if (response.statusCode === 200) {
                // DO GOOD STUFF
            }
            else if (response.statusCode === 404) {
                // DO COOL STUFF
            }
            else {
                temporarilyUnavailable(req, res, next);
            }
            // DO MORE STUFF AND SEND A RESPONSE
        }
    }
}

PORTION OF PSEUDO-CODE FOR TEMPORARILY UNAVAILABLE FUNCTION

res.set({
    'Cache-Control' : 'private, no-cache, no-store, must-revalidate,
    'Content-Type' : 'text/plain;charset=utf-8',
}

res.redirect(302, 'https://' + req.host + '/' + url);

Shoudn't the res.redirect in the TEMPORARILY UNAVAILABLE FUNCTION prevent any code further down from being executed?

Upvotes: 5

Views: 5606

Answers (1)

Brad
Brad

Reputation: 163262

No, it shouldn't.

You're simply calling a function on the response. Code below it can execute. There is nothing magical about res.redirect().

A common practice to avoid this is to simply return when you redirect or otherwise call a callback where you want to exit the current function:

return res.redirect(302, 'https://' + req.host + '/' + url);

Upvotes: 18

Related Questions