Skip to main content

Command Palette

Search for a command to run...

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

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

I'm a solutions engineer lead, GitHub Star, Director of WomenDevsSG, and co founder of ragTech. I work at the intersection of tech, systems, and leadership, and this blog is where I share my journey through all three. Expect honest reflections, real experiences, and thoughts that are still forming rather than polished career advice.

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 https://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

  • https://auth0.com/docs/quickstart/spa/react/01-login
  • https://auth0.github.io/auth0-react/interfaces/auth0_context.redirectloginoptions.html#redirecturi

Read More

N
nameless3y ago

Thanks.

And also thanks for the reply. So by reading your code and the description. Can I conclude that we can outsource the authentication part to the auth0 easily?

V

Yes that's what auth0 platform does

N
nameless3y ago

Victoria Lo That's so cool. Thanks for the explanation. Now I see what auth0 is about. 😁

2
N
nameless3y ago

Very detailed tutorial. I just finished my full-stack course. And now I can finally understand what is this post talking about. Haha.

I have a brief idea how authentication works now. And experienced some other authentication methods too. But do not know what auth0 is about. All I know it is a kind of oauth.

May I know what is auth0 in brief description and What are the differences between it and google-oauth / facebook-oauth?

V

Hi nameless, thanks for the comment :) Congrats on completing your full-stack course.

To answer your question, OAuth 2.0 is a protocol that allows a user to grant limited access to their resources on one site, to another site, without having to expose their credentials. You know like those "Sign in with Google/Facebook/Apple/GitHub" stuff.

On the other hand, auth0 - which is what this tutorial is about, is the platform that allows developers to implement the OAuth2 protocol more conveninently.

So Google OAuth is basically allowing users to Sign Up with Google. And Facebook OAuth allows users to Sign Up with Facebook.

And auth0 is that platform can provide this implementation more easily for you. Hope that answers it :)

1
J

awesome was gonna start a project with auth0 this helped a lot.

1
H

Very Useful! Thanks for this article!!

1
H

This is awesome thank you!

1
V

Thanks Hunter, I'm glad you enjoyed it 😊

Y

Nice step-by-step tutorial Victoria Lo

1
V

Happy to hear that from you, Yogesh :)

I

Great article, as usual, Thanks for sharing Victoria Lo

1
V

Thanks a lot Idris :)

Random Projects to Build

Part 13 of 32

This series features step-by-step tutorials on how to build some quick and simple apps for beginners to practice their skills. From bulletin boards to messaging apps, let's build anything!

Up next

Curate Top Programming Blogs with React and HarperDB

Let's build a simple React app with HarperDB! A step-by-step tutorial for beginners!