Join us to see Frontegg in action live on April 29 and get a free gift 🎁 Save Your Spot
Blog

Add Authentication with Frontegg’s React SDK

This is a quick start guide, with a sample app, on integrating authentication into a client-side React app using Frontegg’s React SDK.

Is this for you?

Prerequisites

Quickstart for Frontegg and React

This guide will walk you through setting up a minimal sample app to get you started exploring the Frontegg platform in a React app using Frontegg’s client-side React SDK.

The app is bootstrapped with Vite and their React template (with Typescript), but Frontegg’s React SDK can be used in any client-side React app.

Setup

Frontegg Application Configuration

From within the Frontegg admin dashboard, create an Application, and make sure to configure at least these:

  • Enter a name.
    • Tip. This name is used in a few different places, so try to aim for a descriptive name that’s easily understandable for anyone, even less technical admins. If you intend to allow self-service configuration, this name will also be visible to customers/users.
  • If you only intend to use this app for testing, go ahead and get creative with it (or not).
  • Type = Web
  • Frontend stack = React
  • App URL = http://localhost:5173
    • the url where you’re app is running
      • http://localhost:5173 is the default url in Vite development mode (a.k.a. when running npm run dev)
    • ℹ️ Your app config in the Frontegg admin dashboard should look something like this:

Optional

Description

  • Add any notes about this app

Auto-assigned app

  • Following the best practice of least privilege, the default setting is that apps need to be assigned to Users in order to login.
  • In other words, Users are restricted from authenticating and, therefore, potentially accessing apps they aren’t “assigned”.
  • However, to make it easier to manage, apps can be assigned to Users in different ways:
Assignment Scopes
  • User
    • assigning apps A and B to User 1 but only app A to User 2, then User 2 will be restricted from app B
  • Account
    • assigning apps A and B to Account X but only app A to Account Y, then all users in Account 2 will be restricted from app B.
  • Auto-assigned
    • Configuring this assigns this to Accounts and Users, i.e., no one is restricted from it
  • You can also mix and match as you see fit!

Don’t forget to add the redirect uri

Under Configurations > Authentication > Login Method in your Frontegg dashboard, add a url back to your app.

For example, when running in Vite dev mode (i.e., npm run dev):

http://localhost:5173/oauth/callback

*Modify the hostname and port as needed if you’ve changed from the defaults or are running in other modes.

CORS & Allowed Origins

If you don’t configure this, you may open your browser’s console to see a bunch of ‘CORS’ errors that say something like:

Cross-Origin Request Blocked:
The Same Origin Policy disallows reading the remote resource at
https://app-abc123.frontegg.com/frontegg/oauth/token.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Status code: 204.

The solution is to add your app’s origin as an ‘Allowed Origin’ which lets Frontegg know that it’s okay to share (potentially) sensitive information there.

How to Configure Allowed Origins in Frontegg

