Frontegg: Best Auth System for your Frontend

Published by Pawan Sargar on

Frontegg: Best Auth System for your Frontend

Whenever we have to build a user authentication or any type of application that requires authentication. We might go with Firebase, Auth0, or a library like Passport.js.

All of the above-mentioned can be quite tricky and has a huge boilerplate code. What if we have an easier method to create social authentication without writing much of the boilerplate code?

So, let me introduce you to a newer and production-ready tool called Frontegg. It provides a modern way to authenticate users. It also provides a Free plan, which we can utilize it up to 5 organizations.

What does Frontegg’s Free Plan provide?

  • Login Box
  • Social Login
  • Passwordless Authentication
  • Admin Portal
  • Profile Management
  • User Invitations
  • User Roles and Permissions

and much more.

What we’ll build today?

We’ll build a very basic user authentication web application using React and of course Frontegg. Pre-requisites are the basics of React is enough like Hooks and Components, etc.

let’s get started.

#1 Create a Frontegg Account ⇒

  • Head over to the Frontegg website and click on start for free.
  • Signup using social or email.
  • Write the name of your website or organization and upload a logo.
Frontegg Tutorial: Create a User Authentication in React
  • Select the authentication methods that you want to use and publish them to the development.
Frontegg social login in React
  • Now, select React as the development environment.

#2 Create a React App

Now let’s start with creating a React app, or you can just create it in seconds using Codesandbox.io.

yarn create react-app frontegg-auth

#or

npx create-react-app frontegg-auth

After installing React install the Frontegg and React router packages.

yarn add @frontegg/react react-router-dom

#or

npm install @frontegg/react react-router-dom

Also, check out,
NextJS vs ReactJS: Which is best for your project?

#3 Let’s initialize the Frontegg ⇒

The Frontegg works like a Context Provider. If you have worked with React Context API or Redux you might know what it means. You don’t need to worry if you don’t know about Context API, I’ll walk you through it.

Now, inside index.js, paste the following code.

import { FronteggProvider } from '@frontegg/react';

const contextOptions = {
  baseUrl: 'your base url',
  clientId: 'your client id'
};

you can get the above code with your client id and base URL from the React documentation, they automatically generate code for your account.

If you are not able to find it, check out the settings you’ll find the required credentials.

Now, add the Frontegg provider to your App component.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

import { FronteggProvider } from "@frontegg/react";

const contextOptions = {
  baseUrl: "your base url",
  clientId: "your client id",
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <FronteggProvider contextOptions={contextOptions} hostedLoginBox={true}>
    <App />
  </FronteggProvider>
);

Now, the initializing part is over, and we can start building the application.

#4 Using the Authentication ⇒

Now, inside the App.jsx, let’s use methods to create an authentication that Frontegg has to provide.

First, let’s import ContextHolder which you can see comes from frontegg/rest-api and useAuth and useLoginWithRedirect which comes from frontegg/react.

import { ContextHolder } from "@frontegg/rest-api";
import { useAuth, useLoginWithRedirect } from "@frontegg/react";

Inside our App component, let’s use these features.

const { user, isAuthenticated } = useAuth();
const loginWithRedirect = useLoginWithRedirect();

useAuth() provides use to the user and isAuthenticated tells us if the user is logged in or not.

useLoginWithRedirect() will help the user to redirect to the login page if not authenticated, or if the authentication fails for some reason.

We first need to check the isAuthenticated,

useEffect(() => {
    if (!isAuthenticated) {
      loginWithRedirect();
    }
  }, [isAuthenticated, loginWithRedirect]);

with the help of useEffect, we can check the status of the user, and if he is not logged in just redirect him to the login page.

Now, let’s manage the logout, it’s pretty easy as well.

const logout = () => {
    const baseUrl = ContextHolder.getContext().baseUrl;
    window.location.href = `${baseUrl}/oauth/logout?    post_logout_redirect_uri=${window.location}`;
 };

From the ContextHolder, we can get them baseUrl and when the user logs out, we can pass that baseUrland log out the session from the current window location.

Now, we have to allow users to authenticate and after authentication, it should show some user details which will be fetched from Frontegg. And, if the user is not logged in we’ll just redirect him to the login page.

let authenticated = (
    <div className="card">
      <div>
        <img src={user?.profilePictureUrl} alt={user?.name} />
        <h2>Welcome {user?.name}</h2>
      </div>
      <div className="detail">
        <span className="heading">Name: {user?.name}</span>
        <span className="heading">Email: {user?.email}</span>
      </div>
      <div>
        <button onClick={() => logout()} className="button">
          Logout
        </button>
      </div>
    </div>
  );

  let notAuthenticated = (
    <div>
      <button onClick={() => loginWithRedirect()} className="button">
        Login
      </button>
    </div>
  );

return (
    <div className="App">
      <h1>Frontegg Auth</h1>
      {isAuthenticated ? authenticated : notAuthenticated}
    </div>
  );

I’ve simplified the code just so you don’t get confused. You can see two variables with authenticated and notAuthenticated, this is what we’ll show users after each action.

As you can see, we are using conditional rendering to show users information based on their actions.

We can get the user data from the user instance provided by Frontegg.

There’s one more feature that we can view the full profile of the user or the Admin of the user.

import { AdminPortal, useAuth, useLoginWithRedirect } from "@frontegg/react";
const showAdmin = () => {
    AdminPortal.show();
  };

Just import the AdminPortal, and use the method AdminPortal.show(), now call that method on an event listener.

let authenticated = (
    <div className="card">
      <div>
        <img src={user?.profilePictureUrl} alt={user?.name} />
        <h2>Welcome {user?.name}</h2>
      </div>
      <div className="detail">
        <span className="heading">Name: {user?.name}</span>
        <span className="heading">Email: {user?.email}</span>
      </div>
      <div>
        <button onClick={() => logout()} className="button">
          Logout
        </button>
					//here
        <button onClick={() => showAdmin()} className="button">
          View full Profile
        </button>
      </div>
    </div>
  );

And, that’s it you’ve successfully built a fully-fledged user authentication using Frontegg.

#5 Let’s test it ⇒

If you now start your React app, you’ll be redirected to your Auth page created with Frontegg,

Frontegg authentication in React

Now, here either you can Sign up or Sign in with all these social logins. After login, you’ll be redirected back to show the information.

Frontegg authentication in React
Now, you can log out and view your full profile. That’s it.

That’s how simple it is to create an authentication in Frontegg, it’s not even 100 lines of code and we’ve created a fully-fledged authentication system.

Get Complete Source Code on GitHub

I hope this post was helpful, if it was make sure to share this post with your friends and let us know what technology would you like to learn next.

Pawan Sargar
Follow him
Spread the love
```html ```

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.