Implementing Auth0 User Authentication in a Vite-React-App

Alana Barrett-Frew
Version 1
Published in
5 min readJan 3, 2024

As a junior developer I am often navigating the complexities of user authentication. After a lot of research and trial and error, I’ve successfully implemented a concise solution using Auth0 in a Vite-React-App. This tutorial offers a straightforward, step-by-step approach to seamlessly integrate Auth0, a trusted authentication platform, into your React application.

Once complete it should look something like this (note my own logo and text will not appear in your app):

Login Page

Login Page

Authenticated Landing Page. As you can see this page has not been developed yet. This is the fun bit where you get to be creative and design your own App.

Landing page

Prerequisites

  • Node.js and npm installed on your machine
  • Basic understanding of React and JavaScript

Step 1: Create a New Vite React App

First, let’s create a new Vite React JS application using the following commands:

npm create vite@latest app-name -- --template react
cd app-name
npm install

Step 2: Install Dependencies

Install the necessary dependencies required for authentication:

npm install @auth0/auth0-react bootstrap react-dom react-router-dom

Step 3: Project Structure Setup

Let’s set up the initial project structure:

  • Create a components folder and pages folder within the src folder.
  • Inside the components folder, create files: LoginButton.jsx, LogoutButton.jsx, and Navbar.jsx.
  • Inside the pages folder, create a file: Home.jsx.

It should look similar to this:

Folder Structure

Step 4: Implementation

Now, let’s add the code to the respective files:

main.jsx

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=''
clientId=''
authorizationParams={{ redirect_uri: window.location.origin }}>
<App />
</Auth0Provider>
);

We will fill the empty domain and clientId fields from the AuthO site later in this guide.

App.jsx

import "./App.css";
import LoginButton from "./components/LoginButton";
import "bootstrap/dist/css/bootstrap.min.css";
import Home from "./pages/Home";
import { useAuth0 } from "@auth0/auth0-react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";

const App = () => {
const { isAuthenticated } = useAuth0();

return (
<Router>
<div>
<Navbar />
{isAuthenticated ? (
<Routes>
<Route path="/" element={<Home />} />
</Routes>
) : (
<LoginButton />
)}
</div>
</Router>
);
};

export default App;

LoginButton.jsx

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

const LoginButton = () => {
const { loginWithRedirect, isAuthenticated } = useAuth0();
if (!isAuthenticated) {
return (
<div className="center-button">
<button className="btn btn-primary loginBtn"
onClick={() => loginWithRedirect()}>
Log In</button>
</div>
);
}
};

export default LoginButton;

LogoutButton.jsx

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

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

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

export default LogoutButton;

Navbar.jsx

import { useAuth0 } from "@auth0/auth0-react";
import LogoutButton from “./LogoutButton";

function Navbar() {
const { isAuthenticated } = useAuth0();

return (
<nav className="navbar navbar-expand-lg bg-body-tertiary">
<div className="container-fluid header">
<a className="navbar-brand" href=“#">
Authentication App
</a>
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
{isAuthenticated && ( // Render the "Home" link if authenticated
<li className="nav-item">
<a className="nav-link active" aria-current="page" href="#">
Home
</a>
</li>
)}
</ul>
{isAuthenticated && <LogoutButton />}
</div>
</div>
</nav>
);
}

export default Navbar;

Step 5: Add CSS styling (you can edit this to your own requirements). Please note I have used a font family from Google Fonts — https://fonts.google.com/ . You will need to add relevant styling to the html file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Rubik+Doodle+Shadow&display=swap"
rel="stylesheet"
/>
<title>App Name</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
body {
background-color: #264653 !important;
}

* {
margin: 0;
padding: 0;
}

/* Header */

nav {
padding: 0 !important;
}
.header {
background-color: #2a9d8f !important;
}

.navbar-brand,
.nav-link {
color: white !important;
font-family: "Rubik Doodle Shadow";
}

.navbar-brand {
font-size: 3em !important;
color: white !important;
}

/* Buttons */

.logoutBtn {
margin: auto;
}

.center-button {
display: flex;
justify-content: center;
align-items: center;
padding: 100px;
}

.btn {
background-color: #e76f51 !important;
border: #e76f51 !important;
font-family: "Rubik Doodle Shadow" !important;
font-size: 2em !important;
}

Step 6: Auth0 Configuration

  • Sign up for an account on https://auth0.com/
  • For a UK account select other and tick the advanced box. This will allow you to select the country
  • Create a new application specifying the details (e.g., Name, Single Page Application, Technology — React).
  • On the side bar, select Applications and then select your application. Obtain your Auth0 domain and clientID from the created application. Add these to the empty ‘ ’ in the main.jsx file.
  • Set allowed callback URLs and logout URLs in the Auth0 Application Settings. Paste this inside text box: http://localhost:5173/ . This will allow you to navigate to the desired pages.
  • SAVE your changes

Step 6: Test Your Application

Run your application and ensure that authentication works as expected:

npm run dev

Note, to stop the application running type the following in the terminal

ctrl + c

Conclusion

Congratulations! You’ve successfully integrated user authentication into your React application using Auth0. From here, you can expand and enhance your application with additional features.

Useful Links to Documentation:

Auth0: Single page app -> react -> add login to your react app

https://auth0.com/docs/quickstart/spa/react/interactive

Getting started with Vite React App

About the Author:
Alana Barrett-Frew is an Associate Consultant at Version 1.

--

--

Alana Barrett-Frew
Version 1

@teacherturnsturtle81 From a 20 year teaching career to a career in Tech "If you always do what you've always done, you will always get what you've always got!"