Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-cache-interceptor-index-route.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@opennextjs/aws": patch
---

Fix cache interception for index routes by normalizing the route path to `/` while reading the generated cache asset from `/index`.
22 changes: 9 additions & 13 deletions packages/open-next/src/core/routing/cacheInterceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,23 +265,23 @@ export async function cacheInterceptor(
localizedPath = localizedPath.replace(/\/$/, "");

// Then we decode the path params
localizedPath = decodePathParams(localizedPath);
localizedPath = decodePathParams(localizedPath) || "/";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

localizedPath is used in the rest of the files in a couple of places (i.e. hasBeenRevalidated, isStale).
Did you check if it has the right value there ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review! It seems that I indeed missed the usage in hasBeenRevalidated and isStale, which should use the cacheKey.

I've added some tests to validate the behavior:

  • /albums still uses /albums for the cache lookup and 'original-mode' cache checks, so existing non-index behavior is unchanged
  • The new index cache key test fails without the route normalization, and now passes.
  • The same index cache key test failed after my initial fix, because hasBeenRevalidated and isStale still received /
    • It now verifies that 'original-mode' tag cache checks use /index
  • The new stale index route path test verifies that background revalidation still uses the public route /, not the cache key /index

As you can imagine this code is all new to me, so let me know if there is anything I can improve (:


// The route is keyed as `/` in the prerender manifest, but the generated
// cache asset for the app index route is uploaded as `/index`.
const cacheKey = localizedPath === "/" ? "/index" : localizedPath;

debug("Checking cache for", localizedPath, PrerenderManifest);

const isISR =
Object.keys(PrerenderManifest?.routes ?? {}).includes(
localizedPath ?? "/",
) ||
Object.keys(PrerenderManifest?.routes ?? {}).includes(localizedPath) ||
Object.values(PrerenderManifest?.dynamicRoutes ?? {}).some((dr) =>
new RegExp(dr.routeRegex).test(localizedPath),
);
debug("isISR", isISR);
if (isISR) {
try {
const cachedData = await globalThis.incrementalCache.get(
localizedPath ?? "/index",
);
const cachedData = await globalThis.incrementalCache.get(cacheKey);
debug("cached data in interceptor", cachedData);

if (!cachedData?.value) {
Expand All @@ -295,7 +295,7 @@ export async function cacheInterceptor(
) {
const _hasBeenRevalidated = cachedData.shouldBypassTagCache
? false
: await hasBeenRevalidated(localizedPath, tags, cachedData);
: await hasBeenRevalidated(cacheKey, tags, cachedData);

if (_hasBeenRevalidated) {
return event;
Expand All @@ -305,11 +305,7 @@ export async function cacheInterceptor(
// Check if the cache entry is stale (valid but needs background revalidation)
const _isStale = cachedData.shouldBypassTagCache
? false
: await isStale(
localizedPath,
tags,
cachedData.lastModified ?? Date.now(),
);
: await isStale(cacheKey, tags, cachedData.lastModified ?? Date.now());

const host = event.headers.host;
switch (cachedData?.value?.type) {
Expand Down
78 changes: 78 additions & 0 deletions packages/tests-unit/tests/core/routing/cacheInterceptor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ vi.mock("@opennextjs/aws/adapters/config/index.js", () => ({
NextConfig: {},
PrerenderManifest: {
routes: {
"/": {
initialRevalidateSeconds: 120,
srcRoute: "/",
dataRoute: "/index.rsc",
},
"/albums": {
initialRevalidateSeconds: false,
srcRoute: "/albums",
Expand Down Expand Up @@ -144,6 +149,15 @@ describe("cacheInterceptor", () => {

const body = await fromReadableStream(result.body);
expect(body).toEqual("Hello, world!");
expect(incrementalCache.get).toHaveBeenCalledWith("/albums");
expect(tagCache.getLastModified).toHaveBeenCalledWith(
"/albums",
expect.any(Number),
);
expect(tagCache.isStale).toHaveBeenCalledWith(
"/albums",
expect.any(Number),
);
expect(result).toEqual(
expect.objectContaining({
type: "core",
Expand All @@ -159,6 +173,70 @@ describe("cacheInterceptor", () => {
);
});

it("should retrieve index app router content from the index cache key", async () => {
const event = createEvent({
url: "/",
});
incrementalCache.get.mockResolvedValueOnce({
value: {
type: "app",
html: "Index page",
},
lastModified: new Date("2024-01-01T23:59:30Z").getTime(),
});

const result = await cacheInterceptor(event);

const body = await fromReadableStream(result.body);
expect(body).toEqual("Index page");
expect(incrementalCache.get).toHaveBeenCalledWith("/index");
expect(tagCache.getLastModified).toHaveBeenCalledWith(
"/index",
expect.any(Number),
);
expect(tagCache.isStale).toHaveBeenCalledWith("/index", expect.any(Number));
expect(result).toEqual(
expect.objectContaining({
headers: expect.objectContaining({
"cache-control": "s-maxage=90, stale-while-revalidate=2592000",
"x-opennext-cache": "HIT",
}),
}),
);
});

it("should revalidate stale index content using the route path", async () => {
const event = createEvent({
url: "/",
});
incrementalCache.get.mockResolvedValueOnce({
value: {
type: "app",
html: "Index page",
},
lastModified: new Date("2024-01-01T23:57:00Z").getTime(),
});

const result = await cacheInterceptor(event);

expect(incrementalCache.get).toHaveBeenCalledWith("/index");
expect(queue.send).toHaveBeenCalledWith(
expect.objectContaining({
MessageBody: expect.objectContaining({
url: "/",
}),
}),
);
expect(result).toEqual(
expect.objectContaining({
headers: expect.objectContaining({
"cache-control": "s-maxage=1, stale-while-revalidate=2592000",
"x-opennext-cache": "STALE",
}),
}),
);
});

it("should take no action when tagCache lasModified is -1 for app type", async () => {
const event = createEvent({
url: "/albums",
Expand Down
Loading