Create a simple POS with React, Node and MongoDB #1: Register and Login with JWT

Create a simple POS with React, Node and MongoDB #1: Register and Login with JWT

Create a simple POS with React, Node and MongoDB #1: Register and Login with JWT

This is the second chapter of our series of creating a simple POS using React, Node, and MongoDB. In the previous chapter, we set up the frontend integrating AdminLTE and connected MongoDB cloud to the Node background. In this tutorial, we are going to add register and login features using JWT.

Register

Let’s Start From the Frontend

We need to get the sample code from AdminLTE. Copy the code wrapped inside <div class="login-box"></div> tags and paste it in a new file named register.js. Convert the pasted HTML code to JSX using the previously installed VSCode extension.

Then, we add Formik and Yup dependencies to easily integrate form and form validation.

Import these two packages inside register.js.

Wrap the created form using the special tag <Formik>. You have to add initial values for the fields that are being used. We use the onSubmit function to display the form values on the console when a user submits the form.

Now we add the showForm function to clean the code and save time.

We inject parameters that are passed on to the form inside this function.

We use onSubmit={handleSubmit} to capture form submission, onChange={handleChange} to capture the values inserted to the forms, and disabled={isSubmitting} to disable form submission.

You can now see the resulting register form.

POS Register page

POS Register page

Try to submit the form and see what happens. Read the output of the console.

2. Formik form object data

2. Formik form object data

Though we have finished creating the form, we need to add client-side validation to the form before sending data to the server.

Validation with Yup

We can create a validation schema as expected using Yup.

Then add the validation schema to Formik.

Now we add CSS that is used to display an error message and change the input border color.

Add the CSS class is-invalid to change the border color to red.

Display the error message from the validation schema.

You can see the full form code below.

The registration form now looks like this.

3.Formik Validation error

3.Formik Validation error

Now we can send an HTTP request with Axios to submit the form.

First, install and import Axios.

Import axios to register.js.

Create a function to send a post request to the backend.

Add this function to the onSubmit function inside Formik and pass the form values and the history object to navigate to another page.

We have completed the frontend implementation of authentication. Next. we will configure the backend to receive the submitted registration form.

Backend: Create a User on the Database

Create a new folder named models and create a file named user_schema.js inside the folder.

Now we have a table structure to store user data.

Next import user_schema to index.js.

We can use the create function to create a new user.

Let’s go back to the frontend to handle the response sent by the server.

Add SweetAlert

To handle the response message, we use SweetAlert. First, install the package using the command yarn add sweetalert. Import the package to register.js as the following line of code shows.

import swal from "sweetalert";

Now use SweetAlert to handle the success or error response accordingly.

Now add submitForm to onSubmit.

Submit valid data through the form and see how the form works.

success submission result

success submission result

Submit an invalid set of data through the form to see how the form handles errors.
error submission result

error submission result

Now you can view the registered user data.

result data in mongodb

result data in mongodb

LOG IN

Backend: Authentication with JWT

We use JWT to handle login by generating a JSON Web Token which can be sent back to the browser to be stored in the LocalStorage.

Create a file named jwt.js inside the backend folder.

Import fs and path libraries to read private and public keys.

Then, define the issuer as follows.

Create a function named sign to create JWTs.

Now import the file to index.js.

We can now implement the login-from database. We search the user from the database and compare the stored and sent passwords using bcrypt.

Login Frontend

We can copy the code from register.js and paste it to login.js. Update the form by removing the username and confirm_password input fields. You can view all updates here.

We need to change how the response is handled in the frontend by adding the code to store the JWT token in LocalStorage. Then, redirect to the dashboard screen.

The resulting login page looks like this.

Success result

Success result

Conclusion

In this chapter, we learned how to use Formik and Yup to create registration and login forms. We learned how to add a user table to the database with mongoose and use JWT to authenticate a logged-in user. In the next chapter, we will add log out and handle the auth state to our application. You can find the full code of the application on Github.

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

Conditional Rendering Methods in React

JSX makes it possible to reuse the conditionals you are already familiar with when working with ...

What the Heck is React Hooks?

In this article, you'll learn what a React Hook is, the benefits and how to use it in your react ...

React and AJAX – The Art of Fetching Data in React

In this article, we discuss how to make AJAX requests (or asynchronous API calls), how to use it in React, where to use it, and some tricks to solve ...

3 comments

Elliot Hughes January 15, 2020 at 6:09 pm
0

Thanks for great insights. Would 0auth work for this too?

 
Krissanawat Kaewsanmuang January 16, 2020 at 9:24 am
0

yup will OAuth provider your want to use

Joshua Harris January 16, 2020 at 5:28 pm
1

This is awesome. I can’t wait for the next part.

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy