WP engine’s Node.js Edge Cache Purge Library for the headless WordPress platform

Francis Agulto Avatar

·

Efficient caching is essential for maintaining performance in modern web applications, but keeping cached content up-to-date can be challenging.  In this article, I will discuss how WP Engine’s Edge Cache Purge Library for Node.js addresses this by allowing targeted cache purging through specific paths or tags, rather than clearing the entire cache.

If you prefer the video format of this article, please access it here:

Prerequisites

Before reading this article, you should have the following prerequisites checked off:

  • Foundational knowledge of JavaScript frameworks
  • A WP engine headless WordPress platform account
  • Node.js

If you’re looking for a headless platform to develop on, you can get started with a WP Engine Headless WordPress sandbox site for free:

Understanding Edge Cache and Its Role in Headless WordPress

In order to understand the benefit of this feature by WP engine, let’s first define and discuss what edge cache is.

Edge caching refers to storing cached content at edge locations, which are servers distributed globally closer to users. This reduces latency by delivering content from the nearest server rather than the origin server, improving load times and overall user experience.

How It Differs from Other Caching Layers

You might ask yourself how it differs from other caching layers. In a headless WordPress setup using a JavaScript frontend framework and WPGraphQL, multiple caching layers exist:

  • Application-Level Caching: This involves caching GraphQL queries or API responses within the application. For example, in Next.js’s server-side rendering or incremental static regeneration. It focuses on reducing the need to repeatedly fetch data from the WordPress backend.
  • CDN Caching: Content Delivery Networks (CDNs) cache static assets like images, CSS, and JavaScript files at edge locations. This is similar to edge caching but focused on static resources.
  • Database Caching: WordPress can use database-level caching with object caches like Redis to speed up database queries and reduce server load.

Edge Cache vs. Other Caches

The main differences between edge cache versus other caching layers are as follows:

Edge Cache: Specifically stores whole pages or HTML responses at edge locations. It can be dynamically purged by paths or tags using tools like WP Engine’s Edge Cache Purge Library. This makes it highly efficient for frequently changing content, allowing rapid updates without waiting for other cache layers to expire.

Application and Database Caches: These are closer to the backend and primarily reduce server load by avoiding redundant data processing.

Benefits of Edge Cache in Headless WordPress

Here are the main benefits you get when using the edge cache library by WP engine:

  • Performance: Delivering cached content from locations near users significantly reduces latency.
  • Scalability: It handles high traffic efficiently without burdening the origin server.
  • Dynamic Purging: Allows for granular control over what gets purged and updated, ensuring content remains fresh without unnecessary full cache clears.

Setup and Installation With SvelteKit

In this example, let’s use SvelteKit (you can use any framework you want and it will work), a great frontend framework similar to Nuxt and Next.

  1. First, install and pull down the SvelteKit framework with npm create:
npm create svelte@latest
Code language: CSS (css)

2. Once you have a SvelteKit app spun up, navigate into the directory of your project and install the edge cache library:

npm install @wpengine/edge-cache 
Code language: CSS (css)

3. Now, ensure you have the necessary environment variables configured, such as authentication credentials and your WPGraphQL endpoint/WordPress endpoint.

4. In this example, let’s purge by path. Navigate to the src/routes folder. In the routes folder, create a folder called blog/[uri] . Once that is done, in the [uri] folder, create a +page.svelte file. You can drop this code block in or something similar to what you decide to use framework-wise:

<script>
  import { onMount } from 'svelte';
  
  let posts = [];
  let loading = true;

  async function fetchGraphQL(query = {}) {
    const queryParams = new URLSearchParams({ query }).toString();
    const response = await fetch(`${import.meta.env.VITE_GRAPHQL_ENDPOINT}?${queryParams}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`Network error: ${response.statusText}`);
    }
    return response.json();
  }

  const GET_POSTS_QUERY = `
    query GetPosts {
      posts(first: 5) {
        nodes {
          id
          title
          slug
          uri
          date
        }
      }
    }
  `;

  onMount(async () => {
    try {
      const { data, errors } = await fetchGraphQL(GET_POSTS_QUERY);
      if (errors) {
        console.error('Errors returned from server:', errors);
      } else {
        posts = data.posts.nodes;
      }
    } catch (error) {
      console.error('An error occurred:', error);
    } finally {
      loading = false;
    }
  });
</script>

{#if loading}
  <div class="flex justify-center items-center min-h-screen">
    <p>Loading...</p>
  </div>
{:else}
  <div class="bg-custom-dark min-h-screen text-hot-pink p-8">
    <h1 class="text-4xl mb-8 font-bold text-center">Fran's Headless WP with SvelteKit Blog Example</h1>
    <ul class="space-y-4">
      {#each posts as post}
        <li class="text-center">
          <a href={`/blog${post.uri}`} class="text-2xl hover:text-pink-600">{post.title}</a>
          {#if post.date}
            <p class="text-gray-500 text-sm">{new Date(post.date).toLocaleDateString()}</p>
          {:else}
            <p class="text-gray-500 text-sm">No date available</p>
          {/if}
        </li>
      {/each}
    </ul>
  </div>
{/if}
Code language: HTML, XML (xml)

This code block executes a single post detail page, dynamically grabbing the post data by its URI.

Just to be clear, this is meant to focus on the framework agnosticism of the headless WordPress platform and this edge cache library. It is not meant to be a SveltKit tutorial. With that being said, you should be able to follow along and use whatever dynamic route file you have with whatever framework you choose.

5. Now that we created the path we want to purge, let’s create the API route we will use to execute the purge logic. Navigate to src/routes and create an api/purge/+server.js folder and file. Add this code block:

// src/routes/api/+server.js
import { purgePaths } from '@wpengine/edge-cache';

export async function GET({ url }) {
    const uri = url.searchParams.get('uri'); // Extracting 'uri' parameter from the query string

    try {
        if (uri) {
            // Purge the specific blog path
            await purgePaths(`/blog/${uri}`);
            return {
                status: 200,
                body: { success: true, message: `Cache purged for /blog/${uri}` }
            };
        } else {
            return {
                status: 400,
                body: { success: false, message: 'URI is required' }
            };
        }
    } catch (error) {
        return {
            status: 500,
            body: { success: false, message: error.message }
        };
    }
}

Code language: JavaScript (javascript)

At the top of this file, we import the purgePaths function from the WP engine Edge Cache library, which is used to purge cache for specific paths.

Following that we define an async function that handles GET requests to that endpoint. Then we have a const that extracts the uri param from the query string for the request URL.

If the uri is provided, it calls the purgePath function with the full path, then returns a success response with status 200.

If uri is not present, it returns a 400 status with an error message indicating that the URI is required.

Following that, we catch any errors during the purge process and return a 500 status with the error message, indicating an internal server error occurred during the operation.

This version allows cache purging through a GET request by passing the uri parameter directly in the query string.

You would have a URL that looks something like this when you pass the URI parameter directly into the query string:

https:your-wpengine-site/api/purge?uri=some-blog-post

Once you have this endpoint, you can set it up in a webhook, for example, to automate the purge. This ensures that when a user visits a blog detail page, you can selectively purge the cache for that specific path, keeping your content up-to-date efficiently.

Conclusion

The WP engine Edge Cache Purge Library, allows you to manage edge cache dynamically and keep your content up-to-date with targeted purges. This setup offers a flexible, framework-agnostic solution that fits well with any Node. js-based application.

We hope you have a better understanding and grasp of the edge cache library. As always, we’re stoked to hear your feedback and what you are building in headless WordPress! Hit us up in our Discord!!