next.jsnext.js15

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.


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