Problem
I once created blog pages and confirmed that they were being statically rendered well before proceeding with development. However, at some point, I discovered that static rendering was not happening, and new rendering was occurring with every request.
Cause
I used the cookies
function provided by Next.js in a Provider located at the top of the app.
import { cookies } from 'next/headers';
function Proivder {
const cookie = cookies().....
}
Next.js uses static rendering by default. However, if uncached requests or dynamic functions are used during rendering, it switches to dynamic rendering.
Dynamic Functions | Data | Route |
---|---|---|
No | Cached | Statically Rendered |
Yes | Cached | Dynamically Rendered |
No | Not Cached | Dynamically Rendered |
Yes | Not Cached | Dynamically Rendered |
cookies
is one of the dynamic functions, and because it was used in the Provider, all pages and components below it also depend on this dynamic data. Therefore, pages that were previously working well as static pages were converted to dynamic pages.
Solution
I solved the issue by adding the following code at the top of the page.
export const dynamic = 'force-static';
However, be aware that inserting this code has the following issues:
- No access to dynamic data: With this setting, you cannot access request-time data such as headers, cookies, etc. Calling these functions will return default values or empty data.