<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ pre rendering - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ pre rendering - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 10:49:52 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/pre-rendering/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What are Pre-Rendering and Hydration in Web Development? A Deep Dive for Devs ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever wondered how Frameworks like Next.js, Gatsby.js, and Remix work? These frameworks use the concepts of Pre-rendering and Hydration, which represent significant advancements in the history of web development. These frameworks leverage the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-pre-rendering-and-hydration-in-web-dev/</link>
                <guid isPermaLink="false">6703ee6b07ec01d7c3c14651</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hydration ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pre rendering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Full Stack Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Salvador Villalon Jr ]]>
                </dc:creator>
                <pubDate>Mon, 07 Oct 2024 14:21:31 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727985850590/fdb7eb16-52bd-41ec-8e1a-e4fb9068a535.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever wondered how Frameworks like <a target="_blank" href="https://nextjs.org/"><strong>Next.js</strong></a>, <a target="_blank" href="https://www.gatsbyjs.com/"><strong>Gatsby.js</strong></a>, and <a target="_blank" href="https://remix.run/"><strong>Remix</strong></a> work?</p>
<p>These frameworks use the concepts of Pre-rendering and Hydration, which represent significant advancements in the history of web development.</p>
<p>These frameworks leverage these concepts to create toolchains that build efficient web applications. In this article, we’ll discuss Pre-rendering and Hydration and why they are important features to use when building single-page applications.</p>
<p>To understand these concepts, we need to explore why they were created and what problem they are trying to solve. Let's take a look at the beginning of web applications.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-web-development-in-the-past-traditional-server-side-rendering">Web Development in the Past: Traditional Server-Side Rendering</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-the-downside-of-traditional-server-side-rendering">The Downside of Traditional Server-Side Rendering</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-traditional-server-side-rendering-vs-single-page-applications">Traditional Server-Side Rendering vs. Single-Page Applications</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-single-page-application-spa">What is a Single Page Application (SPA)?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-single-page-application-flow">Single Page Application Flow</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-entering-a-new-world-with-pre-rendering-and-hydration">Entering a New World with Pre-Rendering and Hydration</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-is-pre-rendering-important">Why is Pre-Rendering Important?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-server-side-rendering">What is Server Side Rendering?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-static-site-generation">What is Static Site Generation (SSG)?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-hydration">What is Hydration?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-reconciliation">What is Reconciliation?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-pre-rendering-and-hydration-in-action">Pre-rendering and Hydration in Action</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-mental-model-for-hydration">A Mental Model for Hydration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-potential-errors-when-working-with-pre-rendering-and-hydration">Potential Errors when working with Pre-rendering and Hydration Frameworks</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-does-it-relate-to-frameworks-like-gatsbyjs-nextjs-and-remix">How does it relate to frameworks like Gatsby.js, Next.js, and Remix?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-moving-forward">Moving Forward</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-moving-forward">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-web-development-in-the-past-traditional-server-side-rendering">Web Development in the Past: Traditional Server-Side Rendering</h2>
<p>Back in the days of traditional server-side rendering, rendering and interactivity were separated. We used server-side languages like <a target="_blank" href="https://nodejs.org/en"><strong>Node.js</strong></a>, <a target="_blank" href="https://www.php.net/"><strong>PHP</strong></a>, <a target="_blank" href="https://www.java.com/en/"><strong>Java</strong></a>, and <a target="_blank" href="https://rubyonrails.org/"><strong>Ruby on Rails</strong></a>.</p>
<p>Within our servers, we created <strong>views</strong> using templating languages like <a target="_blank" href="https://en.wikipedia.org/wiki/Jakarta_Server_Pages"><strong>JSP</strong></a> and <a target="_blank" href="https://ejs.co/"><strong>EJS</strong></a>. Views are HTML pages, and you could inject JavaScript or Java inside them to add functionality, dynamic data retrieved from database queries, and interactive segments with languages like <a target="_blank" href="https://jquery.com/"><strong>JQuery</strong></a>.</p>
<h3 id="heading-the-downside-of-traditional-server-side-rendering">The Downside of Traditional Server-Side Rendering</h3>
<ol>
<li><strong>Performance Issues</strong></li>
</ol>
<ul>
<li><p>A request to the server needed to be made every time the user requested a page!</p>
<ul>
<li><p>This meant there would be a full-page reload.</p>
</li>
<li><p>Complex queries could result in slower speeds.</p>
</li>
</ul>
</li>
</ul>
<ol start="2">
<li><strong>Scalability Challenges</strong></li>
</ol>
<ul>
<li><p><strong>Global Reach</strong>: A <strong>Dynamic CDN</strong> was needed to cache your dynamic files. CDNs are better suited for static content, but companies like Cloudflare created <a target="_blank" href="https://www.cloudflare.com/products/cloudflare-workers/"><strong>Cloudflare-Workers</strong></a> to help with the process.</p>
</li>
<li><p><strong>Upscaling Servers</strong>: If more users started using the application, there would be an increase in demand on the server. You might have needed to invest more in resources such as scaling up by adding more servers.</p>
</li>
</ul>
<ol start="3">
<li><strong>Duplicate Logic</strong></li>
</ol>
<ul>
<li>You may have duplicate code. For example, if you were trying to validate form fields, you'd have to validate in both the EJS file and your API endpoint.</li>
</ul>
<p>Let's look at the code snippet below to see an example of this duplicate Logic:</p>
<p><strong>Code in EJS:</strong></p>
<pre><code class="lang-javascript">&lt;form action=<span class="hljs-string">'/submit-form'</span> method=<span class="hljs-string">'POST'</span> id=<span class="hljs-string">"myForm"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> /&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
&lt;/form&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-built_in">document</span>
        .getElementById(<span class="hljs-string">'myForm'</span>)
        .addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
            <span class="hljs-keyword">const</span> email = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'email'</span>).value;

            <span class="hljs-keyword">if</span> (!email.includes(<span class="hljs-string">'@'</span>)) {
                alert(<span class="hljs-string">'Please enter a valid email.'</span>);
                event.preventDefault();
            }
        });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p><strong>Code in Express.js:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;
