Creating A User Authentication Application using Node.js

Zulaikha Geer
Edureka
Published in
14 min readJan 4, 2019
Node.JS Tutorial — Edureka

If you have ever heard about Node.js then you might know that it is one the most prominent and powerful frameworks of JavaScript. Since its release, it has continued to keep its stranglehold on the IT market. Even with the introduction of new and vibrant JS Frameworks like Angular, React, Meteor etc., the popularity of Node.js never seems to cease. Wondering why? Well, with the help of this Node.js Tutorial, I will be giving you a complete insight into it. So, get ready to fall in love with Node.js.

In this Node.js Tutorial, I will be discussing the below topics:

  • What is Node.js?
  • Node.js Architecture
  • Node.js Installation
  • NPM (Node Package Manager)
  • Node.js Modules
  • JSON File
  • Node.js Basics
  • File System
  • Events
  • HTTP Module
  • Express.js

What is Node.js?

Node.js is a powerful framework developed on Chrome’s V8 JavaScript engine that compiles the JavaScript directly into the native machine code. It is a lightweight framework used for creating server-side web applications and extends JavaScript API to offer usual server-side functionalities. It is generally used for large-scale application development, especially for video streaming sites, single page application, and other web applications. Node.js makes use of an event-driven, non-blocking I/O model which makes it a right pick for the data-intensive real-time applications.

Like any other programming languages, node.js makes use of packages and modules. These are the libraries that contain various functions and are imported from npm (node package manager) into our code and utilized in the programs. Some of the major features, that define Node.js are listed below:

Features of Node.js

  1. Open Source
    Node.js is an open source framework MIT license that is supported by a huge community. Its community is pretty much active have contributed to add new capabilities to Node.js applications.
  2. Simple and Fast
    Since Node.js is built on Google Chrome’s V8 JavaScript Engine, its libraries are capable of fast code execution.
  3. Asynchronous
    All the libraries of Node.js are asynchronous which means the Node.js based servers never wait for an API to send back the response and move on to the next API.
  4. High Scalability
    Because of the event mechanism, Node.js is highly scalable and aids the server in a non-blocking response.
  5. Single Threaded
    With the help of event looping, Node.js is able to follow the single threaded model. This lets a single program to handle multiple requests.
  6. No Buffering
    One of the major functionalities of Node.js applications is that it never buffers any data.
  7. Cross Platform
    Node.js can be easily built and deployed on various platforms like Windows, MAC, and Linux.

So, now let’s dig a little deeper into Node.js and understand its internal architecture further in this Node.js tutorial.

Node.js Architecture

Generally, the server-side technologies like PHP, ASP.NET, Ruby & Java Servers all follow a multi-threaded model. In this traditional architectural approach, each client request creates a new thread or a process.

To avoid this, Node.js uses Single Threaded Event Loop Model Architecture. It means that all the client requests on Node.js are executed on the same thread. But this architecture is not just single threaded, but event-driven as well. It helps Node.js in handling multiple clients concurrently. Below diagram, represents the Single Threaded Event Loop Model architecture.

As you can see in the diagram, the main event loop is single threaded whereas the I/O workers are executed on distinct threads. This is done to accommodate the entire event loop where most of the Node.js API’s are designed to be asynchronous/non-blocking. This reduces the server response time and increases application throughput.

In the next section of this Node.js Tutorial, I will guide you through the installation process of Node.js.

Node.js Installation

In order to install NodeJS and develop an application in your system you need the following SDKs:

  1. Node.js
  2. NPM (Node Package Manager)
  3. IDE or Text Editor

In this section of NodeJS tutorial, I will demonstrate how to install NodeJS.

STEP 1: You can download Node.js from its official site: https://nodejs.org/en/download/.

STEP 2: In the downloads page, you will see various versions of Node. All you need to do is, click on the box, suitable to your system configurations.

STEP 3: Once you have successfully downloaded the software, go to the downloaded file, and double-click on it.

STEP 4: As soon as you click on the file, an installation wizard will come up. Select ‘Next’ and move further with the installation.

STEP 5: Check the “I Agree” checkbox and click on the ‘Next’ button.

STEP 6: By clicking on ‘Change’, set the path, where you want to install the NodeJs file and then click on next.

STEP 7: Again, click on next.

STEP 8: Now, click on the ‘Install’ button to finish up the installation process.

STEP 9: Once done with the installation, click on the ‘Finish’ button to exit the installation wizard.

Now, you are good to start off with the very 1st program in Node.js.

