Post registration role assignment issue using Actions

Hello Team,

I am new to Auth0 and I have created a new action in the library with the following code. But when I try to test it it’s giving me errors. Can someone please help me, if I’m doing something wrong?

Action Type: Post User Registration
Runtime: Node 22

/**
* Handler that will be called during the execution of a PostUserRegistration flow.
*
* @param {Event} event - Details about the context and user that has registered.
* @param {PostUserRegistrationAPI} api - Methods and utilities to help change the behavior after a signup.
*/
exports.onExecutePostUserRegistration = async (event, api) => {
  const axios = require('axios');

const tokenResponse = await axios.post(`https://${event.secrets.AUTH0_DOMAIN}/oauth/token`, {
    client_id: event.secrets.MGMT_CLIENT_ID,
    client_secret: event.secrets.MGMT_CLIENT_SECRET,
    audience: `https://${event.secrets.AUTH0_DOMAIN}/api/v2/`,
    grant_type: 'client_credentials',
  }
);

  const token = tokenResponse.data.access_token;

  await axios.post(
    `https://${event.secrets.AUTH0_DOMAIN}/api/v2/users/${event.user.user_id}/roles`,
    { roles: [event.secrets.DEFAULT_ROLE_ID] },
    {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Accept-Encoding': 'gzip, deflate'
      }
    }
  );
  
};

Update : I have tried the recommendation from this article, but I don’t see any roles being assigned to the newly signed up user.

exports.onExecutePostUserRegistration= async (event, api) => {

  const namespace = `https://${event.secrets.AUTH0_DOMAIN}`;

  const ManagementClient = require("auth0").ManagementClient;

  const management = new ManagementClient({
    domain: event.secrets.AUTH0_DOMAIN,
    clientId: event.secrets.MGMT_CLIENT_ID,
    clientSecret: event.secrets.MGMT_CLIENT_SECRET,
    scope: "read:users update:users read:roles",
  });

  const defaultRole = { id : event.secrets.DEFAULT_ROLE_ID};
  const adminRole = { id : event.secrets.ADMIN_ROLE_ID};
  var data = { "users" : [ event.user.user_id]};

  try {
    if (event.authorization) {
      if (!event.user.email_verified) {
        return;
      } else if (event.user.email && event.user.email.endsWith("@avb.dev")) {
          api.idToken.setCustomClaim(`${namespace}/roles`, event.secrets.adminRole);
          api.accessToken.setCustomClaim(`${namespace}/roles`, event.secrets.adminRole);
          await management.roles.assignUsers(adminRole, data);
      } else {
          api.idToken.setCustomClaim(`${namespace}/roles`, event.secrets.defaultRole);
          api.accessToken.setCustomClaim(`${namespace}/roles`, event.secrets.defaultRole);
          await management.roles.assignUsers(defaultRole, data);
      }
    }
  } catch (e) {
    console.log(e);
  }

};

[Reference Article](https://community.auth0.com/t/adding-roles-to-users-post-registration-using-actions/75671)

Hi @avbdev

Welcome to the Auth0 Community!

What is the error that you are receiving from the Action?

Also, if the login is successful, if the user re-authenticates, does the id token contain the roles?

Kind Regards,
Nik

You’re very close! The issue likely arises because Auth0 Actions don’t allow outbound HTTP requests to Auth0’s Management API by default due to security constraints. Instead, use a machine-to-machine application to assign roles outside of the Action (e.g., via a backend job triggered post-registration via a webhook or event). If you must do it in the Action, ensure all secrets are properly added in the Action’s “Secrets” tab, and consider wrapping your HTTP requests in try/catch blocks to surface specific error messages for easier debugging.