Nodejs authentication - Using bcryptjs - Part 1

Durlav Kalita
3 min readSep 14, 2021

Authentication is perhaps the most important part of an app. Some framework like laravel provides great auth scaffolding out of the box but building a node app with authentication from scratch can be troublesome. Let’s see how to tackle it.

Photo by Markus Spiske on Unsplash

Creating skeleton app

First let’s create a simple node app. I will be using express-generator to create an application skeleton with no view.

npx express-generator --no-view

From the skeleton app you can delete the public folder as well as it’s import in app.js as we will be sending and receiving json data only without view.

Install nodemon to monitor changes in node app and dotenv to access environment variables.

npm i dotenv nodemon

In package.json inside "scripts" object add "dev":"nodemon start" .

To use environment variable create a .env file in root folder and add require('dotenv').config() line inside app.jsto access environment variables.

Set up a database connection. I will be using mongodb cloud database.

To use mongodb let’s first install mongoose with npm i mongoose .

Now add the following lines in app.js

const mongoose = require('mongoose');mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true});var db = mongoose.connection;db.on('error', console.error.bind(console, 'MongoDB connection error:'));

This will setup a mongodb connection from node app to mongo database. The MONGODB_URI is an environment variable. Inside .env file add the line-

MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.zzzbk.mongodb.net/<databasename>?retryWrites=true&w=majority

<username> , <password> and <databasename> is specific for my mongodb cloud which for you would be different so replace them accordingly.

To test everything is working till now run npm run dev .

It should show a message like [nodemon] starting `node ./bin/www start` . If there is some error then stackoverflow is a nice place to ask about it.

Let’s create User model now. In root folder create a file User.js .

We already have a users.js file inside routes folder. Let’s modify the file.

The following pictures show the response of the /register and /login routes. I am using thunder client extension of vscode here.

/register route response
/users/register route response
/users/login route response

Using bcryptjs

So, our register and login function are working but the password is stored as a string without any encryption which is not ideal. That’s where bcryptjs comes in. bcryptjs is an optimized version of bcrypt for javascript. There are many functionality of bcryptjs but we only require to use hash and compare functionality in our app. Install bcryptjs by npm i bcryptjs . Now let’s modify users.js accordingly.

The hash function of bcryptjs takes three arguments-hash(s,salt,callback).

s is the string to be hashed or encrypted which is in this case req.body.password .

salt is simply a number determining strength of encryption and 10 is a common value for it.

callback function handles the output. If there is an error we display it or we get the generated new encrypted password which is stored in database instead of plain string password.

The compare function compares user provided password to hashed password and returns boolean value. callback function can also be used with compare method.

/users/register after using bcryptjs

So, now our password is secure and user can login and register. But what about other routes. How to give user access to certain routes only when logged in and how to know if a user is logged in? For these we use jwt. To know more about jwt implementation follow the second part of this article.

--

--