1

I have an Express middleware function that is checking if the user is authenticated. If they are not authenticated, I want to send some JSON to my frontend that says this, but if they are, I want to continue with my normal function at this route.

For example,

const checkAuth = (req, res, next) => {
    if (!authenticated){
        res.status(401).send("You are not authorized to view this content");
    }
    next();
}


app.get('/protectedRoute', checkAuth, (req, res) => {
    // SOME OTHER DATABASE STUFF HERE WHICH RESULTS IN VARIABLE "data"
    res.json({msg: data});
});

However, I get this error, when trying to return the json:

Cannot set headers after they are sent to client

How would I do this? Thanks!

Tejas_hooray
  • 606
  • 1
  • 6
  • 16

2 Answers2

1

That's because you're executing next() even when the user fails authentication check. This causes you to execute additional code after sending the 401 response which is what the error is complaining about.

Just add an else:

const checkAuth = (req, res, next) => {
    if (!authenticated){
        res.status(401).send("You are not authorized to view this content");
    }
    else {
        next();
    }
}

alternatively, some people prefer to use return to break the flow:

    if (!authenticated){
        res.status(401).send("You are not authorized to view this content");
        return;
    }
    next();
slebetman
  • 109,858
  • 19
  • 140
  • 171
1

Stop the request when you detect the request is not authenticated.

Add return keyword in if true block

const checkAuth = (req, res, next) => {
    if (!authenticated){
        return res.status(401).send("You are not authorized to view this content");
    }
    next();
}
hoangdv
  • 15,138
  • 4
  • 27
  • 48