Create an Authentication API using Node.js, Express, MongoDB and JWT

Creating The Register and Login Routes

To put our data in a database, we will need user info, and this is given to the application through the routes, so let’s create two new ones in the AuthRoutes.js:

To use our model, we need to import it:

const User = require("../models/User");

and we will also need a package to verify/validate the input given by the user and also a package that encrypts our password:

const bcrypt = require("bcryptjs");
const Joi = require("@hapi/joi");

Let’s Validate

We use Joi to validate the data as follows:

Create A User Instance

Let’s guide your step by step through this process:

This checks for errors:

This will hash the password:

const salt = await bcrypt.genSalt(10);
const hashPassword = await bcrypt.hash(req.body.password, salt);

This will create a new user and store it in the database:

So a full Register Route will look like this:

Create A Login Route

Now that we can create a user, we also want to log in, and we will use it for that. Let’s import that first:

const jwt = require("jsonwebtoken");

Just like with the registration part, I will guide you through the process.

This will check for errors and if the user exists:

This will check if the password is correct:

And this will create a JWT token and send it to the browser:

So the full Login Route will look like this: