The Startup
Published in

The Startup

How to Build Simple and Secure REST API for User Authentication Using Node.js, JWT, and MongoDB

Image by Pete Linforth from Pixabay

Agenda ✍️:

  1. User signup/registration with Email verification.
  2. User Login.
  3. Forgot password and reset password.
  4. Session management using JWT (JSON Web Tokens).
  5. JWT gotchas
  6. Bonus: Simple Referral System!

Preparation 🏃:

Project Setup 📑

Server started listening on PORT : 5000
npm i mongoose dotenv body-parser --save
  • Mongoose : An Object Data Modeling (ODM) library for MongoDB and Node.js.
  • Dotenv : Used to load environment variables.
  • Body-parser : Helps to parse the incoming request bodies so that we can access using the req.body convention. If you are new to this don’t worry, you’ll catch up in a moment.
MONGO_URI = <MONGO_CONNECTION_STRING>
Server started listening on PORT : 5000
Database connection Success.
  1. Validate the user entered fields (email, password, confirm password) using joi.
  2. Check whether already an account with the given email exists in our database.
  3. If it exists, then throw an error.
  4. If not, then hash the password using bcryptjs npm module.
  5. Generate a unique user id using the uuid module.
  6. Generate a random 6 digit token ( with an expiry time of 15 minutes ) and send a verification email to the user’s email id.
  7. Then save the user in the database and send a “success” response to the client.
SG_APIKEY = <YOUR SENDGRID KEY>
module.exports.hashPassword = async (password) => {
try {
const salt = await bcrypt.genSalt(10); // 10 rounds
return await bcrypt.hash(password, salt);
} catch (error) {
throw new Error("Hashing failed", error);
}
};
emailToken: { type: String, default: null },
emailTokenExpires: { type: Date, default: null },
const express = require("express");
const router = express.Router();
const cleanBody = require("../middlewares/cleanbody");
const AuthController = require("../src/users/user.controller");
router.post("/signup", cleanBody, AuthController.Signup);module.exports = router;
router.patch(“/forgot”, cleanBody, AuthController.ForgotPassword);
router.patch(“/reset”, cleanBody, AuthController.ResetPassword);

Conclusion :

--

--

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
Pranesh A S

Backend Engineer and Blockchain Developer. Keep learning | Spread Knowledge