Disable caching for custom block for anonymous users I have created a custom Block that extends BlockBase. I don't want the content to be cached for anonymous users (also not for authenticated users). To be more precise, caching would be fine but depending on some url query argument. In my case the url contains a parameter 'mode' (?mode=1 or ?mode=2 and so on). Depending on the parameter the content of the block varies.

I added the following function:

 public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), array('url.query_args:mode'));
  }


Still the block content seems to be cached. Is it neccessary to disable the internal page cache module? Actually I don't want to globally disable caching, I just want my block to be cached correctly depending on the url parameter mode.
The problem is, you don't render the block in a normal way and Display Suite is obviously not able to retrieve the plugin cache metadata. 

Most times it is a better option to include the cache metadata in the render array together with the data it depends on:

public function build() {
  $build = [];
  $request = \Drupal::request();
  $mode = $request-&gt;query-&gt;get('mode');
  $build['mode'] = [
    '#markup' =&gt; t('The query argument is mode=@mode.', ['@mode' =&gt; $mode]),
  ];
  $build['#cache']['contexts'][] = 'url.query_args:mode';
  return $build;
}


Then the cache metadata can bubble up, no matter where and how this block content is embedded.