Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ReactJS Authentication Tutorial, Part 1

DZone's Guide to

ReactJS Authentication Tutorial, Part 1

In this tutorial, I'll show you how easy it is to build a web application with ReactJS and add authentication to it. Check out the repo to get the code.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

ReactJS is a JavaScript library, built and maintained by Facebook. It was developed by Jordan Walke, a software engineer at Facebook. It was open-sourced and announced to the developer community in March 2015. Since then, it has undergone tremendous growth and adoption in the developer community. In fact, at the time of writing this article, ReactJS was the 5th most starred project of all time on GitHub.

Currently, many web platforms use ReactJS to build their user interfaces. Such platforms include Netflix, Instagram, Airbnb, KhanAcademy, Walmart and more. The documentation is very detailed, and there is a vibrant community of users. In addition, a plethora of ReactJS addons exists on GitHub for easy inclusion in your project for whatever functionality you are trying to build.

Understanding Key Concepts in ReactJS

ReactJS was influenced by XHP, an augmentation of PHP and Hack to allow XML syntax for the purpose of creating custom and reusable HTML elements. If you're coming from the world of jQuery and don't have experience with frameworks like Angular, Ember, or VueJS, you may find ReactJS very confusing. There are many questions you might have to ask yourself, such as:

  • Why are JavaScript and HTML together in one script?
  • What is JSX? Why is the syntax so weird?
  • What is a state?
  • Why do we need props?
  • What are and why do we need components in our apps?

Don't worry, you'll have answers to your many questions soon! There are some key concepts you need to know when learning React. Once you have a basic understanding of these concepts, then you'll be able to create your first ReactJS app without banging your head on the wall.

These key concepts are:

  • Components - The Types and API
  • Props
  • State
  • JSX

I'll give a basic overview of these concepts to nourish your understanding of ReactJS.

Components - The Types and API

React is basically about components. A ReactJS app is just one big component made up of interoperable smaller components. Working with ReactJS means you are thinking in components most of the time.

An example of a component is an HTML 5 tag, say <header>. A header can have attributes, it can be styled and also possess its own behavior. In ReactJS, you'll be able to build your own custom component using ES6 like so:

class CustomComponent extends React.Component {
   render() {
      return '<h3> This is my custom component!!!</h3>';
   }
}

So, your component will now be <CustomComponent></CustomComponent>.

React provides some methods that are triggered at various points from creating a component up until the component is destroyed. This is called the Component's Lifecycle. You can declare methods to hook into the component's lifecycle to control the behavior of components in your app. Some examples of these lifecycle hooks are componentDidMount(), componentWillMount(), componentWillUnmount(), shouldComponentUpdate(), componentWillUpdate() , and more.

  • componentWillMount(): This method is called before the component is initially rendered. So it is called before the render method is executed. You can't perform any type of DOM manipulation here because the component isn't available in the DOM yet.
  • componentDidMount(): This method is called right after the component has been rendered. So it is called immediately after the render method has been executed. It's the best place to perform network and AJAX calls.
  • componentWillUnmount(): This method is called right before the component is removed from the DOM.
  • shouldComponentUpdate(): This method determines if a re-rendering should occur or not. It is never called on initial rendering and it's always called before the render method.
  • componentWillUpdate(): This method is called as soon as shouldComponentUpdate returns true. It is called just before the component is rendered with new data.

There are also methods like render and setState that you can use to render an element in the DOM and set the state of a component respectively.

Take this example for a spin and watch how these lifecycle hooks work. Observe the sequence of logs in the browser console.

import React, { Component } from 'react';
import { render } from 'react-dom';

class Experiment extends Component {

  componentWillMount() {
    console.log("This will mount");
  }

  componentDidMount() {
    console.log("This did mount");
  }

  componentWillUnmount() {
    console.log("This will unmount");
  }

  render() {
    console.log("I am just rendering like a boss");
    return <div>I got rendered!</div>;
  }

}

render(
  <Experiment />,
  document.getElementById("root")
);

Props

Props is the short form for properties. Properties are attributes of a component. In fact, props are how components talk to each other. A tag in HTML such as <img> , has an attribute, a.k.a. aprop called src that points to the location of an image.

In React, you can have two components, FatherComponent and SonComponent. Let's see how they can talk to each other.

class FatherComponent extends React.Component {
   render() {
      return <SonComponent quality="eye balls" />;
   }
}

FatherComponent

class SonComponent extends React.Component {
    render() {
      return <p> I am a true son. I have my father's "{ this.props.quality }" . </p>;
    }
}

SonComponent

Now, when the page is served and a <FatherComponent> is called, I am a true son. I have my father's eyes will be rendered on the page.

State

When developing ReactJS applications, it is important to know when and when not to use state in components. The question now is: When do I use state? When do I use props? Props are data that the component depends on to render correctly. Most of the time, it comes from above, meaning it is passed down from a parent component to a child component. Like props, state holds information about the component but it is handled differently. For example, the number of times a button was clicked, user input from a form, etc. When state changes in a component, the component automatically re-renders and updates the DOM.

Inside a component, state is managed using a setState function.

class Layout extends React.Component {
  constructor() {
    super();
    this.state = {
      position: "right"
    };
  }

  render() {
    return (
      { this.state.position }
    )
  }
}
class Button extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0,
    };
  }

  updateCount() {
    this.setState((prevState, props) => {
      return { count: prevState.count + 1 }
    });
  }

  render() {
    return (
      <button onClick={() => this.updateCount()} >
        Clicked {this.state.count} times
      </button>
    );
  }
}

