In NextJS 12 client components would build as static pages and include all HTML for seo purposes with the request inside getStaticProps() method.
I have started a new project in NextJS 13 and whatever I do it will never render a component marked use client in the initial html. It will only do that for server-side components and it’s limited what can be rendered on the server.
Is there anyway to get a client component that requests an api request to build to be statically served as html like in the pages directory with getStaticProps()?
I have tried making the fetch on server component and passing to client component as prop and also making api request inside the client component. I am setting the next tag header for on demand revalidation
The docs say that is default behaviour but it is not. I can find lots of open github tickets with people complaining about same issue but no definitive answer anywhere if it’s actually possible for nextjs13 to serve the html for client components in source.
>Solution :
In Next.js 13, the behavior you described has changed. Client components are now hydrated on the client-side, meaning they are rendered and executed in the browser rather than on the server. This change was introduced to improve performance and reduce the size of initial HTML payload.
As a result, client components that make API requests cannot be statically rendered as HTML using the getStaticProps() method like server-side components. The HTML for client components is not included in the initial server response because it relies on client-side JavaScript execution to render and fetch data.
If you want to pre-render client components with data from API requests, you can use SSR or pre-fetch data and pass it as props.
You mentioned that you tried making the API request in the server component and passing it as a prop to the client component. This approach can work, but the client component will still need to hydrate on the client-side. The initial HTML response will not include the fully rendered client component, but it can receive the pre-fetched data as a prop and use it to render on the client-side. This way, the component will still have access to the data it needs for rendering.
While Next.js 13 focuses on client-side hydration for client components, server components and hybrid components (combination of server and client components) still allow for server-side rendering and inclusion in the initial HTML response. Depending on your use case, you might consider leveraging those components for server-side rendering when necessary.