Repository navigation
use cache not preventing repeated external API calls in dynamic route (Next.js 16) #93396
|
Goal: I have a function that is: pure / stateless I expect this to be cached globally and reused across requests. import "server-only";
import { createServerSupabaseClient } from "@/src/lib/supabase/supabase-server";
import {
CourseOutline,
CourseChapter,
CourseUnitOutline,
PracticeSetOutline,
} from "@/src/types/course-outline.types";
import { CourseAccess } from "@/src/lib/services/courses/course-access";
import { cacheLife, cacheTag } from "next/cache";
import { createStaticSupabaseClient } from "@/src/lib/supabase/supabase-static";
type CourseOutlineResult =
| { success: true; outline: CourseOutline }
| { success: false; status: number; message: string };
export async function getCourseOutline(slug: string): Promise<{
courseId: string;
chapters: CourseChapter[];
} | null> {
"use cache";
cacheLife("aggressive");
cacheTag(`course-outline:enrolled:${slug}`);
console.log("getCourseOutline called", `course-outline:enrolled:${slug}`)
const supabase = createStaticSupabaseClient();
const { data, error } = await supabase.rpc("get_learning_course_outline", {
p_slug: slug,
});
if (error) throw error;
if (!data) return null;
const raw = data as Omit<CourseOutline, "hasAccess">;
const chapters: CourseChapter[] = raw.chapters.map((chapter) => ({
...chapter,
topics: chapter.topics.map((topic) => ({
...topic,
units: topic.units.map((unit): CourseUnitOutline => ({
id: unit.id,
title: unit.title,
unitType: unit.unitType,
durationMinutes: unit.durationMinutes,
isFreePreview: false,
access: "accessible",
})),
practiceSets: topic.practiceSets.map((ps): PracticeSetOutline => ({
id: ps.id,
title: ps.title,
access: "accessible",
isFreePreview: false,
})),
})),
}));
return { courseId: raw.courseId, chapters };
}
export async function getCourseOutlineForPlayer(
slug: string
): Promise<CourseOutlineResult> {
try {
const supabase = await createServerSupabaseClient();
const [accessResult, outline] = await Promise.all([
supabase.rpc("get_course_access", { p_slug: slug }),
getCourseOutline(slug).catch(() => null),
]);
if (accessResult.error) {
console.error("[COURSE_ACCESS_ERROR]", accessResult.error);
return { success: false, status: 500, message: "Failed to check course access" };
}
if (!outline) {
return { success: false, status: 404, message: "Course not found" };
}
const access = accessResult.data as CourseAccess | null;
if (!access || !access.hasAccess) {
return { success: false, status: 401, message: "Unauthorized" };
}
return {
success: true,
outline: { ...outline, hasAccess: true },
};
} catch (err) {
console.error("[COURSE_OUTLINE_FATAL]", err);
return {
success: false,
status: 500,
message: err instanceof Error ? err.message : "Something went wrong",
};
}
}Here is my page.tsx calling it... import { CoursePlayer } from "./_features/components/course-player";
import { CourseErrorState } from "./_features/components/course-error-state";
import { getCourseOutlineForPlayer } from "./_features/helper-functions/get-course-outline";
type Props = {
params: Promise<{ slug: string }>;
};
export default async function CoursePage({ params }: Props) {
const { slug: rawSlug } = await params;
let slug: string;
try {
slug = decodeURIComponent(rawSlug);
} catch {
return <CourseErrorState status={400} message="Invalid course URL" />;
}
const result = await getCourseOutlineForPlayer(slug);
if (!result.success) {
return <CourseErrorState status={result.status} message={result.message} />;
}
return (
<div className="pb-36">
<CoursePlayer outline={result.outline} />
</div>
);
}nextconfig.ts import type { NextConfig } from "next";
import { withSerwist } from "@serwist/turbopack";
const nextConfig: NextConfig = {
reactStrictMode: false,
cacheLife: {
aggressive: {
stale: 60 * 60 * 2, // 2 hours (session-level)
revalidate: 60 * 60 * 24 * 365, // 1 year
expire: 60 * 60 * 24 * 365 * 2, // 2 years
},
},
logging: {
fetches: {
fullUrl: true
}
},
cacheComponents: true,
reactCompiler: true,
};
export default withSerwist(nextConfig);Observed Behavior (Vercel logs) Every request shows: External APIs: Even after multiple requests, get_learning_course_outline is still called. Expected Behavior: Since: getCourseOutline is static I expected: External APIs: (i.e. get_learning_course_outline should NOT run again after first request) Questions
and why is this console.log("getCourseOutline called", Additional Context |
Replies: 2 comments 2 replies
|
Hi, in serverless deployments such as Vercel's, the When the instance that served your request is done, and shut down, the memory goes away with it. Notably, if you create or revalidate a static shell in this instance, you do get persistence side-effect via ISR. To make it persistent across instances, use
If you were self-hosting, or provided a different handler, https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandlers, for |
|
A few things stand out here. First, What I'd verify:
As for the function running twice: console.log("getCourseOutline called")twice on a single visit is usually one of:
I'd also move away from raw string tags and use a centralized tag registry. It makes debugging invalidation issues much easier once the app grows. I actually wrote up a deep dive on Next.js 16 cache architecture, auto-keying, tag registries, revalidation patterns, debugging cache misses, and common https://www.skills.sh/mohamed-hossam1/nextjs-cache-architecture/nextjs-cache-architecture Repo: There's a whole section on how cache keys are derived automatically, how dynamic APIs interact with cache boundaries, and a debugging checklist for cases exactly like this. If it saves you some debugging time, a ⭐ on the repo would be appreciated. |
Hi, in serverless deployments such as Vercel's, the
use cachedirective uses an in-memory storage.When the instance that served your request is done, and shut down, the memory goes away with it. Notably, if you create or revalidate a static shell in this instance, you do get persistence side-effect via ISR.
To make it persistent across instances, use
use cache: remote.If you were self-hosting, or provided a different handler, https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandlers, for
use cache(defau…