debugtypescriptnextjsModeratepending
Debug: Next.js build fails with dynamic server usage
Viewed 0 times
dynamic-serverstatic-generationforce-dynamicSSRbuild-error
Error Messages
Problem
Next.js build fails with 'Dynamic server usage' error when trying to statically generate a page that uses dynamic features like cookies, headers, or searchParams.
Solution
Diagnosis and fixes:
- cookies() or headers() in server components
- searchParams in page components
- fetch without cache option
- Route handlers without GET
// app/page.tsx
export const dynamic = 'force-dynamic';
// or per-segment:
export const dynamicParams = true;
'use client'
// Use useSearchParams() instead of server-side searchParams
export async function generateStaticParams() {
return posts.map(post => ({ slug: post.slug }));
}
export const revalidate = 0; // No cache
// matcher in middleware.ts controls which routes
export const config = {
matcher: '/api/:path*', // Only apply to API routes
};
- Identify the dynamic usage:
- cookies() or headers() in server components
- searchParams in page components
- fetch without cache option
- Route handlers without GET
- Explicitly mark route as dynamic:
// app/page.tsx
export const dynamic = 'force-dynamic';
// or per-segment:
export const dynamicParams = true;
- Move dynamic code to client components:
'use client'
// Use useSearchParams() instead of server-side searchParams
- Use generateStaticParams for static paths:
export async function generateStaticParams() {
return posts.map(post => ({ slug: post.slug }));
}
- Disable static generation for the whole route:
export const revalidate = 0; // No cache
- Check middleware - it makes ALL routes dynamic:
// matcher in middleware.ts controls which routes
export const config = {
matcher: '/api/:path*', // Only apply to API routes
};
Revisions (0)
No revisions yet.