How to use JWT in Node.js Express API with password Hashing & MongoDB

JonathanSanchez.Dev
3 min readOct 18, 2022

--

So you’ve built your Node Express API with password authentication but you are saving the password as a string in the database? 🤨 there is a better way.

If you want to skip directly to the sample code scroll all the way to the bottom or here is the video

Pre-requisites:

  1. Have some Javascript experience mainly with Node.js and building APIs with Express
  2. Have Node installed in your system, if you don’t have it installed, honestly you should not be following this tutorial 😎
  3. Mongo Atlas account — if you don’t have a FREE account, create an account at https://www.mongodb.com/
  4. This tutorial was made for Linux-based OS, like MAC OS, etc…

Overview of steps

  1. Sign up the user, by getting the password from the frontend, then hash the password and save it in the Mongo database
  2. Then let the user Log in if the password sent from the frontend is the same as the hashed password saved in the Mongo Database
  3. If the previous step is successful then create a JWT token with the user information for the API to use for any routes or resources needed

Step 1

If you don’t have a Node Express API, follow these steps.

Create a new folder where we will make our API

// make an API folder
$ mkdir node-jwt-api && cd node-jwt-api
// once inside API folder, initalize it as a Node project
$ npm init -y
// install express, cors, mongodb, bcrypt, jsonwebtoken
$ npm i express cors mongodb bcrypt jsonwebtoken
// make files
$ touch index.js .gitignore .env

Step 2

Setup your API to connect to MongoDB and to use all the libraries we just installed

// index.jsimport express from 'express'
import cors from 'cors'
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import 'dotenv/config'
import { MongoClient } from 'mongodb'
const URI = process.env.MONGO_URI // this comes from the .env file
const client = new MongoClient(URI)
client.connect()
console.log('Connected to Mongo')
const database = client.db('jwt-api') // name of databaseconst usersdb = database.collection('users') // name of collection const app = express()app.use(cors())app.use(express.json())app.listen(4040, () => console.log('Api Running 😎'))

Step 3

Set up your MongoDB Secret URI string, usually get that from your Mongo Atlas database looks like

mongodb+srv://YOUR-USERNAME:YOUR-PASSWORD@your-clusterid.mongodb.net/test

// .env MONGO_URI='mongodb+srv://YOUR-USERNAME:YOUR-PASSWORD@your-clusterid.mongodb.net/test'

Step 4

Create Routes

Sign up route

=> login Route

Login Route

=> Get all Users route

Get All users route

Entire Sample Code

Hope this helped, any questions please send me a comment 😎

--

--

JonathanSanchez.Dev

Developer by day, rockin' drummer by night. Loves dogs🐶 and collaborating with fellow engineers. Passionate, creative, and always up for a coding adventure! 🚀