Drupal 8 & 9 check if current page is user

You may want to check programmatically if you are on a user page or profile in Drupal 8 or 9. Use Drupal’s routeMatch to grab user. Then check if $user is an instance of user. Execute your code on that page.

$user = \Drupal::routeMatch()->getParameter('user');
if ($user instanceof \Drupal\user\UserInterface) {
  // It's a user page!
}
Posted in Drupal, Drupal 8, Drupal 9.