javascriptnode.jsexpressmern

Why the console.log in last use is working even though response is sent by get


    app.use((req, res, next) => {
    console.log('First middleware ran');
    console.log("host: ", req.hostname);
    console.log("path: ", req.path);
    console.log("method: ", req.method);
    next();
});

app.get('/home', (req, res) => {
    res.send('<h1>Home Page</h1>');
});

app.use((req, res) => {
    console.log('Second use middleware ran');
    res.send('<h1>About Page</h1>');
});

app.listen(3000, () => {
    console.log('Server is listening on port 3000');
});

I an confused it shouldn't run the last use since get is sending a response, please explain why is it happening


Solution

  • The app.use middleware runs on every request, and in your case, you've got two of them.

    First, the one at the top runs every time, logging stuff like the host, path, and method. It then calls next(), meaning, "Okay, pass control to the next middleware or route."

    Then, when you hit /home, the app.get('/home') sends the response for that route. But... after that, the second app.use runs anyway, because you didn't stop it with next() in your /home route. So, that second middleware logs, "Second use middleware ran" and tries to send another response (which might cause issues).

    Basically, next() is like passing the baton in a relay race, and both of those use middlewares are in the race unless you stop them.