Access User_Metadata in React?

I added additionalSignUp fields for firstName and lastName to my custom Universal login. I can see the user_metadata when looking at the user object in the dashboard - now I want to be able to reference it in my react app, e.g. show a welcome message with the user’s first name from metadata. I cannot quite figure out how to do this - is there a good working example somewhere than I can reference?

Hi @athome176

Thanks for getting in touch with us at Auth0 Community.

To be able to access the user_metadata via the SDK I believe you’ll need to add the user_metadata to the users id_token first via a Post Login Action, you can learn about Actions here https://auth0.com/docs/customize/actions

For a more specific example you can review this community post https://community.auth0.com/t/need-help-on-getting-idtoken-user-metadata-with-react-auth0-sdk/80740

Hopefully this will help you.

Warm regards.

3 Likes

Thanks for the reply Saqib! This is my post-login action:

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://dev.my-app.com';
  const { firstName, lastName } = event.user.user_metadata;

  if (event.authorization) {
    // Set claims 
    api.idToken.setCustomClaim(`${namespace}/user_metadata.firstName`, firstName);
    api.idToken.setCustomClaim(`${namespace}/user_metadata.lastName`, lastName);
  }
};

But I still have no idea how to actually get anything from metadata in React. For example, here is my HomePage.js:

import React from "react";
import FadeIn from 'react-fade-in';

const HomePage = () => {

    return (
        <FadeIn>
            <div className="list row">
                <div className="col-md-6">
                    <h4>Welcome to your Home Page!</h4>
                </div>
            </div>
        </FadeIn>
    );
};

export default HomePage;

How would I grab the firstName from user_metadata and insert it into the welcome message? This is where I have trouble - I cannot find any working examples of this anywhere and the documentation is not clear, so I have no idea. :sweat_smile:

Hey there @athome176!

Check out the useAuth0 hook, and in particular the getIdTokenClaims method since the metadata now exists as claims in the ID token:

It’s used to get profile information in our React quickstart here:

Hope this helps!

2 Likes

Thanks Tyf! It’s still not clear to me, unfortunately. I know how to get values like user.sub - but I am trying to fetch a value from user_metadata, and that is what I don’t know how to do. How would I refer to my firstName value (for example) from user_metadata after having used the rule to place it into the ID token?