Add a role on user create

Components

In some cases, you may want to add a role when a new user is created regardless of how the user is created (UI, GraphQL, Rest API, or something else). The hook_ENTITY_TYPE_presave() hook is perfect for this.

use Drupal\user\UserInterface;

function MY_MODULE_user_presave(UserInterface $user) {
  if ($user->isNew() && !$user->hasRole('frontend_app')) {
    $user->addRole('frontend_app');
  }
}

About the Author

Goran Nikolovski is a senior developer with over 10 years of experience turning ideas into scalable digital products—from web platforms and mobile apps to AI-powered tools. He is passionate about clean code, creative problem-solving, and shaping the future of digital development.

AI Assistant