Accessing App_Metadata In Next.js Auth0 App

I have a Next.js app where I need to access the user’s app_metadata and retrieve a certain object from the JSOn (planType to be exact) and I haven’t found how retrieve it within the Next.js application.

Right now, I am trying to render it in a getServerSideProps in a dynamically rendered page on my site.

The code is able to successfully get the user from the auth0 nextjs client import for a different use,

But I am unsure how to access the the app_metadata through this (it can access things like user.name, user.email, user.username, and other user data but not app_metadata).

Any idea how to do this if it is possible?

export const getServerSideProps = async (context: any) => {
  const session = await getSession(context.req, context.res);
  const user = session?.user;
  const { query } = context.query;

  const rawData = await fetchXXXXXXXXX(user, query); // uses user to fetch user.name for different task but this works
  const XXXXXXXX = ..... // not important to this problem
    return rest;
  });
console.log(user) // successful.

  const  [APP METADATA VAR] = user?.app_metadata.planType == "paid" //returning an error as this is undefined - this where I am facing problems


  return {
    props: {
      XXXXXXXX,
      [APP METADATA VAR],
    }
  };
};

when I log the user data i get this as well - only the basic user data but not the app_metadata.

{
  nickname: 'XXXXXXXXXXXXXXXX',
  name: 'XXXXXXXXXXXXXXXXXXXXXX',      
  updated_at: '2024-06-24T04:45:31.227Z',
  email: 'XXXXXXXXXXXXXXXXXXXXXX',
  email_verified: true,
  sub: 'XXXXXXXXXXXXXXX',
  sid: 'XXXXXXXXXXXXXXXXXXXXXXXX'
}

Hi there @secomm !

app_metadata and user_metadata aren’t added as claims to user tokens by default - You’ll want to add metadata as custom claims in an Action. For example:

exports.onExecutePostLogin = async (event, api) => {
  // Ensure user_metadata and app_metadata exist
  const userMetadata = event.user.user_metadata || {};
  const appMetadata = event.user.app_metadata || {};

  // Add user_metadata to ID Token
  api.idToken.setCustomClaim('https://example.com/user_metadata', userMetadata);

  // Add app_metadata to ID Token
  api.idToken.setCustomClaim('https://example.com/app_metadata', appMetadata);

  // Add user_metadata to Access Token
  api.accessToken.setCustomClaim('https://example.com/user_metadata', userMetadata);

  // Add app_metadata to Access Token
  api.accessToken.setCustomClaim('https://example.com/app_metadata', appMetadata);
};

After configuring this post login action, the metadata should be included in the user data you’re seeing.

Hi,
Thanks for the help.

If I implement this code after the creation of each user, will I be able to access the app_metadata regularly by using

user.app_metadata.planType

assuming planType is under app_metadata?

And how will I get this to work under development - will I have to add this to my dev Auth0 Action and add the token to the localhost:3000 route?