Open In App

How to Build a React App with User Authentication?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To implement user authentication in a React app, you can use Auth0, a popular authentication service that simplifies the process of handling login, logout, and user profile management. With Auth0, you can avoid managing authentication from scratch, which saves time and ensures security. In this article, we’ll walk through setting up a React app with user authentication using Auth0.

Prerequisites

Approach To Create User Authentication

  • Install Auth0 library and configure Auth0Provider in index.js.
  • Create LoginButton.js with useAuth0 hook to redirect login, and display the login button after checking the authentication status. Implement LogoutButton.js logout functionality and profile display.
  • Create Profile.js for displaying user details like name, email, etc., and style it with custom CSS.
  • In App.js, integrate all the components (login, logout buttons, and navbar), and import CSS (App.css, Bootstrap).

Steps To Build React App with User Authentication

Step 1: Create a React JS application using the following command

npx create-react-app react-authenticator

Step 2: Now move to the react-authenticator folder using the ‘cd’ command

cd react-authenticator

Step 3: Install the following dependencies

npm install @auth0/auth0-react bootstrap

Project Structure

Folder Structure

Dependencies

"dependencies": {
"@auth0/auth0-react": "^2.2.4",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: Create the following files and add codes in these files.

CSS
/*App.css*/

* {
    margin: 0;
    padding: 0;
}

.appName {
    color: #fff;
}

.logoutBtn {
    margin: auto;
}

.userInfo {
    background-color: #d9d9d9;
    box-shadow: 5px 0px 0px grey;
    width: 35%;
    padding: 20px;
    border-radius: 6px;
    font-weight: 600;
}
JavaScript
//index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Auth0Provider } from '@auth0/auth0-react';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Auth0Provider
        domain='dev-mf6lqfng.us.auth0.com'
        clientId='5c1HQIOd6HlVEi2CLLfTPO7HCImJ9qZr'
        redirectUri={window.location.origin}>
        <App />
    </Auth0Provider>
);
JavaScript
//LoginButton.js

import React from "react";
import { useAuth0 } from "@auth0/auth0-react";

const LoginButton = () => {
    const { loginWithRedirect, isAuthenticated } = useAuth0();
    if (!isAuthenticated) {
        return <button className="btn btn-primary 
            mx-5 my-5 px-4"
            onClick={() => loginWithRedirect()}>
            Log In</button>;
    }
};

export default LoginButton;
JavaScript
//Profile.js

import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';

const Profile = () => {
    const { user } = useAuth0();

    return (
        <>
            <div className="container">
                <p className="userInfo" id="userInfo1">
                    Name: {user.name}</p>
                <p className="userInfo" id="userInfo2">
                    Given Name: {user.given_name}</p>
                <p className="userInfo" id="userInfo3">
                    Family Name: {user.family_name}</p>
                <p className="userInfo" id="userInfo4">
                    Email: {user.email}</p>
                <p className="userInfo" id="userInfo5">
                    Sub: {user.sub}</p>
            </div>
        </>
    )
}

export default Profile
JavaScript
//LogoutButton.js

import React from "react";
import { useAuth0 } from "@auth0/auth0-react";
import Profile from "./Profile";

const LogoutButton = () => {
    const { logout, isAuthenticated } = useAuth0();

    if (isAuthenticated) {
        return (
            <>
                <button className="btn btn-primary 
                    mx-5 my-5 px-4 logoutBtn"
                    onClick={() => logout({ returnTo: window.location.origin })}>
                    Log Out
                </button>
                <br />
                <Profile />
            </>
        );
    }
};

export default LogoutButton;
JavaScript
//App.js

import './App.css';
import LoginButton from './components/LoginButton';
import LogoutButton from './components/LogoutButton';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
    return (
        <>
            <nav className="navbar bg-dark">
                <div className="container-fluid">
                    <span className="appName">
                        React User Authentication</span>
                </div>
            </nav>
            <LoginButton />
            <LogoutButton />
        </>
    );
}

export default App;


To start the application run the following command.

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

When we click on the login button, we are redirected to the auth0 login portal. On successful login, we can see the user information displayed. And when we click on the Logout button, we are redirected to the homepage.



Similar Reads