
Next.js 15(App Router)를 사용할 때, cookies(), headers(), 또는 useSearchParams()와 같은 서버 전용 함수를 조건문이나 동적 로직(예: try-catch 블록이나 if 문) 안에서 호출하면 “Dynamic Server Error” 오류가 발생할 수 있습니다.
Next.js는 서버 함수가 서버 컴포넌트의 최상위에서 무조건적으로 호출되어야 한다고 요구합니다. 조건부 호출은 Next.js가 서버 컴포넌트를 빌드 시간에 정적 분석하고 최적화하는 것을 방해하기 때문입니다.
cookies()를 try-catch나 조건문 안에 두면 불확실성이 생기고, 이로 인해 Next.js가 빌드 시간에 “Dynamic Server Error”를 발생시킵니다.// ❌ 이 코드는 "Dynamic Server Error"를 발생시킵니다
export default async function Page() {
try {
const cookieStore = await cookies(); // 동적 서버 사용
const accessToken = cookieStore.get("accessToken")?.value;
if (!accessToken) {
redirect("/?error=NO_TOKEN");
}
return <SomePage />;
} catch (error) {
console.log(error);
redirect("/");
}
}
서버 전용 API 호출을 서버 컴포넌트의 최상위로 이동시키고, 조건문 바깥에서 호출해야 합니다.
// ✅ 해결: cookies()를 최상위에서 무조건적으로 호출
export default async function Page() {
const cookieStore = await cookies(); // 최상위에서 무조건적으로 호출
try {
const accessToken = cookieStore.get("accessToken")?.value;
if (!accessToken) {
redirect("/?error=NO_TOKEN");
}
return <SomePage />;
} catch (error) {
console.log(error);
redirect("/");
}
}
이 패턴을 따르면 “Dynamic Server Error”를 방지하고, Next.js에서 서버 컴포넌트를 매끄럽게 사용할 수 있습니다. 🚀
When working with Next.js 15 (App Router), you might encounter a “Dynamic Server Error” if you use server-only functions like cookies(), headers(), or useSearchParams() inside conditional or dynamic logic (e.g., try-catch blocks or if statements).
This happens because Next.js requires server functions to be called unconditionally at the top level of server components. Conditional or dynamic usage prevents Next.js from statically analyzing and optimizing your server component during build time.
// ❌ This code throws a "Dynamic Server Error"
export default async function Page() {
try {
const cookieStore = await cookies(); // Dynamic server usage
const accessToken = cookieStore.get("accessToken")?.value;
if (!accessToken) {
redirect("/?error=NO_TOKEN");
}
return <SomePage />;
} catch (error) {
console.log(error);
redirect("/");
}
}
Move your server-side API calls to the top level of your server component, outside of any conditional logic.
// ✅ Fixed: Unconditional top-level call to cookies()
export default async function Page() {
const cookieStore = await cookies(); // Called unconditionally at the top level
try {
const accessToken = cookieStore.get("accessToken")?.value;
if (!accessToken) {
redirect("/?error=NO_TOKEN");
}
return <SomePage />;
} catch (error) {
console.log(error);
redirect("/");
}
}
By following this pattern, you’ll avoid the “Dynamic Server Error” and ensure your server components work seamlessly in Next.js. 🚀
위 글은 원글을 바탕으로 AI에 의해 작성되었습니다.