To verify whether your installation was successful or not, try executing a Node.js file.

Open your IDE/Text Editor and type in the below code.

console.log('Welcome To Edureka NodeJS Tutorial!');

Save the file with a .js extension such as filename.js

Now open your Node.js command prompt, navigate to the folder containing the js file. Now, type in the below command and hit enter to display the text in your console.

node filename.js

This was a basic program to print the data on the console. Let’s now advance further and see how to deploy the actual code on the browser. But before that, you need to get into the nitty-gritty of Node.js.

In the next section of this article, I will talk about the most important component of Node.js i.e., npm.

NPM (Node Package Manager)

NPM stands for Node Package Manager which as the name suggests is a package manager for Node.js packages/modules. From Node version 0.6.0. onwards, npm has been added as default in the node installation. It saves you from the hassle of installing npm explicitly.

NPM basically helps in two ways:

  1. Provides and hosts Online repositories for node.js packages/modules which can be easily downloaded and used in our projects. You can find them here: npmjs.com
  2. Provides the Command line utility in order to install various Node.js packages, manage Node.js versions and dependencies of the packages.

But now, you must be wondering what exactly these modules are and how do they help us in building the Node.js applications. Well, in the next section of this Node.js tutorial, I will give you a complete insight into Node.js modules.

Node.js Modules

The modules in Node.js represents various functionalities that are bundled up into single or multiple JS files. These modules have a unique context, thus, they never interfere nor pollute the scope of other modules.

These modules enable the code reusability and enhance the ease of usage. Node.js basically provides three types of modules:

  1. Core Modules
  2. Local Modules
  3. Third Party Modules

Core Module

Since Node.js is a very lightweight framework, the core modules bundle the absolute minimum functionalities. These modules generally get loaded when the Node process starts its execution. All you need to do is, import these core modules in order to use them in your code.

Below I have listed down a few of the important Core modules.

You can load your core module, using the below code:

var module = require('module_name');

Lets now see, what are ‘local modules’.

Local Modules

The local modules of Node.js are custom modules that are created locally by user/developer in the application. These modules can include various functionalities bundled into distinct files and folders which can be easily distributed in the Node.js community using NPM.

These modules are loaded in a similar way to core modules. Let show you, how to do it using a basic example.

Create your custom/local module.js file

var detail = {
name: function (name) {
console.log('Name: ' + name);
},
domain:function (domain) {
console.log('Domain: ' + domain);
}
};
module.exports = detail;

Include your module file in your main application file.

var myLogModule = require('./Local_module.js');
myLogModule.name('Edureka');
myLogModule.domain('Education');

Now you can execute these files using below command:

node application.js

Let me now show you what are external modules.

External Modules

You can use the external or 3rd party modules only by downloading them via NPM. These modules are generally developed by other developers and are free to use. Few of the best external modules are express, react, gulp, mongoose, mocha etc.

Globally Loading the 3rd party modules:

npm install --g <module_name>

Include your module file in your main application file:

npm install --save <module_name>

JSON File

The package.json file in Node.js is the heart of the entire application. It is basically the manifest file that contains the metadata of the project. Thus, understanding and working with this file becomes very important for a successful Node project development.

The package.json file generally consists of the metadata of the application, which is further categorized into below two categories:

  1. Identifying metadata properties: This consists of properties like the project name, current module version, license, author of the project, project description etc.
  2. Writing directly to file: You can directly write the necessary information into the package.json file and include it, in your project.

By now you have already familiarized with the various components of Node JS application. In the next section of this Node.js Tutorial, I will be sharing some Node Js basics so that we can start off with the hands on.

Node.js Basics

For now, I will be brushing you up with some Node.js basics like:

Data Types

Like any other programming language, Node.js has various datatypes, which are further categorized into Primitive and Non-Primitive datatypes.

Primitive Data Types are:

  1. String
  2. Number
  3. Boolean
  4. Null
  5. Undefined

Non-Primitive Data Types are:

  1. Object
  2. Date
  3. Array

Variables

Variable are entities that hold values which may vary during the course of a program. To create a variable in Node.js, you need to make use of a reserved keyword var. You do not have to assign a data type, as the compiler will automatically pick it.

Syntax:

var varName = value;

Operators

Node.js supports the below operators:

Functions

Functions in Node.js is a block of code that has a name and is written to achieve a particular task. You need to use the keyword function to create it. A function is generally a two-step process. First is defining the function and the second is invoking it. Below is the syntax of creating and invoking a function:

Syntax:

