Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Building a Simple CLI Youtube Video Downloader in NodeJS

    Interview

    Interview with Igor Mikhalev

    Programming

    19. Уроки Node.js. Безопасный Путь к Файлу в fs и path.

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Sunday, September 28
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / POS Tutorial / Create a simple POS with React, Node and MongoDB #1: Register and Login with JWT
    JavaScript

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

    Krissanawat KaewsanmuangBy Krissanawat KaewsanmuangJanuary 14, 2020Updated:May 26, 2024No Comments9 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Create a simple POS with React, Node and MongoDB #1: Register and Login with JWT
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    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

    Defenition: POS – “Point of Sale”. At the point of sale, the merchant calculates the amount owed by the customer, indicates that amount, may prepare an invoice for the customer (which may be a cash register printout), and indicates the options for the customer to make payment.

    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.

    yarn add formik yup

    Import these two packages inside register.js.

    import React, { Component } from "react";
    import { Formik } from "formik";
    import * as Yup from "yup";

    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.

    render() {
        return (
          <div className="register-box">
            <div className="register-logo">
              <a href="../../index2.html">
                <b>Basic</b>POS
              </a>
            </div>
            <div className="card">
              <div className="card-body register-card-body">
                <p className="login-box-msg">Register a new membership</p>
    
                <Formik
                  initialValues={{
                    fullname: "",
                    email: "",
                    password: "",
                    confirm_password: ""
                  }}
                  onSubmit={(values) => {
                    console.log(values);
                  }}
                >
                  {props => this.showForm(props)}
                </Formik>
              </div>
              {/* /.form-box */}
            </div>
            {/* /.card */}
          </div>
        );
      }
    }

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

    showForm = ({
        values,
        errors,
        touched,
        handleChange,
        handleSubmit,
        setFieldValue,
        isSubmitting
      }) => {}

    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.

    return (
          <form onSubmit={handleSubmit}>
            <div className="form-group has-feedback">
              <input
                type="text"
                name="username"
                onChange={handleChange}
                value={values.username}
                className="form-control"
                placeholder="Username"
            
              />
            </div>
            <div className="form-group has-feedback">
              <input
                type="text"
                name="email"
                onChange={handleChange}
                value={values.email}
                placeholder="Email"
              />
            </div>
            <div className="form-group has-feedback">
              <input
                type="password"
                name="password"
                onChange={handleChange}
                value={values.password}
                className="form-control"
                placeholder="Password"
              />
            </div>
            <div className="form-group has-feedback">
              <input
                type="password"
                name="confirm_password"
                onChange={handleChange}
                placeholder="Confirm Password"
              />
            </div>
            <div className="row">
              <div className="col-md-12">
                <button
                  disabled={isSubmitting}
                  type="submit"
                  className="btn btn-primary btn-block btn-flat"
                >
                  Confirm
                </button>
              </div>
            </div>
          </form>
        );

    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.

    const SignupSchema = Yup.object().shape({
      username: Yup.string()
        .min(2, "username is Too Short!")
        .max(50, "username is Too Long!")
        .required("username is Required"),
      email: Yup.string()
        .email("Invalid email")
        .required("Email is Required"),
      password: Yup.string().required("Password is required"),
      confirm_password: Yup.string().oneOf(
        [Yup.ref("password"), null],
        "Both password need to be the same"
      )
    });

    Then add the validation schema to Formik.

               <Formik
                  initialValues={{
                    fullname: "",
                    email: "",
                    password: "",
                    confirm_password: ""
                  }}
                  onSubmit={(values, { setSubmitting }) => {
                    console.log(values);
                    setSubmitting(false);
                  }}
               validationSchema={SignupSchema}
               >

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

    Read More:  How to Architect a Node.Js Project from Ground Up?

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

               className={
                  errors.username && touched.username
                    ? "form-control is-invalid"
                    : "form-control"
                }

    Display the error message from the validation schema.

             {errors.fullname && touched.fullname ? (
                <small id="passwordHelp" class="text-danger">
                  {errors.username}
                </small>
              ) : null}

    You can see the full form code below.

    return (
          <form onSubmit={handleSubmit}>
            <div className="form-group has-feedback">
              <input
                type="text"
                name="username"
                onChange={handleChange}
                value={values.username}
                className="form-control"
                placeholder="Username"
                className={
                  errors.username && touched.username
                    ? "form-control is-invalid"
                    : "form-control"
                }
              />
              {errors.fullname && touched.fullname ? (
                <small id="passwordHelp" class="text-danger">
                  {errors.username}
                </small>
              ) : null}
            </div>
            <div className="form-group has-feedback">
              <input
                type="text"
                name="email"
                onChange={handleChange}
                value={values.email}
                className={
                  errors.email && touched.email
                    ? "form-control is-invalid"
                    : "form-control"
                }
                placeholder="Email"
              />
              {errors.email && touched.email ? (
                <small id="passwordHelp" class="text-danger">
                  {errors.email}
                </small>
              ) : null}
            </div>
            <div className="form-group has-feedback">
              <input
                type="password"
                name="password"
                onChange={handleChange}
                value={values.password}
                className="form-control"
                placeholder="Password"
                className={
                  errors.password && touched.password
                    ? "form-control is-invalid"
                    : "form-control"
                }
              />
              {errors.password && touched.password ? (
                <small id="passwordHelp" class="text-danger">
                  {errors.password}
                </small>
              ) : null}
            </div>
            <div className="form-group has-feedback">
              <input
                type="password"
                name="confirm_password"
                onChange={handleChange}
                className={
                  errors.confirm_password && touched.confirm_password
                    ? "form-control is-invalid"
                    : "form-control"
                }
                placeholder="Confirm Password"
              />
              {errors.confirm_password && touched.confirm_password ? (
                <small id="passwordHelp" class="text-danger">
                  {errors.confirm_password}
                </small>
              ) : null}
            </div>
            <div className="row">
              <div className="col-md-12">
                <button
                  disabled={isSubmitting}
                  type="submit"
                  className="btn btn-primary btn-block btn-flat"
                >
                  Confirm
                </button>
              </div>
              {/* /.col */}
            </div>
          </form>
        );

    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.

    yarn add axios

    Import axios to register.js.

    import axios from "axios";

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

    submitForm = (values) => {
        axios
          .post("http://localhost:8080/register", values)
          .then(res => {
            console.log(res);
          })
          .catch(error => {
            console.log(error);
          });
      };

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

               <Formik
                  initialValues={{
                    fullname: "",
                    email: "",
                    password: "",
                    confirm_password: ""
                  }}
                  onSubmit={(values, { setSubmitting }) => {
                    this.submitForm(values, this.props.history);
                    setSubmitting(false);
                  }}
                  validationSchema={SignupSchema}
                >

    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.

    const mongoose = require("mongoose");
    const schema = mongoose.Schema({
      username: String,
      email: String,
      password: String,
      level: { type: String, default: "normal" },
      created: { type: Date, default: Date.now }
    });schema.index({ username: 1 }, { unique: true });
    module.exports = mongoose.model("users", schema);

    Now we have a table structure to store user data.

    Next import user_schema to index.js.

    require("./db");
    const Users = require("./models/user_schema");

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

    app.post("/register", async (req, res) => {
      try {
        req.body.password = await bcrypt.hash(req.body.password, 8);
        await Users.create(req.body);
        res.json({ result: "success", message: "Register successfully" });
      } catch (err) {
        res.json({ result: "error", message: err.errmsg });
      }
    });

    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.

    Read More:  React Native vs. Flutter: Which One Would Suit You Better?

    import swal from "sweetalert";

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

    submitForm = (values, history) => {
        axios
          .post("http://localhost:8080/register", values)
          .then(res => {
            console.log(res.data.result);
            if (res.data.result === "success") {
              swal("Success!", res.data.message, "success")
              .then(value => {
                history.push("/login");
              });
            } else if (res.data.result === "error") {
              swal("Error!", res.data.message, "error");
            }
          })
          .catch(error => {
            console.log(error);
            swal("Error!", "Unexpected error", "error");
          });
      };

    Now add submitForm to onSubmit.

                 onSubmit={(values, { setSubmitting }) => {
                    this.submitForm(values, this.props.history);
                    setSubmitting(false);
                  }}

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

    success submission result
    Submit an invalid set of data through the form to see how the form handles errors.
    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.

    const fs = require('fs');
    const path = require('path');
    const jwt = require('jsonwebtoken');
    var publicKEY = fs.readFileSync(path.join(__dirname + '/public.key'), 'utf8');
    var privateKEY = fs.readFileSync(path.join(__dirname + '/private.key'), 'utf8');

    Then, define the issuer as follows.

    var i 	= 'Krissio';    	// Issuer (Software organization who issues the token)
    var s 	= 'admin@kriss.io';	// Subject (intended user of the token)
    var a 	= 'https://kriss.io';	// Audience (Domain within which this token will live and function)

    Create a function named sign to create JWTs.

    module.exports = {
        sign : (payload)=>{
             // Token signing options
             var signOptions = {
                issuer: 	i,
                subject: 	s,
                audience: 	a,
                expiresIn: "30d",    // 30 days validity
                algorithm: "RS256"
            };
            return jwt.sign(payload, privateKEY, signOptions);
        },
    }

    Now import the file to index.js.

    const jwt = require("./jwt");

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

    app.post("/login", async (req, res) => {
      let doc = await Users.findOne({ username: req.body.username });
      if (doc) {
        if (bcrypt.compareSync(req.body.password, doc.password)) {
          const payload = {
            id: doc._id,
            level: doc.level,
            username: doc.username
          };
    
          let token = jwt.sign(payload);
          console.log(token);
          res.json({ result: "success", token, message: "Login successfully" });
        } else {
          // Invalid password
          res.json({ result: "error", message: "Invalid password" });
        }
      } else {
        // Invalid username
        res.json({ result: "error", message: "Invalid username" });
      }
    });

    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.

    submitForm = (values, history) => {
        axios
          .post("http://localhost:8080/login", values)
          .then(res => {
            if (res.data.result === "success") {
              localStorage.setItem("TOKEN_KEY", res.data.token);
              swal("Success!", res.data.message, "success")
             .then(value  => {
                history.push("/dashboard");
              });
            } else if (res.data.result === "error") {
              swal("Error!", res.data.message, "error");
            }
          })
          .catch(error => {
            console.log(error);
            swal("Error!", error, "error");
          });
      };

    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.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Krissanawat Kaewsanmuang
    • Website
    • X (Twitter)

    Developer Relation @instamobile.io

    Related Posts

    Streamlining Resource Allocation for Enhanced Project Success

    December 18, 2024

    Conducting Effective Post-Project Evaluations: A Guide

    December 16, 2024

    Strategies for Keeping Projects on Track and Meeting Deadlines

    December 10, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    JavaScript April 30, 2019

    Web Development Newsletters: JavaScript, React, Vue, Angular Email Newsletters

    Interested in following and subscribing to JavaScript email newsletters? Lucky for you, we’ve gathered a bunch of valuable resources and newsletters for you to follow the latest news and trends in the JavaScript community.

    Interview With Oleg

    May 2, 2017

    How to Build Real-Time Applications Using Node.js and WebSockets

    May 27, 2023

    Maximizing Efficiency: The Crucial Role of Lean Startup Methodology

    November 26, 2024

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Integrating Data Privacy into Effective Software Development

    Development December 17, 2024

    Структура организации

    Programming September 22, 2016

    Spring Security Basics

    Java December 8, 2020

    HR Tech Conferences Worth Your Time [2019]

    Events August 8, 2019

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    JavaScript

    React Lesson 4: Homework. Decorators and Mixins

    Marketing Trends

    How Privacy-First Marketing Will Transform the Industry Landscape

    React

    Build Real-World React Native App #8 : implement Dark mode

    Most Popular

    Node.js Lesson 11: Echo Server

    Node.js

    Optimizing LinkedIn Lead Generation: Seamless CRM Integration

    LinkedIn

    Tempor Nec Feugiat Nislpretium Fusce Platea Dictumst

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.