Auth with NodeJS, Express, Mongoose and JWT

Security of your database is one of the most important factor to consider when building a new project.

There are several ways to implement a solid authentication system.
In this article I’ll show you how to make one using JWT, completely from scratch and without the need to use third party services.

What technologies are we going to use?

  • NodeJS: a tool to server-side execute JavaScript code.

Setup our environment

First of all, be sure to have NodeJS installed. If you haven’t, check out this link. Then, create a new MongoDB instance. You can create one here, for free.
Finally, install NPM packages in our project folder via command line.

npm install express jsonwebtoken body-parser bcryptjs

Ready to code!

Now, we need to create our server scripts:

  • app.js, in which we’ll handle all our server requests.

Let’s create a very simple Express application: it will be the basic structure of our app.

The “SECRET_JWT_CODE” is the encryption key we are going to use when generating our tokens.

Before proceeding implementing our endpoints, we should get a look at the db.js file.

db.js

This file essentially creates our DB model schemas. This means that each user related data is going to be saved under a document (collection) called “users” and will have two attributes, “email” and “password”. Of course, you can create as many models as you want, with as many attributes as you want.

Now we need to implement our routing system. The app will essentially have two endpoints, the first one for the sign up and the second one for the login.

app.js — sign up
app.js — login

It works!

Screenshot of the data saved on our DB after having made a call to our /user/signup endpoint

Final steps

We successfully implemented our authentication system. Now, the client should save the token after the login and send it back every time it makes a new request.

Remember that Json Web Tokens have an expiration time. There are many ways to stay the user logged in. For example, whenever it happens, the client could refresh the token making a new login call.

On the backend side, this is how you could check if the token is valid:

app.js
app.js

You can find the Github gist here!😊

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store