reactjsfacebook-login

How can I secure a component in ReactJS?


I have created two React components - Login and Secure. Login hosts the FacebookLogin component from this package.

When the button is pressed, it submits the login attempt and I get a successful response from Facebook. Next, the app should navigate to the Secure page, which I do using the react-router-dom package.

However, I found that I can just navigate directly to the Secure component in the URL. How can I make it so that any attempt to navigate to a secure page is redirected to the Login page first?


Solution

  • According to that component's documentation, you can get the login status in code:

    FacebookLoginClient.login((res) => {
      // "res" contains information about the current user's logged-in status
    });
    

    So in any component that needs to know the status, simply reference the library:

    import { FacebookLoginClient } from '@greatsumini/react-facebook-login';
    

    And use that FacebookLoginClient.login to check the user's logged-in status. If the status doesn't meet the criteria you define, redirect the user. (For example, you can check this in a useEffect when the component first loads, or perhaps on every render if you're paranoid about it.)


    For more detail on rendering the target component, since useEffect occurs after the initial render, you can rely on additional state to check. For example, consider this structure:

    const [canRender, setCanRender] = useState(false);
    
    useEffect(() => {
      FacebookLoginClient.login((res) => {
        // check the status and call "setCanRender" accordingly
      });
    }, []);
    
    if (!canRender) return <>Checking authentication...</>;
    
    // your existing return for the component goes here
    

    The idea here is to default the component to a kind of "loading state" and only render the "secure" content after the authentication has been verified.