React User Authentication Using JWT

In this article, we will learn how to use JWT authentication in react js

To authenticate a user, a client application must send a JSON Web Token (JWT) in the permission header of an HTTP request to your backend API.

You don’t have to create any code to handle authentication in your API because API Gateway validates the token on your behalf.

1. Make a configuration file for the API to utilise.

The file contains a list of all the constants that are utilised in various places and scenarios. For the time being, we only require the API SERVER address:

export const DUMMY_API = "http://localhost:5000/api/";

2. In the src folder, create a new folder called api.

3. Create an index.js file containing API settings.

import Axios from "axios";
import { DUMMY_API } from "../config/constant";

const axios = Axios.create({
  baseURL: `${DUMMY_API }`,
  headers: { "Content-Type": "application/json" },

  (config) => {
    return Promise.resolve(config);
  (error) => Promise.reject(error)

  (response) => Promise.resolve(response),
  (error) => {
    return Promise.reject(error);

export default axios;

4. Create a file called auth.js that contains all of the API requests.

import axios from "./index";

class AuthApi {

  static Login = (logindata) => {
    return`users/login`, logindata);

  // don't forget to add the register and logout methods

export default AuthApi;

5. Create a new context folder in the src directory.

const AuthContext = React.createContext(null);

export const AuthProvider = ({ userDummyData, children }) => {
  let [userFlag, setUserFlag] = React.useState(userDummyData);

  return (
    <AuthContext.Provider value={{ userFlag, setUserFlag }}>

export const useAuth = () => React.useContext(AuthContext);

6. The Context Provider and the App object must be connected.

const App = () => {
  // we get the user from the localStorage because that's where we will save their account on the login process
  let userData = localStorage.getItem("userData");
  userData = JSON.parse(userData);

  return (
    <AuthProvider userData={userData}>
      <Routes />

export default App;

7. Protected Routes should be defined.

export const ProtectedRoute = ({ }) => {
  let { userData } = useAuth();

  if (!userData || !userData.token || userData.token === "") {
    return (
      // component which inform the user that they must be logged in

  // let user through if they're logged in
  return <Route {} />;

8. The Auth Flow should be coded.

After you’ve identified the Auth Components, you can start working on the Authentication process. Consider the Login Component as an example:

const loginHandler = async (loginevent) => {
   if (loginevent) {

   //handle exceptions like: no email entered, no password entered, here.

   try {
     let response = await AuthApi.Login({
     if ( && === false) {
       //display error coming from server
       return setLoginError(;
     return setProfile(response);
   } catch (error) {
     //display error originating from server / other sources
     if (err.response) {
       return setLoginError(;
     return setLoginError("There has been an error.");

SetProfile helper is called if the user credentials are valid, and the user information is saved in the app store.

const setProfile = (response) => {
  let userdummydata = { };
  userdummydata.token =;
  userdummydata = JSON.stringify(userdummydata);
  //setUser is imported from the useAuth React Context
  //also set the user in local storage
  localStorage.setItem("user", userdummydata);
  return history.push("/admin/dashboard");

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories