Purge StackPath CDN Cache with GitHub Actions: Automated Deploy Guide

by Fahim

You push a frontend fix, verify your CI build passed, open your production site, and there it is: yesterday’s broken CSS. You hard-refresh. Still broken. Edge nodes are still holding onto stale assets with an 86400 TTL.

I hit this exact problem deploying a client’s static portal. The build and rsync finished in 40 seconds flat, but end users kept loading old JS bundles for hours unless someone logged into the StackPath dashboard and manually cleared the cache. We can fix this permanently with a simple curl script hooked straight into GitHub Actions.

Purge StackPath CDN Cache with GitHub Actions: Automated Deploy Guide
Purge StackPath CDN Cache with GitHub Actions: Automated Deploy Guide

The StackPath Authentication Architecture

StackPath doesn’t give you static API keys for edge operations. Instead, their v1 API uses an OAuth2 client credentials grant: you pass a Client ID and Client Secret, and they hand back a short-lived bearer token.

Once you’ve got that bearer token, you make a second call to invalidate the cache for your specific CDN site ID. The token expires in an hour, but our runner only needs it for about ten seconds anyway.

You’ll need three values from the StackPath portal before touching YAML:

  • Stack ID: The UUID representing your top-level account or organization container.
  • Site ID: The UUID for the specific CDN site you’re purging.
  • API Client ID & Secret: Generated under your user profile’s API Management section.

You can grab your Site ID right out of the browser URL bar when clicking into your site settings. If you already ran through our guide to connect a Namecheap domain to Hostinger with StackPath CDN, you probably have these IDs stashed in your password manager already.

Setting Up GitHub Secrets

Never bake credentials into workflow files. Add them as encrypted repository secrets so GitHub passes them directly as environment variables to the runner.

Head to your repo, go to Settings > Secrets and variables > Actions, and add these four secrets:

  1. STACKPATH_CLIENT_ID: Your API client ID string.
  2. STACKPATH_CLIENT_SECRET: The secret key from the same API pair.
  3. STACKPATH_STACK_ID: The UUID from your StackPath overview page.
  4. STACKPATH_SITE_ID: The UUID of the site you want to wipe.

Watch out for trailing spaces or hidden newlines when copy-pasting into GitHub’s UI. StackPath’s OAuth endpoint will kick back a generic 401 Unauthorized without any helpful debug clues if a newline sneaks in.

Creating the Purge Script

You can cram curl calls straight into your workflow YAML, but debugging multi-line curl syntax inside GitHub Actions is painful. I prefer keeping the purge logic in an isolated shell script at .github/scripts/purge-stackpath.sh.

Here’s the script to handle authentication, parse the token with jq, and fire the purge request:

#!/usr/bin/env bash
set -euo pipefail
if [[ -z "${SP_CLIENT_ID:-}" || -z "${SP_CLIENT_SECRET:-}" || -z "${SP_STACK_ID:-}" || -z "${SP_SITE_ID:-}" ]];
then
echo "Error: Missing required environment variables." >&2
exit 1
fi
echo "Requesting bearer token from StackPath OAuth endpoint..."
AUTH_RESPONSE=$(curl -s -X POST https://gateway.stackpath.com/identity/v1/oauth/token 
-H "Content-Type: application/json" 
-d "{ "client_id": "${SP_CLIENT_ID}", "client_secret": "${SP_CLIENT_SECRET}", "grant_type": "client_credentials" }")
ACCESS_TOKEN=$(echo "${AUTH_RESPONSE}" | jq -r '.access_token // empty')
if [[ -z "${ACCESS_TOKEN}" ]];
then
echo "Failed to fetch access token. Response: ${AUTH_RESPONSE}" >&2
exit 1
fi
echo "Token received. Sending purge request for Site ID: ${SP_SITE_ID}..."
PURGE_RESPONSE=$(curl -s -w "%{http_code}" -o /tmp/purge_out.json 
-X DELETE "https://gateway.stackpath.com/cdn/v1/stacks/${SP_STACK_ID}/sites/${SP_SITE_ID}/purge" 
-H "Accept: application/json" 
-H "Content-Type: application/json" 
-H "Authorization: Bearer ${ACCESS_TOKEN}" 
-d '{"items": [{"recursive": true, "url": "/"}]}')
if [[ "${PURGE_RESPONSE}" -ne 200 && "${PURGE_RESPONSE}" -ne 202 ]];
then
echo "Purge failed with HTTP status: ${PURGE_RESPONSE}" >&2
cat /tmp/purge_out.json >&2
exit 1
fi
echo "StackPath cache purge initiated successfully!"

Remember to make it executable before committing: chmod +x .github/scripts/purge-stackpath.sh. The script relies on standard POSIX shell tools plus the jq command-line JSON processor, which is already installed on all standard Ubuntu GitHub runners.

The GitHub Actions Workflow

Now wire this up to execute whenever you push or merge into main. The workflow builds your frontend, syncs or uploads the build output to your server, and then fires off the purge script.

Drop this into .github/workflows/deploy.yml:

