React: Call an API

View on Github

React: Call an API

Gravatar for dan.arias@auth0.com
By Dan Arias

This tutorial demonstrates how to make API calls to the Auth0 Management API. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to integrate with my app

15 minutes
  1. Set Up the Auth0 Service
  2. Get an Access Token
Or

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: React 16.8

The focus of this guide is to show you how to configure the SDK to call APIs protected by OAuth 2. Instead of creating a demo API to test the client-server connection, you'll use the Auth0 Management API, which comes bundled with your Auth0 tenant. However, you can adapt this guide to work with any API that you are securing with Auth0.

Set Up the Auth0 Service

The Auth0Provider setup is similar to the one discussed in the Configure the Auth0Provider component section: you wrap your root component with Auth0Provider to which you pass the domain and clientId props. The values of these two props come from the "Settings" values of the single-page application you've registered with Auth0.

However, your React application needs to pass an access token when it calls a target API to access private resources. You can request an access token in a format that the API can verify by passing the audience and scope props to Auth0Provider as follows:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Auth0Provider } from "@auth0/auth0-react";

ReactDOM.render(
  <Auth0Provider
    domain="{yourDomain}"
    clientId="{yourClientId}"
    authorizationParams={{
      redirect_uri: window.location.origin,
      audience: "https://{yourDomain}/api/v2/",
      scope: "read:current_user update:current_user_metadata"
    }}
  >
    <App />
  </Auth0Provider>,
  document.getElementById("root")
);

Was this helpful?

/

Auth0 uses the value of the authorizationParams.audience prop to determine which resource server (API) the user is authorizing your React application to access.

The actions that your React application can perform on the API depend on the scopes that your access token contains, which you define as the value of authorizationParams.scope. Your React application will request authorization from the user to access the requested scopes, and the user will approve or deny the request.

Get an Access Token

Once you configure Auth0Provider, you can easily get the access token using the getAccessTokenSilently() method from the useAuth0() custom React Hook wherever you need it.

Take this Profile component as an example:

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

const Profile = () => {
  const { user, isAuthenticated, getAccessTokenSilently } = useAuth0();
  const [userMetadata, setUserMetadata] = useState(null);

  return (
    isAuthenticated && (
      <div>
        <img src={user.picture} alt={user.name} />
        <h2>{user.name}</h2>
        <p>{user.email}</p>
        <h3>User Metadata</h3>
        {userMetadata ? (
          <pre>{JSON.stringify(userMetadata, null, 2)}</pre>
        ) : (
          "No user metadata defined"
        )}
      </div>
    )
  );
};

export default Profile;

Was this helpful?

/

As it is, userMetadata is always null in the Profile component. Add the following useEffect() hook to the component to fetch the user metadata from an API:

useEffect(() => {
  const getUserMetadata = async () => {
    const domain = "{yourDomain}";

    try {
      const accessToken = await getAccessTokenSilently({
        authorizationParams: {
          audience: `https://${domain}/api/v2/`,
          scope: "read:current_user",
        },
      });

      const userDetailsByIdUrl = `https://${domain}/api/v2/users/${user.sub}`;

      const metadataResponse = await fetch(userDetailsByIdUrl, {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      });

      const { user_metadata } = await metadataResponse.json();

      setUserMetadata(user_metadata);
    } catch (e) {
      console.log(e.message);
    }
  };

  getUserMetadata();
}, [getAccessTokenSilently, user?.sub]);

Was this helpful?

/

You use a React Effect Hook to call an asynchronous getUserMetadata() function. The function first calls getAccessTokenSilently(), which returns a Promise that resolves to an access token that you can use to make a call to a protected API.

You pass an object with the authorizationParams.audience and authorizationParams.scope properties as the argument of getAccessTokenSilently() to ensure that the access token you get is for the intended API and has the required permissions to access the desired endpoint.

You can then include the access token in the authorization header of the API call that you make. The API will take care of validating the access token and processing the request.

Upon success, you extract the user_metadata property from the API response and use setUserMetadata() to make React aware of it.

For a more detailed example, see how to create a useApi hook for accessing protected APIs with an access token.

Checkpoint

Your application will show "No user metadata defined" if you have not set any user_metadata for the logged-in user. To further test out this integration, head to the Users section of the Auth0 dashboard and click on the user who is logged in. Update the user_metadata section with a value like { "theme": "dark" } and click "Save". Refresh your React application and verify that it reflects the new user_metadata.

As a final reminder, consult the Auth0 API quickstarts to learn how to integrate Auth0 with your backend platform.

Use Auth0 for FREE