Node JS User Registration Login Example

This example is a user account register and login demo implemented with node.js. The function is simple, but is enough for demonstrate how to use node js to create a request router, how to create and use custom node js module and how to use http, url and querystring built-in modules.

1. Node Example Introduction.

There are five javascript files in this example. You can see them in below picture.

node user register and login example javascript files

  1. request-router.js : This is the request dispatcher javascript file, it is used to receive user request and invoke related node module’s method according to the request url path.
  2. home.js : This is a custom node module js that is used to display home page welcome message when user browse the default url.
  3. login.js : Also a custom node module that process login related issue such as show login page and check user login credential.
  4. register.js : Custom node module which provide functions to display register page and register user info.
  5. http_util.js : A util custom node module provide parse request url query string, build navigation bar and generate web page by template functions.

Below is example js files relation diagram.

user register and login diagram

Below is the example demo use a gif picture.

node js user registration and login example
2. Router Module File.

request-router.js

/**
 * This is the dispatcher module for this example.
 *
 * It create a http web server and listen on port 8888.
 *
 * When client send request, it will dispatch the request to different module by request url path.
 */

var http = require('http');

var http_util = require('../util/http_util');

var home_module = require('./home');

var login_module = require('./login');

var register_module = require('./register');

var http_server_port = 8888;


/* This is the callback function which will be used by http web server.
*
*  This function will process client request.
* */
var http_server_callback_function = function(req, resp){

   // Parse query strings.
   http_util.getUrlParams(req, resp);

   // Get request url path value.
   var url_path = req.query_url.pathname;

   // Invoke different module's function by different request path.
    if(url_path === '/')
    {
        home_module.showHomePage(req, resp);
    }else if(url_path === '/login' )
   {
      login_module.showLoginPage(req, resp);
   }else if(url_path === '/check-login')
   {
        login_module.checkLoginAccount(req, resp);
   }else if(url_path === '/register')
    {
        register_module.showRegisterPage(req, resp);
    }else if(url_path === '/register-submit')
    {
        register_module.registerSubmit(req, resp);
    }else
   {
      resp.writeHead(404, {'Content-Type' : 'text/html'});
      resp.end("Request url is not valid : " + req.url.toString());
   }
}

// Create a http web server use above callback function.
var http_server = http.createServer(http_server_callback_function);

// Server is listen on port 8888.
http_server.listen(http_server_port);

// Print log data in console.
console.log('http server lisetning on port ' + http_server_port);

3.Home Module File.

home.js

// Require http_util module.
var http_util = require('../util/http_util');

/* This method will show home page with welcome message. */
exports.showHomePage = function buildLoginPage(req, resp, error_message) {

    var page_title = "Home Page";

    var page_menu = http_util.pageMenu();

    var page_content = "<font color='red'>Welcome to user register and login home page.<br/>Click above link to take action.</font>";

    // Generate home page with page template and special title, menu and content.
    var page_data = http_util.buildPage(page_title, page_menu, page_content);

    resp.writeHead(200, {'Content-Type':'text/html'});

    resp.end(page_data);
}

4.Login Module File.

login.js

/**
 * New node file
 */


var http_util = require('../util/http_util');

/* Return login form page to client request.

   This function is exported so can be invoked out side current module. */
exports.showLoginPage = function(req, resp){
   buildLoginPage(req, resp, '');
}


/* Verify user input login account data. Exported function also. */
exports.checkLoginAccount = function(req, resp){

   // Use node query string module to parse login form post data.
   var query_string = require('querystring');

   // If client use post method to request.
    if (req.method == 'POST') {

       var req_body = '';

        req.on('data', function (data) {
            req_body += data;

            // If the POST data is too much then destroy the connection to avoid attack.
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (req_body.length > 1e6)
                req.connection.destroy();
        });

        req.on('end', function () {

           // Parse post data from request body, return a JSON string contains all post data.
            var post_data = query_string.parse(req_body);

            // Get user name from post data.
            var user_name = post_data["user_name"];

            // Get password from post data.
            var password = post_data["password"];

            // If user name and password is correct.
            if(user_name === 'jerry' && password === 'dev2qa.com')
            {
                resp.writeHead(200, {'Content-Type':'text/html'});

                // Assign page title.
                var page_title = "Login success";

                // Assign page navigation menu data.
                var page_menu = http_util.pageMenu();

                // Assign page content.
                var page_content = "<font color=red>User name and password is correct, login success.</font>";

                // Build login success page.
                var login_success_page = http_util.buildPage(page_title, page_menu, page_content);

                // Send login success page html source data to response.
                resp.end(login_success_page);
            }else
            {
               // If user name and password is not correct.
               req.user_name = user_name;
               req.password = password;

               // Return login form page back to response.
            buildLoginPage(req, resp, 'User name or password is not correct.')
            }
        });
    }
}


/* This is a private function which can only be invoked in this module.
*  This function is used to build login form page and return it to client.
* */
function buildLoginPage(req, resp, error_message) {

    http_util.getUrlParams(req, resp);

    var page_title = "Login Page";

    var page_menu = http_util.pageMenu();

    var login_form = "<h3>Input user name and password to login.</h3>";

    if(error_message!=='' && error_message!==null && error_message!==undefined)
   {
      login_form += "<font color=red>" + error_message + "</font><br/><br/>";
   }

   login_form += "<form method='post' action='/check-login'>" +
        "User Name : <input type='text' name='user_name' value='{user_name}'/><br/><br/>" +
        "Password :<input type='password' name='password' value='{password}'/><br/><br/>" +
        "<input type='submit' value='Login'/><br/><br/>" +
        "</form>";

    if(req.user_name==null || req.user_name==undefined)
    {
        req.user_name = '';
    }

    if(req.password==null || req.password==undefined)
    {
        req.password = '';
    }

    login_form = login_form.replace("{user_name}", req.user_name);

    login_form = login_form.replace("{password}", req.password);

    var login_page_data = http_util.buildPage(page_title, page_menu, login_form);

    resp.writeHead(200, {'Content-Type':'text/html'});

    resp.end(login_page_data);
}

