Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript User Authentication With Express and Mongo User Registration Adding Data to the Database

Charles-Antoine Francisco
Charles-Antoine Francisco
27,426 Points

Why is the Sign Up Form Validation done on the server?

In the code for the POST /register route, we check that all form fields (email, name, favoriteBook, password, confirmPassword) are entered and that the password and confirmPassword fields match.

I think this could be done on the frontend part of the app and avoid a network call to the server.

// POST /register
router.post('/register', function(req, res, next) {
  if (req.body.email && req.body.name && req.body.favoriteBook &&
    req.body.password && req.body.confirmPassword) {
      // confirm that user typed same password twice
      if (req.body.password !== req.body.confirmPassword) {
        var err = new Error('Passwords do not match.');
        err.status = 400;
        return next(err);
      }
      // insert document into Mongo...
    } else {
      var err = new Error('All fields required.');
      err.status = 400;
      return next(err);
    }
})

1 Answer

Steven Parker
Steven Parker
231,236 Points

Validation should always be done on the server.

Ideally, it would also be done on the front end, to avoid transmitting known bad data to the server. But it should still be done at the server to catch any possible errors caused by unexpected browser behavior or front-end tampering.

Charles-Antoine Francisco
Charles-Antoine Francisco
27,426 Points

Thanks, that clarifies things. I didn't think about users who could modify the frontend code. Good points.