I am using nextjs v15. I have some pages where my content is fully static, and as such I want to pre-render it. However, in my layout.tsx, each page also has my header component which is not static, and retrieves auth data that has headers/cookies.
If I attempt to export dynamic to ‘error’ as such:
export dynamic = 'error';
which will try to force the page to be rendered statically, and will error out if it can’t, then I get this:
Error: Route / with `dynamic = "error"` couldn't be rendered statically because it used `headers`. See more info here:
https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering
and then some reference code to my layout.tsx where I include the auth()
call.
Is there a way to prerender statically the actual page, but not the header? Any other alternatives?
Instead of getting the authentication on the server, I could just have my header / client component do the auth call, but then my header has a loading state waiting for the authentication. I don’t want that, and just want my header/authentication to be fully rendered by the time it is sent to the user.
2
Answers
You have several options:
useEffect
.To make your page static, you should not be using a Dynamic API and cache your data
An example
If you want your header to be visible without waiting your auth call to finish, consider Streaming
To do that, define your Header component as a client component and pass a server component in which you do your auth call as a prop to it (supported pattern)
Your component in which you do your auth call
Your header component
Your layout
Application starts and…
after 3 seconds
Read the following links for further information
https://nextjs.org/docs/app/building-your-application/rendering/server-components#static-rendering-default
https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming
https://nextjs.org/docs/app/building-your-application/caching#data-cache
https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns