# Help with calling Auth0 management api

**URL:** <https://community.auth0.com/t/help-with-calling-auth0-management-api/136156>\
**Category:** Get Help\
**Tags:** users, management-api\
**Created:** [June 11, 2024, 8:19pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156 "2024-06-11T20:19:56Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![rodyli123](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@rodyli123](https://community.auth0.com/u/rodyli123)\
**Post date:** [June 11, 2024, 8:19pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/1 "2024-06-11T20:19:57Z")

</div>

I am following the quick start guide for react. I copied all the code for calling an api and everything before it such as login button, logout button, and profile page. However, my fetch to the api to read the current user is always returning this error: Cannot read properties of undefined (reading ‘sub’). I’m not sure how to fix this error and was wondering if anyone could help. Thanks in advance.

This is my main.jsx

```auto
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';

const root = createRoot(document.getElementById('root'));

root.render(
  <Auth0Provider
    domain="dev-o751rwb3mvfsttg1.us.auth0.com"
    clientId="5VuwmvtQ0290VPQiDalLveiZQMWuspR7"
    authorizationParams={{
      redirect_uri: window.location.origin,
      audience: "https://dev-o751rwb3mvfsttg1.us.auth0.com/api/v2/",
      scope: "read:current_user update:current_user_metadata"
    }}
  >
    <App />
  </Auth0Provider>
);

```

This is my Profile.jsx

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

const Profile = () => {
    const { user, isAuthenticated, getAccessTokenSilently } = useAuth0();
    const [userMetadata, setUserMetadata] = useState(null);
    useEffect(() => {
        const getUserMetadata = async () => {
            const domain = "dev-o751rwb3mvfsttg1.us.auth0.com";

            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]);
    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;

```

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [June 12, 2024, 6:05pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/3 "2024-06-12T18:05:19Z")

</div>

Hey there @rodyli123 welcome to the community!

Thanks for the detailed description 🙂 Is the main reason for calling the Management just to get the user’s metadata?

---

<div class="post-metadata">

**Author:** ![rodyli123](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@rodyli123](https://community.auth0.com/u/rodyli123)\
**Post date:** [June 12, 2024, 6:26pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/4 "2024-06-12T18:26:30Z")

</div>

Correct, but later down the line I would like to use the management api to update my user. The work around I’m currently implementing is storing a user model in my database, but obviously it would be more convenient to update the user on auth0 database.

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [June 12, 2024, 6:57pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/5 "2024-06-12T18:57:32Z")

</div>

Thanks for clarifying!

Do you plan on only updating `userMetadata`? As Management API Access Tokens in a SPA are [limited](https://auth0.com/docs/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-tokens-for-single-page-applications#limitations) in scope, it may be easier/more flexible to add metadata as a [custom claim](https://auth0.com/docs/get-started/apis/scopes/sample-use-cases-scopes-and-claims#add-custom-claims-to-a-token)(s) in tokens and access it through the `user` object directly. As far as updating a user, if you need to update more than `userMetadata` it would be best to consider proxying the request through a backend service - This allows for fully scoped Management API Access Tokens:

[https://community.auth0.com/t/how-can-i-enable-users-to-change-their-email-address-from-a-spa-or-native-app/44064](https://community.auth0.com/t/how-can-i-enable-users-to-change-their-email-address-from-a-spa-or-native-app/44064)

---

<div class="post-metadata">

**Author:** ![rodyli123](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@rodyli123](https://community.auth0.com/u/rodyli123)\
**Post date:** [June 12, 2024, 7:09pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/6 "2024-06-12T19:09:00Z")

</div>

I appreciate the response. I now understand that I am unable to update the user from the SPA and instead will have to go through my backend. However, shouldn’t the code above theoretically work. I remember seeing somewhere that reading the current user through the management api is possible through the SPA.

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [June 12, 2024, 10:07pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/7 "2024-06-12T22:07:02Z")

</div>

> [@rodyli123](#):
>
> However, shouldn’t the code above theoretically work. I remember seeing somewhere that reading the current user through the management api is possible through the SPA.

That’s correct, you should be able to read user metadata through the SPA - I don’t see anything that immediately stands out in your code, but I’ll try to test this flow in my own environment to see what I can come up with.

---

<div class="post-metadata">

**Author:** ![rodyli123](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@rodyli123](https://community.auth0.com/u/rodyli123)\
**Post date:** [June 12, 2024, 10:32pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/8 "2024-06-12T22:32:25Z")

</div>

No worries if nothing comes to mind, thanks for the replies I appreciate it.

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [June 12, 2024, 11:35pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/9 "2024-06-12T23:35:16Z")

</div>

Happy to help!

While not exactly your code, I was able to get it working by building off the [React sample app](https://github.com/auth0-samples/auth0-react-samples/blob/master/Sample-01/src/views/Profile.js).

Here’s my `index.js`

```auto
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { Auth0Provider } from "@auth0/auth0-react";

ReactDOM.render(
  <Auth0Provider
    domain="{your_domain}.us.auth0.com",
    clientId="{client_id}",
    authorizationParams={{
      redirect_uri: window.location.origin,
      audience: "https://{domain}/api/v2/",
      scope: "read:current_user"
    }}
  >
    <App />
  </Auth0Provider>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

```

`Profile.js`

```auto
import React, { useEffect, useState } from "react";
import { Container, Row, Col } from "reactstrap";
import Highlight from "../components/Highlight";
import Loading from "../components/Loading";
import { useAuth0, withAuthenticationRequired } from "@auth0/auth0-react";

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

  useEffect(() => {
    const getUserMetadata = async () => {
      try {
        const domain = "{your_domain}";
        const accessToken = await getAccessTokenSilently({
          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}`,
          },
        });

        if (!metadataResponse.ok) {
          throw new Error(`Failed to fetch user metadata: ${metadataResponse.statusText}`);
        }

        const { user_metadata } = await metadataResponse.json();
        setUserMetadata(user_metadata);
      } catch (e) {
        console.error(e.message);
      }
    };

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

  if (user["https://yournamespace.com/isNewUser"]) {
    alert("this is a new user");
  }

  return (
    <Container className="mb-5">
      <h2>{user.name}</h2>
      <Row className="align-items-center profile-header mb-5 text-center text-md-left">
        <Col md={2}>
          <img
            src={user.picture}
            alt="Profile"
            className="rounded-circle img-fluid profile-picture mb-3 mb-md-0"
          />
        </Col>
        <Col md>
          <p className="lead text-muted">{user.email}</p>
        </Col>
      </Row>
      <Row>
        <Highlight>{JSON.stringify(user, null, 2)}</Highlight>
      </Row>
      <Row>
        <h3>User Metadata</h3>
        {userMetadata ? (
          <Highlight>{JSON.stringify(userMetadata, null, 2)}</Highlight>
        ) : (
          <p>No user metadata defined</p>
        )}
      </Row>
    </Container>
  );
};

export default withAuthenticationRequired(ProfileComponent, {
  onRedirecting: () => <Loading />,
});

```

---

<div class="post-metadata">

**Author:** ![rodyli123](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@rodyli123](https://community.auth0.com/u/rodyli123)\
**Post date:** [June 13, 2024, 3:40am UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/10 "2024-06-13T03:40:01Z")

</div>

Another question that came up in my mind is that whenever I add the audience and scope parameter for the authorization params my user in const { user } = useAuth0(); only displays a sub field rather than everything else in the meta data such as name, email, etc. Why is this?

Additionally, if I wanted to work around this by making a call to the backend to get the user meta data would I still have to include the audience and scope the authorization params?

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [June 13, 2024, 3:37pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/11 "2024-06-13T15:37:49Z")

</div>

> [@rodyli123](#):
>
> Another question that came up in my mind is that whenever I add the audience and scope parameter for the authorization params my user in const { user } = useAuth0(); only displays a sub field rather than everything else in the meta data such as name, email, etc. Why is this?

If you inspect the request to `/authorize` (browser dev tools) do you see any other scopes being passed? You’ll just want to make sure `openid` and `profile` are being passed as well to get more claims on the user.

> [@rodyli123](#):
>
> Additionally, if I wanted to work around this by making a call to the backend to get the user meta data would I still have to include the audience and scope the authorization params?

No, basically you would authorize the user to call your own API/backend - Your API would validate this request and then make a M2M call to Auth0 Management API on behalf of the user.

---

<div class="post-metadata">

**Author:** ![rodyli123](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@rodyli123](https://community.auth0.com/u/rodyli123)\
**Post date:** [June 13, 2024, 6:38pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/12 "2024-06-13T18:38:23Z")

</div>

> [@ty.frith](#):
>
> If you inspect the request to `/authorize` (browser dev tools) do you see any other scopes being passed? You’ll just want to make sure `openid` and `profile` are being passed as well to get more claims on the user.

Passing in openid and profile as well fixed the issue thank you.

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [June 13, 2024, 7:05pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/13 "2024-06-13T19:05:03Z")

</div>

Awesome, thanks for confirming! 🙂

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [June 27, 2024, 7:05pm UTC](https://community.auth0.com/t/help-with-calling-auth0-management-api/136156/14 "2024-06-27T19:05:45Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
