Why the document object is not available during server-side rendering (SSR) in Next.js

AKRAM BOUTZOUGA
2 min readJun 23, 2024

--

SSR stands for the fact that in Next.js, Server Side Rendering leaves a render of components to static HTML in a server rather than a browser. It allows HTML to be sent to the client already pre-populated, enhancing performance and SEO.

In server rendering, there is no access to any of the browser-specific APIs or objects, like `document`, `window`, or `localStorage`. It is because these objects are part of the browser environment and hence inaccessible in the Node.js environment, where server-side rendering happens.

Here’s a more detailed explanation:

Browser vs Server Environment:

Ambiente Browser: Any code run in the browser will have available the whole set of APIs exposed by the browser, thus to `document`, `window,` and generally in all the other objects related to the DOM. These latter are provided from the browser itself to interact with the structure, with the style, and with the behavior of the Web page.
Server Environment: On a server, in the Node.js environment, running this code will fail because it does not have access to browser APIs. Following is the reason; the server doesn’t have a DOM; it is instead responsible for handling requests, executing server-side logic, and then sending back the rendered HTML to the client.

Why SSR is Important:

SSR can improve performance by decreasing time-to-interactive. It also improves SEO since search engines are able to crawl and index the fully rendered HTML content.

Handling SSR in Next.js:

Quite often in Next.js, you want to ensure that some code runs only on the client-side, given availability of browser APIs. This is commonly done through lifecycle methods as per useEfect, or conditional rendering, to avoid the server attempting to access a browser-specific object.

Here’s an article that delves into the details of that topic:

Summary:

  • No `document` on Server: On the server, there is no DOM, and hence `document` is `undefined` during Next.js SSR.
  • Client-Side Only: Be sure to put code that accesses `document` in a `useEffect` or conditional render so that it only runs on the client side.
  • Better Performance/SEO: SSR can improve page load times and SEO by sending pre-rendered HTML to the client.

Keep in mind, and effectively handle, the differences between client-side and server-side environments so you can effectively use Next.js SSR without running into errors involving browser-specific objects such as `document`.

--

--

AKRAM BOUTZOUGA
AKRAM BOUTZOUGA

Written by AKRAM BOUTZOUGA

Junior Calisthenics Engineer, Ai Enthusiast. Coding and Flexing! 💻💪

No responses yet