4

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

1
  • Put options: no_cache: TRUE into your rest route.
    – user21641
    Jul 21, 2016 at 10:15

3 Answers 3

4

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.

1
  • 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 Jul 21, 2016 at 10:00
5

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()

2
  • For anyone that might read this, this helped me in a GET resource as well, not just POST.
    – Joum
    Mar 17, 2017 at 15:25
  • Has this always been a problem? I swear this started recently for us (around 8.5.4).
    – atwixtor
    Sep 26, 2018 at 16:33
0

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 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.