diff --git a/next-js/src/app/gb-revalidate/route.ts b/next-js/src/app/gb-revalidate/route.ts new file mode 100644 index 0000000..386a2a2 --- /dev/null +++ b/next-js/src/app/gb-revalidate/route.ts @@ -0,0 +1,10 @@ +import { NextRequest } from "next/server"; +import { revalidateTag } from "next/cache"; + +// Use a route handler to refresh all cache entries related to GrowthBook. +// GrowthBook SDK webhooks can be used to trigger this event immediately after +// making a change on the platform. +export const POST = (_req: NextRequest) => { + // TODO assert request is authorized from GrowthBook instance + revalidateTag("growthbook"); +}; diff --git a/next-js/src/app/server/combo/page.tsx b/next-js/src/app/server/combo/page.tsx index fc5b0c8..cbdca8a 100644 --- a/next-js/src/app/server/combo/page.tsx +++ b/next-js/src/app/server/combo/page.tsx @@ -1,8 +1,6 @@ import { createGB } from "@/lib/growthbook"; import ClientComponent from "./ClientComponent"; -export const revalidate = 3600; // refresh cache every hour - export default async function ServerCombo() { // create instance per request, server-side const gb = createGB(); diff --git a/next-js/src/lib/growthbook.ts b/next-js/src/lib/growthbook.ts index 82ce506..e813db0 100644 --- a/next-js/src/lib/growthbook.ts +++ b/next-js/src/lib/growthbook.ts @@ -1,4 +1,20 @@ -import { GrowthBook, Context } from "@growthbook/growthbook"; +import { GrowthBook, Context, setPolyfills } from "@growthbook/growthbook"; + +setPolyfills({ + fetch: ( + url: Parameters[0], + opts: Parameters[1] + ) => + fetch(url, { + ...opts, + next: { + // cache results for an hour at most (static pages) + revalidate: 3600, + // see route handler for revalidating cache tagged under 'growthbook' + tags: ["growthbook"], + }, + }), +}); // It's important to create a new instance per request when server-side to prevent // race condtions from occurring between different user requests.