Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Building Secure User Registration and Authentication in Node.js
Aneeqa Khan
Aneeqa Khan

Posted on • Edited on

     

Building Secure User Registration and Authentication in Node.js

Table of Contents

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

Introduction

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

Install Dependencies

Firstly, let's install the required libraries:

npmibcryptjsnpmijsonwebtoken
Enter fullscreen modeExit fullscreen mode

Generate JWT Token

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

constjwt=require("jsonwebtoken");constbcrypt=require("bcryptjs");constasyncHandler=require("express-async-handler");constUser=require("../models/userModel");// Generate JWTconstgenerateToken=(id)=>{returnjwt.sign({id},process.env.JWT_SECRET,{expiresIn:"30d"});};
Enter fullscreen modeExit fullscreen mode

Don't forget to initialize theJWT_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 inuserController.js file.

constregisterUser=asyncHandler(async(req,res)=>{const{name,email,password}=req.body;if(!name||!email||!password){res.status(400);thrownewError("Please add all fields");}// check if user existsconstuserExists=awaitUser.findOne({email});if(userExists){res.status(400);thrownewError("User already exists");}// create hash passwordconstsalt=awaitbcrypt.genSalt(10);consthashedPassword=awaitbcrypt.hash(password,salt);// create userconstuser=awaitUser.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);thrownewError("Invalid user data");}});
Enter fullscreen modeExit fullscreen mode

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

register user postman

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

register user error

Authenticate User

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

constloginUser=asyncHandler(async(req,res)=>{const{email,password}=req.body;if(!email||!password){res.status(400);thrownewError("Please add all fields");}// Check for user emailconstuser=awaitUser.findOne({email});if(user&&(awaitbcrypt.compare(password,user.password))){res.json({_id:user.id,name:user.name,email:user.email,token:generateToken(user._id),});}else{res.status(400);thrownewError("Invalid credentials");}});
Enter fullscreen modeExit fullscreen mode

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

login postman

login error postman

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(8)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
nazimboudeffa profile image
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

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 ?

CollapseExpand
 
aneeqakhan profile image
Aneeqa Khan
Software Engineer by profession, Artist by heart
  • Email
  • Location
    London, United Kingdom
  • Education
    MCS
  • Pronouns
    she/her
  • Work
    Finding work
  • Joined

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

CollapseExpand
 
nazimboudeffa profile image
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
• Edited on• 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 onmy GitHub
I am thinking about writing a tutorial on how I am coding it, it was inspired by Medusajs early versions

Thread Thread
 
aneeqakhan profile image
Aneeqa Khan
Software Engineer by profession, Artist by heart
  • Email
  • Location
    London, United Kingdom
  • Education
    MCS
  • Pronouns
    she/her
  • Work
    Finding work
  • Joined

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

CollapseExpand
 
hasanelsherbiny profile image
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

good job 👏👏

CollapseExpand
 
teaganga profile image
teaganga
  • Work
    my very own CEO
  • Joined

Nice series of tutorial. I'm adding this here as an intro, abouthow to secure APIs in node, using Basic Authentication, API Keys and JWT tokens. JWT tokens are definitely the best, especially for jam-stack apps.

CollapseExpand
 
samir419 profile image
Samir
Keep moving forward
  • Location
    Ghana
  • Education
    UNIVERSITY OF CAPE COAST
  • Pronouns
    Him
  • Work
    Student
  • Joined

What database do you use

CollapseExpand
 
aneeqakhan profile image
Aneeqa Khan
Software Engineer by profession, Artist by heart
  • Email
  • Location
    London, United Kingdom
  • Education
    MCS
  • Pronouns
    she/her
  • Work
    Finding work
  • Joined

For this series, I used MongoDB.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

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

Software Engineer by profession, Artist by heart
  • Location
    London, United Kingdom
  • Education
    MCS
  • Pronouns
    she/her
  • Work
    Finding work
  • Joined

More fromAneeqa Khan

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp