Building Secure User Registration and Authentication in Node.js (2024)

Aneeqa Khan

Posted on • Updated on

Building Secure User Registration and Authentication in Node.js (3) Building Secure User Registration and Authentication in Node.js (4) Building Secure User Registration and Authentication in Node.js (5) Building Secure User Registration and Authentication in Node.js (6) Building Secure User Registration and Authentication in Node.js (7)

#node #javascript #beginners #tutorial

Table of Contents

  • Introduction
  • Install Dependencies
  • Generate JWT Token
  • Register User
  • Authenticate User

For this series, I'm following an excellent video tutorial from Traversy Media

Introduction

To get started with user registration and authentication, we'll begin by installing the necessary dependencies. Specifically, we'll use the bcryptjs library to securely store user passwords as hashes, and the jsonwebtoken library to generate JSON Web Tokens (JWT) for user authentication.

Install Dependencies

Firstly, let's install the required libraries:

npm i bcryptjsnpm i jsonwebtoken

Generate JWT Token

In this step, we are creating a function to generate a JWT token to use later. Write this function in userController.js file.

const jwt = require("jsonwebtoken");const bcrypt = require("bcryptjs");const asyncHandler = require("express-async-handler");const User = require("../models/userModel");// Generate JWTconst generateToken = (id) => { return jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn: "30d" });};

Don't forget to initialize the JWT_SECRET variable in your .env file. You can choose any suitable value for it.

Register User

Now, we'll write down the logic for registering a user in userController.js file.