//Defining a function
function display_Name(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}
//Invoking the function
display_Name("Park", "Jimin");

Objects

An object is a non-primitive data type that can hold multiple values in terms of properties and methods. Node.js objects are standalone entities as there is no concept of class. You can create an object in two ways:

  1. Using Object literal
  2. Using Object constructor

Syntax:

// object with properties & method
var employee = {
//properties
firstName: "Minho",
lastName: "Choi",
age: 35,
salary:50000,
//method
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};

File System

To access the physical file system, Node.js makes use of the fs module which basically takes care of all asynchronous and synchronous file I/O operations. This module is imported using the below command:

var fs = require('fs');

Some of the general use for the File System modules are:

Read files

  1. fs.readFile()
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('script.txt', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);

Create files

  1. appendFile()
  2. open()
  3. writeFile()

Update files

  1. fs.appendFile()
  2. fs.writeFile()

Delete files

  1. fs.unlink()

Rename files

  1. fs.rename()

So, with these commands, you can pretty much perform all the required operations on your files. Let’s now move further with this Node.js Tutorial and see what are Events and how they are handled in Node.js.

Events

As I have already mentioned, Node.js applications are single threaded and event-driven. Node.js supports concurrency as it is event-driven, and thus makes use of concepts like events and callbacks. The async function calls help Node.js in maintaining concurrency throughout the application.

Basically, in a Node.js application there is a main loop which waits and listens for events, and once any event is completed, it immediately initiates a callback function.

Below diagram represents how the events are driven in Node.js.

The below code shows a simple representation of Event execution in Node.js.

