How can I create user lifecycle hooks in v4?

So as of 2024 the solution to this is the same but the controller you use is different.

Here is the updated code:

// /src/extensions/user-permissions/strapi-server.ts
export default function (plugin) {
  const registerController = plugin.controllers.auth.register;
  plugin.controllers.auth.register= async(ctx)=> {
    const body = ctx.request.body

    // do some modifications
    body.username = Math.random()

    await registerController(ctx)
  }

  return plugin;
}

If you want to create a user with a role, you can update the user after:

// /src/extensions/user-permissions/strapi-server.ts
export default function (plugin) {
  const registerController = plugin.controllers.auth.register;
  plugin.controllers.auth.register= async(ctx)=> {
    const body = ctx.request.body

    // do some modifications
    body.username = Math.random()

    await registerController(ctx)

    // bind role
    const user = ctx.response._body.user;
    const updatedUser = await strapi.entityService.update("plugin::users-permissions.user", user.id, {
      data: {
        role: ctx.request.body.role
      },
      populate: {role: true}
    })

    user.role = updatedUser.role;
  }

  return plugin;
}

^^ with this you can pass the role in the request body as: role: 4

4 Likes