const registerUser = asyncHandler(async (req, res) => { const { name, email, password } = req.body; if (!name || !email || !password) { res.status(400); throw new Error("Please add all fields"); } // check if user exists const userExists = await User.findOne({ email }); if (userExists) { res.status(400); throw new Error("User already exists"); } // create hash password const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(password, salt); // create user const user = await User.create({ name, email, password: hashedPassword, }); if (user) { res.status(201).json({ _id: user.id, name: user.name, email: user.email, token: generateToken(user._id), }); } else { res.status(400); throw new Error("Invalid user data"); }});

Let's test the registration process using Postman and ensure everything works as expected.

And it'll show an error if you try to add the same user again.

Authenticate User

To enable authentication for a registered user, we will implement a 'Login User' function within the userController file, which will involve verifying the user's identity by comparing their provided email and password.

const loginUser = asyncHandler(async (req, res) => { const { email, password } = req.body; if (!email || !password) { res.status(400); throw new Error("Please add all fields"); } // Check for user email const user = await User.findOne({ email }); if (user && (await bcrypt.compare(password, user.password))) { res.json({ _id: user.id, name: user.name, email: user.email, token: generateToken(user._id), }); } else { res.status(400); throw new Error("Invalid credentials"); }});

Let's test the login process with correct and incorrect credentials.

In the next article, we'll work on Authentication Middleware and also create a new API to get logged-in user data.

Connect with me

Top comments (7)

Subscribe

Nazim Boudeffa

Hi, I am a coder and a dudeist, excuse my english I am a french speaker that maintain a certain international english level

  • Joined

Nov 14 '23

  • Copy link

Thank you for sharing this is what I am goign to use for my project
Do you know how to add a middleware to routes ?

Aneeqa Khan

Aneeqa Khan

Software Engineer by profession, Artist by heart

  • Email

    aneeqa.k25@gmail.com

  • Location

    London, United Kingdom

  • Education

    MCS

  • Pronouns

    she/her

  • Work

    Finding work

  • Joined

Nov 14 '23

  • Copy link

I'm glad that it is helpful for you.
I am going to write about middleware in my next blog but you can also check this video.

Nazim Boudeffa

Nazim Boudeffa

Hi, I am a coder and a dudeist, excuse my english I am a french speaker that maintain a certain international english level

  • Joined

Nov 14 '23 • Edited on Nov 14 • Edited

Thank you very much for the video link it was helpful because I was stuck on how to use the token
I know Traversy Media from Packt Publishing site, Brad is a very good tutor
So I have been able to finish a first version of a project API
You can find it on my GitHub
I am thinking about writing a tutorial on how I am coding it, it was inspired by Medusajs early versions

Aneeqa Khan

Aneeqa Khan

Software Engineer by profession, Artist by heart

  • Email

    aneeqa.k25@gmail.com

  • Location

    London, United Kingdom

  • Education

    MCS

  • Pronouns

    she/her

  • Work

    Finding work

  • Joined

Nov 14 '23

  • Copy link

Certainly, it's a great idea to explore that topic in writing.

Hasan Elsherbiny

Hasan Elsherbiny

Senior Full-stack .Net Developer who has Created and optimized scalable web applications for over 8 years ,leveraged troubleshooting anddebugging expertise to contribute to the successful development

  • Education

    Bachelor of Physics and Computer Science

  • Work

    Senior Full stack Developer

  • Joined

Nov 11 '23

  • Copy link

good job 👏👏

Samir

Samir

Keep moving forward

  • Location

    Ghana

  • Education

    UNIVERSITY OF CAPE COAST

  • Pronouns

    Him

  • Work

    Student

  • Joined

Apr 28

  • Copy link

What database do you use

Aneeqa Khan

Aneeqa Khan

Software Engineer by profession, Artist by heart

  • Email

    aneeqa.k25@gmail.com

  • Location

    London, United Kingdom

  • Education

    MCS

  • Pronouns

    she/her

  • Work

    Finding work

  • Joined

Apr 28

  • Copy link

For this series, I used MongoDB.

For further actions, you may consider blocking this person and/or reporting abuse

Building Secure User Registration and Authentication in Node.js (2024)
Top Articles
Understanding Lot in Futures Trading
Despite Slowdown, Life Science Still Poised for Long-Term Growth | Voit Real Estate Services
NOAA: National Oceanic & Atmospheric Administration hiring NOAA Commissioned Officer: Inter-Service Transfer in Spokane Valley, WA | LinkedIn
Citibank Branch Locations In Orlando Florida
According To The Wall Street Journal Weegy
Monticello Culver's Flavor Of The Day
Clairememory Scam
[PDF] INFORMATION BROCHURE - Free Download PDF
Blue Beetle Showtimes Near Regal Swamp Fox
Athens Bucket List: 20 Best Things to Do in Athens, Greece
Job Shop Hearthside Schedule
Craigslist Apartments In Philly
Stihl Km 131 R Parts Diagram
Gdlauncher Downloading Game Files Loop
Q Management Inc
Skyward Login Jennings County
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
Der Megatrend Urbanisierung
Ibukunore
Pinellas Fire Active Calls
Icivics The Electoral Process Answer Key
Craigslist Lakeville Ma
Doki The Banker
R. Kelly Net Worth 2024: The King Of R&B's Rise And Fall
Directions To Cvs Pharmacy
The Banshees Of Inisherin Showtimes Near Broadway Metro
Rugged Gentleman Barber Shop Martinsburg Wv
Craftybase Coupon
Lilpeachbutt69 Stephanie Chavez
Swgoh Boba Fett Counter
2430 Research Parkway
Verizon TV and Internet Packages
The Pretty Kitty Tanglewood
Heavenly Delusion Gif
Puffco Peak 3 Red Flashes
Sams La Habra Gas Price
Lyca Shop Near Me
Hometown Pizza Sheridan Menu
Wunderground Orlando
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
Ig Weekend Dow
Rocky Bfb Asset
Grand Valley State University Library Hours
Academic Notice and Subject to Dismissal
News & Events | Pi Recordings
Erica Mena Net Worth Forbes
Steam Input Per Game Setting
Acuity Eye Group - La Quinta Photos
Craigslist Anc Ak
Tyrone Unblocked Games Bitlife
King Fields Mortuary
Obituary Roger Schaefer Update 2020
Latest Posts
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 5744

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.