I've implemented kind of a page hit counter as REST request. The article page renders a JS into the page that does a jQuery.getJSON to the REST resource later.

So far that works fine. The page is delivered from cache (X-Drupal-Cache:"HIT") and the browser does an extra request to the REST resource (/api/v1/check/l/1?_format=json).

Unfortunately the REST handler is not called for guest user views. Instead, Drupal delivers the cached response. It only works for authenticated users.

For guest I get

Cache-Control:"must-revalidate, no-cache, private"
X-Drupal-Dynamic-Cache:"UNCACHEABLE"

BUT:

X-Drupal-Cache:"HIT"

And the REST handler is not executed. My REST response is

return (new ResourceResponse($rc))->addCacheableDependency(null);

Thanks

  • Put options: no_cache: TRUE into your rest route. – user21641 Jul 21 '16 at 10:15
up vote 3 down vote accepted

This is probably the page cache for anonymous users, which works independently from the dynamic cache.

You can disable it with this command:

\Drupal::service('page_cache_kill_switch')->trigger();

You can trigger this anywhere in your code and it will be valid for any response you send for the request. So this should also work for a REST response.

  • Yes, works! Thanks. I have inserted that trigger right before my ResourceResponse return, now it invalidates the page cache for the REST request only. Exactly what I need. ThumbsUp – Rainer Feike Jul 21 '16 at 10:00

I have a resource post (for anonymous). The above answers Didn't help me.

The following did :

$response = new ModifiedResourceResponse($result);
return $response;

Read more at ModifiedResourceResponse()

  • For anyone that might read this, this helped me in a GET resource as well, not just POST. – Joum Mar 17 '17 at 15:25
  • This should be the accepted answer. Thanks. – Toilal Oct 13 '17 at 9:13
  • Has this always been a problem? I swear this started recently for us (around 8.5.4). – atwixtor Sep 26 at 16:33

Try add 'addCacheableDependency' to 'ResourceResponse'

$response = new ResourceResponse($result);
$response->addCacheableDependency($result);
return $response;

Create Rest Resource for GET Method in Drupal 8

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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