DEV Community

Cover image for Add Authentication to your React App with Frontegg
Anthony Dombrowski
Anthony Dombrowski

Posted on • Edited on

Add Authentication to your React App with Frontegg

frontegg-vite-react-ts

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

Is this for you?

  • You’re looking to for an IdP, authentication, authorization, OAuth/OIDC login and SSO, user management
  • You’re working with a client-side React app (SPA)
    • The Frontegg React SDK is specifically designed for client-side React apps
    • If that’s not you, you may want to see if any of the other SDKs offered here meet your needs:
    • Most of what will be talked about here is abstract enough to apply to the other tech stacks as well
  • The accompanying sample app uses Vite and their React (with Typescript) template as a starting point.

Prerequisites to follow along:

Sign up for Frontegg

Download the Sample App

At least Node 20 (LTS)

NodeJS Downloads

Quickstart for Frontegg and React

Vite React w/ Typescript and Frontegg is a minimal sample app to get started with Frontegg Authentication 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 you configure at least these:

  • Enter a name.

    • Tip.
      • Ideally, aim for a descriptive name that’s easily understandable for anyone that may end up becoming a Frontegg admin. And, if you intend to allow self-service configuration, this name will 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:

    App Config Example

Optional

  • Description
  • 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!

Forgot 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
Enter fullscreen mode Exit fullscreen mode

*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.
Enter fullscreen mode Exit fullscreen mode

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 the Frontegg Dashboard

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 3 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,

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 ###
################################################################################
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

Running the App

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

npm run dev
Enter fullscreen mode Exit fullscreen mode

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 help!

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'

  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.1
    2. Select the Application configuration which you're using.

Create a user:

  1. Under Management > Users (or on a specific Account's page under the Users tab), click the Create user button.2
    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.3

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.

    • This is what's referred to as the "Hosted Login" (as opposed to the "Embedded Login"4). You can change the UI using the "Login Builder" found in the dashboard.
  • 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 a layer 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

This means the User you tried signing in with belongs to an Account which doesn't have the Application linked. 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 an Account which the User belongs to. If you're user does belong to an Account where the Application is linked. Find the User and open the context menu (3 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.

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.

The 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.

Steps Summary

1. The necessary dependencies

  • Frontegg React SDK
    1. @frontegg/react
    2. Recommended to use npm at it is tested and while some kinks are being worked out with compatibility with yarn v2+
  • React Router
    1. 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.

9. 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.

10. 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.

Key Points and Benefits of using Frontegg for Authentication in your client-side React App

  • 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

Drop any questions in the comments!

Frontegg

@frontegg/react Docs
@frontegg/react on npm
Frontegg's Hosted Login Page Intro
Free Trial Signup
Slack Channel
Frontegg on GitHub

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.

Other

What is OpenID Connect

Top comments (0)