Building an e-Commerce website with Node – Part 15 – Sign up

It is time to create a sign up route for your Node.js application. Before doing that, we should put all our routes in a different folder.

This post might be confusing but at the end of this post you will have the code for all of the files involved!

So, under the project folder, create a new folder and name it routes. In it create two files and name them main.js and user.js.

Node.js signup page

The main.js file will contain all of the main routes while the user.js file will contain the routes related to the user. Before going any further we have to clean some code.

Go to server.js and move the home and about routes into the main.js file. We are not going to use app.get(), instead we are going to use route.get(). The route is the sub-path of a certain route.

On the top of the main.js and files type the following code:

var router = require(‘express’).Router();

This line of code says that we are using the router method which is coming from express.

So, this is what we have up to now in the main.js file:

var router = require(‘express’).Router();

router.get('/', function(req, res) {

router.get('/about', function(req, res) {

module.exports = router;

Next, in the middleware section of the server.js, cut the‘/create-user’... and paste it into the user.js file. Change the'/create-user'... to'/signup'...

Now we have to create in the server.js file two new middlewares that require the main routes and the user routes.

var mainRoutes = require(‘./routes/main’);
var userRoutes = require(‘./routes/user’);

Let’s go back to user.js and add some kind of validation for the email. For that we are going to use one of the mongoose’s methods named findOne. It finds one document in the user database.

This is the code that we are going to add to the user.js file.

  User.findOne({ email: }, function(err, existingUser) {

    if (existingUser) {
      console.log( + " already exist");
      return res.redirect('/signup');
    } else {, user) {
        if (err) return next(err);

        res.json("New user has been created");

As I said findOne is a mongoose method that checks for a document in the database. In our case it checks for the email. If it finds the email to be already used in the database (remember, the email is set up to be unique), it will give a message that tells the user the email already exist and redirects the user to the signup page. If the email is new then it creates a new user and returns a message that says “ New user has been created”.

sign up page with Node.js

Go to Postman and create new user.

Below you can download server.js, main.js, and user.js.

server.js – [Download not found]
main.js – [Download not found]
user.js – [Download not found]

Leave a Reply