<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;

<span class="hljs-comment">// To received form data</span>
app.use(
  express.urlencoded({
    <span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span>,
  }),
);

<span class="hljs-comment">// view engine setup. Need a folder called views</span>
app.set(<span class="hljs-string">"views"</span>, path.join(__dirname, <span class="hljs-string">"views"</span>));
app.set(<span class="hljs-string">"view engine"</span>, <span class="hljs-string">"ejs"</span>);

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-comment">// To render the view</span>
  res.render(<span class="hljs-string">"index"</span>, { <span class="hljs-attr">errors</span>: <span class="hljs-literal">null</span> });
});

app.post(<span class="hljs-string">"/submit-form"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> email = req.body.email;

  <span class="hljs-keyword">if</span> (!email.includes(<span class="hljs-string">"@"</span>)) {
    res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">"Invalid email."</span>);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-comment">// Proceed with form processing</span>
});

app.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Sandbox listening on port <span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<p>Traditional Server-Side Rendering had significant downsides, but the introduction of <strong>single-page applications</strong> marked a new era in web development.</p>
<h2 id="heading-traditional-server-side-rendering-vs-single-page-applications">Traditional Server-Side Rendering vs. Single-Page Applications</h2>
<h3 id="heading-what-is-a-single-page-application-spa">What is a Single Page Application (SPA)?</h3>
<blockquote>
<p><strong><em>A Single-page application (SPA) is a web app implementation that loads only a single web document and then updates the body content of that single document via JavaScript APIs such as Fetch when different content is to be shown. Allows users to use websites without loading whole new pages from the server. (</em></strong><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/SPA"><strong><em>Source: MDN</em></strong></a><strong><em>)</em></strong></p>
</blockquote>
<p>A popular way to implement SPA is by using React. React lets you create fast applications and simplifies updating the UI more easily than DOM manipulation methods.</p>
<p>It offers several advantages:</p>
<ul>
<li><p><strong>Improved User Experience</strong></p>
<ul>
<li><p>An SPA loads a single HTML file and dynamically updates the content as the user interacts with it. All of this is done without a full page reload.</p>
</li>
<li><p>An SPA can update the state of the UI easily and provide instant feedback to users based on actions taken on the app.</p>
</li>
</ul>
</li>
<li><p><strong>Reduced Server Load</strong></p>
<ul>
<li>Most of the work is done by the browser. This reduces the load on the server!</li>
</ul>
</li>
<li><p><strong>Better Scalability</strong></p>
<ul>
<li><p>The browser is now doing most of the work. We can now deploy dedicated servers focused on serving data via APIs. We can easily scale horizontally. We have the option of using servers or serverless functions like <a target="_blank" href="https://aws.amazon.com/lambda/"><strong>AWS lambda</strong></a>.</p>
</li>
<li><p>An SPA can be hosted on a static CDN like <a target="_blank" href="https://docs.netlify.com/platform/what-is-netlify/"><strong>Netlify</strong></a>.</p>
</li>
</ul>
</li>
</ul>
<p>With the addition of toolchains like <a target="_blank" href="https://vitejs.dev/"><strong>Vite</strong></a> and <a target="_blank" href="https://create-react-app.dev/"><strong>Create React App</strong></a> to automate the setup of a modern JavaScript application, engineers no longer had to worry about configuring Webpack manually.</p>
<p>There are some downsides to implementing SPAs. The big one is that it relies on the browser to load all the JavaScript and HTML for us. This means that on mobile devices and for people with slow internet, users may experience delays in seeing the page. Let’s examine the flow to explain this:</p>
<h3 id="heading-single-page-application-flow">Single Page Application Flow</h3>
<blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725392287290/04dba828-9903-4ca6-bf8e-0c0d875d587b.png?auto=compress,format&amp;format=webp" alt="Single Page Application React Flow. (Source: How NextJS REALLY Works: https://youtu.be/d2yNsZd5PMs?si=RmnywZJEAuurseQm)" width="854" height="487" loading="lazy"></p>
</blockquote>
<p>Several steps are needed for the users to finally see the HTML page.</p>
<p>First, the browser fetches the HTML. This initial HTML will be blank and incorrect. Why? Because the content comes from JavaScript. This means that it takes time for the browser to fetch JavaScript, load it, and execute it. Since the initial HTML is wrong, web crawlers and search engines will not find relevant content on the website and skip it.</p>
<p>Take a look at the below GIF. Here JavaScript is disabled on the Chrome Developer Tools. The website fails to load without JavaScript. If JavaScript is enabled but the internet connection is slow, users may see a blank page for an extended period.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725392877108/d5a2eb1c-f784-4879-b02f-8c340d405c9c.gif?auto=format,compress&amp;gif-q=60&amp;format=webm" alt="Single Page Application JavaScript Disabled Test." width="1916" height="908" loading="lazy"></p>
<p>This was a big problem. This led to Web Development evolving into <strong>the Pre-Rendering era.</strong></p>
<h2 id="heading-entering-a-new-world-with-pre-rendering-and-hydration">Entering a New World with Pre-Rendering and Hydration</h2>
<h3 id="heading-why-is-pre-rendering-important">Why is Pre-Rendering Important?</h3>
<p>People realized that we could generate the HTML in advance. It could be generated from our server or at build time, depending on the methods used.</p>
<p>Pre-rendering can be done in two ways - <a target="_blank" href="https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering"><strong>Server Side Rendering (SSR)</strong></a> or <a target="_blank" href="https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation"><strong>Static Site Generation (SSG)</strong></a></p>
<h3 id="heading-what-is-server-side-rendering">What is Server Side Rendering?</h3>
<p>React components are rendered on the server, and the resulting HTML is sent to the browser. This can improve SEO and initial load times. <strong>The rendering process occurs on each page request.</strong></p>
<h3 id="heading-what-is-static-site-generation-ssg">What is Static Site Generation (SSG)?</h3>
<p><strong>Static HTML pages are generated at build time.</strong> These pages can be served quickly without requiring a server to render them on the fly.</p>
<p>Either method is beneficial! <strong>Now the HTML that the user receives will be correct.</strong> They will see a page with content instead of a blank page as seen using Vite or Create React App.</p>
<p>But there is a problem: the HTML the user receives is not interactive. They cannot click on it or submit a form. How can we add interactivity to our app? By Hydrating properly🚰 🌊!</p>
<h3 id="heading-what-is-hydration">What is Hydration?</h3>
<p><a target="_blank" href="https://react.dev/reference/react-dom/hydrate#hydrating-server-rendered-html"><strong>Hydration</strong></a> is what adds interactivity to our app. It loads the JavaScript that makes our app interactive.</p>
<blockquote>
<p><strong><em>In React, "hydration" is how React "attaches" to existing HTML that was already rendered by React in a server environment. During hydration, React will attempt to attach event listeners to the existing markup and take over rendering the app on the client. (</em></strong><a target="_blank" href="https://react.dev/reference/react-dom/hydrate#hydrating-server-rendered-html"><strong><em>Source: React Docs</em></strong></a><strong><em>)</em></strong></p>
</blockquote>
<p>Let's see what the flow looks like for an app that uses Pre-Rendering and Hydration:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725392958385/eaee78cb-736c-4d49-8fb7-c9cb098d3652.png?auto=compress,format&amp;format=webp" alt="Pre-rendering flow." width="851" height="499" loading="lazy"></p>
<h3 id="heading-what-is-reconciliation"><strong>What is Reconciliation?</strong></h3>
<blockquote>
<p><strong><em>Reconciliation is the process by which React determines the most efficient way to update the UI in response to changes in data or component hierarchy. (Source:</em></strong> <a target="_blank" href="https://www.educative.io/answers/what-is-the-concept-of-reconciliation-in-react"><strong><em>What is the difference between virtual and real DOM (React)?</em></strong></a><strong><em>)</em></strong></p>
</blockquote>
<p>Reconciliation is when React figures out how to update the UI in response to changes in data or components hierarchy.</p>
<p>When components are rendered, a Virtual DOM is created. If there are changes in state or props, then a new Virtual DOM is created. React then uses its diff algorithm to compare the new Virtual DOM with the previous Virtual DOM to check for changes. This is <strong>reconciliation</strong>.</p>
<p>Based on the changes found, <strong>React is not going to update the entire UI</strong>. Instead, it will <strong>select which elements need to be updated.</strong> This <a target="_blank" href="https://www.educative.io/answers/what-is-the-concept-of-reconciliation-in-react"><strong>article</strong></a> helped me understand Reconciliation.</p>
<h3 id="heading-pre-rendering-and-hydration-in-action"><strong>Pre-rendering and Hydration in Action</strong></h3>
<p>During the Pre-rendering and Hydration flow, first, the user will see HTML with the correct content.</p>
<p>Then Hydration kicks in and loads JavaScript to give interactivity to the application.</p>
<p>Let's simulate the process of what happens if the Hydration process takes a long time (due to a slow internet connection) or if the user has JavaScript disabled.</p>
<p>Here is a gif where I disable JavaScript on my Portfolio. I created my portfolio using <a target="_blank" href="https://www.gatsbyjs.com/"><strong>Gatsby</strong></a> a static-site-generation framework (it also has server-side rendering capabilities):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725554638438/698fd854-e828-44cd-996a-e01b154803d1.gif?auto=format,compress&amp;gif-q=60&amp;format=webm" alt="Portfolio JavaScript Disabled Test." width="1916" height="908" loading="lazy"></p>
<p>Even though there is no JavaScript, I can still see content on my portfolio. That’s because the user received <strong>pre-render HTML</strong>! You can see that I cannot click on the <strong>dropdown menu items or the buttons</strong> that say About Me, Projects, and Experience. That’s because the JavaScript did not load so the user cannot interact with it.</p>
<h3 id="heading-a-mental-model-for-hydration"><strong>A Mental Model for Hydration</strong></h3>
<p><a target="_blank" href="https://www.joshwcomeau.com/"><strong>Josh Comeau</strong></a> created a cool mental model for Hydration. Josh calls it the <strong>“Two Pass Rendering.”</strong></p>
<blockquote>
<p><strong><em>The first pass, at compile-time, produces all of the static non-personal content and leaves holes where the dynamic content will go. Then, after the React app has mounted on the user's device, a second pass stamps in all the dynamic bits that depend on the client state. (Source:</em></strong> <a target="_blank" href="https://www.joshwcomeau.com/react/the-perils-of-rehydration/#mental-models-13"><strong><em>The Perils of Hydration</em></strong></a><strong><em>)</em></strong></p>
</blockquote>
<p>To Summarize:</p>
<ol>
<li><p><strong>The First Pass</strong>: the user sees the pre-render HTML. It contains static content, but it is missing the dynamic content.</p>
</li>
<li><p><strong>The Second Pass:</strong> JavaScript starts loading and fills in the missing dynamic pieces that depend on the client state.</p>
</li>
</ol>
<h3 id="heading-potential-errors-when-working-with-pre-rendering-and-hydration-frameworks"><strong>Potential Errors When Working with Pre-rendering and Hydration Frameworks</strong></h3>
<p>When working with frameworks like Next.js, the server will return static pre-render HTML, and then Hydration occurs which loads JavaScript.</p>
<p>But we must be careful when working with dynamic data and client-only properties. For example, take a look at this code:</p>
<h4 id="heading-dynamic-data-error">Dynamic Data Error</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">HydrationErrors</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hydration Errors<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Today date in milliseconds is {new Date().getTime()}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<p>Here, the server will generate HTML with a timestamp in milliseconds. For example: <code>1724869161034</code>. The Hydration process begins, and then the client loads the HTML. Time has passed and the timestamp is different, it is now <code>172486193750</code>! This scenario causes the following error:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725555403697/ebb398ec-cd58-4b9a-aa63-c43a9b511eeb.png?auto=compress,format&amp;format=webp" alt="Mismatch text content from server and client hydration error." width="977" height="788" loading="lazy"></p>
<p>This happens because the <code>getTime()</code> function will generate a different timestamp.</p>
<p>This means that the server and client generate different HTML. The Network Tab shows us the server's response. It is a different HTML from what the client loads.</p>
<p><strong>The server's response below:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725555472118/d76c7ad0-92ab-4b77-92ea-b3d9d6a3b4fe.png?auto=compress,format&amp;format=webp" alt="Different server html generated." width="904" height="836" loading="lazy"></p>
<p><strong>The client's response below:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725555518535/af27855d-d362-44e3-8007-b01fde1d2455.png?auto=compress,format&amp;format=webp" alt="Different client html generated." width="1624" height="853" loading="lazy"></p>
<p><strong>To Fix the Error:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">HydrationErrors</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [date, setDate] = useState&lt;number&gt;();

  useEffect(<span class="hljs-function">() =&gt;</span> {
    setDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime());
  }, []);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hydration Errors<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Today date in milliseconds is {date}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<p>You can use the <code>useEffect</code> hook. Why would this work? Because the HTML that the server and client render will contain an empty <code>date</code> state variable.</p>
<p>Once the component mounts, the <code>useEffect</code> activates and adds the dynamic data from the state variable or you can use the <code>suppressHydrationWarning</code> flag and set it to true.</p>
<pre><code class="lang-javascript">  &lt;p suppressHydrationWarning={<span class="hljs-literal">true</span>}&gt;Today date <span class="hljs-keyword">in</span> milliseconds is {date}&lt;/p&gt;
</code></pre>
<h4 id="heading-using-client-only-properties-error">Using Client-Only Properties Error</h4>
<p>Remember you cannot use <code>window</code> or <code>localStorage</code>. They do not exist on the server. Take the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">HydrationErrors</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        {typeof window !== "undefined" &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This p tag will appear<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<p>Here, the server returns HTML with an empty <code>&lt;div&gt;</code> tag, but the client loads HTML that includes the <code>&lt;p&gt;</code> tag. This creates a <strong>HYDRATION ERROR!</strong></p>
<p>This is the error that you get:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725555844562/443c435c-308a-4422-b184-b2f321672519.png?auto=compress,format&amp;format=webp" alt="Cannot use client-side properties hydration error." width="952" height="778" loading="lazy"></p>
<p>The Network Tab shows us the server's response. It is an empty <code>&lt;div&gt;</code> tag.</p>
<p><strong>The server's response below:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725555958286/aeeaa522-3266-4b60-856d-d0cd3bf4d9c9.png?auto=compress,format&amp;format=webp" alt="Different server html generated." width="908" height="850" loading="lazy"></p>
<p>But the client loads HTML that says "This p tag will appear".</p>
<p><strong>The client's response below:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725556187527/173bf82a-1754-4835-9921-adea0f2e864a.png?auto=compress,format&amp;format=webp" alt="Different client html generated." width="1618" height="835" loading="lazy"></p>
<p>This demo was inspired by <a target="_blank" href="https://www.youtube.com/@deeecode"><strong>Deeecode The Web</strong></a> in <a target="_blank" href="https://youtu.be/7UOyuEHYmSE?si=Ql8z5D_pAryvTyFf"><strong>Why Do HYDRATION ERRORS Exist? And how to solve them</strong></a>. He gives a great explanation of why Hydration Errors occur. I recommend watching it!</p>
<h2 id="heading-how-does-it-relate-to-frameworks-like-gatsbyjs-nextjs-and-remix">How Does it Relate to Frameworks like Gatsby.js, Next.js, and Remix?</h2>
<p>Everything we have discussed is what all these frameworks focus on.</p>
<p>Static-Site Generation and Server-Side Rendering can be implemented using Gatsby.js, Next.js, and Remix. They focus on creating a pre-render HTML ready for the user to see, then initiate Hydration to add interactivity to the app.</p>
<p>Gatsby.js, Next.js, and Remix do not replace the concept of single-page applications – they add to the process. Take a look at this flow:</p>
<blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725556321232/7d8629fd-b528-4cd7-9bc2-7de0bf1ab630.png?auto=compress,format&amp;format=webp" alt="Pre-rendering and Single Page Application combined flow. (Source: How NextJS REALLY Works)" width="1164" height="500" loading="lazy"></p>
</blockquote>
<p>It is adding to the current SPA flow! If you did not have Pre-rendering, the process starts where the pink box begins, with an incomplete HTML.</p>
<h2 id="heading-moving-forward">Moving Forward</h2>
<p>This article is meant as an introduction to pre-rendering and hydration.</p>
<p>Next.js first implemented these concepts with the <a target="_blank" href="https://nextjs.org/docs/pages">Pages Router</a>. Pages Router was great and introduced the world to functions like <code>getServerSideProps</code>, <code>getStaticPaths</code>, and <code>getStaticProps</code> to implement Static-Site Generation and Server-Side Rendering.</p>
<p>These implementations had their pros and cons. For example, Josh W Comeau mentioned that with <code>getServerSideProps</code><strong>:</strong></p>
<blockquote>
<ol>
<li><p>This strategy only works at the route level, for components at the very top of the tree. We can't do this in any component.</p>
</li>
<li><p>Each meta-framework came up with its own approach. Next.js has one approach, Gatsby has another, Remix has yet another. It hasn't been standardized.</p>
</li>
<li><p>All of our React components will <em>always</em> hydrate on the client, even when there's no need for them to do so.</p>
<p> <a target="_blank" href="https://www.joshwcomeau.com/react/server-components/">(Source: Making Sense of React Server Components)</a></p>
</li>
</ol>
</blockquote>
<p>The React team saw this too and created a new paradigm called <a target="_blank" href="https://react.dev/reference/rsc/server-components">React Server Components (RSC)</a>. To implement RSC, the Vercel team created the <a target="_blank" href="https://nextjs.org/docs/app">App Router</a>. App Router still uses the concepts of pre-rendering and hydration, but it no longer uses <code>getStaticProps</code>, <code>getStaticPaths</code>, and <code>getServerSideProps</code>. It uses RSC and other great App Router features to implement better web applications. I recommend taking a look at App Router when you get a chance.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks for reading this far 😃!</p>
<p>I learned a lot from writing this article. I started this research because I used Gatsby to create my <a target="_blank" href="https://salvador-villalon.netlify.app/"><strong>portfolio version 4</strong></a> and Next.js in my job, but I did not understand the concepts behind these frameworks and why they were created.</p>
<p>I made a web application to demonstrate the topics covered in the article.</p>
<ul>
<li><p>Application: <a target="_blank" href="https://the-nextjs-pagesrouter-guide.vercel.app/"><strong>https://the-nextjs-pagesrouter-guide.vercel.app/</strong></a></p>
</li>
<li><p>GitHub Repo: <a target="_blank" href="https://github.com/salvillalon45/the-nextjs-pagesrouter-guide"><strong>https://github.com/salvillalon45/the-nextjs-pagesrouter-guide</strong></a></p>
</li>
</ul>
<p>In the GitHub repo you can find the code snippets for the following:</p>
<ul>
<li><p>A page implementing getStaticProps and getStaticPaths</p>
</li>
<li><p>A page implementing getStaticProps</p>
</li>
<li><p>A page implementing getServerSideProps with Client Side fetching</p>
</li>
<li><p>A page to demonstrate Hydration Errors</p>
</li>
<li><p>Using the API directory to implement our own API routes</p>
</li>
</ul>
<h3 id="heading-resources">Resources</h3>
<p>Here are some key learning resources I used to write this article in case you want to dig in even deeper:</p>
<ul>
<li><p><a target="_blank" href="https://youtu.be/R-BKadZWYnQ?si=imNFJL36knSPdF7S"><strong>What is Hydration</strong></a><strong>?</strong> by Builder</p>
</li>
<li><p><a target="_blank" href="https://youtu.be/87i0pejrULw?si=e179x9x2KkaR8AxL"><strong>What Exactly is REACT HYDRATION? And why does it matter?</strong></a> by Deeecode The Web</p>
</li>
<li><p><a target="_blank" href="https://youtu.be/d2yNsZd5PMs?si=UZYKHUrajdXQd1y4&amp;t=1"><strong>How NextJS REALLY Works</strong></a> by Theo Browne</p>
</li>
<li><p><a target="_blank" href="https://youtu.be/xfX8nVpaycU?si=ZV-r2piDoWhLAKMi"><strong>Next.js - GetServerSideProps vs GetStaticProps</strong></a> by Morado Web Development</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
