getting Cannot set headers after they are sent to the client error in express js

Viewed 25

I have created a middleware that authenticate the user that whether he is verified or not. At the first request when i try to go on protected routes it gives me success messages and verifies the jwt token but when i hit the same request again i get this error.

here is my code !

const Anime = require("../models/admin_model");
const jwt = require("jsonwebtoken");
const checkUserAuthentication = async (req, res, next) => {
  const token = req.headers.token;
  if (token) {
    jwt.verify(token.toString(), "secret", async (err, token_decode) => {
      if (err) {
        return res.json({
          status: 0,
          err: err,
          msg: "Authorization failed",
        });
      }
      console.log(token_decode);
      res.json({ data: token_decode });
      next();
      return;
    });
  }
  return res.json({
    status: 0,
    msg: "Authorization failed",
  });
};

module.exports = checkUserAuthentication;
2 Answers
 res.json({ data: token_decode });
 next();

You are responding with JSON, then you are handing control over to the next middleware or route endpoint which (presumably) is making its own response (but it can't because you already responded).

I changed my code to this.

Well maintained if-else statements.

const Anime = require("../models/admin_model");
const jwt = require("jsonwebtoken");
const checkUserAuthentication = async (req, res, next) => {
  const token = req.headers.token;
  if (token) {
    jwt.verify(token.toString(), "thisissecs", async (err, token_decode) => {
      if (!err) {
        console.log(token_decode);
        res.json({ data: token_decode });
        next();
      } else {
        return res.json({
          status: 0,
          msg: "Authorization failed",
        });
      }
    });
  }
  else{
    return res.json({
      status: 0,
      msg: "Authorization failed",
    });
}
};

module.exports = checkUserAuthentication;
Related