Getting Started with Optimizely SaaS Core and Next.js Integration: Testing Content Updates

In our previous blog post Getting Started with Optimizely SaaS Core and Next.js Integration, we created the Start Page with two properties: Title and Description. Now, let’s delve into testing what happens when you update content from the Optimizely CMS. When you modify the Title on the page item and publish the changes, you may notice that the new content is not immediately reflected on the website.

The Problem: Apollo Client’s Local Caching

When utilizing the Apollo client in your Next.js application, one notable aspect is the local caching of responses from any query sent to the server. By default, Next.js caches these responses locally. This caching mechanism is a valuable feature as it significantly enhances the speed of our application.

The Advantage of Local Caching

The local caching mechanism in Next.js plays a crucial role in optimizing application performance. Instead of redundantly querying the server for data that is already present on the client side, Apollo retrieves the requested data directly from the local cache. This not only reduces the latency associated with server queries but also contributes to a smoother and more responsive user experience.

The Catch: Content Update Challenges

However, this local caching strategy can present challenges when it comes to reflecting real-time updates from external sources, such as content changes made in the Optimizely CMS. In our scenario, after modifying the Title in the CMS and publishing the changes, Next.js, might still serve the cached content instead of fetching the updated data from the server.

Addressing the Challenge with revalidate

To overcome this challenge, we used the revalidate parameter in the client query. While this parameter serves the purpose of forcing cache revalidation at regular intervals (in this case, every 5 seconds), it’s not the ideal long-term solution. In a production environment, we would aim for more targeted cache updates triggered by specific events, such as content authoring actions in the CMS.

Implementing revalidate in Code

Let’s take a closer look at how the revalidate parameter is implemented in the code:

var data = await client.query({
  query: gql`
    query MyQuery {
      StartPage {
        items {
          Title
          Description
        }
      }
    }
  `,
  context: {
    fetchOptions: {
      next: { revalidate: 5 },
    },
  },
});

In this snippet, the revalidate parameter is set to 5 seconds, indicating that the cache will be revalidated at this interval. While this approach facilitates testing updates on the website, keep in mind that it’s not the optimal solution for production.

To learn more about optimizing your Next.js and Apollo integration, you can explore additional insights in the blog post Why Use Next.js with Apollo? from LogRocket.

Future Considerations: Implementing a Webhook and API for Efficient Cache Refresh

In a production setting, continually fetching data at fixed intervals can be resource-intensive and suboptimal. Instead, consider creating an API to efficiently revalidate all data, eliminating the need for the revalidate parameter every few seconds.

To implement this approach:

Create the folders api/revalidate in your Next.js project if they don’t exist. Inside this folder, create a file named route.tsx.

Use the following code in api/revalidate/route.tsx:

import { NextRequest, NextResponse } from "next/server";
import { revalidatePath } from "next/cache";

export async function POST(request: NextRequest) {
  revalidatePath("/", "layout");
  return Response.json({ revalidated: true, now: Date.now() });
}

Access the API endpoint by using the URL http://localhost:3000/api/revalidate.

In this code snippet, the revalidatePath function is used to specify the path and layout that should be revalidated. This approach allows for a more targeted and controlled cache refresh.

Stay tuned for further insights and best practices in optimizing your Optimizely SaaS Core and Next.js integration!

Leave a comment