Skip to main contentArrow Right
Blog cover graphic labeled "Developer Guide" with a rounded square icon of two interlocking chain links, above the title "Add Magic Links & RBAC to React."

Table of Contents

Summarize with AI

Don't have the time to read the entire post? Our human writers will be sad, but we understand. Summarize the post with your preferred LLM here instead.

This tutorial was written by Sesethu Mhlana, a software engineer with a passion for developing innovative solutions for web and desktop applications. Connect with him on LinkedIn to see more of his work!


In modern React applications, simplifying user authentication without compromising security is key. Magic link authentication provides an elegant solution by allowing users to log in using a secure, passwordless link sent to their email. With no passwords to remember or store, this method reduces friction for users while making life easier for the IT department.

In this tutorial, we’ll walk you through integrating React magic link authentication with Descope. As an added bonus, we'll also show you how to implement role-based access control (RBAC) for fine-grained user management. 

By the end of this guide, you’ll have:

  • A working passwordless login system using magic link authentication

  • A seamless authentication flow in your React app

  • Basic implementation of RBAC for managing user permissions

Magic link authentication offers a seamless, secure login method for React apps by allowing users to log in without passwords. The process begins when a user enters their email on your React app’s login screen. From there, the server generates a unique token and sends it to the user’s email as a magic link. When the user clicks the link, they’re redirected back to the app, where the server verifies the token. If the token is valid, the user is authenticated and logged in—no password required. This system relies on email for verification, combining convenience with security.

Flow diagram titled "How magic links work." The steps run left to right across the top row, then right to left across the bottom row. First, the User "Visits app," with an arrow to the App. The App "Requests email" from the User. The User "Sends email" to the App. The App "Generates and stores token," with an arrow down to the App Server. The App Server "Builds & sends magic link" to the User. The User "Clicks magic link," with an arrow to the App, shown as a laptop icon beside a server icon. The App "Checks token," and an arrow leads up to a check mark labeled "Authenticated."
Fig: How magic link authentication works

To integrate magic link authentication in your React app, you need to set up a system where users can log in via magic links sent to their email. After that, you can control access to different parts of the app based on the roles assigned to users.

In this tutorial, you’ll create a recipe app that fetches recipes from DummyJSON and displays them to logged-in users. Using RBAC (which we’ll set up later), you’ll then control which information about the recipes is displayed based on the user’s role.

Before you start, you need to create a Free Forever Descope account that allows you to build and test your app before going to production. You’ll use this account throughout the tutorial.

Descope is a React authentication provider that streamlines authentication with secure, passwordless methods, adaptive MFA and more. With a drag & drop editor, you can implement robust, customizable auth flows with minimal coding, getting both security and a smooth user experience.

Read more: Add Authentication & Authorization to a React App With Descope 

Create the React application

First, create a new React app using the create-react-app command:

npx create-react-app descope-app

After the project is created, install the Descope package using the following command:

npm i @descope/react-sdk

Configure an authentication flow on Descope

To integrate Descope into your project, you need to configure an authentication flow using the developer console. Sign in to Descope. This will take you to the developer console. Once there, click on Getting Started and select Consumers:

Descope Console Getting Started wizard on step 1, Build, of three steps: Build, Integrate, and Customize. Under the question "Who uses your application?" are two cards, Businesses and Consumers, with Consumers selected. A hint below reads "Choose this if you are building applications which individuals use in their day-to-day lives." A Next button sits at the lower right. The left navigation highlights Getting Started, and the project is named familiar-ivory-pasteur on the Free Plan.
Fig: Descope Getting Started Wizard

Click Next and choose Magic Link as the form of authentication:

Descope Console Getting Started wizard on step 1, Build, with a B2C tag and the question "Which authentication methods do you want to use?" and the note "You can choose up to 2 methods that will appear in your login screen." Seven method cards are shown: Passkeys (WebAuthn), Social Login (OAuth / OIDC) with "e.g. Google, Microsoft," one-time password, magic link, Enchanted Link, Authenticator Apps (TOTP), and SSO with "e.g. SAML." The magic link card is selected and tagged Primary, and Enchanted Link is grayed out. A Back link sits at the lower right.
Fig: Choosing magic link authentication

Choose Go ahead without MFA, as you won’t be using it for this tutorial. You can always set up MFA later. Then, you’ll see a preview of the selected options:

Descope Console Getting Started wizard on step 1, Build, with the heading "We're now ready to show you Descope in action!" and the text "Clicking Next will generate the following flows for you to use:". Four flows are listed. Sign In: "Allows registered users to login to your app." Sign Up: "Allows users to register to your app for the first time." Sign Up or In: "A single flow that combines the sign up and sign in functionalities." Step Up: "Extra validation of the user, before performing high risk actions in your app." A warning reads "If these flows have already been edited, clicking Next will override them." On the right, a preview panel lists Primary methods: magic link, and Secondary method: None, above a sample login screen with the heading "Welcome!", an Email address field, and a Continue button. Back and Next buttons sit below the preview.
Fig: Previewing selected options

To integrate the authentication flow into your project, wrap your entire application with <AuthProvider> component. In index.js, replace the existing code with the following to set up the SDK and include the necessary project ID (found in the developer console):

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { AuthProvider } from '@descope/react-sdk';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <AuthProvider
            projectId='<your-descope-project-id>'
        >
            <App />
        </AuthProvider>
    </React.StrictMode>
);

You now have easy access to the logged-in user via the user object.

With the authentication flow now integrated, modify App.js to configure the Descope authentication flow for your React app:

import './App.css';
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { React, useEffect, useState } from 'react';

function App() {
  const { isAuthenticated, isSessionLoading } = useSession()
  const { user, isUserLoading } = useUser()
  const { logout } = useDescope()

  // State property to store the recipes
  const [recipes, setRecipe] = useState([]);

  // Fetch the recipes and store them in the recipe state property
  const fetchRecipes = async () => {
    await fetch("https://dummyjson.com/recipes")
        .then((response) => response.json())
        .then((results) => {
          setRecipe(results.recipes);
        })
        .catch(error => console.error(error));
  }
  
  useEffect(() => {
    fetchRecipes();
  }, []);

  const handleLogout = () => {
    logout()
  };

  return <>
    // Log a message if the authentication succeeds or fails
    {!isAuthenticated &&
      (
        <div style={{ display: "flex", justifyContent: "center" }}>
          <div style={{ width: "400px" }}>
            <Descope
              flowId="sign-up-or-in"
              onSuccess={(e) => console.log(e.detail.user)}
              onError={(e) => console.log('Could not log in!')}
            />
          </div>
        </div>
      )

    }

    {
      (isSessionLoading || isUserLoading) && <p>Loading...</p>
    }

    {!isUserLoading && isAuthenticated &&
      (
        <div style={{padding:"0 0 3rem 3rem"}}>
          <p>Hello {user.name}</p>
          <button onClick={handleLogout}>Logout</button>
          <div style={{padding:"1rem 0 0 0"}}>Here are some delicious recipes:</div>
          {recipes.length > 0 && 
            <>
              {recipes.map((recipe) => {
                return (
                  <div key={recipe.id}>
                    <h1>{recipe.name}</h1>
                    <p>Ingredients: {recipe.ingredients.join(', ')}.</p>
                    {recipe.instructions.map((instruction, index) => {
                      return (<p key={index}>{instruction}</p>)
                    })}
                  </div>
                )
              })}
            </>
          }
        </div>
      )}
  </>;
}
export default App;

After the user successfully logs in, the application fetches recipes from the DummyJSON API and displays them. The user's information is stored in the user object, allowing you to access details like the user's name and customize the app accordingly.

Now that the authentication flow is set up, navigate to your project directory using the following command:

cd descope-app

And then run the application using this command:

