How to create React App With Auth0?
Create React App
Install the create-react-app
command-line tool and use it to create a new React app :
npm install -g create-react-app
create-react-app my-app
Considering that your react application was created in my-app
directory, get into that directory :
cd my-app
To start the new application, run :
npm start
By default you should be able to access a brand new react app at http://localhost:3000
and see the app initial page :
Create Auth0 account
Sign up for an Auth0 account and create a new application: https://auth0.com/signup
This will give you a domain, client ID, and client secret that you can use to authenticate your users.
Add Auth0 Rect SDK
Install the Auth0 Rect SDK with npm:
npm install @auth0/auth0-react
Add Auth0Provider
Add Auth0Provider component in your src/index.js
, wrapping the App
component and configure it with your Auth0 application domain
and clientId
, set redirectUri
to your local app url:
import { Auth0Provider } from '@auth0/auth0-react';
<Auth0Provider
domain="your-auth0-domain.com"
clientId="your-client-id"
redirectUri="http://localhost:3000"
>
<App />
</Auth0Provider>
Create and add Login button
Create a LoginButton.js
file in src
directory and add the code that uses loginWithRedirect
function to handle login flow on click event.
import { useAuth0 } from '@auth0/auth0-react';
const LoginButton = () => {
const { loginWithRedirect } = useAuth0();
return (
<button onClick={() => loginWithRedirect()} className="App-button">
Log In
</button>
);
};
export default LoginButton;
To moke the button bit more accessible on different devices, let's add a simple styling to make it bigger.
Add this style in your App.css
file :
.App-button {
font-size: 1.4rem;
font-weight: bold;
padding: 10px;
}
This is how your React App should look like once the Login button is added :
Once you hit the Login button you should be redirected to your app login page :
Create and add User Profile component
user information
import { useAuth0 } from '@auth0/auth0-react';
const Profile = () => {
const { user, isAuthenticated, isLoading } = useAuth0();
if (isLoading) {
return <div><p>Loading ...</p></div>;
}
return (
isAuthenticated && (
<div>
<img src={user.picture} alt={user.name} className="App-profile-picture" />
<p>{user.name}</p>
</div>
)
);
};
export default Profile;
.App-profile-picture {
height: 120px;
weight: 120px;
}
Create and add Logout button
Create a LogoutButton.js
file in src
directory and add the code that uses logout
function to handle logout flow on click event.
import { useAuth0 } from '@auth0/auth0-react';
const LogoutButton = () => {
const { logout } = useAuth0();
return (
<button onClick={() => logout({ returnTo: window.location.origin })} className="App-button">
Log Out
</button>
);
};
export default LogoutButton;