6

For example, I have a piece of code to check if I am a client or a server to have the appropriate logic.

For example. I can use isClient to know that I am in client component.

le khanh
  • 61
  • 1
  • 4

2 Answers2

2

There are probably better solutions out there. Assuming you only need to do this while you're developing, one way to check is to see where your console logs end up. Running a console.log() from a server component will only log the output in terminal/CLI. If you don't see anything in terminal and only see in the browser's console, this means that you are within the context of a client component.

For instance, running console.log('Server only'); from a root component in your app directory should only show up in terminal.

KMcAloon
  • 588
  • 5
  • 11
0

Server components : All components inside the app directory are React Server Components by default, including special files and colocated components.

Client Components enable you to add client-side interactivity to your application. In Next.js, they are prerendered on the server and hydrated on the client. You can think of Client Components as how Next.js 12 and previous versions worked

learn more in next official doc

If you want to know during runtime if the component is being rendered on the server or client. you can check if window is defined or not:

const componentType = typeof window === 'undefined' ? 'server' : 'client';

The window object is the reference to an open window in a browser. Therefore, the window object is only available on the client-side

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
  • This doesn't answer the OP. They are asking for a function/way to help determine during runtime if the component is being rendered on the server or client. The above is just a general overview but doesn't cover all cases nor provide a solution. – KMcAloon Apr 07 '23 at 20:40
  • @KMcAloon Yes, you're right, I didn't read the question properly, I updated my answer – Ahmed Sbai Apr 07 '23 at 22:36
  • 1
    Hey Ahmed, so that's definitely a step in the right direction. The only problem is it won't always be accurate depending on how the component is being rendered (ie SSR, ISR, SSG, etc). Even "client components" will have window undefined if they are initially being rendered on the server before rehydration. – KMcAloon Apr 13 '23 at 17:20