MERN Stack

This post will show you how to get people to sign up and log in to your app through MERN Stack, and it will also provide you with the code to implement it. MongoDB, Express.js, React.js, and Node.js are some technologies used to build this locally. I anticipate you to have all of them installed and a text editor on your computer. Installing Mongo Compass is also a good idea to visualize your data.

Setup is the first step. This MERN boilerplate code is what we’ll be utilizing. It’s a good place to start because it’s simple, doesn’t require Redux, and has only one port for both the backend and the frontend (8080). The code can be downloaded or cloned by clicking on the green button on the right-hand side.

This process may take a few minutes so we will get started now. Navigate to the folder in your terminal and type:

npm install

 npm install bcrypt –save

Open your source code in a text editor while this is installed. Before we can run our code, we need to modify one file.

You’ll need to rename config.example.js to config.js, and it will be ignored by Git when committing. If the server connection is successful, this value will be returned. All work in this post is done in a development environment exclusively. Because of this, we only need to alter dbdev to get it to function. Set up a local database mongodb://localhost:27017/login_demo_db .

The MERN boilerplate code can now be executed. Once the setup is complete and the configuration file has been saved, run the following command:

npm run start: dev

User Model

New files regarding our customers will be created. A User (User.js) is needed to describe our data structure for users. The attributes of a user will be stored in this file, located in the /server/models/ directory.

• Email

• Password

• The Date You’ve Been Accepted

• Also, whatever else that your platform decides to keep…

Sign Up

Because it’s difficult to log in if you haven’t signed up, we’ll start with that step. After that, an entirely new file will need to be created, an endpoint added to it, and the frontend changed to accept email and passwords.

A file called signin.js should be created at this point. This file contains all of the endpoints for logging into the system.

The User model object is imported first at the top of the file (see below). The API endpoint for signing up is the next logical step. You’ll go through these motions in this step:

1. Retrieve the email address and password from the body of the request

2. Verify that both values are correct

3. Search for an existing user with the same email address.

4. Create a new User object and save it.

const User = require(‘../../models/User’);

 module.exports = (app) => {

   /*

    * Sign up

    */

   app.post(‘/api/account/signup’, (req, res, next) => {

     const { body } = req;

     const {

       password

     } = body;

     let {

       email

     } = body;

     if (!email) {

       returnres.send({

         success: false,

         message: ‘Error: Email cannot be blank.’

       });

     }

     if (!password) {

       returnres.send({

         success: false,

         message: ‘Error: Password cannot be blank.’

       });

     }   

email = email.toLowerCase();

     email = email.trim(); // Steps:

     // 1. Verify email doesn’t exist

     // 2. Save

     User.find({

       email: email

     }, (err, previousUsers) => {

       if (err) {

         returnres.send({

           success: false,

           message: ‘Error: Server error’

         });

       } else if (previousUsers.length> 0) {

         returnres.send({

           success: false,

           message: ‘Error: Account already exist.’

         });

       } // Save the new user

       constnewUser = new User(); newUser.email = email;

       newUser.password = newUser.generateHash(password);

       newUser.save((err, user) => {

         if (err) {

           returnres.send({

             success: false,

             message: ‘Error: Server error’

           });

         }

         returnres.send({

           success: true,

           message: ‘Signed up’

         });

       });

     }); 

}); // end of sign up endpoint

 };

We have successfully signed up. Creates an API account but does not log the user in.

Login to your account

Setup, verification, and validation of user APIs are all on the agenda. Create a UserSession model object as a starting point. Login to your account.

In server/models/UserSession.js and add:

const mongoose = require(‘mongoose’);constUserSessionSchema = new mongoose.Schema({

   userId: {

     type: String,

     default: ”

   },

   timestamp: {

     type: Date,

     default: Date.now()

   },

   isDeleted: {

     type: Boolean,

     default: false

   }

 });module.exports = mongoose.model(‘UserSession’, UserSessionSchema);

It’s a pretty simple file. As the name implies, userId represents the Mongo Document id for a particular user. That will serve as the main key for our database. You have the option of making this the user’s email address instead. Just keep in mind that it won’t alter. The UserSession doc id will serve as the session token/code, but I’ll detail that later.

Add a new endpoint to the server/routes/api/signin.js backend file.

Reading this makes you want to learn more about it, so why wait in a hurry and join MERN Stack Online Training by enrolling yourself in the best institute in Delhi NCR.

By Anurag Rathod

Anurag Rathod is an Editor of Appclonescript.com, who is passionate for app-based startup solutions and on-demand business ideas. He believes in spreading tech trends. He is an avid reader and loves thinking out of the box to promote new technologies.