Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Determine client/server component in next.js

I just started next.js. One thing I’ve seen is, sometimes even if I don’t put "use client" at top of my files, some of them renders in the client. And some in the server.

How to quickly check if it’s a client or server component when developing?

Thanks in advance. I’m new in the web development sector, your help is appriciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First of all,

Why some components render in client side even though you didn’t put "use client" in the file.

When your component (A.jsx) is a descendant of a client side component, it (A.jsx) automatically becomes a client side component. Even if you don’t put "use client" at the top of (A.jsx).

Now, back to your main question.

How to check if my component is a client/server side component?

1. Make it async

Just add async in front of your function. And next.js will throw an error if it is a client side component.
If you get no error, then your component is server side.

Let’s say your component is this:

const Unknown = () =>{
    return <div>Idk if it's client side or not</div>
}

Make it async:

const Unknown = async () =>{
    return <div>Idk if it's client side or not</div>
}

If it’s a client side component, you’ll see the following error:
error when used async

2. console.log window

If you don’t want to check it using the first method, you can do this too.

Add a console.log statement in your component.

console.log(window)

If it’s a server side component, you’ll get the following error:
error when logged window

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading