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.
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.
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