Authentication in Node.js
An easy to implement authentication for your back-end

One of the most important features in our apps is the ability to confirm that the client is who they say they are. With web-security being constantly in the news (and not in a good way), a successful and trusted website/app needs appropriate authentication and authorisation. Today we will focus on the first part — the authentication.
We will build an extremely simple and stripped-down version of an app’s backend sign-up and login focused purely on hashing new users’ passwords and authenticating existing users. Following these steps, you can easily implement the functionality in your own projects.
First, let’s start with the list of what we need:
- Node.js — it’s a JavaScript runtime built on Chrome’s V8 JavaScript engine.
- Express — a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. The philosophy behind it states that the goal “is to provide small, robust tooling for HTTP servers, making it a great solution for single-page applications, web sites, hybrids, or public HTTP APIs.” Hence why is the “go-to” choice of many developers and included in our little example.
- Bcrypt — a library to hash passwords. From Wikipedia:
A password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher, and presented at USENIX in 1999. Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.
- Last, of course, we will need a good code editor. My choice is Visual Studio Code
Onto the actual build. We will create two functions: a sing-up and a login, but first, let’s install the dependencies.
- After installing VS code, start the application and open a new terminal. Navigate to your chosen folder and create a new subfolder for our app. Let’s call it backend-auth.
mkdir backend-auth
- Initialise the project with npm and add flag y to opt-in for the defaults (you can always change these later). This will create package.json and package-lock.json files in the main directory for all the dependencies.
npm init -y
- Next step is to install the two npm packages express (for the routing) and bcrypt (for the password hashing).
npm express bcrypt
- Create server.js.
touch server.js
- Finally, we are at the step where we are actually going to write some code, albeit being just the scaffold for our app! Open server.js and require both packages.
- Next, we need to create our app constant and allow it to accept JSON objects — our future users. Also, we will have to assign a port for our server to listen to. Usually, this will be port 3000 (for development only).

Sign-up
We mentioned that bcrypt will hash the passwords for us, but why we should do it and what does that involve? The “why” is easy: you never want to store your users’ passwords in plain text. NEVER! Even the biggest companies make mistakes and there are people out there that will take advantage of an exploit and use it for their benefit. This usually is in the form of selling the data they have acquired, which could be passwords, bank account details and other personal information. If this data is not stored securely, the affected could face life-changing consequences. And we as developers are responsible for the security of the users that trust us with their data. The minimum we could do is to hash the sensitive information using good algorithms. Bcrypt is based on the Blowfish block cypher cryptomatic algorithm. It also uses “salt” to change every secured piece of data (“salting” refers to adding a very long random string to the data). More information about it could be found here.
Having convinced you (hopefully!) to always secure your sensitive data, let’s have a look at the implementation.

You will notice that we create a users constant to store our user data. I’ve taken this approach only because I wanted to keep everything needed in one file, so it’s easy to understand and refer back to. In reality, the data will be stored in a database.
The Sign-up has the usual Express syntax with the only difference that the callback function it takes is asynchronous. Here is why Bcrypt’s team recommends this approach:
Why is async mode recommended over sync mode?
If you are using bcrypt on a simple script, using the sync mode is perfectly fine. However, if you are using bcrypt on a server, the async mode is recommended. This is because the hashing done by bcrypt is CPU intensive, so the sync version will block the event loop and prevent your application from servicing any other inbound requests or events. The async version uses a thread pool which does not block the main event loop.
First, on line 11 we create a hashed version of the user's password using the hash method on bcrypt, passing in the received password and the number of rounds for the “salting”(the default number is 10). Bcrypt will then take the password, add “salt” and hash it. On the next line, we create our user with the new secured password and then we save it and send the response to the frontend. Or if there is an error we send status code 500.
Log-in

Again, we will be using async as advised by team Bcrypt. First, we need to check if the user exists (users.find()). If not, then send 404 — “Not Found” to the client. If it does, we have to compare(bcrypt.compare()) the password they sent with the password we have stored in our backend. This happens on line 26 and if the result is positive, we log the user in and if the data doesn’t match we send them a 401 status code — “Unauthorised”.
That’s it. It only took two bcrypt methods: hash — to secure the data and compare — to match the provided and stored data.

P.S. While this will work as-is, do not forget to add functionality to handle errors. I have not covered these in this blog-post, but watch this space — we will go over the implementation soon. And just to spice it up… it’s not harder than what we’ve covered. Actually, it’s easier.
I hope you enjoyed this post and found it helpful and if so, hit that clap button!
