0

I have a page in NextJS..

function MyPage({ props }) {
    console.log('page')
    return (<>
        <MyComponent />
    </>)
}

And a component...

export function MyComponent() {
    console.log('component')
    return (
        <>
            
        </>
    );
}

When I run yarn dev and browse to http://localhost:3000

I get the following logs in both the terminal and the browser console window...

page
component

This makes 0 sense. Server pages should not render on the browser. And components should not render on the server.

So my questions are...

  1. What is happening here?
  2. How do I tell if a component/page is a server 'thing' or a dynamic component for sure? (I seem to be mistaken here)
Exitos
  • 29,230
  • 38
  • 123
  • 178

2 Answers2

1

These both are client-side rendering. For server-side rendering, you'll need to use getServerSideProps

The props generated from this function will be managed and computed on the server and then returned to the browser. Console logs added in getServerSideProps will not be visible in the browser.

For example:

function Page({ data }) {
  // Render data...
}


export async function getServerSideProps() {

  const res = await fetch(`https://.../data`)
  const data = await res.json()

  console.log("SSR component")
  return { props: { data } }
}

export default Page
Raman Saini
  • 365
  • 1
  • 11
0

Think you can use

typeof window === 'undefined'

Explanation you can find on here

For example,

if (typeof window === 'undefined') {
    // Only run on server
}

if (typeof window !== 'undefined') {
    // Only run in browser
}
vimuth
  • 5,064
  • 33
  • 79
  • 116