DEV Community

Cover image for Add authentication to your React apps in minutes with Auth0
Pratik Bhagat
Pratik Bhagat

Posted on • Updated on

Add authentication to your React apps in minutes with Auth0

Intro

This blog will teach you how to add authentication to your React applications with Auth0.

Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications.

Setting up the application

Create a new react application with the command

npx create-react-app app-name
Enter fullscreen mode Exit fullscreen mode

Head to the Auth0 website Sign up for a free Auth0 account and create a new Single Page Web Application and select React as the technology you will use.

Next, go to the settings of the application and under Application URIs in Allowed callback URLs, Allowed logout URLs and Allowed Web origins add https://localhost:3000

Add Url

We do this because Auth0 redirects us to their website which handles all of the authentications and redirects us back to the application.

During development, it will be https://localhost:3000 and in production, you should change it to your application URL.

React app

Create a .env in the root of the directory and add two variables

REACT_APP_AUTH0_DOMAIN = {domain}

REACT_APP_AUTH0_CLIENT_ID = {Client_ID} 
Enter fullscreen mode Exit fullscreen mode

Copy the Domain and Client ID from the settings of the application in Auth0.

Install Auth0

Next, we have to install the Auth0 package in our application

To do that run the following command in the terminal:

npm i @auth0/auth0-react

Enter fullscreen mode Exit fullscreen mode

Index.js

Open Index.js file in React application.

The first thing we need is to import Auth0Provider from the Auth0 package we installed.

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

Enter fullscreen mode Exit fullscreen mode

Auth0Provider uses React's Context API so we will wrap our App component with Auth0Provider to
access all of its properties within our app

Auth0Provider takes a couple of parameters i.e the domain and client id so we will import the environmental variables we created before.

After all the changes your Index.js file should look something like this

// index.js

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Auth0Provider } from "@auth0/auth0-react";
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID;

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <Auth0Provider
    domain={domain}
    clientId={clientId}
    redirectUri={window.location.origin}
  >
    <App />
  </Auth0Provider>
);


Enter fullscreen mode Exit fullscreen mode

As you can see Auth0Provider takes in another parameter i.e the redirectUri that takes our current location so after logging in the user will be redirected to the current Url in the browser meaning our App.

Components

Next, create a components folder under the src directory in our react app. In this app, we will create two components one for the login button and the other for the logout button.

Login Button

Create a LoginButton.js component under the components directory.

Import useAuth0 hook that is provided by the Auth0 package we installed

We will use loginWithRedirect from the useAuth0 hook and we will return a login button with loginWithRedirect as the onClick event

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

export default function LoginButton() {
  const { loginWithRedirect } = useAuth0();
  return (
  <button onClick={() => loginWithRedirect()}>
  Log In
  </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

Import the LoginButton component in App.js

When you click this button it should redirect you to the Auth0 authentication form.

Login form

Logout Button

Create another component but this time for the logout button

This is similar to the login button the only difference is we will use logout method from the useAuth0 hook

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

export default function LogoutButton() {
  const { logout } = useAuth0();
  return (
    <button
      onClick={() => {
        logout();
      }}
    >
      Log Out
    </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

App.js

Import and display both Login and Logout buttons

Your App.js file should look like this

import "./App.css";
import LoginButton from "./components/LoginButton";
import LogoutButton from "./components/LogoutButton";


function App() {
  return (
    <>
      <LoginButton />
      <LogoutButton />
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Buttons

User

Now to let the user know that they are logged in will just display the user information.

To do that we will create another component User.js and display JSON user data

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

export default function User() {
  const { user } = useAuth0();
  return <div>{JSON.stringify(user, null, 2)}</div>;
}

Enter fullscreen mode Exit fullscreen mode

If the user is logged in it will display the JSON data.

Click on the login button and after logging in you should see the JSON data.

User Info

That's it for this blog. Drop a like if you found this useful :)

Feel free to connect with me https://bio.link/bhagatpratik07

Top comments (0)