Nodejs redirecting issue as 'Error: Can't set headers after they are sent'

In nodejs, I am facing one issue like 'Error: Can't set headers after they are sent' when I am trying to redirect after saving the form. The application used to get crash here.

Here is the code.

exports.createNewUser = function(req, res) {
   var data = {};
   data.title = 'All users';

      if(req.method == 'POST'){
        var firstName = req.body.firstName;
        var lastName = req.body.lastName;
        var email =;
        var gender = req.body.gender;
        var mobile =;
        var address = req.body.address;

        // Validation
        req.checkBody('firstName', 'Firstname is required').notEmpty();
        req.checkBody('lastName', 'Lastname is required').notEmpty();
        req.checkBody('email', 'Email is required').notEmpty();
        req.checkBody('email', 'Email is not valid').isEmail();
        req.checkBody('mobile', 'Mobile is required').notEmpty();
        req.checkBody('gender', 'Please choose you gender').notEmpty();
        req.checkBody('address', 'Address is required').notEmpty();
        req.checkBody('checkbox', 'You need to accept the terms').notEmpty();

        var errors = req.validationErrors();
           data.errors = errors;
           var passwordGen = generator.generate({length: 10,numbers: true});
           var newUser = new User({
             firstName: firstName,
             email: email,
             password: passwordGen,
             mobile : mobile,
             gender : gender,
             address : address

          // save user to database
, doc) {
            if (err) {
                data.error = 'There are some error';
                req.flash('error_msg', 'There are some error');
                req.flash('success_msg', 'You created a new user');



  res.render('user/add', data);

Don't know what I am doing wrong here. Please help. Thank you.

2 answers

  • answered 2018-01-11 20:46 Koray Gocmen

    After saving the new user, you try to redirect the user to '/users/all'. But at the end of your controller, you also try to render a page.

    Your code probably succeeds creating the new user and tries to redirect, but before finishing that it receives a render page command as well. To fix the issue you should add

    req.flash('success_msg', 'You created a new user');

    By including a return, you ensure to redirect the user and not to continue with the rest of the logic.

  • answered 2018-01-11 20:46 HTownGirl17

    in function you list err & doc inside function. doc isn't used in your if else statements after it. What's the point of doc, then?