documentation icon indicating copy to clipboard operation
documentation copied to clipboard

Bypassing Cache with HTTP Headers Doc Update

Open rowan-nicetouch opened this issue 2 years ago • 2 comments

Re: Bypassing Cache with HTTP Headers

Priority: Medium

Issue Description:

I think that there may be a bug in the WordPress code example in the Bypassing Cache with HTTP Headers documentation. I recently needed to ensure that an endpoint under /wp-json was not cached. I found the article mention ed above and followed the instructions however, the endpoint in question was still cached. After reading through the code and tracing the hooks through WordPress core, I was able to discern a potential issue and create a solution.

The issue was identified in this block which is hooked into core WordPress filter rest_post_dispatch:

// Re-define the send_header value with any custom Cache-Control header
function filter_rest_post_dispatch_send_cache_control( $response, $server ) {
    $server->send_header( 'Cache-Control', 'no-cache, must-revalidate, max-age=0' );
    return $response;
}

Here, the header is immediately sent by calling a method of parameter 2 $server. Producing an effect goes against the semantics of a filter which is intended to conditionally modify and return the value passed as parameter one.

Also, It was not producing the results that I was expecting. I believe that this is because it sends a Cache-Control header too early and, somewhere down the line, a subsequent call to header() overwrites it.

I was able to refactor the example to call the header() method of parameter one $response instead. This method stores the header in memory instead of sending it right away.

function filter_rest_post_dispatch_send_cache_control( $response, $server ) {
  $response->header('Cache-Control', 'no-cache, must-revalidate, max-age=0');
  return $response;
}

Suggested Resolution

Update the documentation incorporating a working WordPress solution for bypassing cache in REST API requests,

rowan-nicetouch avatar Sep 11 '23 15:09 rowan-nicetouch