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!