Is it normal that all components in Next.js are client components? – Next.js

by
Ali Hasan
next-auth next.js react-typescript reactjs server-side-rendering

Quick Fix: A server component can contain a client component as its child, but not the other way around.

<ClientComponent>
  <ServerComponent />
</ClientComponent>

The Problem:

In a Next.js application, all pages seem to be rendered on the client-side after wrapping the entire application in a ‘SessionProvider’ for session accessibility. Even page components (such as buttons and inputs) have become client-side, potentially affecting server-side rendering (SSR) functionality.

The Solutions:

Solution 1: Use Server Components

Every component under the app folder is, by default, a server component, meaning it’s rendered on the server side. By using use client, you’re converting server components into client components.

You can mix server and client components by nesting them. For example:

<ClientComponent>
  <ServerComponent />
</ClientComponent>

This will allow server-side rendering for ServerComponent while utilizing client-side rendering for ClientComponent.

For more information, refer to the following resources:

Solution 2: Just the wrapper component

Creating a wrapper component allows you to segregate client-side functionality from server-side functionality. This wrapper component can be imported and used as a container for components that need to access client-side APIs, while ensuring that other components remain server-side rendered. The wrapper component will handle the logic of checking the user’s authentication status, and only render its children if the user is authenticated.

Q&A

I have a Next app. I use app folder and Next Auth library. So that each page has access to the session, I wrapped the entire application in a SessionProvider. But since it’s useContext under the hood, I had to add the &#39;use client&#39; directive everywhere. This resulted in all pages being client-side since they use useSession. And all page components (buttons, inputs) also became client-side.

Every component under the app folder is, by default, a server component, meaning that it’s rendered on the server side, and its code stays on the server side.

Is it normal that all pages and components are now rendered on the client?

You can mix server component in client component as its children.

No, not every component needs to be a client component. You could create a wrapper component that is a client component which receives children.

Both server and client components can be passed to client components as children.

Video Explanation:

The following video, titled "Server vs client components in NextJs 13 – When to use which ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this video, we'll compare server and client components, discuss when to use each, and examine common patterns ...