Search code examples
javascriptnode.jsexpresspassport.jspassport-local-mongoose

I am trying to return JSON for successful authentication via passportjs but I'm getting "Error Cannot set headers after they are sent to the client."


I am trying to send a JSON file after registering a user and authenticating them. Callback function after authentication is running as well, but the following error is thrown. Please help!

Here is the controller function :

var passport = require("passport");
var connection = require("../config/dataBase");
var User = connection.models.User;

const signUp = (req, res) => {
  User.register(
    {
      username: req.body.username,
      data: {
        firstName: req.body.firstName,
        lastName: req.body.lastName,
      },
    },
    req.body.password,
    function (err, user) {
      if (err) {
        console.log(err);
      } else {
        console.log("1");
        passport.authenticate("local", {
          failureRedirect: "/login",
          failureMessage: true,
        }),
          (function (err, usr) {
            console.log("Registered and Authenticated");
            return res.json({
              authenticated: true,
              status: {
                message: "Successfully Signed up and authenticated",
                code: 200,
              },
            });
          })(req, res);
      }
    }
  );
  res.end();
};

module.exports = signUp;

Here is the full Error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/pristyncare/Documents/MERN-Blog/Server/node_modules/express/lib/response.js:767:10)
at ServerResponse.json (/home/pristyncare/Documents/MERN-Blog/Server/node_modules/express/lib/response.js:264:10)
at /home/pristyncare/Documents/MERN-Blog/Server/controllers/signupController.js:26:24
at /home/pristyncare/Documents/MERN-Blog/Server/controllers/signupController.js:33:13
at /home/pristyncare/Documents/MERN-Blog/Server/node_modules/passport-local-mongoose/index.js:247:30
at processTicksAndRejections (node:internal/process/task_queues:96:5) {

code: 'ERR_HTTP_HEADERS_SENT' }


Solution

  • My bad, i was sending response twice. Just needed to remove res.end() part at the end of snippet and it worked.