name: Build, Deploy, and Purge Cache on: push: branches: - main jobs: deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: 20 cache: 'npm' - name: Install dependencies and build run: | npm ci npm run build - name: Deploy to Origin Server run: | echo "Deploying build output to origin server..." # Replace this block with your rsync, scp, or S3 deployment command - name: Purge StackPath CDN Cache env: SP_CLIENT_ID: ${{ secrets.STACKPATH_CLIENT_ID }} SP_CLIENT_SECRET: ${{ secrets.STACKPATH_CLIENT_SECRET }} SP_STACK_ID: ${{ secrets.STACKPATH_STACK_ID }} SP_SITE_ID: ${{ secrets.STACKPATH_SITE_ID }} run: bash .github/scripts/purge-stackpath.sh

Order of operations matters here. The cache only purges after the deploy step finishes cleanly. If your build breaks or your upload step errors out, the pipeline aborts before hitting the purge step, which keeps your existing edge cache intact rather than leaving visitors with a half-broken deploy.

Selective Cache Purging vs Full Site Purge

The script above sends {"items": [{"recursive": true, "url": "/"}]}. That’s a full wipe. It flushes every edge node globally, meaning the CDN has to re-fetch HTML, CSS, images, and fonts directly from your origin.

On small sites, a full wipe is harmless. On high-traffic apps, it can cause a cache stampede: thousands of simultaneous requests slamming your origin server for heavy un-cached assets all at once. If your backend can’t handle sudden spikes, read through our guide on how to prevent CDN cache stampedes with Origin Shield and stale-while-revalidate.

To purge just the critical paths (like your HTML entry point and app manifest) while keeping images warm, modify the JSON payload in your curl command:

{ "items": [ { "url": "/" }, { "url": "/index.html" }, { "recursive": true, "url": "/assets/" } ]
}

Targeting specific paths keeps static vendor bundles and large media cached at the edge while immediately delivering your freshly built app shell to users.

Handling Query Strings and Cache Invalidation

A quick gotcha I ran into: if your bundler hashes assets via query parameters like bundle.js?v=1.0.4 instead of changing the filename (like bundle.1.0.4.js), StackPath treats those URLs as distinct cache keys depending on your edge settings.

If your edge isn’t stripping query strings, users loading an old URL variation might still get stale code. Take a look at our walkthrough on how to ignore query strings on static assets in StackPath CDN so you don’t chase phantom caching bugs across releases.

Common Pitfalls and How I Fixed Them

A few runtime errors I hit while dialing this in, and how to resolve them quickly:

1. The 401 Unauthorized Response

If step one fails against /identity/v1/oauth/token, double-check these two common culprits:

  • You grabbed Stack API credentials instead of platform OAuth API credentials. StackPath separates permissions. Make sure the client has full CDN access.
  • Accidental whitespace or quotes when pasting secrets into GitHub. Wipe the secret and paste raw plaintext.

2. The 404 Not Found on Purge

If you get an OAuth token back with a 200 OK, but the purge call returns a 404, check your URL. The route strictly expects both IDs in this format:

https://gateway.stackpath.com/cdn/v1/stacks/{stack_id}/sites/{site_id}/purge

It’s easy to accidentally swap the Stack ID and Site ID. The Stack ID belongs to your account container; the Site ID belongs to the edge CDN service inside it.

3. CORS Headers Dropping Post-Purge

If your frontend loads web fonts or cross-origin assets, wiping the cache can expose origin misconfigurations. If your origin doesn’t send CORS headers on cold requests, StackPath caches that missing-header response. If fonts fail to render after a fresh purge, check out how to fix CORS errors on web fonts and static assets in StackPath CDN.

Verifying Cache Purges with cURL

Don’t rely on your browser to test if the purge worked. Local disk caches and aggressive 304 handling will make you think your CDN is broken when it isn’t.

Use curl in your terminal to see exactly what StackPath’s edge servers are returning:

curl -I https://www.yourdomain.com/

Check the cache header in the output:

HTTP/2 200
server: StackPath
date: Wed, 24 May 2024 14:18:22 GMT
content-type: text/html; charset=UTF-8
x-cache: MISS
x-hw: 1684937902.dpo016.pa2.t,1684937902.cds022.pa2.c

Immediately after your GitHub Action runs, the first request should return x-cache: MISS. Run the exact same command a second time: you should immediately get x-cache: HIT. That confirms the edge cleared the old asset, fetched the new build from your origin, and primed the edge for everyone else.

Frequently Asked Questions

Does purging the CDN cache cost extra money?

No. API purges are included in your StackPath service plan. The only real cost is origin bandwidth if you do frequent full-site wipes and force every edge node to pull assets again.

How long does it take for a StackPath cache purge to take effect?

In practice, it propagates globally within 150ms to 400ms across their PoPs. By the time your deployment notification hits Slack, the edge nodes are already cleared.

Can I purge only a specific file like styles.css?

Yes. Swap {"recursive": true, "url": "/"} in your purge payload with {"url": "/css/styles.css"}.

Can I run this purge script inside GitLab CI or Bitbucket Pipelines?

Yes. The script in .github/scripts/purge-stackpath.sh only requires bash, curl, and jq. Pass the same four environment variables in GitLab CI or Bitbucket Pipelines and it works out of the box.

Next Steps

With automated purges running on every deploy, you never have to manually clear CDN caches or explain stale bundles to clients again. If you’re managing complex routing or multi-tenant setups, check out how to configure wildcard subdomains in Namecheap DNS for dynamic web apps.

all_in_one_marketing_tool