I think on Drupal 7 I had previously used something like menu_get_object() to find out what content I was on. For example, with mysite.com/content/my-page, it would tell me that this was a node, its content type, its ID, etc.

Ideally I'm trying to do it even if the URL is the site's front page, I'd like to be able to reverse engineer what content it is showing me.

  • What's your end goal? Knowing that might get you suggestions for different (perhaps better) approaches
    – Clive
    May 24, 2022 at 16:23
  • @Clive, I already have a system that is sending analytics data based on the URL the user is on, but it can get confused if the default homepage is set to something else within the site, because they could have visited the homepage anonymous or authenticated. Unfortunately I'm not building it for a once use case, it's for multiple sites, so that's why I want something kinda open-ended for any of my platforms I send it to May 24, 2022 at 16:31
  • Which is why I wanted to see if there was an easy enough way to get Drupal to tell me what page you are on, so that I could also send that data, as well as just my URL May 24, 2022 at 16:32
  • Ah I see, that makes sense. I think that's quite difficult to do generically, as the answer below mentions you can do it per-entity type easily enough but I think you'll need to test for all of the different things the page could be manually, rather than Drupal telling you
    – Clive
    May 25, 2022 at 9:24

1 Answer 1


You are looking for a route parameter, which is automatically upcasted to an entity object if you are on an entity route.

For example on a node route:

use Drupal\node\NodeInterface;

  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof NodeInterface) {
    $content_type = $node->getType();
    $id = $node->id();
  • Ah excellent, thank you May 25, 2022 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.