Securing Routes with Firebase User Authentication in ReactJS

Currently, I am encountering an issue with the auth.onAuthStateChanged function in my Firebase user authentication service integrated with ReactJS. The function fires after the component has already been rendered, causing problems with redirecting users to specific pages when using protected routes and passing props. For example, upon successful authentication on the domain.com/signin page, the user should be redirected to domain.com/customers. However, the current behavior only directs them to domain.com, and upon logout, they should be redirected back to domain.com/signin.

Here is the code snippet: https://codesandbox.io/s/serverless-leaf-pgtf1?fontsize=14

In an attempt to resolve this issue, I tried implementing the following code:

auth.onAuthStateChanged(user => {
    if (user && user.emailVerified) {
       this.setState({
         authenticated: true
      });
    } else {
       this.setState({
         authenticated: false
       });
    }
});

Answer №1

Your high order component, UnauthorizedRoute, is designed to redirect users to the home page at domain.com/ when they are not authenticated.

const UnauthorizedRoute = ({
  component: Component,
  authenticated,
  ...rest
}) => {
  return (
    <Route
      {...rest}
      render={props =>
        authenticated === false ? (
          <Component {...props} {...rest} />
        ) : (
          <Redirect to="/" />
        )
      }
    />
  );
};

To customize the redirection path for authenticated users, you can add an additional prop called afterAuthPath to the UnauthorizedRoute component. If this prop is provided, the component will redirect users to the specified path after authentication. Here's how you can implement it:

const UnauthorizedRoute = ({
  component: Component,
  authenticated,
  afterAuthPath,
  ...rest
}) => {
  const redirectPath = afterAuthPath || "/";
  return (
    <Route
      {...rest}
      render={props =>
        authenticated === false ? (
          <Component {...props} {...rest} />
        ) : (
          <Redirect to={redirectPath} />
        )
      }
    />
  );
};

You can apply this behavior to routes like sign in by specifying the desired redirection path after authentication:

<UnauthorizedRoute
  authenticated={props.authenticated}
  path="/signin"
  afterAuthPath="/customers"
  component={SignInCustomer}
/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Utilizing the Image onLoad event in isomorphic/universal React: Activating event registration once the image has been

When a page is rendered isomorphically, the image can be downloaded before the main script.js file. This means that the image may already be loaded before the react register's the onLoad event, resulting in the event never being triggered. script.js ...

Enhancing ReactJS App with PHP backend: Tips for implementing hot reload on your local machine

Currently, I am in the process of developing a ReactJS-App that is connected to a PHP backend. To streamline my workflow, I have MAMP set up on my local machine with a virtual host pointing to the root of my project, and I utilize webpack for bundling my R ...

Deleting entries from a selection of items in a list generated from an auto-fill textbox

I have successfully implemented an auto-complete Textbox along with a styled div underneath it. When the client selects an item from the Textbox, it appears in the div after applying CSS styling. Now, I am looking to create an event where clicking on the s ...

A guide to injecting HTML banner code with pure Vanilla Javascript

Looking for a solution to incorporate banner code dynamically into an existing block of HTML on a static page without altering the original code? <div class="wrapper"><img class="lazyload" src="/img/foo01.jpg"></div> <div class="wrapp ...

HTML: Ensure that a user fills out a minimum of one text box before submission

<tr><td> First Name: </td><td><input type="text" name="FirstName" required></td> </tr> <tr><td> Last Name: </td><td><input type="text" name="LastName" required> </td></tr> ...

How can I modify a PHP file to be compatible with Ajax functionality?

I'm currently exploring the world of CodeIgniter and facing some challenges with AJAX. This is my first time working with it, so I have quite a few questions popping up. What I'm looking for: I want to be able to post data using AJAX and retrie ...

Incorrectly loading static images in React SSR

I am currently working on a React SSR app and my folder structure looks like this: My static express middleware successfully handles static files and images in the tag on the client side: However, when I attempt to renderToPipeableStream for server-side ...

How can I ensure that all row checkboxes are automatically marked as checked upon loading the Material Table in ReactJS?

I'm currently working on a project using React Material Table and I need to have the selection option pre-checked by default. Is there a way to accomplish this? function BasicSelection() { return ( <MaterialTable title="Basic Selec ...

Organize items within an array based on dual properties rather than a single one

Here is an array of objects that I would like to group based on certain keys (JSON format): [ { "name": "john", "lastName": "doe", "gender": "male" }, { "name": &qu ...

Angular directive ng-template serves as a component type

In the code snippet below, <!DOCTYPE html> <html> <head> ..... </head> <body ng-app="app"> <script type="text/ng-template" id="my-info-msg.html"> <s ...

Unable to store user data in the MongoDB Database

I'm currently facing an issue while trying to store user information in my MongoDB database. Everything was working fine until I implemented hashing on the passwords using bcrypt. After implementing password hashing, I am encountering difficulties in ...

One click wonder: Easily print any webpage content with just the click of a button!

For example, upon clicking the button on my webpage, I want the content of another page to be sent directly to a printer. The objective is to bypass the print dialog box and print preview that typically appears when using the browser's default printin ...

The issue of pseudo elements not functioning properly in Material-UI makeStyles with React.js has been a frustrating

The use of pseudo elements in Material-UI makeStyles is not functioning correctly. innerBox: { borderRadius: "10px", background: "#fff", boxShadow: "0px 1px 3px 0px rgba(0, 0, 0, 0.36)", maxHeight: "50px", "& ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

Implementing the session injection into a request body within an asynchronous function in Node.js

I've been trying to inject a session value into the request in order to use it in various parts of my app. What I'm currently attempting is to call a function by providing an ID to search for a user in the database and retrieve the name of that s ...

Adding Currency Symbol to Tooltip Data in Material-UI Sparklinechart

Below is a SparklineChart example using MUI library: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-charts/SparkLineCha ...

Transform a numerical variable into a string data type

I am faced with a situation where I have a variable named val which is currently set to the number 5. Now, my goal is to update the value of val so that it becomes a string containing the character "5". Could someone guide me on how to achieve this? ...

Clicking on the button will allow you to sort the items in

I need assistance with sorting a table: when I click on a header, the order changes to ascending but does not toggle back to descending. Despite having a boolean value that should switch between true and false, it keeps returning the initial value. Can s ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

Implementing a JavaScript file and ensuring W3C compliance

I recently purchased a template that included a javascript file in the main page with the following code: <script src="thefile.js?v=v1.9.6&sv=v0.0.1"></script> Upon inspection, I noticed there are two arguments at the end of the file ...