Revalidate Cache in Next.js Starter Storefront

In this guide, you'll learn about the general approach to revalidating cache in the Next.js Starter Storefront when data is updated in the Medusa application.

Approach Overview#

By default, the data that the Next.js Starter Storefront retrieves from the Medusa application is cached in the browser. This cache is used to improve the performance and speed of the storefront.

In some cases, you may need to revalidate the cache in the storefront when data is updated in the Medusa application. For example, when a product variant's price is updated in the Medusa application, you may want to revalidate the cache in the storefront to reflect the updated price.

You're free to choose the approach that works for your use case, custom requirements, and tech stack. The approach that Medusa recommends is:

  1. Create a subscriber in the Medusa application that listens for the event that triggers the data update. For example, you can listen to the product.updated event.
  2. In the subscriber, send a request to a custom endpoint in the Next.js Starter Storefront to trigger the cache revalidation.
  3. Create the custom endpoint in the Next.js Starter Storefront that listens for the request from the subscriber and revalidates the cache.
Tip: Refer to the Events Reference for a full list of events that the Medusa application emits.

Example: Revalidating Cache for Product Update#

Consider you want to revalidate the cache in the Next.js Starter Storefront whenever a product is updated.

Start by creating the following subscriber in the Medusa application:

Code
1import type {2  SubscriberArgs,3  SubscriberConfig,4} from "@medusajs/framework"5
6export default async function productUpdatedHandler({7  event: { data },8  container,9}: SubscriberArgs<{ id: string }>) {10  // send request to next.js storefront to revalidate cache11  await fetch(`${process.env.STOREFRONT_URL}/api/revalidate?tags=products`)12}13
14export const config: SubscriberConfig = {15  event: "product.updated",16}

In the subscriber, you send a request to the custom endpoint /api/revalidate in the Next.js Starter Storefront. The request includes the query parameter tags=product-${data.id} to specify the cache that needs to be revalidated.

Note: Make sure to set the STOREFRONT_URL environment variable in the Medusa application to the URL of the Next.js Starter Storefront.

Then, create in the Next.js Starter Storefront the custom endpoint that listens for the request and revalidates the cache:

src/app/api/revalidate/route.ts
1import { NextRequest, NextResponse } from "next/server"2import { revalidatePath } from "next/cache"3
4export async function GET(req: NextRequest) {5  const searchParams = req.nextUrl.searchParams6  const tags = searchParams.get("tags") as string7
8  if (!tags) {9    return NextResponse.json({ error: "No tags provided" }, { status: 400 })10  }11
12  const tagsArray = tags.split(",")13  await Promise.all(14    tagsArray.map(async (tag) => {15      switch (tag) {16        case "products":17          revalidatePath("/[countryCode]/(main)/store", "page")18          revalidatePath("/[countryCode]/(main)/products/[handle]", "page")19        // TODO add for other tags20      }21    })22  )23
24  return NextResponse.json({ message: "Revalidated" }, { status: 200 })25}

In this example, you create a custom endpoint /api/revalidate that revalidates the cache for paths based on the tags passed as query parameters.

You only handle the case of the products tag in this example, but you can extend the switch statement to handle other tags as needed.

To revalidate the cache, you use Next.js's revalidatePath function. Learn more about in the Next.js documentation.

Test it Out#

To test out this mechanism, run the Medusa application and the Next.js Starter Storefront.

Then, update a product in the Medusa application. You can see in the Next.js Starter Storefront's terminal that a request was sent to the /api/revalidate endpoint, meaning that the cache was revalidated successfully.

Was this page helpful?
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break