Nextjs-auth0: How to get app_metadata properties from session object in afterCallback()

SDK: @auth0/nextjs-auth0
Version: v1.2.0

Hi all,

First time user of Auth0 and Next.js here so excuse any oversight in my question below.

I want to add two custom properties (I think they’re called claims in the auth world) to each user. These properties essentially represent the User profile type and a particular resource they have access to.

I’ve added the two properties under app_metadata from the Auth0 dashboard and am using Passwordless Email login using a code.

Now, in Next.js I want to intercept the callback when a user logs in successfully and redirect them to the correct private page based on their profile type and the resource they have access to.

In the afterCallback() function within api/auth/[…auth0].js file in my Next.js project I have the following code:

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

However, the user property in the session object I am logging in the code above only contains what i understand to be the default properties of a JWT token.

What is the best way for me to add profileType and resourceId to this object so that I can do a check and redirect the user to the correct page?

I know it must be possible because the docs for AfterCallback use a isAdmin property in the example: handlers/callback | @auth0/nextjs-auth0

Hi @zaarheed,

Welcome to the Community!

You can add custom claims such as a property in a user’s app_metadata to the ID Token using a rule:

function(user, context, callback) {
  const namespace = 'https://myapp.example.com/';
  context.idToken[namespace + 'preferred_contact'] = user.user_metadata.preferred_contact;
  callback(null, user, context);
}

Your app will then have access to the custom claim in the ID Token.

Let me know if you have additional questions for setting this up!

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