Fixing a Surge cache issue with ActivityPub

wee.press is a WordPress site that uses the ActivityPub plugin to add functionality to interact with Fediverse platforms, like Mastodon. This makes it possible for people to directly follow posts without visiting the web site. But after my last post, some people told me that the post was returning raw code, not the regular web page. Oh no 😱!

I suspected this could be caused by caching. Only sometimes the post was displaying code. And this is a typical issue, because there are only two hard problems in computer science:

  1. Cache invalidation
  2. Naming things
  3. Off-by-one errors

This site uses the Surge caching plugin. I remembered reading about this problem somewhere. After some duckduckgoing, I found the post that Dominik Schilling wrote about the HTTP Accept header. Turns out that you can save different caches based on the requested content. For ActivityPub this would be application/activity+json, and not text/html.

To change the caching behaviour for Surge, you will have to create a caching file. You are free to name this file and where to put it. For example, you can call it cache-config.php and put it next to the wp-config.php file. In this file you can define the different variants that should be cached. For this site, a variant for html (the default) and json are defined. Below is the code to achieve this.

<?php
$config['variants']['representation'] = 'html';
if (
  isset( $_SERVER['HTTP_ACCEPT'] ) &&
  preg_match(
    '%^application\/((activity|ld)\+)?json$%i',
    $_SERVER['HTTP_ACCEPT']
  ) 
) { 
  $config['variants']['representation'] = 'json';
}

return $config; 

To activate the file, you will have define the location of the caching file in the wp-config.php.

define( 'WP_CACHE_CONFIG', __DIR__ . '/cache-config.php' );

WP_CACHE_CONFIG is a specific setting for the Surge plugin, not a global setting, despite what the name might suggest.

So now all problems are gone (hopefully) and you can read the posts like you would expect.