04Sep
React User Login Authentication using useContext and useReducer.
React User Login Authentication using useContext and useReducer.

Introduction

Authentication is one of the parts you might have to deal with when building frontend applications. Usually, this involves using a token generated by the server to authenticate the request to the server and also secure protected the frontend(pages that require a user to be signed in).

Due to the fact that you might be using this token and other data in multiple components in the frontend of your application to make requests to the server, it is important that we should be able to share this token across components that need it.

Usecontext

Use context is a hook that allows us pass data to multiple components without prop drilling. UseContext allows us read the current value from a context object and triggers a serenader when the context provider value has changed. You can read more in the docs

This is a simple example to pass a dark theme down multiple components.

//Context.js

import React from 'react';
 
export const AppThemeContext = React.createContext('dark');

To use react context you have first create a context object, we do that using the `React.createContext` then we pass the value for the context object we created.

After creating the context object a context provider component is used to wrap all the components that need access to that context object, this means that only components under the context provider tree can get access to the theme value.

//ParentComponent.js

import {ThemeContext} from './Context';
 
const ParentComponent = () => (
  <ThemeContext.Provider value="dark-mode">
    <Dashboard />
    <Login />
    <Setting/>
  </ThemeContext.Provider>
);

Now we have the value of the Themecontext provider available to all its child components (Dashboard, Login and Setting) all we have to do is read that value from the context object using useContext Hook in the component that needs the theme value.

// Dashboard.js

import React,{useContext} from 'react';
import {ThemeContext} from './Context';
 
const DashBoard = () => {
  const themeMode = useContext(ThemeContext); //dark
 
  return (
    <div className={themeMode}>
      ......
    </div>
  );
};

When we pass the context object(ThemeContext) as an argument to the useContext hooks and it gives us the current value in the Context object if the context value of the `ThemeContext.Provider` changes any component that calls the useContext will be rerendered with the latest value in the context provider.

Note that you can pass other objects, arrays e.t.c as the value in the context object(ThemeContext.Provider) it is not limited to only strings.

UseReducer

Usereducer is a bit similar to Usestate hooks but it uses the state reducer pattern to update/change state. The useReducer hook accepts a reducer of type `(state, action) => newState` and returns the current state and a `dispatch` function that you can use to trigger state changes.

//useReducer Example

const initialState = {count=0}