Under Configurations > Keys & domains > Domains tab > Allowed Origins section in your Frontegg dashboard, add your app’s origin (the scheme, domain, and port parts of the url: e.g., http://localhost:5173 or https://example.com).

Required Environment Variables

These are the three environment variables necessary for integrating Frontegg along with where to navigate in the admin portal to find their values:

  1. VITE_FRONTEGG_BASE_URL
    • “Keys & Domains” > “Domains” tab, in the “Frontegg Domain” section labeled as the “Domain Name”
  2. VITE_FRONTEGG_CLIENT_ID
    • “Keys & Domains” > “General” tab, in the “API Key” section labeled as the “Client ID”
  3. VITE_FRONTEGG_APP_ID
    • App ID’s are unique per application and can be found by opening a particular Application in the Frontegg Dashboard.
    • “Applications” > {name_of_app} > “Settings” tab labeled as the “ID” .env.Example contains the required Frontegg variables used in the app that you can use by simply swapping in your actual config values for the placeholder values.

To use the template:

  • Create a copy of the file (or copy and paste below into a new file) and name it ‘.env
  • Replace the placeholder values with your Frontegg details

The .env file Template

################################################################################
### FRONTEGG CONFIG ###
################################################################################
# ! The 'VITE_' prefix exposes values client-side. !
# This is necessary for Base URL, Client ID, and App ID for the Frontegg React SDK, but take care
# not to expose any secrets!
#
# The "Base URL" and "Client ID" values can be found in the Frontegg Dashboard
# under "Keys & Domains".
#
# "Keys & Domains" > "Domains" > "Domain Name"
# Under the "Domains" tab, in the "Frontegg Domain" section labeled as the "Domain Name"
VITE_FRONTEGG_BASE_URL='https://app-rndCharsHere.frontegg.com'
#
# "Keys & Domains" > "General" > "Client ID"
# Under "General" tab, in the "API Key" section labeled as the "Client ID"
VITE_FRONTEGG_CLIENT_ID='looks-like-a-rnd-uuid'
#
#
# App ID's are unique per application and can be found by opening a particular Application in the
# Frontegg Dashboard.
#
# "Applications" > {name_of_app} > "Settings" > "App ID"
# Under the "Settings" tab labeled as the "ID"
VITE_FRONTEGG_APP_ID='looks-like-a-rnd-uuid-too'
################################################################################
### FRONTEGG CONFIG ###
################################################################################

Caution

*The VITE_ prefix exposes environment variables client-side!

🤫 Be careful not to expose any secrets! This is what we want for the 3 variables above, but be careful when adding more! And, make sure you add it to your `.gitignore`, if using git for source control and a public repo, if you add any sort of secrets to avoid accidentally publishing.

Install

Install required packages with npm: *yarn v2+ may cause some strange and seemingly unrelated errors when trying to run the app. It’s currently being investigated. It’s suggested to use `npm` for now

npm install

Running the App

Start the dev server as you would with any Vite React app by running:

npm run dev

In your browser, navigate to http://localhost:5173* *or the url printed by Vite once running.

If everything goes smoothly 🤞

Vite + React + Frontegg

You should see the vite React template…plus a little more

When you open your running app in the browser, you should land on a page that looks like the gif at the top of this readme, i.e., the Vite React template PLUS some Frontegg parts like the logo and login button.

*If you need help creating a Frontegg Account with a User with the Application assigned, check out the next section for steps!

Clicking on the login button should bring you to your login page, customizable via the Login Box Builder in the admin portal.

After successfully logging in, you should be redirected back to the original page with the login button replaced with a logout button and the logged in user’s email displayed.

Trying it out

To test it out (a.k.a. to try logging in), you’ll need an Account with a User!

Create an ‘Account’

To create a new account from the dashboard:

  1. Under Management > Accounts in the dashboard, create a new Account.
  2. Open your newly created Account and click on the Applications tab.
  3. If you don’t see your Application here:
    1. Click on Assign applications to allow users in this Account to authenticate via your Application.
    2. Select the Application configuration which you’re using.

Create a user

To create a new user:

  1. Under Management > Users (or on a specific Account’s page under the Users tab), click the Create user button.
    1. Make sure your app is added to the list of Applications in the create user modal. It needs to be assigned to this Account first, though, otherwise it won’t be available to select.
    2. And, if you started from the Users page, make sure you add the Account you’re using to the list in the modal.
      1. Starting from the Users tab of a specific Account connects the user to that Account right away.
    3. Inviting by email provides an easy way to start testing. Once you’ve successfully created the user, you’ll receive a link to the corresponding email to activate the account.

Run the app and login

Run the app (e.g., npm run dev) and open the app in a browser where you should see a page with the three logos and some stuff below (gif shown at the top).

  • Clicking the login button should redirect you to your Frontegg login page.
  • After successfully authenticating, you should be brought back to the app (localhost:5173 in dev mode),
    • With a small difference indicating you’ve logged in!
      • The Login button should be replaced with a Logout button and the email of the user you just authenticated with.

What to do in case…

First debug steps

There are a lot of different values that are usually mostly random strings used in a lot of different places, so it’s easy to accidentally use the wrong value for several reasons.

Double check the following are match between your code and what’s in the Frontegg dashboard:

  • Environment Variables
  • App URL
  • redirect_uri (more below)

redirect_uri not found

Hit the dreaded redirect_uri not found error? 

Don’t worry, everyone using OAuth 2/OIDC hits at some point. I can’t seem to get enough of it. But, it’s an important part of how the security of  OAuth 2, and therefore OIDC (OIDC is built on top of OAuth 2), works

First, check that everything looks as expected from the step above in the Configuring Frontegg section: *Don’t forget to add your redirect_uri

User is not associated with the requested application

TLDR: Assign your Frontegg Application to your User

This means the User you tried signing in with doesn’t have the Application assigned.

If you can’t assign the Application to the User, make sure the Account that the User exists under has the Application assigned first:

  • Find the User and open the context menu (three dots at the end of the User’s row) and click Edit applications and assign the corresponding Application.
  • This can happen if the Application is assigned to the Account after the User was already added there.

In other words, the Application with the corresponding App ID you used for the Client ID in the environment variables needs to be assigned to the User (first assigning it to an Account which the User belongs to if you haven’t already done so).

More Info

Minimal React sample

To help make it easier to focus on the pieces relevant for integrating Frontegg, this sample app is simply the Vite React (Typescript) Template with a few additions. The Vite.dev docs are a great place to start if you want to learn more about the surrounding “non-Frontegg” pieces.

Goal

The goal of this article and the accompanying sample app is to remove everything that’s not necessary to start exploring or evaluating Frontegg in an actual app, an app that you can test with, play with, share, blow up, and maybe (hopefully?) learn from.

What to expect

Following the guide here or the one in the repo’s README to learn how to integrate Frontegg into a React app. And, since it makes use of the cloud-hosted login page (Frontegg also provides an “embedded” option for maximal control), you, or someone you invite, can make changes from the Frontegg dashboard and have them immediately reflect in the app without you touching any bit of code.

Starting Point

Is the Vite React with Typescript template app. capabilities it makes up for in you over that first blocker to seeing the possibilities of what you can accomplish with Frontegg’s platform.

Summarizing the Steps

1. The necessary dependencies

  • Frontegg React SDK
    • @frontegg/react
    • Recommended to use npm at it is tested and while some kinks are being worked out with compatibility with yarn v2+
  • React Router
    • react-router-dom

2. Import the Frontegg Context and Components:

  • Import the necessary components from the Frontegg React SDK into your React application. This typically includes a context provider and hooks for accessing authentication state and functions.

3. Wrap Your Application with the Frontegg Provider:

  • Wrap your root React component with the Frontegg provider component. This will make the authentication context available throughout your application.

4. Configure the Frontegg Provider:

  • Pass your Frontegg application ID and other relevant configuration options to the Frontegg provider component.

5. Add Login and Logout Functionality:

  • Use the login and logout functions provided by the Frontegg hooks to add login and logout buttons or links to your application.

6. Protect Routes and Components:

  • Use the authentication state provided by the Frontegg hooks to conditionally render routes or components based on whether the user is logged in or not.

7. Display or Utilize User Information:

  • Use the user object provided by the Frontegg hooks to display the user’s name, email, or other relevant information in your application.

8. Customize the User Interface:

  • Frontegg often provides customizable UI components for login, registration, and profile management. Use these components or build your own to match the design of your application.

9. Consider Advanced Features:

  • Explore advanced features provided by Frontegg, such as social logins, multi-factor authentication, role-based access control, and audit logs. These features can enhance the security and functionality of your application.

Benefits of Frontegg for Authentication

  • Simplifies authentication: Frontegg handles the complexities of authentication, allowing you to focus on building your application’s core features.
  • Pre-built UI components: Frontegg often provides pre-built UI components for login, registration, and self-service management, saving you development time.
  • Customization: Frontegg allows you to customize the UI and behavior of the authentication flow to match your application’s design and requirements.
  • Security: Frontegg implements security best practices to protect your application and user data.
  • Scalability: Frontegg’s cloud-based infrastructure can handle the authentication needs of applications of all sizes.

Resources

Frontegg

Vite

To help make it easier to focus on the pieces relevant for integrating Frontegg, this sample app is simply the Vite React (Typescript) Template with a few additions. The Vite.dev docs are a great place to start if you want to learn more about the surrounding “non-Frontegg” pieces.

Concepts and Best Security Practices

Identity and Access Management (Authentication and Authorization)

Authentication: What It is and How It Works

What Is Access Management? Risks, Technology, and Best Practices

OAuth 2 and OIDC

What is OpenID Connect

What Is OpenID Connect (OIDC) and How It Works 

RFC6749: The OAuth 2.0 Authorization Framework 

Best practice guidance

RFC8725: JSON Web Token Best Current Practice 

RFC9700: Best Current Practice for OAuth 2.0 Security 

OWASP Cheat Sheet Series 

CORS

Cross-Origin Resource Sharing (CORS)

MDN Web Docs Glossary: Origin