How to define a new cache context for a node I am preprocessing a node with some data, i want to define a new cache context  based on this data.

function hook_preprocess_node(&amp;$variables) {
    $variables['change'] = rand(0,5);
}


Once i have defined the new context i think i shuold be able to use it as follows.

function  hook_entity_build_defaults_alter(array &amp;$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode) {
  if($entity-&gt;getType() == 'page'){
    $build['#cache']['contexts'][] = 'change';
  }
}


I can't seem to find out how to define a brand new cache context based on the data in my preprocess so that i can use it in hook_entity_build_defaults_alter();
You will need to define a cache context in yourmodule/src/Context. This will be a class implementing CacheContextInterface, as described in the docs here (see 'How to recognize, discover and create?).

If you search for implements CacheContextInterface in your code base you should be able to see some examples. The class will provide getContext() and getCacheableMetadata() methods.