function reducer(state,action)
    switch (action.type) {
    	case 'increment':
      		return {count: state.count + 1};
   	case 'decrement':
      		return {count: state.count - 1};
   	default:
      		throw new Error();
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

The above example is from the React docs

If you have used redux in the past you will be familiar with this. What happens here is that we pass the useReducer function two arguments a reducer and an initial state,  when we want to update the state we call the dispatch method with type property that specifics the type of state changes we want to affect.

In the example when you increment the counter, the dispatch method is passed an object with a `type` property which the reducer will use to calculate a new state `count: state.count + 1`.

useReducer gives us a way to track what changes state and how state changes.

Now that we have a basic idea of how useContext and useReducer works lets see how we can combine both of them in handling login authentication in React applications.

Walkthrough

We will be building a login authentication using useReducer to manage state and React context to share this state across multiple components. The idea is that we will have a login page with two input fields for username and password that we authenticated on submit. If the login details are valid they are routed to the dashboard page which is a protected route then you can navigate to other protected routes and perform actions restricted to authenticated users.

Before we dive deep into the tutorial, let’s try to understand how the different components will fit together in order to build this application.

Folder Structure

This is what the final project structure should look like:

//Final folder structure

├── .gitignore
├── README.md
├── package.json
├── public   
├── src
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── Components
│   │   └── AppRoute.js
│   ├── Config
│   │   └── routes.js
│   ├── Context
│   │   ├── actions.js
│   │   ├── context.js
│   │   ├── index.js
│   │   └── reducer.js
│   ├── Pages
│   │   ├── Dashboard
│   │   │   ├── dashboard.module.css
│   │   │   └── index.js
│   │   ├── Login
│   │   │   ├── index.js
│   │   │   └── login.module.css
│   │   └── NotFound
│   │       ├── index.js
│   │       └── notfound.module.css
│   ├── index.css
│   ├── index.js
│   ├── logo.svg
│   ├── serviceWorker.js
│   └── setupTests.js
└── yarn.lock

We have a components folder which contains all the reusable components we use in this tutorial.

  • AppRoute: This is a component used to define protected routes(routes that can only be accessed by authenticated users)

Then we will have a context folder where all the context related files are, we have

  • actions.js: I used a redux motivated file structure, this file contains and exports async functions that need to dispatch state changes to the reducer.
  • context.js: This file is where we initialize the different context objects we will be needing and some custom hooks that compose logic.
  • reducer.js: This file contains the reducer that we will use to manage the authentication state.
  • Index.js: The file simply exports the contents of the three files above

We have a Config file where our route config and any other config files are:

  • routes.js: This file will contain config for the different routes in our application

Finally, we have two pages we mean we will be using a routing library(react-router) to route between these pages.

  • Login page
  • Dashboard page

This is most of the components that will be used in this tutorial, now we can dive in setting up and writing code.

Scaffold Application

Enter any directory on your PC or where you keep your pet projects, then in your terminal run the command below to bootstrap a new react application using create-react-app

npx create-react-app login-auth
cd login-auth

This uses the create-react-app to create a simple react application inside a directory named login-auth with the basic dependencies installed:

Install dependencies.

We will need a routing library because will need to handle routing between different pages. I decided to go with react-router for this project, to install it run:

npm install react-router-dom

or

yarn add react-router-dom

Create folders

Before we can dive into the code lets create the folders that will house the different parts of our application. We will set up the folders for our configs, components, context(for react context related code), and pages(pages for the different routes).

Ensure you are in the projects root directory then run this in terminal to change into the `src` directory:

cd src

In the src folder create the following folders:

  • Components
  • Context
  • Pages
  • Config

Setup Routing(React Router)

We installed react-router as one of our dependencies because we need to handling routing between pages in our application. In the Config folder create a file called `routes.js` , in this file we will define all the routes we want to have in this application.

In the `routes.js`  file add the following code:

// Config/routes.js

import React from "react";
import Login from '../Pages/Login'
import Dashboard from '../Pages/Dashboard'
import PageNotFound from '../Pages/PageNotFound'

This is all the page components we will be using in our application. We will create these components later in this article, it is not magic don’t worry.

Now let’s define the different routes for our application, In the same file (routes.js) we create an array of objects that define what path is mapped to what `component`:

// Config/routes.js

const routes =[
  {
    path:'/',
    component: Login
  },
  {
    path:'/dashboard',
    component: Dashboard
  },
  {
    path:'/*',
    component: PageNotFound
  },
]

export default routes

Now lets setup react-router in the `App.js` file, it can be found in the application’s root directory.

// App.js

import React from 'react';
import {
  BrowserRouter as Router,
  Redirect,
  Route,
  Switch,
} from 'react-router-dom';
import routes from './Config/routes.js';

function App() {
  return (
    <Router>
      <Switch>
        {routes.map((route) => (
          <Route
            key={route.path}
            path={route.path}
            component={route.component}
          />
        ))}
      </Switch>
    </Router>
  );
}

export default App;

What happens here is that we loop through the routes we defined in the routes.js in the react-router `Switch` component in order to set up routing in our application.

Create Page Components

In the `Page` Folder lets create a `Login` Folder which will house all the login page related files, in this folder create two files an `index.js` and `login.module.css`

In the index.js file add the following:

// Pages/Login/index.js

import React from 'react';

import styles from './login.module.css';

function Login(props) {
  return (
    <div className={styles.container}>
      <div className={styles.formContainer}>
        <h1>Login Page</h1>

        <form>
          <div className={styles.loginForm}>
            <div className={styles.loginFormItem}>
              <label htmlFor='email'>Username</label>
              <input type='text' id='email' />
            </div>
            <div className={styles.loginFormItem}>
              <label htmlFor='password'>Password</label>
              <input type='password' id='password' />
            </div>
          </div>
          <button>login</button>
        </form>
      </div>
    </div>
  );
}

export default Login;

This is the HTML for the login page so now let’s add the styles for this page in the `login.module.css` file.

/* Pages/Login/login.module.css */

.container {
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.formContainer {
  width: 200px;
}
.error {
  font-size: 0.8rem;
  color: #bb0000;
}

.loginForm {
  display: flex;
  flex-direction: column;
}

.loginFormItem {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}

These are the styles for the login page. Next we in the `Pages` Folder we create a Dashboard folder then create two files index.js and dashboard.module.css in that folder.

In the `index.js` file add the following markup for the dashboard page

// Pages/Dashboard/index.js

import React from 'react'
import styles from './Dashboard.module.css'

function Dashboard(props) {
   
    return (
        <div style={{ padding: 10 }}>
            <div className={styles.dashboardPage} >
                <h1>
                    Dashboard
                </h1>
                <button className={styles.logoutBtn} >Logout</button>
            </div>
            <p>Welcome to the dashboard</p>
        </div>
    )
}

export default Dashboard

Then we can add the styles for the dashboard page to the `dashboard.module.css` file:

/* Pages/Dashboard/dashboard.module.css */

.logoutBtn {
  height: '30px';
  width: '100px';
}

.dashboardPage {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

Finally, we create the component for the NotFound page, this is a page that shows when a user tries to access a route that is not defined in out routes config. Similar to the other page we have created, we can go ahead and create a `NotFound` folder then inside it we create an `index.js` and a `notfound.module.css` file.

In the `index.js` file add the following code:

// Pages/NotFound/index.js

import React from 'react';
import styles from './notfound.module.css';

function NotFound(props) {
	return (
		<div className={styles.container}>
			<h1>Page not found</h1>
		</div>
	);
}

export default NotFound;

Then we can add the styles for that page to the `notfound.module.css`:

/* Pages/NotFound/notfound.module.css */

.container {
	min-height: 100vh;
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}

We have successfully created all the pages and set up our router, now we should be able to view these different pages and navigate between pages.

Run the below code in the project root to start the application:

Yarn start 


    or


Npm start

Our application should start then we can view the Login page in the http://localhost:3000/login route and the Dashboard Page in http://localhost:3000/dashboard 
route.

Setup Context for Authentication

We will start by creating the context objects we will be using in our application, we will create two context object:

  • AuthStateContext: This context object will contain the authentication token and user details.
  • AuthDispatchContext: We will use this context object to pass the dispatch method given to us by the `useReducer` that we will be creating later to manage the state. This makes it easy to provide the dispatch method to components that need it.

In the `Context` folder we created earlier, create a file called `context.js`. This file will contain the context objects and everything we need to use the context object.

To create the context objects we add the below to the `context.js` file:

// Context/context.js

import React from "react";

const AuthStateContext = React.createContext();
const AuthDispatchContext = React.createContext();

Next, we will want to create custom hooks that will help us read values from these context objects without having to call React.useContext in every component that needs that context value and it also does some error handling in case these contexts are used outside the context providers.

In the same file (context.js) we create a `useAuthDispatch` hook and a `useAuthDispatch` :

// Context/context.js

[...]

export function useAuthState() {
  const context = React.useContext(AuthStateContext);
  if (context === undefined) {
    throw new Error("useAuthState must be used within a AuthProvider");
  }

  return context;
}

export function useAuthDispatch() {
  const context = React.useContext(AuthDispatchContext);
  if (context === undefined) {
    throw new Error("useAuthDispatch must be used within a AuthProvider");
  }

  return context;
}


This will be useful later in the article when we start adding state to our components.

Finally, for the context file we create a custom provider named `AppStateProvider`, This provider composes the logic that helps us manage our application.

Add the following code to the `context.js` file:

// Context/context.js

export const AuthProvider = ({ children }) => {
  const [user, dispatch] = useReducer(AuthReducer, initialState);

  return (
    <AuthStateContext.Provider value={user}>
      <AuthDispatchContext.Provider value={dispatch}>
        {children}
      </AuthDispatchContext.Provider>
    </AuthStateContext.Provider>
  );
};

The above function is our own “state management library”, in the AuthProvider function we first create a means of keeping/managing state using `useReducer`. We haven’t created the reducer function and the initial state(initialState) object passed as arguments to the `useReducer` hook yet but we will later in this tutorial.

The useReducer returns a user object as state and a dispatch method for triggering state updates/changes, then we pass the user object to as `value` `AuthStateContext` provider also we pass the dispatch method as value to the `AuthDispatchContext` provider.
What this means is that the user object and dispatch method are available to any children of the `AuthProvider` component.

Now we can go ahead to create the `AuthReducer` and the `initialState` object that was used by the `useReducer` hook. In the `Context` folder create a new file called `reducer.js`.

In the `reducer.js` file we just created add the following code to create the `AuthReducer` reducer and the `initialState` object:

// Context/reducer.js

import React, { useReducer } from "react";

let user = localStorage.getItem("currentUser")
  ? JSON.parse(localStorage.getItem("currentUser")).user
  : "";
let token = localStorage.getItem("currentUser")
  ? JSON.parse(localStorage.getItem("currentUser")).auth_token
  : "";

export const initialState = {
  userDetails: "" || user,
  token: "" || token,
  loading: false,
  errorMessage: null
};

export const AuthReducer = (initialState, action) => {
  switch (action.type) {
    case "REQUEST_LOGIN":
      return {
        ...initialState,
        loading: true
      };
    case "LOGIN_SUCCESS":
      return {
        ...initialState,
        user: action.payload.user,
        token: action.payload.auth_token,
        loading: false
      };
    case "LOGOUT":
      return {
        ...initialState,
        user: "",
        token: ""
      };

    case "LOGIN_ERROR":
      return {
        ...initialState,
        loading: false,
        errorMessage: action.error
      };

    default:
      throw new Error(`Unhandled action type: ${action.type}`);
  }
};

We create the initial state object which has four properties :

  • `userDetails`: userDetails is for storing the user object returned from the server on successfully login. We try to read the userDetails from the localStorage on initialization in other to persist the login state across sessions.
  • `token`: It is for storing the authentication token(JWT) returned from the server, it is also persisted using the browsers local storage.
  • `loading`: it is for storing the loading state of the login form when it is being submitted.
  • `errorMessage`: it is for storing error message returned if the login fails.

After creating the initial state we create the reducer function that will be used by the `useReducer` state hook. Like I said earlier when explaining reducers, it is a function that accepts an initialState and an action object({type: “ACTION_TYPE”}) as arguments and then returns a new state based on the action type specified.

Finally, for the context folder, we want to define some async functions that I call actions(similar to actions in redux). These function dispatch multiple state updates as a result of an Http request or side-effect.
we have two of this actions, a `loginUser` and `logout` function, the `loginUser` function will handle asynchronous requests to the server to authenticate a user login details and a `logout` function used to log a user out of an authenticated session.

I will be defining these functions in an `actions.js` file similar to how it is done in redux where all the asynchronous functions that change/update state are called actions.

// Context/actions.js


const ROOT_URL = 'https://secret-hamlet-03431.herokuapp.com';

export async function loginUser(dispatch, loginPayload) {
  const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(loginPayload),
  };

  try {
    dispatch({ type: 'REQUEST_LOGIN' });
    let response = await fetch(`${ROOT_URL}/login`, requestOptions);
    let data = await response.json();

    if (data.user) {
      dispatch({ type: 'LOGIN_SUCCESS', payload: data });
      localStorage.setItem('currentUser', JSON.stringify(data));
      return data
    }

    dispatch({ type: 'LOGIN_ERROR', error: data.errors[0] });
    return;
  } catch (error) {
    dispatch({ type: 'LOGIN_ERROR', error: error });
  }
}

export async function logout(dispatch) {
  dispatch({ type: 'LOGOUT' });
  localStorage.removeItem('currentUser');
  localStorage.removeItem('token');
}

`loginUser` action(function) is passed a dispatch method and login payload as arguments, Immediately `loginUser` is called we dispatch a state update of type `REQUEST_LOGIN` to trigger a state update of the AuthReducer state, this tells the AuthReducer that the login requests have started.

Then if the login was successful an action of type `LOGIN_SUCCESS` and payload containing the login response is passed to the AuthReducer to update the state(the user details and auth token).

Finally, if the login request fails an action of type `LOGIN_ERROR` is dispatched with an error object as payload to the AuthReducer to update the state(error message).

For the `logout` action(function), it is also passed a dispatch method. Immediately `logout` is called it dispatches an action of type `LOGOUT`, this resets the AuthReducer state to the initial state(remove the token and user details object from state) and then the remove the `currentUser` and `token` from local storage.

Now we have done all the setup for our context and state management with useReducer, we will create an `index.js` file in the `Context` folder where we export all the contents of the `Context` folder.
I usually do this so I have cleaner import statements where I need to use these different modules. Add the following code to the `index.js` you just created:

// Context/index.js


import { loginUser, logout } from './actions';
import { AuthProvider, useAuthDispatch, useAuthState } from './context';

export { AuthProvider, useAuthState, useAuthDispatch, loginUser, logout };

Integrate Context into our application

Now we have all we need to manage our authentication state globally, we can now integrate it into our application. First we start by wrapping our application in the custom provider(`AuthProvider`) we created earlier. This ensures that every component in our application has access to the context objects we created earlier.

To do this we go to our applications entry point in `App.js`, we import the custom provider(AuthProvider) and wrap it around all our routes as shown below:

// App.js

import routes from './Config/routes.js';
import { AuthProvider } from "./Context";

function App() {
  return (
    <AuthProvider>
      <Router>
        <Switch>
          {routes.map((route) => (
            <Route
              key={route.path}
              path={route.path}
              component={route.component}
            />
          ))}
        </Switch>
      </Router>
    </AuthProvider>
  );
}

export default App;

Now the context objects are available to all the routes and sub-components in our application, all we need to do now is read this object where it needs it.

Implement authentication in the Login page component

In the Logic component we created earlier we want to implement the login authentication logic, that is :

  • Get the values from the login form
  • Submit the login details to the server for authentication
  • Handle failed login attempt
  • Navigate to the dashboard on successful login.

In the `Login` component we created earlier in `/Pages/Login/index.js`, define state and input handlers for the email and password input fields.

// Pages/Login/index.js

[...]

function Login(props) {

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

   

    return (
        <div className={styles.container}>
            <div className={{ width: 200 }}>
                <h1>Login Page</h1>
               
                <form >
                    <div className={styles.loginForm}>
                        <div className={styles.loginFormItem}>
                            <label htmlFor="email">Username</label>
                            <input type="text" id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
                        </div>
                        <div className={styles.loginFormItem}>
                            <label htmlFor="password">Password</label>
                            <input type="password" id='password' value={password} onChange={(e) => setPassword(e.target.value)}  />
                        </div>
                    </div>
                    <button>login</button>
                </form>
            </div>
        </div>
    )
}
[...]

At this point we have the email and password field available in state, we can now create a function to handle submission of this form details to the server. We will call this function `handleLogin` and will be called on click of the `login` button.

In the Login component we create the handleLogin function:

// Pages/Login/index.js

function Login(props) {

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')




    const handleLogin = async (e) => {
       e.preventDefault()
    	let payload = {name, email}
        
    	// async request to the server
    }

    return (
        [...]
        <button onClick={handleLogin} >login</button>
        [...]

    )
}

In the `handleLogin` function we can choose to make this async request(authentication request) in this component that needs it and handle all the state changes in this component but in some cases, you might find yourself duplicate similar logic in multiple components instead of just having one action that encapsulates all that logic.

So this one of the reasons why we choose to abstract this async logic to a `loginUser` action/function. `loginUser`  accepts the dispatch method and the payload for the login request. This function then makes a request to the server and dispatches the appropriate state change over the request-response cycle.

The `loginUser` takes a dispatch method so we can use the `useAuthDispatch` hook we created earlier to get the dispatch method from context.

Our `handleLogin` function should look something like this now:

// Pages/Login/index.js

[…]

import { loginUser, useAuthState, useAuthDispatch } from '../../Context' 
[…]

function Login(props) {

    […]

    const dispatch = useAuthDispatch() //get the dispatch method from the useDispatch custom hook
  

    const handleLogin = async (e) => {
        e.preventDefault()
        let payload = {name, email}
        try {
            let response = await loginUser(dispatch, payload) //loginUser action makes the request and handles all the neccessary state changes
            if (!response.user) return
            props.history.push('/dashboard') //navigate to dashboard on success
        } catch (error) {
            console.log(error)
        }
    }

    return (
        <div className={styles.container}>
            <div className={{ width: 200 }}>
                <h1>Login Page</h1>
               <form >
                    <div className={styles.loginForm}>
                        <div className={styles.loginFormItem}>
                            <label htmlFor="email">Username</label>
                            <input type="text" id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
                        </div>
                        <div className={styles.loginFormItem}>
                            <label htmlFor="password">Password</label>
                            <input type="password" id='password' value={password} onChange={(e) => setPassword(e.target.value)}  />
                        </div>
                    </div>
                    <button onClick={handleLogin} >login</button>
                </form>
            </div>
        </div>
    )
}

export default Login

To test the login details are email: `[email protected]` and password: `admin123`, on successful login we navigate the user to the dashboard page.

This login page is not complete yet, right now it doesn’t show any error messages or any loading state to tell the user that the form is still being submitted.

Lucky for us the `loginUser` action already handles the different state updates based on the response of the login request and all we have to do is read the error message and loading state from context. How lucky can we be? Ok so we have another custom hook we created earlier to read the values from the AuthStateContext called useAuthState.

We can update the Login component to look like this:

// Pages/Login/index.js

[…]

import { loginUser, useAuthState, useAuthDispatch } from '../../Context'


function Login(props) {

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const dispatch = useAuthDispatch()
    const { loading, errorMessage } = useAuthState() //read the values of loading and errorMessage from context




    const handleLogin = async (e) => {
        e.preventDefault()

        try {
            let response = await loginUser(dispatch, { email, password })
            if (!response.user) return
            props.history.push('/dashboard')
        } catch (error) {
            console.log(error)
        }
    }

    return (
        <div className={styles.container}>
            <div className={{ width: 200 }}>
                <h1>Login Page</h1>
                {
                    errorMessage ? <p className={styles.error}>{errorMessage}</p> : null
                }
                <form >
                    <div className={styles.loginForm}>
                        <div className={styles.loginFormItem}>
                            <label htmlFor="email">Username</label>
                            <input type="text" id='email' value={email} onChange={(e) => setEmail(e.target.value)} disabled={loading} />
                        </div>
                        <div className={styles.loginFormItem}>
                            <label htmlFor="password">Password</label>
                            <input type="password" id='password' value={password} onChange={(e) => setPassword(e.target.value)} disabled={loading} />
                        </div>
                    </div>
                    <button onClick={handleLogin} disabled={loading}>login</button>
                </form>
            </div>
        </div>
    )
}

export default Login

We read the `errorMessage` and `loading` states from the `useAuthState` hook, then we display the error message on failed login attempt and we disable the form when the login request is being made.

Ideally, you will want to create a separate context object for your loading and error states but I kept them together because this is supposed to be a trivial example.

Implement Logout in Dashboard

Here we will try to implement the logout functionality in the dashboard and display the user’s name on the dashboard. Similar to the `loginUser` async action, we have a `logout` action that is used to logout a user from the current session and it takes a dispatch method as an argument.

Also, we can show the email of the current user by just reading the `email` from context using the `useAuthState` hook

Our `Dashboard` component should look something like this now:

// Pages/Dashboard/index.js

import React from 'react'
import { useAuthDispatch, logout, useAuthState } from '../../Context'
import styles from './dashboard.module.css'

function Dashboard(props) {
    const dispatch = useAuthDispatch() // read dispatch method from context
    const userDetails = useAuthState() //read user details from context


    const handleLogout = () => {
        logout(dispatch) //call the logout action
        
        props.history.push('/login') //navigate to logout page on logout
    }
    return (
        <div style={{ padding: 10 }}>
            <div style={styles.dashboardPage} >
                <h1>
                    Dashboard
                </h1>
                <button className={styles.logoutBtn} onClick={handleLogout}>Logout</button>
            </div>
            <p>Welcome {userDetails.user.email}</p>
        </div>
    )
}

export default Dashboard

We are almost done with this simple login application but there is a problem, despite the facts that we have authentication now, users can still access routes like the dashboard route even when they are not authenticated.

Protect authenticated routes

To fix this we need to define private routes(routes that can only be accessed by authenticated users ) and create a higher-order component Route component that renders the appropriate component if the users is authenticated, if not they are redirected to the Login page

First, in our routes config, we want to add a property `isPrivate` that specifies if a route is private or not. The two private routes in our application are the Dashboard page and the 404 page.

// Config/routes.js

[…]
const routes = [
  {
    path: '/login',
    component: Login,
    isPrivate: false,
  },
  {
    path: '/dashboard',
    component: Dashboard,
    isPrivate: true,
  },
  {
    path: '/*',
    component: NotFound,
    isPrivate: true,
  },
];


export default routes;

Next, we create a higher-order component that will help for protected routes. In our Components folder, lets create a file called `AppRoutes.js`.
Then we can add the following in the AppRoute component

// Components/AppRoute.js

import React from "react";
import { Redirect, Route } from "react-router-dom";

import { useAuthState } from '../../Context'

const AppRoutes = ({ component: Component, path, isPrivate, ...rest }) => {

    const userDetails = useAuthState()
    return (
        <Route
            path={path}
            render={props =>
                isPrivate && !Boolean(userDetails.token) ? (
                    <Redirect
                        to={{ pathname: "/login" }}
                    />
                ) : (
                        <Component {...props} />
                    )
            }
            {...rest}
        />
    )
}

export default AppRoutes

What this component does is instead of rendering the component by passing a component attribute to react router’s `Route` component , we use the render prop instead, we check if it is a private route per the config and if there is a `token` present in the AuthStateContext to determine what to render to the user.

Now we can replace the react-router’s Route component we used to set up routing in the `App.js` and replace it with the `AppRoute` higher-order component we just created.

// //App.js

[...]
import AppRoute from './Components/AppRoute';

function App() {
  return (
    <AuthProvider>
      <Router>
        <Switch>
          {routes.map((route) => (
            <AppRoute
              key={route.path}
              path={route.path}
              component={route.component}
              isPrivate={route.isPrivate}
            />
          ))}
        </Switch>
      </Router>
    </AuthProvider>
  );
}

[...]

This will ensure that only authenticated users have access to the private route.

Testing out the application

We are now done!! Now we can go ahead and test the app. In your terminal run:

yarn start or npm start

The application should run and you should be able to test the login authentication.

Code

You can find the code for the completed version of this tutorial on Github or You can play with it live on Codesandbox

Conclusion

I think we have learned how to combine useReducer and `useContext` to handle login authentication. What I would like us to focus on is how we created our own mini-state management library using React context and useReducer because this can be applied anywhere you need to manage/pass state in a React application.

References

Bootstrap your next Preact application with Bun

In recent times, runtimes like Node.js and Deno have increased in popularity due to their role in revolutionizing the JavaScript ecosystem. However, there is also increased consideration for speed and native features that the runtimes provide, as they aren’t as fast and also do not provide native features for certain actions like bundling, transpiling, and package management.

How to Upload Images and Videos to Cloudinary in Your Node.js Application: Step-by-Step Tutorial

In this detailed tutorial, I will demonstrate how to upload images and videos to Cloudinary within a Node.js application. I’ll personally guide you through configuring your Cloudinary account and integrating the necessary packages into your application. Subsequently, we’ll delve into the implementation details, and I’ll provide code snippets to help you navigate the uploading process.

16 Replies to “React User Login Authentication using useContext and useReducer.”

  1. Thanks for this fantastic work, it has helped me get most of the way towards getting private routes working in a project I’ve inherited. My only problem is how to render multiple components for each route.

    The way this project has been set up, it uses multiple components in each route (ie ).

    I can get this working fine for one component, but I’m not having any joy with multiple components. I’ve tried arrays of components and mapping over them, but with no success, so I’m at a bit of a loss as to how to do this.

    Any pointers?

    1. Adaware Oghenero 4 years ago

      Hi peter

      I dont really understand why you would want to render multiple components for each route. Can you share a code snippet?

    2. Hi Adaware,

      The routing as it was set up was rendering multiple components under each route. I’ve changed it now to be a single component, that then renders the children (which is as it should have been) and all is now good.

      Thanks for the question.

  2. Thanks for this tutorial through Amplify with React Auth.
    It will be really helpful for me, thanks again !

  3. i have an error . how to fix this ?

    Error: Objects are not valid as a React child (found: object with keys {errorMessage}). If you meant to render a collection of children, use an array instead.
    in div (at Login/index.js:29)
    in Login (created by Context.Consumer)
    in Route (at App.js:27)
    in Switch (at App.js:16)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:15)
    in AuthProvider (at App.js:14)
    in App (at src/index.js:9)
    in StrictMode (at src/index.js:8)

    1. It looks like you were trying to render an object and not a component. The errorMessage is an object, to render it you must access the keys.
      i.e. return(errorMessage.error) rather than return(errorMessage)

  4. How much harder would it be to add role based authentication to this? So admins have access to all pages and moderators only have access to a subset, etc.

    1. Add an additional property for role type and handle the UI accordingly. Apply the role based ACL server side, the UI only shows what features are available based on the role type, if you don’t handle the role based ACL server side then anyone with access to your API can make any changes

  5. Anderson 4 years ago

    Beautiful article. I found it very useful

  6. Excellent article though how do you validate the token on each protected page? i.e. say token is valid for 30 minutes, how do you ensure that user is still not accessing private pages with an expired token? In my case I am using @azure/msal-browser npm package to authenticate users using my org’s AD. I need to ensure that the token is only valid for 30 minutes of idle session and remove the token and force user to re-login .. how do I achieve this?

    1. You should not rely on the client to apply the TTL for authentication, this should be handled server side, the server should check that the token is valid before returning the request. Assign a TTL to the tokens server side.

      1. @Ed so are you saying that the token acquired from Azure after successful login should be stored in the backend database with TTL and also in the local storage and for every request to protected page, first check should be made against the DB for the supplied token to ensure that it’s still valid else redirect it to the login page?

  7. Error: Objects are not valid as a React child (found: TypeError: Cannot read properties of undefined (reading ‘0’)). If you meant to render a collection of children, use an array instead. in p (at Login/index.js:29) in div (at Login/index.js:27) in div (at Login/index.js:26) in Login (at AppRoute.js:15) in Route (at AppRoute.js:9) in AppRoutes (at App.js:13) in Switch (at App.js:11) in Router (created by BrowserRouter) in BrowserRouter (at App.js:10) in AuthProvider (at App.js:9) in App (at src/index.js:9) in StrictMode (at src/index.js:8)

  8. I try update it to react router v6 but I recive so much errors =\

  9. Thanks for this excellent article. I have a question on routing. In my app, I want user to be routed to a secured page if user logs in successfully. I tried to use Navigate() (aka usNavigate) post emitting AuthService(dispatch) though no luck. Is there any way this can be achieved?

  10. This is one of the most in depth, detailed yet ready to understand posts I have found on doing Auth in react. I’m guessing a few bits like react router might be a bit outdated now, but I really can’t thank you enough for making this so straight forward. Absolutely fantastic

Leave a Reply