This week I practiced my knowledge about NodeJS and MongoDB by creating an authentication system. I am going to cover the steps used to do so.
First thing you need to have is Node installed, so go to NodeJS and download it. Then create a folder for your project, open it in VSCode, open your terminal and type:
This will create a package.json file that will hold all of the packages.
The first package that I installed was express that will handle the routes.
npm install express
Another package was nodemon which is going to restart the server. I added — save-dev so it is not included in the main packages that are going to be sent to a server.
npm install --save-dev nodemon
Then create a new file index.js in the main directory. Once this is installed, we can initiate our first server. Create a const express that require ‘express’, then another const app that will invoke the function that we just created.
To start up the server, use the app function that listen to a port, in this case 3000 as the first argument, then a callback function that will print a message.
Next create a new ‘routes’ folder containing a auth.js file (our authentication routes). In this new file, create a constant router that will require ‘express’ and invoke Router. In this app, we can then set up our first route which will be a post request to our base url followed by ‘register’. This takes 2 arguments, a request (req) and response (res).
Then we need to import the route in index.js and add the middleware:
What line 8 means is that ‘/api/user’ will be our prefix and that what follows is what we have in our authRoute, aka our auth.js file.
To start your server, update your package.json and where it says start:, replace it with:
"start": "nodemon index.js"
You can now run ‘npm start’ and should see a message that says that the server is up and running.
Set up Postman
If you don’t have Postman, you should download it here. Open up your application and make a post request to ‘http://localhost:3000/api/user/register. Make sure that the format you use is JSON. The response should be ‘Register’.
Set up MongoDB
To connect to a database, I used MongoDB. If you don’t have an account, create one at https://www.mongodb.com/. Once you have an account, you have to ‘build a new cluster’. You will find tutorials on how to set up a FREE cluster.
In your terminal in VSCode, we are going to need to install a package called ‘mongoose’ that will help us set up our user model with datas (email, password, username…)
npm install mongoose
In index.js, we need to import mongoose. To do so, once your cluster is created, you need to go to connect > connect your application and you should see a screen like below where you will copy the connection string and paste it in your index.js. Also, install ‘dotenv’ so that you can create a .env file that keeps your information protected. Inside of this file, create a create a key that I called ‘DB_CONNECT’ in this case that contains the information that we copied from mongoDB.
Note that line 16 actually set up a middleware so that we can send post requests.
When you run ‘npm start’ now, you should see an additional message saying ‘connected to db’.
Create the user model
In your project main repo, create a model folder that will contain a User.js file and write the schema that you want your model to follow.
Update your auth.js file to import the data:
In Postman, make a post request sending datas as JSON.
When you browse your collection in MongoDB, it should look like this:
Note that the password is hashed; it is because I installed and set bcrypt up later. But you should get the same object with an unprotected password at this point. Once you get the data back and everything looks fine, you can go ahead and delete it.
Set up validations
First, install @hapi/joi by running the command:
npm install @hapi/joi
Create a new file in the main repo called ‘validation.js’. Import Joi, and create a function that will define your validations:
In auth.js, import this new function, and write validations like so:
If everything is set up correctly, you should see an error message like in the screenshot below if the password is too short, or if the email is not a valid email for example
Setting up the login
Once you get to this point, setting up the login is easier as it is repetitive. First in validation.js, add a loginValidation constant. Import both constant in auth.js and write a route for login like so:
To install bcrypt, run the command:
npm install bcryptjs
Import it in auth.js, and created a salt constant which basically created a hashed password and simply used this hashedPassword in your body.
If you made it to here, you should know be able to register a new user with correct datas using the validations, and also be able to login also respecting the validations.
I later used JWT so that a user could for example make another request by posting a post.