5. Register Module File.

register.js

/**
 * New node file
 */


var http_util = require('../util/http_util');


/* Exported function which is used to display user register form page. */
exports.showRegisterPage = function (req, resp) {
    buildRegisterPage(req, resp, "");
}


/* Exported function also used to send a register success message to client. */
exports.registerSubmit = function (req, resp) {

    resp.writeHead(200, {'Content-Type':'text/html'});

    var page_title = "Register Success";

    var page_menu = http_util.pageMenu();

    var page_content = "User info registration success.";

    var page_data = http_util.buildPage(page_title, page_menu, page_content);

    resp.end(page_data);
}


/* Private function that create and return user register form page. */
function buildRegisterPage(req, resp, error_message) {

    http_util.getUrlParams(req, resp);

    var page_title = "Register Page";

    var page_menu = http_util.pageMenu();

    var register_form = "<h3>Input user data to register.</h3>";

    if(error_message!=='' && error_message!==null && error_message!==undefined)
    {
        register_form += "<font color=red>" + error_message + "</font><br/><br/>>";
    }

    register_form += "<form method='post' action='/register-submit'>" +
        "User Name : <input type='text' name='user_name' value='{user_name}'/><br/><br/>" +
        "Password :<input type='password' name='password' value='{password}'/><br/><br/>" +
        "Email :<input type='text' name='email' value='{email}'/><br/><br/>" +
        "<input type='submit' value='Register'/><br/><br/>" +
        "</form>";

    if(req.user_name==null || req.user_name==undefined)
    {
        req.user_name = '';
    }

    if(req.password==null || req.password==undefined)
    {
        req.password = '';
    }

    if(req.email==null || req.email==undefined)
    {
        req.email = '';
    }

    register_form = register_form.replace("{user_name}", req.user_name);

    register_form = register_form.replace("{password}", req.password);

    register_form = register_form.replace("{email}", req.email);

    var register_page_data = http_util.buildPage(page_title, page_menu, register_form);

    resp.writeHead(200, {'Content-Type':'text/html'});

    resp.end(register_page_data);
}

6. Http Util Module File.

http_util.js

/**
 * This is the util module used by other module.
 */

// Require node url module.
var http_url = require('url');


/* This function will parse client request query string and passe out related query parameter and value.*/
exports.getUrlParams = function(req, resp){
   
   req.query_url = http_url.parse(req.url, true);
   
   console.log(req.query_url);
   
   req.user_name = req.query_url.user_name;
   
   req.password = req.query_url.password;
   
   req.email = req.query_url.email;
   
   req.mobile_phone = req.query_url.mobile_phone;
   
   req.home_phone = req.query_url.home_phone;
   
}

/* This function will return web page navigation menu html source code. */
exports.pageMenu = function(){

   var ret = '<a href="/">Home</a>';
   ret += '&nbsp&nbsp';
   ret += '<a href="/register">Register</a>';
   ret += '&nbsp&nbsp';
   ret += '<a href="/login">Login</a>';
   
   return ret;
}


/* This function will use input parameter to replace place holder in the page template file. */
exports.buildPage = function(page_title, page_menu, page_content){
   
   var page_template = "<html>" +
         "<head>" +
         "<title>{page_title}</title>" +
         "</head>" +
         "<body>" +
         "<table>" +
         "<tr><td>{page_menu}</td></tr><tr>" +
         "<tr><td>{page_content}</td></tr>" +
         "</table>" +
         "</body></html>";
   
   var ret = page_template;
   ret = ret.replace("{page_title}", page_title, "g");
    ret = ret.replace("{page_title}", page_title, "g");
    ret = ret.replace("{page_menu}", page_menu, "g");
    ret = ret.replace("{page_content}", page_content, "g");

   return ret;
      
}
READ :   Node JS Event Loop And Custom Event Example

15 Comments


  1. This isn’t working.
    Best regards.

    Reply

  2. the data isnt being passed through to a database so how can the login possibly work

    Reply

  3. if(user_name === ‘jerry’ && password === ‘dev2qa.com’)

    you hard coded the user name and password used in the gifs, how would a user be able to put in new name/passwords? seems like you are purposely misleading people about the functionality of this code.

    Reply

    1. This is just a demo, you can save username and password in file or database, then check the username and password from the file or database.

      Reply

  4. Hi jerry,
    I’m getting Error: Cannot find module ‘../util/http_util’ this error how to resolve this, thanks and regards

    Reply

  5. I have a error which is like this message “> [email protected] start /Users/soung/df
    > node index

    internal/modules/cjs/loader.js:797
    throw err;
    ^

    Error: Cannot find module ‘/Users/soung/df/index’
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
    at Function.Module._load (internal/modules/cjs/loader.js:687:27)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11 {
    code: ‘MODULE_NOT_FOUND’,
    requireStack: []
    }
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! [email protected] start: `node index`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the [email protected] start script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR! /Users/soung/.npm/_logs/2019-10-28T21_34_38_864Z-debug.log

    I deleted module and json file but situation is same.

    Reply

  6. Why do you need use this pithon util? Is it code for mining coins?

    Reply

  7. best sharing, it will very helpful for Jr. Node JS developer and also experiences,
    in this content, you covered hole steps and explain the easiest way,
    Good work,

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.