title: How to validate a users username when registering using express validator
body: <p>I am using express/node to create a back-end api for authentication/authorization and using mongodb to store the data.</p>
  
  <p>I'm using <a href="https://github.com/ctavan/express-validator" rel="nofollow">express-validator</a> to validate the input req. I want to validate whether a username already exists or not - the library recommends i should use an async function to do this.</p>
  
  <p>Although it returns the data with the correct error message in postman, my server crashes with the message. </p>
  
  <blockquote>
    <p>Error: Can't set headers after they are sent.</p>
  </blockquote>
  
  <p><strong>Server.js</strong></p>
  
  <pre><code>app.use(validator({
  
      customValidators: {
  
          isUsernameAvailable: function(username) {
              return new Promise(function(resolve, reject) {
  
                  User.findOne({'username': username}, function(err, results) { 
  
                      if(err) {
                          return resolve(err);
                      }
                      reject(results);
  
                  });
  
              });
          }
      }
  
  }));
  </code></pre>
  
  <p><strong>auth.route.js</strong></p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var controller = require('../controllers/auth.controller');
  var middleware = require('../middleware/auth.middleware');
  
  router.post('/login', controller.login);
  router.post('/register', middleware.register, controller.register);
  
  module.exports = router;
  </code></pre>
  
  <p><strong>auth.middleware.js</strong></p>
  
  <pre><code>module.exports.register = function(req, res, next)
  {
      req.checkBody({
  
          'username': {
              notEmpty: true,
              errorMessage: 'Username is required'
          },
  
          'email': {
              notEmpty: true,
              isEmail: {
                  errorMessage: 'Invalid Email Address'
              },
              errorMessage: 'Email is required'
          },
  
          'password': {
              notEmpty: true,
              errorMessage: 'Password is required'
          },
  
          'password_confirmation': {
              notEmpty: true,
              errorMessage: 'Password Confirmation is required'
          }
  
      });
  
      req.assert('password_confirmation', 'Passwords do not match').equals(req.body.password);
  
      req.check('username', 'This username is already taken').isUsernameAvailable();
  
  
      var errors = req.validationErrors(true);
  
      if(errors) {
  
          return res.json({
              success: false,
              errors: errors
          });
  
      }
  
      req.asyncValidationErrors().catch(function(errors) {
  
          if(errors) {
              return res.json({
                  success:false,
                  errors: errors
              });
          };
      });
  
  
      next();
  
  }
  </code></pre>