Skip to content
Advertisement

How come Next.JS code runs on both the Server and the Client?

In a Next.JS app, you see that the code for a component runs on both the Server and the Client.

So if you have the following code:

const Title = () => {
  console.log('--> Hello')

  return (<h1>Some title</h1>)
}

and you run this in a dev environment (npm run dev), you will see the console.log statement print to both the Server in the terminal as well as the Browser’s console.

So firstly, what is happening here? How come all the code on the page gets run in both places on every page load?

Wouldn’t Next.JS just sent a pre-transpiled HTML file to the Browser? How come that console.log statement is getting run in the Server even though we’re not in getServerSideProps or something similar?

Now, this may be a core feature of React that I’ve overlooked, so please tell me if it’s just that manifesting in Next.JS

Advertisement

Answer

Wouldn’t Next.JS just sent a pre-transpiled HTML file to the Browser?

Yes, this is correct. But to transpile it to html it first needs to run your app and render it with ReactDOMServer.renderToString method.

So it is not specifically Next.js feature, but just a React SSR thing, every similar framework would do the same thing.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement