In drupal 8, how do you load the node object in hook_preprocess_page() when on the node preview page?

I had a bug come up where this standard way of loading the current node object was failing on the preview page:

$node = \Drupal::routeMatch()->getParameter('node');

1 Answer 1


If you need to use the node object in hook_preprocess_page() on the preview page, you need to use the "node_preview" parameter, instead of the "node" parameter:

function mymodule_preprocess_page(&$vars) {

  $route_name = \Drupal::routeMatch()->getRouteName();

  if ($route_name == 'entity.node.canonical') {
    $node = \Drupal::routeMatch()->getParameter('node');
  elseif ($route_name == 'entity.node.preview') {
    $node = \Drupal::routeMatch()->getParameter('node_preview');
  • I was wondering about the preview node for at least a year! Is parameter node_preview something new? Commented Oct 17, 2017 at 9:34
  • 1
    It's loaded from tempStoreFactory, since the node object wouldn't exist in preview. So it saves it as a separate object with a uuid, that is then retrieved on the preview page. It's annoying that the variable name is different, but it's a signal that it's not a real node. So things like $node_preview->url() won't work. I'm going to have to fix some bugs related to that in my current project. See nodeForm::preview() for the code that saves the node object and redirects.
    – oknate
    Commented Oct 17, 2017 at 14:17

Your Answer

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

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