Now, this works great for simple applications like the one we'll build in this tutorial. For medium and large apps, it is recommended to use a state management library like Redux or MobX to avoid big balls of messy code and also to help you track every event happening within your app.

JSX

Initially, looking at JSX seems awkward. JSX is the combination of HTML and JavaScript code in the same file. You can decide to name the extension of the file .jsx or just .js. An example of JSX is:

class Layout extends React.Component {
  render() {
    return <p>Hello {this.props.layoutStructure ?  'Frontend layout' : 'Backend Layout'}</p>;
  }
}

You can check out more information on JSX here.

Next, let's build an application with ReactJS.

Our App: Chuck Norris World

Chuck Norris World

The app we will build in this series is called Chuck Norris World. Our app is an eye into the world of Chuck Norris and his greatness. The Chuck Norris World app will display different jokes about the legend. A list of common food jokes will be available to the general public, while the celebrity jokes will only be accessible to registered members.

Note: These days, celebrities demand a lot of cash for jokes made at their expense, and Chuck Norris isn't helping matters. Always cracking jokes about them, sigh!

Build the Back-End

Let's build an API to serve the list of jokes to our app. We'll quickly build the API with Node.js. The API is simple. This is what we need:

  • An endpoint to serve jokes about food - /api/jokes/food.
  • An endpoint to serve jokes about celebrities - /api/jokes/celebrity.
  • Secure the endpoint that serves celebrity jokes, so that it can only be accessed by registered users.

Go ahead and fetch the Node.js backend from GitHub.

Your server.js should look like this:

'use strict';

const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwks = require('jwks-rsa');
const cors = require('cors');
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

const authCheck = jwt({
  secret: jwks.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        // YOUR-AUTH0-DOMAIN name e.g prosper.auth0.com
        jwksUri: "https://{YOUR-AUTH0-DOMAIN}/.well-known/jwks.json"
    }),
    // This is the identifier we set when we created the API
    audience: '{YOUR-API-AUDIENCE-ATTRIBUTE}',
    issuer: '{YOUR-AUTH0-DOMAIN}',
    algorithms: ['RS256']
});

app.get('/api/jokes/food', (req, res) => {
  let foodJokes = [
  {
    id: 99991,
    joke: "When Chuck Norris was a baby, he didn't suck his mother's breast. His mother served him whiskey, straight out of the bottle."
  },
  {
    id: 99992,
    joke: 'When Chuck Norris makes a burrito, its main ingredient is real toes.'
  },
  {
    id: 99993,
    joke: 'Chuck Norris eats steak for every single meal. Most times he forgets to kill the cow.'
  },
  {
    id: 99994,
    joke: "Chuck Norris doesn't believe in ravioli. He stuffs a live turtle with beef and smothers it in pig's blood."
  },
  {
    id: 99995,
    joke: "Chuck Norris recently had the idea to sell his urine as a canned beverage. We know this beverage as Red Bull."
  },
  {
    id: 99996,
    joke: 'When Chuck Norris goes to out to eat, he orders a whole chicken, but he only eats its soul.'
  } 
  ];
  res.json(foodJokes);
})

app.get('/api/jokes/celebrity', (req,res) => {
  let CelebrityJokes = [
  {
    id: 88881,
    joke: 'As President Roosevelt said: "We have nothing to fear but fear itself. And Chuck Norris."'
  },
  {
    id: 88882,
    joke: "Chuck Norris only lets Charlie Sheen think he is winning. Chuck won a long time ago."
  },
  {
    id: 88883,
    joke: 'Everything King Midas touches turnes to gold. Everything Chuck Norris touches turns up dead.'
  },
  {
    id: 88884,
    joke: 'Each time you rate this, Chuck Norris hits Obama with Charlie Sheen and says, "Who is winning now?!"'
  },
  {
    id: 88885,
    joke: "For Charlie Sheen winning is just wishful thinking. For Chuck Norris it's a way of life."
  },
  {
    id: 88886,
    joke: "Hellen Keller's favorite color is Chuck Norris."
  } 
  ];
  res.json(CelebrityJokes);
})

app.listen(3333);
console.log('Listening on localhost:3333');

server.js

Your package.json file should look like this:

{
    "name": "chuck-norris-jokes",
    "version": "0.0.1",
    "description": "",
    "main": "server.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node server.js",
        "dev": "nodemon server.js"
    },
    "author": "Auth0",
    "license": "MIT",
    "dependencies": {
        "body-parser": "^1.15.2",
        "cors": "^2.8.1",
        "express": "^4.14.0",
        "express-jwt": "^3.4.0"
    }
}

package.json

Note: Make sure you have nodemon installed globally.

Once you have cloned the project, run an npm install, then use postman to serve your routes like so:

API serving food jokesAPI serving food jokes

API serving celebrity jokesAPI serving celebrity jokes

The Food jokes endpoint should be http://localhost:3333/api/jokes/food.

The Celebrity jokes endpoint should be http://localhost:3333/api/jokes/celebrity.

Don't worry about the middleware in charge of securing our endpoint for now. We'll deal with that later.

In Part 2 of this series, we'll build our frontend with ReactJS. Woot woot!

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
web dev ,reactjs ,api ,backend ,nodejs

Published at DZone with permission of Prosper Otemuyiwa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}