A simple BunnyCDN Edge Script (Middleware) to automatically purge the BunnyCDN cache for your Ghost blog based on Ghost's native X-Cache-Invalidate header.
This script provides a lightweight alternative to running a separate proxy service (like the original ghost-cache-invalidation-proxy by Magic Pages, which inspired this approach) if your primary goal is simply to purge the BunnyCDN cache.
- Intercepts Origin Response: The script uses BunnyCDN's
onOriginResponsetrigger, which executes after your Ghost origin server responds but before BunnyCDN caches the response. - Detects Header: It checks the response headers from Ghost for the
X-Cache-Invalidateheader. - Parses Paths: If the header is found, it parses the value (which can be
/*for site-wide invalidation or specific paths like/post-slug/). - Calls Purge API: It uses the
fetchAPI to make direct calls to the BunnyCDN Purge API (https://api.bunny.net/purge?url=...) for each path identified, using your API key for authentication.
Ghost sends the X-Cache-Invalidate header reliably for various actions, including:
- Publishing/unpublishing posts or pages (
/*). - Editing content of published posts/pages (specific paths like
/post-slug/). - Changing themes or site settings (
/*). - Updating tags, labels, users (
/*). - Comment actions (specific path of the post).
- Simplicity: No separate proxy server/container to deploy, manage, or update.
- Leverages CDN: Runs directly on BunnyCDN's infrastructure.
- Direct Integration: Calls the BunnyCDN API directly.
- Resource Efficient: Avoids the need for resources to run a proxy.
- Copy the Script: Get the code from the
middleware.jsfile in this repository. - Navigate to Pull Zone: Log in to your BunnyCDN dashboard and go to the settings for the Pull Zone serving your Ghost site.
- Add Edge Rule: Go to the "Edge Rules" tab. Click "Add Edge Rule".
- Set Action: Choose the action "Execute EdgeScript".
- Paste Code: Give the script a name (e.g., "Ghost Cache Invalidation") and paste the full JavaScript code from
middleware.jsinto the editor. - Configure Environment Variables:
- Scroll down to the "Environment Variables" section within the Edge Rule settings.
- Click "Add Variable".
- Add
BUNNY_API_KEYand paste your actual BunnyCDN account API key as the value. (Required) - Optionally, click "Add Variable" again. Add
GHOST_PUBLIC_URLand set its value to your blog's full public base URL (e.g.,https://yourdomain.com). This is recommended to ensure correct purging of relative paths.
- Set Trigger:
- Add a trigger. A simple "Request URL" trigger matching
*(all requests) is usually sufficient. - Important: Ensure the "Execute Before Cache Lookup" option is disabled. The script needs to run after the origin responds.
- Add a trigger. A simple "Request URL" trigger matching
- Save: Save the Edge Rule. Make sure it's enabled.
Now, cache purging based on Ghost updates should happen automatically via BunnyCDN.