npm start

After successfully compiling, open the URL displayed in the terminal (usually http://localhost:3000/). You’ll see the login screen:

Descope login screen in the React app. A dashed placeholder box reads "Your logo here" above the heading "Welcome!" Below are a required Email Address field, the text "By continuing, I agree to the Company's Privacy Statement and Terms of Service" with both document names as links, and a blue Continue button.
Fig: Login screen

Enter the email address and click on Continue. You will receive a magic link in your inbox. Click the link, and you will be authenticated and redirected to the application. Once authenticated, the recipes will be visible:

React app after login, on a dark background. The page greets the user with "Hello" and a blurred name, shows a Logout button, and reads "Here are some delicious recipes:". Three recipes follow. Classic Margherita Pizza: "Ingredients: Pizza dough, Tomato sauce, Fresh mozzarella cheese, Fresh basil leaves, Olive oil, Salt and pepper to taste." Steps: "Preheat the oven to 475°F (245°C). Roll out the pizza dough and spread tomato sauce evenly. Top with slices of fresh mozzarella and fresh basil leaves. Drizzle with olive oil and season with salt and pepper. Bake in the preheated oven for 12-15 minutes or until the crust is golden brown. Slice and serve hot." Vegetarian Stir-Fry: "Ingredients: Tofu, cubed, Broccoli florets, Carrots, sliced, Bell peppers, sliced, Soy sauce, Ginger, minced, Garlic, minced, Sesame oil, Cooked rice for serving." Steps: "In a wok, heat sesame oil over medium-high heat. Add minced ginger and garlic, sauté until fragrant. Add cubed tofu and stir-fry until golden brown. Add broccoli, carrots, and bell peppers. Cook until vegetables are tender-crisp. Pour soy sauce over the stir-fry and toss to combine. Serve over cooked rice." Chocolate Chip Cookies: "Ingredients: All-purpose flour, Butter, softened, Brown sugar, White sugar, Eggs, Vanilla extract, Baking soda, Salt, Chocolate chips." The rest of the cookie recipe is cut off at the bottom of the image.
Fig: After authentication is successful

Implement RBAC in React

Now that the user can see the recipes, you can configure RBAC to control which data is accessible to specific users.

RBAC is a method of regulating access to resources by assigning users to roles, which are defined by specific permissions related to job functions. This simplifies user management and enhances security by adhering to the principle of least privilege. You can learn more in Descope’s RBAC documentation.

Define user roles

To implement RBAC in your React app, the first step is to define user roles in the Descope console. For this tutorial, we’ll create two roles: Chef and User.

  • The User role can only list the recipes.

  • The Chef role can list recipes as well as view detailed information, like ingredients and instructions.

In the Descope console, navigate to the Authorization page. 

  • Click + Role to add a new role.

  • Fill in the following details:

    • Name: Chef

    • Description: A chef who will view all recipes, including ingredients and instructions.

Descope Console Authorization page, described as "Configure Role-Based Access Control (RBAC) for your users, by creating Roles and Permissions," with the Roles tab selected. Red outlines mark the Authorization item in the left navigation and the + Role button at the upper right. An Add Role dialog is open with the Name field set to Chef, the Description field starting "A chef who will view all recipes including the ingredie" (cut off by the field width), an empty Permissions dropdown, and Cancel and Add buttons. Behind the dialog, the roles table shows one existing role, Tenant Admin, of type Project, created May 25, 2024 14:44, with Total Rows: 1.
Fig: Adding a role

Leave the permissions as they are.

  • Then add another role for the user:

    • Name: User

    • Description: A user who can list recipes only.

Now you should have two roles created.

Descope Console Authorization page with the Roles tab selected, listing three roles in a table with the columns Name, Description, Permissions, Type, and Created Time. User: "A user who will list the recipes.", type Project, created June 09, 2024 09:06. Chef: "A chef who will view all recipes including the ingredients and instructions.", type Project, created June 09, 2024 09:03. Tenant Admin: no description, permissions "User Admin, Impersonate, SSO Ad..." (truncated), type Project, created May 25, 2024 14:44. A + Role button sits above the table, and the footer reads Total Rows: 3.
Fig: Viewing newly added roles

Assign roles to users

To assign a role to a user:

  • Navigate to Users in the Descope console.

  • Find the user you want to assign a role to, then select Edit.

Users page in the Descope Console for the project familiar-ivory-pasteur, on the Free Plan. The page heading reads "Users" with the description "An overview of all of your users and their information. Edit their configuration, and manage custom attributes. Learn More." The Users tab is selected next to a Custom Attributes tab, above a Search field, a Filter control, and "+ User" and "Import Users" buttons. The user table has the columns Login ID, Status, Display Name, Email, Phone, Created Time, Tenants, Roles, and Consent Expiration, and lists two users, both with the status Active and verified email addresses, created June 08, 2024 22:10 and June 02, 2024 13:20. Their login IDs, display names, and email addresses are redacted, and the Tenants and Roles columns are empty. The three-dot menu for a user row is open with the options Edit, Disable, Delete, and Force Logout, and Edit is outlined in red. The left navigation shows Home, Getting Started, a Build section (Authentication Methods, Flows, Widgets, Styles, Localization, Connectors), a Manage section (Users, which is selected, Access Keys, Tenants, Applications, Authorization, Audit), and a Settings section (Project, Company). The table footer reads "1-2 of 2."
Fig: Editing a user’s details to assign a role
  • In the modal that appears, go to the Authorization section and select the Chef role from the Roles drop-down.

  • Click Save.

Edit user modal in the Descope Console, opened over the Users page for the project familiar-ivory-pasteur. The modal header shows the user's redacted name with an Active badge. Fields listed from top to bottom are a read-only user ID (U2hbzBuqOgmpU6jbGfQwLOq834JF), Login ID (redacted), Name (redacted), Given Name, Middle Name, Family Name, Email (redacted, with a verified check mark), and Phone. Below is an Authorization section with the text "Define user access to tenants, and assign roles:" followed by a Tenants drop-down and a Roles drop-down with plus and minus buttons. The Roles drop-down is open and lists three options: Chef, Tenant Admin, and User, with Chef highlighted. A second line reads "Define user access to applications:" with an Applications field set to "All Applications." Cancel and Save buttons sit at the bottom right of the modal.
Fig: Assigning a role to a user

You have now assigned a role to the user.

Implement roles in your React app

Now that the roles are defined, let’s integrate them into your app.

Create a new file called roles.js and define the roles as follows:

export const roles = { 
    USER: 'User', 
    CHEF: 'Chef' 
};

Then, update App.js to conditionally render certain details about the recipes based on the assigned user role:

import './App.css';
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { React, useEffect, useState } from 'react';
import { roles } from './roles';

function App() {
  const { isAuthenticated, isSessionLoading } = useSession()
  const { user, isUserLoading } = useUser()
  const { logout } = useDescope()

  const [recipes, setRecipe] = useState([]);

  const fetchRecipes = async () => {
    await fetch("https://dummyjson.com/recipes")
        .then((response) => response.json())
        .then((results) => {
          setRecipe(results.recipes);
        })
        .catch(error => console.error(error));
  }
  
  useEffect(() => {
    fetchRecipes();
  }, [isAuthenticated, user]);

  const handleLogout = () => {
    logout()
  };

  return <>
    {!isAuthenticated &&
      (
        <Descope
          flowId="sign-up-or-in"
          onSuccess={(e) => console.log(e.detail.user)}
          onError={(e) => console.log('Could not log in!')}
        />
      )
    }

    {
      (isSessionLoading || isUserLoading) && <p>Loading...</p>
    }

    {!isUserLoading && isAuthenticated &&
      (
        <div style={{padding:"0 0 3rem 3rem"}}>
          <p>Hello {user.name}</p>
          <button onClick={handleLogout}>Logout</button>
          {(user.roleNames.includes(roles.CHEF) || user.roleNames.includes(roles.USER)) && 
            <div>
              <div style={{padding:"1rem 0 0 0"}}>Here are some delicious recipes:</div>

              {recipes.length > 0 && 
                <>
                  {recipes.map((recipe) => {
                    return (
                      <div key={recipe.id}>
                        <h1>{recipe.name}</h1>

                        {
                          user.roleNames.includes(roles.CHEF) &&
                          <>
                            <p>Ingredients: {recipe.ingredients.join(', ')}.</p>
                            {recipe.instructions.map((instruction, index) => {
                              return (<p key={index}>{instruction}</p>)
                            })}
                          </>
                        }
                      </div>
                    )
                  })}
                </>
              }
            </div>
            }
        </div>
      )}
  </>;
}
export default App;

How this works:

  • The roles.js file stores the roles and can be easily imported into your application.

  • The code checks the user.roleNames from the user object, and based on the assigned role (either Chef or User), it conditionally renders the recipe details.

  • Users can see only the recipe titles, while Chefs can view both the recipe titles and the full details, including ingredients and instructions.

This setup uses RBAC to manage access to different parts of the app, ensuring that only users with the Chef role can view detailed recipe information, while others are limited to basic recipe listings.

Descope, a CIAM platform, offers several alternatives to magic link authentication for React apps, each providing unique benefits.

Discover more: Adding OAuth 2.0 to React for Authentication & Authorization 

Enchanted links

Enchanted links are an enhanced version of traditional magic links. These unique, single-use links are sent via email for authentication. The key difference? They allow users to initiate the login process on one device and authenticate by clicking the link on another device.

Once the user clicks the correct link from a set of three options, their session on the original device is validated, and they’re logged in. Enchanted links can be used for both new user sign-ups and existing user logins.

Two-panel graphic titled "Enchanted Links." The left panel shows a Descope authentication screen that reads "We've sent a verification link to abh****@descope.com. In the email, click the following number to authenticate," followed by the number 13, a progress bar, a "Send again" button, and a "Choose another authentication method" link. The right panel shows the email the user receives: "Hi there, Click on the button matching the number in the authentication screen to enter Descope Inc." Three buttons are labeled 13, 00, and 83. Below them, the text "Or sign in with the appropriate link below:" introduces three long login URLs labeled [13], [00], and [83], each beginning with https://app.descope.com/login?descope-login-flow=sign-up-or-in. The email ends with "The links above will expire in 3 minutes." The number 13 on the authentication screen matches the first button in the email.
Fig: Descope enchanted links

Learn more about customizing enchanted links with Descope Flows here.

Embedded links

Embedded links generate unique tokens. These tokens can be sent via email, SMS, or even used programmatically without clicking a link, similar to enchanted links.

The token is authenticated using the magic link verification function. It’s created with the Descope SDK on the backend (such as Node.js), then sent to the user. After clicking, the token is sent back to the backend for verification. 

Learn how to implement embedded links with Descope Flows here.

In this article, you’ve learned how to implement a seamless magic link authentication flow in your React app. You’ve also seen how to assign user roles and control access based on those roles. By eliminating password management challenges, magic links improve user adoption and conversion rates. This approach also simplifies authentication for developers, reducing infrastructure and development overhead.

Descope makes magic link integration easy with visual workflows that speed up both setup and ongoing modifications to your authentication flows.

Have questions about Descope? Book time with our experts.

Descope Flows diagram of a magic link login flow. A "Start" node points to a screen step labeled "Sign In." The Sign In step connects to an action step labeled "Sign In / Magic Link / Email," which has two outputs marked with green check marks. The first output points to a screen step labeled "Magic Link Sent," which connects back into the action step. The second output points to the "End" node. The fields inside each step are blurred placeholders.
Drag & drop magic link authentication with Descope