How to prevent caching of field element data in custom field formatter? I have a custom field formatter that performs dynamic calculations to determine the output. However, for anonymous user's the previous data is always stored until a cache clear is performed.

in the field formatter viewElements() function I have the $elements #cache max-age set to 0. I thought this would resolve the issue but it does not. Am I missing something?

 public function viewElements(FieldItemListInterface $items, $langcode) {


    $elements = [];

    foreach ($this-&gt;getEntitiesToView($items, $langcode) as $delta =&gt; $file) {
      // Check if gate cookie is set

      if (isset($_COOKIE['Drupal_visitor_resource_gate'])){

        //$tags = $file-&gt;getCacheTags();
        //Cache::invalidateTags($tags);
        $item = $file-&gt;_referringItem;

        $elements[$delta] = [
          '#theme' =&gt; 'file_link',
          '#file' =&gt; $file,
          '#description' =&gt; $this-&gt;getSetting('use_description_as_link_text') ? $item-&gt;description : NULL,
          '#cache' =&gt; [
            'max-age' =&gt; 0,      
          ],
        ];

        // Pass field item attributes to the theme function.
        if (isset($item-&gt;_attributes)) {
          $elements[$delta] += ['#attributes' =&gt; []];
          $elements[$delta]['#attributes'] += $item-&gt;_attributes;
          // Unset field item attributes since they have been included in the
          // formatter output and should not be rendered in the field template.
          unset($item-&gt;_attributes);
        }
        $elements['#cache']['max-age'] = 0;
        return $elements;
      }else{
...
}
For anonymous traffic in general there are probably better solutions client-side. If you want to build this server-side in Drupal then better use a session, this will pass the built in page cache for anonymous traffic.

If you want to handle your own cookies you have to uninstall the Internal Page Cache and cache the pages only in the Internal Dynamic Page Cache. Then for better caching performance set a cache context for the cookie instead of max-age:

  $elements['#cache']['contexts'][] = 'cookies:Drupal_visitor_resource_gate';