A Quick Beginner's Guide to Set Up Auth0 + React

A Quick Beginner's Guide to Set Up Auth0 + React

How to set up basic Auth0 authentication with React for beginners for Hashnode's Auth0 hackathon

Featured on Hashnode
Victoria Lo's photo
Victoria Lo

Published on Aug 20, 2021

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Hello everyone, Hashnode's Auth0 hackathon is still ongoing. For those who have not used Auth0 before and just getting started on their hackathon projects to implement Auth0, here is a super quick step-by-step guide to set up and integrate it to a React app.

Step 1: Sign Up For An Account

Go to auth0.com/signup to create a free Auth0 account. image.png

Follow the sign-up steps. You can continue with the default tenant domain name and region they set for you, or customize it yourself.

image.png

Tenant: represents the user domain that has access to the Auth0 application configurations, assets, connections, etc. The tenant domain name will be the URL used to access resources such as the Auth0 API.

Step 2: Create an Application

Now, you will be redirected to your Auth0 Dashboard. Let's start by clicking on 'Create Application', as shown in the image below.

image.png

An application can be a native app, SPA (Single Page App), web app or even CLIs. For this tutorial, let's select SPA since we're building a React app. Remember to give it a cool app name at the top.

image.png

Step 3: Configure Application Settings

You will then be redirected to your app page. Simply click on the 'Settings' tab. Note that this is where you will need to copy information such as the Domain and Client ID to enable authentication on your React app using Auth0.

settings.PNG

Scroll down to Application URIs. Add the URL that you want Auth0 to redirect after logging in under Allowed Callback URLs. Similarly, add the URL you want Auth0 to redirect after logging out under Allowed Logout URLs.

Finally, add the URL under Allowed Web Origins you want Auth0 to allow silent log-in between user sessions. This way, the user doesn't have to log in to the website every time the page is refreshed. For our example, all URLs will be http://localhost:3000.

image.png

Scroll all the way down and click 'Save Changes'. Now, we can start integrating Auth0 into a React app.

Step 4: Create new React app

In a new React app, install the Auth0 SDK with the command:

npm install @auth0/auth0-react

Then, create an .env file in the project's root folder. Paste the Domain and Client ID from Step 3 into the file like so:

REACT_APP_AUTH0_DOMAIN = your domain
REACT_APP_AUTH0_CLIENT_ID = your client id

In index.js, import the Auth0Provider from the SDK we installed and wrap it around the App component. Pass the domain and clientId as shown below.

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

ReactDOM.render(
  <Auth0Provider
    domain= {process.env.REACT_APP_AUTH0_DOMAIN}
    clientId= {process.env.REACT_APP_CLIENT_ID}
    redirectUri={window.location.origin}
  >
    <App />
  </Auth0Provider>,
  document.getElementById('root')
)

Step 5: Create components

We can now create 3 components. Under src, create a new folder called components. This is where we will store our LoginButton.js, LogoutButton.js and User.js components.

Here's how the project directory should look like at this point:

image.png

In LoginButton.js, we will create a Login button by doing the following:

  1. Import useAuth0 Hook from the Auth0 SDK
  2. Create a LoginButton that will redirect users to the Auth0 login page when clicked using loginWithRedirect
  3. Export the LoginButton
//1.
import React from "react";
import { useAuth0 } from "@auth0/auth0-react"; 

const LoginButton = () => {
  //2.
  const { loginWithRedirect } = useAuth0();

  return <button onClick={() => loginWithRedirect()}>Log In</button>;
};

//3.
export default LoginButton;

Next, in our LogoutButton.js, we will have a Logout button. It is similar to its Login counterpart, except that instead of calling loginWithRedirect onClick, it will call logout. This will redirect users to our http://localhost:3000 upon logging out, as we have configured earlier in Step 3.

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

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

  return (
    <button onClick={() => logout({ returnTo: window.location.origin })}>
      Log Out
    </button>
  );
};

export default LogoutButton;

Finally, our third component we have created will be the User component. It will display the logged-in user's name, picture and email.

Using the same useAuth0 hook, we can get the user's details from the user object. At the same time, we can verify whether a user is authenticated via the isAuthenticated boolean. If the user is indeed authenticated, then we can show his/her details.

Here's what our User component should look like:

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

export default function User() {
    const { user, isAuthenticated } = useAuth0();

  return (
    isAuthenticated && (
      <div>
        <img src={user.picture} alt={user.name} />
        <h2>{user.name}</h2>
        <p>{user.email}</p>
      </div>
    )
  );
}

Step 6: Putting it Altogether

Now that we have our components, let's import them at the top of our App.js file, along with the useAuth0 hook.

import { useAuth0 } from '@auth0/auth0-react';
import LoginButton from './components/LoginButton';
import LogoutButton from './components/LogoutButton';
import User from './components/User';

In our App.js, we want to do 2 things:

  1. Show LoginButton if isAuthenticated is false
  2. Show LogoutButton and User if isAuthenticated is true

In this tutorial, we can use simple conditional statements to render the components according to the value of isAuthenticated, as seen in the code below.

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

  return (
    <div className="App">
      {!isAuthenticated ? (
        <div>
          <p style={{ fontSize: "1.5rem" }}>Please Login.</p>
           <LoginButton />
        </div>
      ) :
        <div>
            <LogoutButton />
            <User />
        </div>}
    </div>
  );
}

export default App;

Result

With that, we're done! Our React App has Auth0 authentication all set up! I took the liberty to quickly add some styling to the components and present the logged-in user with a quiz rather than only displaying their details.

Here's a final result:

quiz.gif

Note: This is just an example, you can make the app do anything you want after the user logs in.

And there you go!

I hope this guide will encourage you to take on this hackathon as a challenge. Feel free to use this GitHub repo as a start to set up a React + Auth0 project quickly.

If you have never participated in a hackathon, now's the time to try. Hashnode's hackathons are truly great for developers at any level. You can engage with the community and exchange ideas or questions in their Discord server here. Whether you win the hackathon or not, there's always something more valuable that you gain from building a hackathon project.

For those who are currently building their awesome projects for the hackathon, I can't wait to read and see them. Feel free to link your articles/project below in the comments, so I can check them out. Thanks for reading. Cheers!


References

Read More

Did you find this article valuable?

Support Victoria Lo by becoming a sponsor. Any amount is appreciated!

See recent sponsors |Β Learn more about Hashnode Sponsors
Β 
Share this