var emitter = require('events').EventEmitter;function iterateProcessor(num) {
var emt = new emitter();
setTimeout(function () {for (var i = 1; i <= num; i++) {
emt.emit('BeforeProcess', i);
console.log('Processing Iteration:' + i);emt.emit('AfterProcess', i);
}
}
, 5000)
return emt;
}
var it = iterateProcessor(5);
it.on('BeforeProcess', function (info) {
console.log('Starting the process for ' + info);
});
it.on('AfterProcess', function (info) {
console.log('Finishing processing for ' + info);

HTTP Module

Generally, Node.js is used for developing server-based applications. Using this, you can easily create web servers that can respond to the client requests. Modules like http and request, facilitate Node.js in processing the server requests.

Below I have written a code, that shows how a Web Server is developed in Node.js.

var http = require('http');
var url = require('url');
var server = http.createServer(function (req, res) {
res.writeHead(200, ('Content-Type', 'text/html'));
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt);
});
server.listen(8082);

In the next section of this Node.js Tutorial, I will be talking about Express.js which is heavily used for server-side web application development.

Express.js

Express.js is a framework built on top of Node.js that facilitates the management of the flow of data between server and routes in the server-side applications. It is a lightweight and flexible framework that provides a wide range of features required for the web as well as mobile application development.

Express.js is developed on the middleware module of Node.js called connect. The connect module further makes use of a http module to communicate with Node.js. Thus, if you are working with any of the connect based middleware modules, then you can easily integrate with Express.js.

Not, only this, few of the major advantages of Express.js are:

  • Makes web application development faster
  • Helps in building mobile and web application of single-page, multi-page, and hybrid types
  • Express provides two templating engines namely, Jade and EJS
  • Express follows the Model-View-Controller (MVC) architecture
  • Makes integration with databases such as MongoDB, Redis, MySQL
  • Defines an error handling middleware
  • Simplifies configuration and customization easy for the application.

With all these features, Express takes responsibility of backend part in the MEAN stack. Mean Stack is the open-source JavaScript software stack that is used for building dynamic websites and web applications. Here, MEAN stands for MongoDB, Express.js, AngularJS, and Node.js.

Lets now see a simple example to understand, how Express.js works with Node.js to ease our work. But before you start working with Express.js, you need to install it in your system.

To install Express.js globally you can use the below command:

npm install -g express

Or, if you want to install it locally into your project folder, you need to execute the below command:

npm install express --save

Since we are done with all the preparations, let’s now jump directly into practical implementation. Here, I will be showing a simple User Authentication Application using Node.js and Express.js.

For this, we will be needing below files:

  • package.json
  • script.js
  • views
  1. index.jade
  2. login.jade
  3. secure.jade
  4. unauthorized.jade
  5. welcome.jade
  • lib
  1. routes.js

So, let’s start with package.json.

{
"author": "Edureka",
"name": "Express_Demo",
"description": "Express with Node.js",
"version": "0.0.0",
"scripts": {
"start": "node script.js"
},
"engines": {
"node": "~0.4.12"
},
"dependencies": {
"connect-flash": "^0.1.1",
"cookie-parser": "^1.4.3",
"express": "^3.21.2",
"jade": "^0.20.3",
"req-flash": "0.0.3"
},
"devDependencies": {}
}

Next, you need to create the script.js.

var express = require('express');
var http = require('http');
var port = 8999;
var app = express();
const flash = require('connect-flash');
var cookieParser = require('cookie-parser')
var server = http.createServer(app);
function checkAuth (req, res, next) {
console.log('checkAuth ' + req.url);
// don't serve /secure to those not logged in
if (req.url === '/secure' && (!req.session || !req.session.authenticated)) {
res.render('unauthorised', { status: 403 });
return;
}
next();
}
app.use(flash());
app.use(cookieParser());
app.use(express.session({ secret: 'example' }));
app.use(express.bodyParser());
app.use(checkAuth);
app.use(app.router);
app.set('view engine', 'jade');
app.set('view options', { layout: false });
require('./lib/routes.js')(app);app.listen(port);
console.log('Node listening on port %s', port);

Now, create a folder named view, under which you will be adding the jade files that will be responsible for various page views. The first view file you need to create is index.jade.

!!! 5
html(lang='en')
head
title User Authentication Example
<link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
body
h1
center Authentication Demo using Express
h3 Navigate to
h4
ul
li: a(href="/secure") Secure content
li: a(href="/welcome") Welcome page
li: a(href="/logout") Logout

Now, create the login.jade file.

!!! 5
html(lang='en')
head
title Express authentication example
<link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
body
h1
center Sign-in to this Express authentication example
center
p Use <i>user</i> for the username and <i>pass</i> for the password.
form(method='post')
p
label(for='username') Email Address
input(type='text', name='username', class='form-control', id='exampleInputPassword1' , placeholder='Email', style='width:400px;')
p
center
label(for='password') Password
input(type='password', name='password', class='form-control' , id='exampleInputPassword1', placeholder='Password', style='width:400px;')
p
center <button type="submit" class="btn btn-info">Submit</button>
- each message in flash
h4(style="color: red;") #{message}

Next step is to create the welcome.jade.

!!! 5
html(lang='en')
head
title User Authentication Example
<link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
body
h1
center Welcome To The Edureka Tutorial!

Next, create the secure.jade file.

!!! 5
html(lang='en')
head
title Express Authentication Example
<link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
body
h1
center Hi, secure user.
p Navigate to
ul
li: a(href="/secure") Secure content
li: a(href="/welcome") Welcome page
li: a(href="/logout") Logout

Now, create the unauthorized.jade file.

!!! 5
html(lang='en')
head
title User Authentication Example
<link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
body
h1
center Unauthorized
p You're unauthorized to view this page.
p Please <a href="/login">login</a> to continue

Now, you need to create a folder and name it lib. Now, create a route.js file which will map all the pages.

var util = require('util');module.exports = function (app) {app.get('/', function (req, res, next) {
res.render('index');
});
app.get('/welcome', function (req, res, next) {
res.render('welcome');
});
app.get('/secure', function (req, res, next) {
res.render('secure');
});
app.get('/login', function (req, res, next) {
res.render('login', {flash: req.flash() } );
});
app.post('/login', function (req, res, next) {// you might like to do a database look-up or something more scalable here
if (req.body.username && req.body.username === 'user' && req.body.password && req.body.password === 'pass') {
req.session.authenticated = true;
res.redirect('/secure');
} else {
req.flash('error', 'Username and password are incorrect');
res.redirect('/login');
}
});app.get('/logout', function (req, res, next) {
delete req.session.authenticated;
res.redirect('/');
});
};

With this, we come to an end of this Node.js Tutorial. I hope I was able to explain the concepts of Node.js from the ground up. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, Python, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Node.js

1. NodeJS Tutorial

2. Build a CRUD Application Using Node.js and MySQL

3. Build CRUD Application using Node.JS and MongoDB

4. Best 3 Ways to Make Node.js Requests

5. How To Dockerize a Node.js App?

6. Build REST API with Node.js

7. Best 3 Ways to Make Node.js Requests

8. Express.js Fundamentals

Originally published at www.edureka.co on January 4, 2019.

--

--

Zulaikha Geer
Edureka

A technology enthusiast with expertise in several different domains including Data Science, DevOps and Web Development.