Headless Kirby to purge cache using hooks (Netlify)

Hello,

I’m improving a nuxt.js website I naively deployed to Netlify without leveraging the full potential of a cache-layer…

I want to setup my headless Kirby so it purges the cache whenever I update or create a page. In my config I’ve put this together to make a call to the Netlify api for a purge:

return: [
    'hooks' => [
        'page.update:after' => function ($page) {
            if (env('KIRBY_ENV') !== 'production') {
                throw new Exception('Page updated in ' . env('KIRBY_ENV'), 0);
                return;
            }
            $this->purgeNetlifyCache([env('NETLIFY_API_KEY')]);
        },
        'page.create:after' => function ($page) {
            if (env('KIRBY_ENV') !== 'production') {
                throw new Exception('Page created in ' . env('KIRBY_ENV'), 0);
                return;
            }
            $this->purgeNetlifyCache([env('NETLIFY_API_KEY')]);
        },
    ]
]

function purgeNetlifyCache($tags)
{
    $SITE_ID = env('NETLIFY_SITE_ID');
    $endpoint = `https://api.netlify.com/api/v1/sites/$SITE_ID/purge`;
    $apiKey = 'YOUR_NETLIFY_API_KEY';
    $data = json_encode(['tags' => $tags]);

    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response);
}

]

Since I’ve never worked with hooks I’m not quite sure what will happen… Especially since I don’t want to mess things up… I’m still a bit scared about caching :sweat_smile:

I see some weird syntax errors in the above, is that the code you have in your config as posted, or is that just a pasting issue? e.g. return :, missing semi-colon after the return array, stray closing bracket after the function…

I don’t really understand what the problem is apart from thoses issues? Does the code work when executed?

Excuse me :slight_smile: That was clearly a pasting issue. My config has none of those issues :grin:

However, when I test this while in development (localhost in this case) the page is not saved. What Am I misunderstanding here? I thought this hook would fire after it’s saved(?)

Ecuse me again… the throw exceptions in the hooks prevent the page from saving. I’m okay with a error_log()