DEV Community

Cover image for User authentication in MERN stack (Backend)
FARHAN KHAN
FARHAN KHAN

Posted on • Updated on

User authentication in MERN stack (Backend)

In this tutorial, we will dive into the fundamentals of user authentication, covering key concepts such as registration, login, password hashing. It will guide you through the process of setting up a secure authentication system, from building the backend API using Node.js and Express.js to creating a user-friendly frontend with React.

Whether you are a beginner looking to gain a solid foundation in user authentication or an experienced developer seeking to enhance your skills with the MERN stack, this tutorial will provide you with the knowledge and tools necessary to implement robust user authentication in your web applications.

Prerequisites:

Folder Structure

Image description

The folder structure for user authentication of mern website contains:

  • A server.js file - where the main express app is initiated.

  • A model folder - which contains all mongodb documents Schema files in which the documents schemas are defined.

  • A router folder - which contains all route files where routes are defined.

  • A controllers folder - which contains all controller files where the authentication logic is written.

Server.js

As mentioned above in server.js file the express app is initiated.

Image description

To start with the server.js we first of all need to import all necessary dependencies such as:

Image description

After importing all the necessary dependencies we have used middleware such as

  • app.use(bodyParser.urlencoded({ extended: true })) - to parse URL encoded data

  • app.use(bodyParser.json()) - to parse json data.

Image description

We have also created post request for api/podcasts,login,signup.
After that we have made connection with mongoDB database (cloud i.e atlas or compass) .

userSchema.js

The userSchema.js file is in the models folder where the schema for user authentication is defined.

Image description

In userSchema.js first of all we import mongoose which is used to create the schema. Then we create the schema having fields username, email, password and confirmpassword.

user.js

The user.js file is inside the routes folder where routers for login and signup are defined.

Image description

In user.js first of all we import express which is required for creating routes. Then we import the login and signup controllers from Usercontroller.js. Then we create router using express.Router(). After that we create routers for login and signup.

Usercontroller.js

The Usercontroller.js file in controllers folder contains the logic of login and signup.

Image description

To start with the user controller we first of all import all necessary dependencies such as:

Signup Logic

Image description

  1. Get the values of field such as username, email, password and confirmpassword using req.body
  2. Check for the empty fields.
  3. If any empty field is present throw error ('Please fill the field')
  4. Check whether the entered email by the user is present in the databse or not.
  5. If the entered email is already present in the database than return res.status(400).json('Email already exist') .
  6. If the entered email is not present in the database than create the instance of the schema model and pass the new values. const user = new User({ username:username, email:email, password:password, confirmpassword:confirmpassword })
  7. Create the salt value using await bcrypt.genSalt(10).
  8. Then we create hash value using await bcrypt.hash(password,salt).
  9. Once the hash value is created we store it as the user password user.password = hash.
  10. After that we save the instance of the schema user.save().

Login Logic

Image description

  1. For the login we first get the values of fields using req.body.
  2. Check for the empty fields
  3. if any empty field is present than throw error ('Please fill the field').
  4. Check if the entered email by the user is present in the database or not.
  5. If the entered email is not present than throw err return res.status(404).json({error:"User not found"}).
  6. If the entered email is present than compare the entered password and the hash password using bcrypt.compare.

Image description

So in this tutorial we have covered the backend part of user authentication in MERN where we have seen the folder structure of the backend, also Schema for document, routes and controllers(logic of Signup and login).

In the second part of this blog we are going to see frontend and the backend connection.

Top comments (2)

Collapse
 
coderx profile image
Soumya Mondal

You've missed quite a few things, on user router, controllers(jwt), hashing before comparison and a few minor improvements.

Collapse
 
itsfarhankhan28 profile image
FARHAN KHAN

Yes bro . Will work on the improvement soon . Thanks a lot for visiting the blog😊