User Metadata in useUser - Next.js

Please include the following information in your post:

  • Which SDK this is regarding: @auth0/nextjs-auth0
  • SDK Version: 1.6.1
  • Platform Version: node v14.18.1
  • Code Snippets/Error Messages/Supporting Details/Screenshots:

Hi,

I try to fetch user_metadata.

I did two things so far:

Created Action

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://<AUTH0-DOMAIN>.com';
  api.idToken.setCustomClaim(`${namespace}/user_metadata`, event.user.user_metadata);
};

Changed API Route

I’ve changed the API route in pages/api/[...auth0].js

import { handleAuth, handleCallback } from "@auth0/nextjs-auth0";

const afterCallback = async (req, res, session, state) => {
    console.log(session);
    return session;
}

export default handleAuth({
    async callback(req, res) {
        try {
            await handleCallback(req, res, { afterCallback });
        } catch (error) {
            res.status(error.status || 500).end(error.message);
        }
    }
});

If I understand it correctly I should see the user_metadata now in the session object but I don’t see it.

In the end, I’d like to fetch it from the frontend via the useUser hook.

Thanks for your help!

Hi @sandro,

Welcome to the Auth0 Community!

I understand you’ve encountered issues retrieving the user’s user_metadata in your Next.js app.

First, I noticed that your Post-Login Action script uses a reserved namespace, specifically your Auth0 domain. Unfortunately, this is not allowed as described in our Create Custom Claims documentation.

Because of this, you’ll need to use any non-Auth0 HTTP or HTTPS URL as your namespace identifier:

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://my-app.example.com';
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/user_metadata`, event.user.user_metadata);
  }
};

Once that is addressed, you’ll be able to see the user_metadata.

Lastly, you may find the Add claims to a token example with Actions helpful.

Please let me know if there’s anything else I can do to help.

Thank you.

Thank you so much that works!

1 Like

Hi @sandro,

I’m glad that everything is working now!

If you have any further questions, please don’t hesitate to reach out.

Have a great rest of your day!

Thank you.

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