How does SSR on NextJS really works?

Viewed 1554

I've been using NextJS for a while, but don't fully get how its SSR process really works.

I've put a console.log inside some components return method, and I see that those are executed on the client side. Shouldn't these be displayed on the server's console instead because SSR is being used?

Also, when I try to console.log the window object, NextJS throws an error saying that window is not defined. That left me more confused, because according to my previous test, console.log is running on the client side, but according to this error, it is running on the server.

2 Answers

If you've set up React components to render on the server (which you should for non static sites), when code executes on the server in NodeJS, there is no window object. That only exists in the browser. You need to account for that in SSR components.

There are features of Next to control when components are available to the client or server only, like dynamic imports.

In the end, on the server, Next is mostly doing renderToString, and serving the HTML from the server, no different than any other webserver serving HTML.

Once in the client, React "hydrates" the rendered DOM, as in it re-runs React over the HTML created by the server. It doesn't change the DOM, but it does add things like interactivity, click handlers, etc, that you've defined for your app.

Server side nextjs generates .js in your .next directory if it is GetServerSideProps. If it is ISR (GetStaticProps + revalidate), then it generates .html, .json, and .js files in the .next directory for that page (or those pages if dynamic). If using GetStaticProps sans revalidate, it generates .html and .json in the .next directory. If using no server side rendering method (e.g., GetStaticProps or GetServerSideProps) then it only generates .html at build time (automatic static optimization).

There is more to it, but this is what I've noticed from inspecting the contents of the output pages in the .next directory

Related