0

I have this piece of middleware where if no token found the request responds and that is what happens but the console.log line still runs after the request responds. Why does that happen? I always thought that the res.json call would "end" the middleware. Thanks in advance.

const jwt = require("jsonwebtoken")
const config = require("../../utils/config")

const requireAuthenticated = (req, res, next) => {
    const token = req.headers.authorization

    if (!token) {
        res.status(400).json({ error: 'Token required' })
    }

    console.log(jwt.verify(token, config.JWT_SECRET))
}

module.exports = requireAuthenticated
ray
  • 3
  • 1
  • return res.status(400).json({ error: 'Token required' }); would terminate the execution if that's what you intend. – Adil Khalil Apr 09 '21 at 18:26
  • What is it that makes you believe that execution will end upon calling `res.json(...)` without a `return` statement? – Martin Apr 09 '21 at 18:32
  • Thanks Adil, good point, i googled and found this helpful [link](https://stackoverflow.com/questions/37726863/nodejs-difference-between-res-json-and-return-res-json). – ray Apr 09 '21 at 18:33

1 Answers1

0

Well its just how Javascript works. When a function is called, there no special way to know if the function execution is complete/incomplete. It just runs the complete function. However you can exit the function whenever you want.

You can use return statement to stop executing after the condition fails

Option1: Add return after res.json().

if (!token) {
    res.status(400).json({ error: 'Token required' });
    return;
}

Option 2: You can also return res.json()

if (!token) {
    return res.status(400).json({ error: 'Token required' })
}