<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" 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/">
<channel>
<title><![CDATA[Gatsby - Rafael Quintanilha]]></title>
<description><![CDATA[Essays about software engineering, web development, artificial intelligence, quantitative analysis, financial markets, books and tradition.]]></description>
<link>https://rafaelquintanilha.com/topic/gatsby/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>Gatsby - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/gatsby/</link></image>
<lastBuildDate>Sun, 27 Nov 2022 15:46:55 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/gatsby/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[How to incrementally migrate a Gatsby app to TypeScript]]></title>
<description><![CDATA[Learn how you can safely adopt TypeScript in your project, right now, without major changes.]]></description>
<link>https://rafaelquintanilha.com/how-to-incrementally-migrate-a-gatsby-app-to-typescript/</link>
<guid isPermaLink="false">6383829114168e003dd8f5b1</guid>
<category><![CDATA[React]]></category><category><![CDATA[Gatsby]]></category><category><![CDATA[TypeScript]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 27 Jul 2022 15:43:00 GMT</pubDate>

<content:encoded><![CDATA[<figure class="image"><img alt="Tips on how to migrate a Gatsby app to TypeScript" loading="lazy" decoding="async" width="730" height="487" src="https://rafaelquintanilha.com/_astro/how-to-incrementally-migrate-gatsby-app-typescript--1--1.CSmy53RC_27UfQz.webp"><figcaption>Tips on how to migrate a Gatsby app to TypeScript</figcaption></figure>
<p>It shouldn’t come as a surprise that TypeScript is getting more traction among developers by the day. Support for it has grown considerably, as well as the community and number of projects adopting this technology.</p>
<p>It wasn’t always like that, though. Web developers have been burned before by hot technologies that disappeared, and it’s only fair that some in the community are more skeptical about big changes. In fact, <a href="https://en.wikipedia.org/wiki/Lindy_effect" rel="noopener noreferrer" target="_blank">the Lindy effect</a> proposes that every day a piece of technology continues to survive, the longer it is expected to exist.</p>
<p>The goal of this article is not to convince you to migrate to TypeScript; I assume that if you are here, you have already been sold on the benefits of static typing in a dynamic language like JavaScript. However, if you are like me, you probably have been delaying the migration, fearful of the amount of work needed to set it in motion.</p>
<p>Well, fear no more! I’ve done the heavy lifting for you. In this article, you will learn how to adopt TypeScript incrementally, so you can have a smooth transition and a good night of sleep after work.</p>
<h2 id="why-incrementally"><strong>Why incrementally?</strong></h2>
<p>Why do we have “incrementally” in the title of this article? Isn’t that just delaying the inevitable? Why not perform a full migration at once?</p>
<p>Those are valid points, and in some cases, they can even be the most advisable. However, I am assuming you have a somewhat large project, big enough that using a codemod won’t work (or will require too much workaround).</p>
<p>Or maybe you work on a specific part of an app in a larger team and want to run a pilot before doing the big change.</p>
<p>In all cases, there are valid scenarios where one would take the cautionary road first. And even though you will find a bunch of codemods or migration methods that claim to be seamless, the reality is that if your project has some complexity, it might not be as easy as they preach.</p>
<p>However, to offer a counterpoint, the folks at Stripe seem to disagree with me. They just recently published a <a href="https://stripe.com/blog/migrating-to-typescript" rel="noopener noreferrer" target="_blank">piece claiming to have migrated millions of lines of code to TypeScript.</a> If you are feeling adventurous, it’s worth checking it out!</p>
<h2 id="how-to-set-up-typescript-in-an-existing-gatsby-app"><strong>How to set up TypeScript in an existing Gatsby app</strong></h2>
<p>Alright, for today’s experiment we’ll assume you already have a Gatsby app and want to perform a gradual migration.</p>
<p>Remember that if you are creating a new project today, Gatsby already supports TypeScript as the main language from the beginning. Unfortunately, that’s not the case for most projects that were bootstrapped in older versions of Gatsby, so we are going to take a different route.</p>
<p>The Gatsby docs already present a <a href="https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/#migrating-to-typescript" rel="noopener noreferrer" target="_blank">good guide on how to migrate</a>. However, there are a few tweaks that we need to do in order to get it up and running smoothly.</p>
<h3 id="change-your-js-files-to-tsx"><strong>Change your .js files to .tsx</strong></h3>
<p>The easier part is to change all components you want to migrate to .tsx, or create new ones in this format. No work is needed on Gatsby’s side for this to work! That’s pretty neat.</p>
<h3 id="install-dependencies"><strong>Install dependencies</strong></h3>
<p>There are, however, some libraries to be installed. Make sure you add them to your <code>devDependencies</code>:</p>
<figure class="code"><figcaption>shell</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="shell"><code><span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> npm</span><span style="color:#97CCAE"> i</span><span style="color:#97CCAE"> –save-dev</span><span style="color:#97CCAE"> @types/node</span><span style="color:#97CCAE"> @types/react</span><span style="color:#97CCAE"> @types/react-dom</span><span style="color:#97CCAE"> typescript</span></span></code></pre></figure>
<h3 id="generate-tsconfig"><strong>Generate</strong> <strong><code>.tsconfig</code></strong></h3>
<p>TypeScript has a config file called <code>.tsconfig</code>, which is hugely customizable and will vary from project to project. However, there are some specific changes we need to make in order to allow TypeScript and JavaScript to coexist in harmony, as this is a requirement for everyone to adopt TS gradually.</p>
<p>An example of a working <code>.tsconfig</code> is as follows. Make sure to add it to the root folder of your project:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#97CCAE">  "compilerOptions"</span><span style="color:#ECEBE8">: {</span></span>
<span class="line"><span style="color:#97CCAE">    "target"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"es2016"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "jsx"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"react"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "module"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"commonjs"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "allowJs"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "outDir"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"./dist"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "esModuleInterop"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "forceConsistentCasingInFileNames"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "strict"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "skipLibCheck"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span></span>
<span class="line"><span style="color:#ECEBE8">  },</span></span>
<span class="line"><span style="color:#97CCAE">  "exclude"</span><span style="color:#ECEBE8">: [</span><span style="color:#97CCAE">"node_modules"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"public"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">".cache"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>You can also check an example <a href="https://github.com/rafaelquintanilha/gatsby-ts-vanilla-extract/blob/master/tsconfig.json" rel="noopener noreferrer" target="_blank">on this public repo in GitHub</a>.</p>
<p>Some of the needed configs are as follows:</p>
<ul>
<li>Add <code>"jsx": "react" </code>to make sure the compiler knows we are in a React project</li>
<li>Set <code>allowJs: true</code>; once JavaScript and TypeScript need to coexist, this flag should be turned on</li>
<li>Add <code>outDir: "./dist"</code>, which makes VS Code happy and prevents unwanted errors</li>
</ul>
<h3 id="declaring-globals"><strong>Declaring globals</strong></h3>
<p>If you got this far, you already have most of your setup working. However, there are still some rough edges.</p>
<p>The most obvious is about CSS modules; Gatsby works with CSS modules by default and we need to let TypeScript be happy about it. If you use <a href="https://blog.logrocket.com/how-to-use-svgs-in-react/" rel="noopener noreferrer" target="_blank">SVGs as components as described here</a>, this will also be useful.</p>
<p>At the <code>src</code> folder of your project, create a file called <code>globals.d.ts</code> and add the following:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">declare</span><span style="color:#A1C1E4"> module</span><span style="color:#97CCAE"> "*.module.css"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">declare</span><span style="color:#A1C1E4"> module</span><span style="color:#97CCAE"> "*.module.scss"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">declare</span><span style="color:#A1C1E4"> module</span><span style="color:#97CCAE"> "*.svg"</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> content</span><span style="color:#A1C1E4">:</span><span style="color:#A1C1E4"> string</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> content;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>This will make sure that both CSS and SVG are <a href="https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html" rel="noopener noreferrer" target="_blank">treated and handled as modules</a>.</p>
<p>Again, you can check <a href="https://github.com/rafaelquintanilha/gatsby-ts-vanilla-extract/blob/master/src/globals.d.ts" rel="noopener noreferrer" target="_blank">a working example in GitHub</a>.</p>
<blockquote>
<p>If you are using ESLint, it may complain about .d.ts files. In this case, you can <a href="https://stackoverflow.com/questions/63238879/eslint-only-declares-and-type-imports-are-allowed-inside-declare-module/63239805#63239805" rel="noopener noreferrer" target="_blank">disable the linter in such extensions</a>.</p>
</blockquote>
<h2 id="typing-using-prop-types"><strong>Typing using prop types</strong></h2>
<p>One of the main advantages of TypeScript is to allow static typing in JavaScript. When developing with React, this is much welcomed, because it makes it harder for us to add non-existing props or even pass the wrong variable.</p>
<p>Before TypeScript was a thing, the React team popularized <a href="https://reactjs.org/docs/typechecking-with-proptypes.html" rel="noopener noreferrer" target="_blank">typechecking with prop types</a>.</p>
<p>Prop types were an intermediary step between no validation and strict typing. With prop types, developers could list all props in a given component, their corresponding type, and whether they are optional or mandatory.</p>
<p>For example, suppose we have a component that receives a prop called <code>magicNumber</code>, which of course should have the type number:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> PropTypes </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'prop-types'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> MyComponent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ magicNumber }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> { … } </span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">MyComponent.propTypes </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  magicNumber: PropTypes.number.isRequired</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Suppose then that we render <code>MyComponent</code> but forget to pass <code>magicNumber</code> as prop, or pass a string instead. We would see a warning like this in the console, when in dev mode:</p>
<figure class="image"><img alt="Warning in dev mode" loading="lazy" decoding="async" width="768" height="68" src="https://rafaelquintanilha.com/_astro/warning-in-dev-mode.CFyX5tVT_2ajXlX.webp"><figcaption>Warning in dev mode</figcaption></figure>
<p>However, there would be no static validation, and it’s easy to overlook this kind of error in bigger components or larger projects. Also, we can add a prop but forget to set its type (there are some linters that help you with that though).</p>
<p>Using static typing, you can deprecate prop types in favor of regular TypeScript types:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">type</span><span style="color:#EDCC95"> Props</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  magicNumber</span><span style="color:#A1C1E4">:</span><span style="color:#A1C1E4"> number</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> MyComponent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ magicNumber }</span><span style="color:#A1C1E4">:</span><span style="color:#EDCC95"> Props</span><span style="color:#ECEBE8">) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> { … }</span></span></code></pre></figure>
<p>Now, if you have a .tsx component that renders <code>MyComponent</code>, passing a prop with the wrong type will raise an error at build time:</p>
<figure class="image"><img alt="Build time error" loading="lazy" decoding="async" width="730" height="208" src="https://rafaelquintanilha.com/_astro/build-time-error--1-.BK12cyVy_Hg3NI.webp"><figcaption>Build time error</figcaption></figure>
<p>And that’s it! Safer, but less verbose, and comes with all typing benefits. All in all, prop types work but are less powerful than a robust typing strategy like TypeScript. If you want to get deeper on this subject, I recommend you read our preview article on the subject: <a href="https://blog.logrocket.com/comparing-typescript-and-proptypes-in-react-applications/" rel="noopener noreferrer" target="_blank">Comparing TypeScript and PropTypes in React applications</a>.</p>
<p>If you are convinced that static typing is superior to prop types, you should also know that there’s a caveat when ditching prop types in a project that is a hybrid of TypeScript and JavaScript.</p>
<p>Suppose that we have a <code>WithTypeScript.tsx</code> component that renders the TypeScript version of <code>MyComponent</code>. If we try to pass <code>magicNumber="Hello World"</code> this is going to raise an error once there’s a type mismatch, as seen above.</p>
<p>However, if <code>WithTypeScript.tsx</code> receives <code>magicNumber</code> from a parent component written in pure JavaScript and passes it along to <code>MyComponent.tsx</code>, there is no way to validate if the variable is indeed a number. Once the parent component has no typing, no static error will be raised. And because there are no prop types in <code>MyComponent.tsx</code>, no runtime error will be raised. As such, this type mismatch won’t be raised anywhere.</p>
<figure class="image"><img alt="No runtime error" loading="lazy" decoding="async" width="730" height="282" src="https://rafaelquintanilha.com/_astro/no-runtime-error--1-.y26EYQZ8_Z1h5bGI.webp"><figcaption>No runtime error</figcaption></figure>
<p>Note how <code>IndexPage.js</code> calls a TypeScript component <code>WithTypeScript.tsx</code> with a wrong prop type. No warning is seen either in the editor or in the browser console.</p>
<p>Bear in mind that this only happens when .js and .tsx components are communicating, which will inevitably happen if you are gradually adopting TypeScript. Fortunately, there’s a solution for it: we can have the best of both worlds by inferring types from prop types in TypeScript components. This way, we retain the prop types, but automatically convert them into types using the function <code>InferProps</code> from the <a href="https://www.npmjs.com/package/prop-types" rel="noopener noreferrer" target="_blank">prop-types</a> library.</p>
<p>This would be <code>MyComponent.tsx</code> combining types and prop types:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> PropTypes, { InferProps } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "prop-types"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> Props </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  magicNumber: PropTypes.number.isRequired,</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">type</span><span style="color:#EDCC95"> MyComponentTypes</span><span style="color:#A1C1E4"> =</span><span style="color:#EDCC95"> InferProps</span><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">typeof</span><span style="color:#ECEBE8"> Props>;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> MyComponent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ magicNumber }</span><span style="color:#A1C1E4">:</span><span style="color:#EDCC95"> MyComponentTypes</span><span style="color:#ECEBE8">) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> { … };</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">MyComponent.propTypes </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> Props;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> MyComponent;</span></span></code></pre></figure>
<p><a href="https://github.com/rafaelquintanilha/gatsby-ts-vanilla-extract/blob/master/src/components/ChildTypeScript.tsx" rel="noopener noreferrer" target="_blank">A full example can be seen here</a>.</p>
<p>The above solution will raise a static error at build time if there’s a type mismatch but also raise a runtime error in the browser console if the wrong type is passed from a .js to a .ts component along the way. The drawback is that your code becomes more verbose.</p>
<p>However, if newer components only communicate with other .ts files, then it should be safe to ditch prop types. Eventually, when the migration is complete, you can completely remove them.</p>
<h2 id="conclusion"><strong>Conclusion</strong></h2>
<p>TypeScript is an exceptional tooling, but some developers refrain from adopting it in an existing codebase. This article aimed to elucidate how you can do it safely in your project, right now, without major changes.</p>
<p>While Gatsby in particular supports .tsx files out of the box, you need some workarounds to make your compiler happy considering typical approaches present in Gatsby codebases. Declaring globals for CSS Modules and SVGs are common pain points.</p>
<p>Finally, by having JavaScript communicating with TypeScript, we can’t guarantee that some typing errors won’t be opaque. Because of that, we can leverage the prop-types library and infer the types, getting the best of both worlds until we are safe to deprecate.</p>
<p>All code and examples present in this article can be found in <a href="https://github.com/rafaelquintanilha/gatsby-ts-vanilla-extract" rel="noopener noreferrer" target="_blank">this repo on GitHub</a>. Give it a try!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Leveraging Gatsby Incremental Builds With ButterCMS]]></title>
<description><![CDATA[Learn how to speed up your static builds with code examples.]]></description>
<link>https://rafaelquintanilha.com/leveraging-gatsby-incremental-builds-with-buttercms/</link>
<guid isPermaLink="false">63838a7b14168e003dd8f663</guid>
<category><![CDATA[Gatsby]]></category><category><![CDATA[ButterCMS]]></category><category><![CDATA[Netlify]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 08 Dec 2021 18:08:00 GMT</pubDate>

<content:encoded><![CDATA[<p>In the first days of the web, all pages were <a href="https://buttercms.com/blog/what-is-a-static-site/" rel="noopener noreferrer" target="_blank"><em><strong>static</strong></em></a>. This meant that a typical communication between a client and a server happened just once when the user first loaded the page. At that time, all resources were fetched and the content was rendered to the screen. If later the user came back to the same page, as long as the content hadn’t changed, they would get the same result.</p>
<p>As time went on, the need for <em>dynamic</em> content became more apparent. For example, if I were at a <a href="https://buttercms.com/blog/using-zapier-zeit-and-buttercms-to-generate-a-news-aggregator-site/" rel="noopener noreferrer" target="_blank"><strong>news website</strong></a>, I would want to get fresh content. Or maybe if I were following stock market prices, I would want real-time data. Social network feeds could also be a clear use case for dynamic, always-changing content. As you can see, the static approach was doomed.</p>
<p>With <em>dynamic</em> architecture, though, data is pulled routinely. That way, your newsfeed can be regularly updated without the need for <em>requesting</em> new information. Plus, if only <em>part</em> of the content changes, all you need to do is fetch that part, preventing you from having to download all the data again. It’s a huge win.</p>
<figure class="image"><img alt="Static vs dynamic architecture" loading="lazy" decoding="async" width="1201" height="629" src="https://rafaelquintanilha.com/_astro/static-vs-dynamic-architecture--1-.DOMVrDt9_1A3nzu.webp"><figcaption>Static vs dynamic architecture</figcaption></figure>
<p>That model enabled the boom of <em>web applications</em>, given that web pages started to get more dynamic, more interactive, more powerful, and faster. Data is being constantly updated based on user actions, and because we are smart enough to pull only the freshest information, performance for complex applications has increased as well.</p>
<p>As good as it sounds, the dynamic model still has its flaws. First, because data is being constantly fetched, the application should be “mounted” on the fly, being loaded in chunks and either rendered asynchronously or after an unnecessarily long wait. Additionally, this wait is bad for SEO since the <em>web crawler</em> has to wait until the data is fetched and the page is mounted to be able to start properly indexing the application (and Google had limitations with that for years).</p>
<p>The static model overcomes these flaws. Because the content is already rendered and stored in the server, you download it only once (when you land on the page) and everything is ready to use. Crawlers are happy too — they can start indexing your page right away, saving your <a href="https://developers.google.com/search/blog/2017/01/what-crawl-budget-means-for-googlebot" rel="noopener noreferrer" target="_blank"><strong>crawl budget</strong></a>. Faster loading times plus no waste of crawl budget equals a higher-ranked SEO page, which in turn means more organic users, less money spent on advertising, more revenue, and so on. In short: static sites are less flexible but more SEO-friendly. The big question then becomes: is it possible to make them more malleable and still retain the SEO benefits?</p>
<h2 id="enter-server-side-rendered-apps"><strong>Enter server-side rendered apps</strong></h2>
<p>Server-Side Rendering (SSR) applications are, as the name suggests, rendered on the server. How is that different from the traditional <em>static</em> model?</p>
<p>In SSR architecture, the application is regularly built during the build phase. In each build, the freshest data available is gathered, which means that every build has dynamic content. This solves the problem for applications that aren’t time-sensitive. If your app can afford to update data, say, every 30 minutes, then an SSR approach might make sense for you. Every 30 minutes, you download the freshest data available, build (<em>render</em>) your page, and upload (<em>deploy</em>) the content to the server. Your users will then fetch the page as a static resource (like in the old days), and the content will be at most 30 minutes delayed.</p>
<figure class="image"><img alt="Server-Side Rendering" loading="lazy" decoding="async" width="1200" height="628" src="https://rafaelquintanilha.com/_astro/server-side-rendering--1-.BDl1K7Mh_ZcY38A.webp"><figcaption>Server-Side Rendering</figcaption></figure>
<p>Or maybe you have a website with content that doesn’t change very often, like a blog, but that you want to rebuild every time it changes (maybe a new edition is made or a new post is added.) In that scenario, you could set a <em>deploy hook</em> that would rebuild and deploy your application as needed.</p>
<p>Now, imagine this blog is really big. For example, it has thousands of entries. If you change page A, you really don’t want to rebuild all the other entries. That can get really problematic at scale. In other words, the desired effect is to rebuild only the content that changed, nothing else. Now how are we able to do that?</p>
<h2 id="incremental-builds"><strong>Incremental builds</strong></h2>
<p>The answer to this question lies in <em>incremental builds.</em> As the name suggests, and our intuition indicates, incremental builds will build only what is necessary (i.e. what has been added or updated.) A <em>full build</em>, on the other hand, rebuilds the whole application at once, notwithstanding the number of pages and the time needed to accomplish this.</p>
<figure class="image"><img alt="Standard vs Incremental Builds" loading="lazy" decoding="async" width="1201" height="629" src="https://rafaelquintanilha.com/_astro/standard-vs-incremental-build--1-.oQQMQ-dE_2rwTU1.webp"><figcaption>Standard vs Incremental Builds</figcaption></figure>
<p>In the big blog example, it means that when page A is modified or added, the others won’t be rebuilt. In terms of build time, this is a huge win—the faster your website is rebuilt, the sooner your users will have access to fresh data.</p>
<p>The benefits are not limited to only blog posts but product catalogs, social network profiles, stock market indicators, and basically everything that is bound to be read from a CMS can potentially make the most of incremental builds. In general, if your app relies on data from another source—for example, a CMS editor such as ButterCMS—incremental builds are a really smart choice.</p>
<h3 id="when-not-to-use-incremental-builds"><strong>When not to use Incremental Builds</strong></h3>
<p>Sometimes it'll be in your best interest to do a full build. For example, if you add a new feature to your application that is visible throughout the app (say, a sidebar), you will want it to be present on every page.</p>
<p>Also, as mentioned before, if your application is sensitive to real-time data then an SSR approach (and, therefore, incremental builds) won’t be adequate.</p>
<h2 id="gatsbys-approach-to-incremental-builds"><strong>Gatsby’s approach to incremental builds</strong></h2>
<p>When <a href="http://gatsbyjs.com/" rel="noopener noreferrer" target="_blank"><strong>Gatsby</strong></a> launched their <a href="https://www.gatsbyjs.com/products/cloud/" rel="noopener noreferrer" target="_blank"><strong>cloud service</strong></a>, one of the main benefits was — you guessed it — incremental builds, a long-awaited feature of the community.</p>
<p>As expected, this approach became very popular—to the point that since the launching of Gatsby v3 in March of 2021, <a href="https://www.gatsbyjs.com/blog/gatsby-v3/" rel="noopener noreferrer" target="_blank"><strong>incremental builds became available to everyone</strong></a> <em>by default.</em> Now, content creators who are integrating their CMS with Gatsby have this functionality right off the bat, allowing faster build times and better scalability.</p>
<p>Later, we will see how Gatsby’s incremental builds work in practice.</p>
<h2 id="leveraging-incremental-builds-with-buttercms"><strong>Leveraging incremental builds with ButterCMS</strong></h2>
<p>I mentioned before that incremental builds are particularly interesting for content creators. It gets even better for users who use a <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><strong>headless CMS</strong></a>.</p>
<p>A headless CMS is a data source that abstracts away the need to change <em>code</em> when all you want to change is <em>content</em>. Suppose you want to deploy a landing page for a brand-new product of yours. Well, you may be working closely with the marketing team, tweaking texts, adding images, changing colors, and so on in a never-ending search for perfection. Now, if you have a team of engineers, it’s arguably not the best use of their time and expertise to tweak pixels on the screen.</p>
<p>A headless CMS is a solution for the aforementioned problem that delegates the creation of the landing page to a dedicated team and, later on, integrates the end result into your app.</p>
<p><a href="https://buttercms.com/" rel="noopener noreferrer" target="_blank"><strong>ButterCMS</strong></a> is an excellent example of a headless CMS. Butter users can create and edit landing pages in addition to maintaining posts and other content while integrating it easily with several programming languages. One of the most popular is Gatsby, which has a <a href="https://www.gatsbyjs.com/docs/sourcing-from-buttercms/" rel="noopener noreferrer" target="_blank"><strong>simple plugin</strong></a> to source data directly from ButterCMS in each build.</p>
<p>Now, if you have been following me since the beginning, you know what I’m getting at: Gatsby enables incremental builds when content changes by default (since v3), and also integrates seamlessly with ButterCMS. ButterCMS, in turn, is a headless CMS that empowers content creators. Can we connect them all and testify to the miracle of <em>incremental builds with Gatsby and ButterCMS?</em> Heck, yeah.</p>
<p>In the next section, we will learn how to create a simple Gatsby website that sources data from ButterCMS. We will also deploy this application to <a href="https://www.netlify.com/" rel="noopener noreferrer" target="_blank"><strong>Netlify</strong></a> to understand how incremental builds work in practice.</p>
<h2 id="tutorial-creating-a-simple-blog-using-buttercms-and-gatsbys-incremental-builds"><strong>Tutorial: Creating a simple blog using ButterCMS and Gatsby’s incremental builds</strong></h2>
<h3 id="before-you-begin"><strong>Before you begin</strong></h3>
<p>There are a couple of things you are going to need in order to follow through with this tutorial. One of them is a ButterCMS account. Go to <a href="https://buttercms.com/join" rel="noopener noreferrer" target="_blank"><strong>https://buttercms.com/join</strong></a> and sign up, if you still haven’t. Once you are logged in, click on your account and hit “Settings.” Select the “API Keys” tab and copy what is under “Read API Token,” which we will need to fetch information from Butter. Make sure to store it safely.</p>
<p>Next, make sure you have NodeJS installed. <a href="https://www.gatsbyjs.com/docs/tutorial/part-0/#nodejs" rel="noopener noreferrer" target="_blank"><strong>Gatsby’s Docs have a section</strong></a> explaining how to do it for every OS. Also, it’s a good idea to follow through with their tutorial if you are a complete newbie to Gatsby.</p>
<p>Finally, create an account on Netlify. We will host our application there (don’t worry, it’s free!) so we can see in practice how incremental builds work in a production environment. We’ll get to that part later.</p>
<h3 id="what-were-building"><strong>What we're building</strong></h3>
<p>To showcase how incremental builds work, we are going to build an application that pulls posts from ButterCMS. We will render this content to our site and watch how builds react as content changes.</p>
<h3 id="step-1-creating-a-gatsby-app"><strong>Step 1: Creating a Gatsby app</strong></h3>
<p>The first thing to do is to create the Gatsby application. Follow their <a href="https://www.gatsbyjs.com/docs/quick-start/" rel="noopener noreferrer" target="_blank"><strong>quick start</strong></a> to create an initial boilerplate. Don’t worry about all the customizations; we are not going to need them now. After completing the quick start, make sure you can visit localhost:8000 and see your brand-new Gatsby app.</p>
<h3 id="step-2-sourcing-data-from-buttercms"><strong>Step 2: Sourcing data from ButterCMS</strong></h3>
<p>Our app is so far pretty simple. We are going to color it a bit by integrating data with ButterCMS. The first thing you want to do, if you haven’t already, is to add some content in Butter!</p>
<p>In Butter’s admin panel, click on “Blog posts” in the side menu and add a couple of entries. In the end, it should look something like this:</p>
<figure class="image"><img alt="ButterCMS admin panel" loading="lazy" decoding="async" width="1023" height="786" src="https://rafaelquintanilha.com/_astro/incremental-builds-buttercms-blog-posts--1-.DtWZITcX_ZP9Ixs.webp"><figcaption>ButterCMS admin panel</figcaption></figure>
<p>Now that we have actual content in our CMS, we are ready to <em>source it</em> in Gatsby. As mentioned before, Gatsby and Butter have a handy integration plugin called <em>gatsby-source-buttercms.</em> You can follow the <a href="https://www.gatsbyjs.com/docs/sourcing-from-buttercms/" rel="noopener noreferrer" target="_blank"><strong>official docs from Gatsby</strong></a> for more context.</p>
<p>In your project’s directory, add the plugin:</p>
<p><code>$ npm install gatsby-source-buttercms</code></p>
<p>Once the installation is done, open <em>gatsby-config.js</em> and add the following to the <em>plugins</em> array:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#ECEBE8">      resolve: </span><span style="color:#97CCAE">`gatsby-source-buttercms`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      options: {</span></span>
<span class="line"><span style="color:#ECEBE8">        authToken: YOUR_TOKEN</span></span>
<span class="line"><span style="color:#ECEBE8">      },</span></span>
<span class="line"><span style="color:#ECEBE8">    },</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Replacing <em>YOUR_TOKEN</em> with the token you grabbed from Butter’s panel before. If everything is correct, start the Gatsby server again and go to <a href="http://localhost:8000/___graphql" rel="noopener noreferrer" target="_blank"><strong>http://localhost:8000/___graphql</strong></a> where you should be able to see this:</p>
<figure class="image"><img alt="GraphQL interface" loading="lazy" decoding="async" width="1111" height="559" src="https://rafaelquintanilha.com/_astro/incremental-builds-local-host-1--1-.sDD9xK55_Z2l4x9w.webp"><figcaption>GraphQL interface</figcaption></figure>
<p>Note how there are Butter <a href="https://www.gatsbyjs.com/docs/reference/graphql-data-layer/node-interface/" rel="noopener noreferrer" target="_blank"><strong>nodes</strong></a> in the Explorer! You can easily test that the data is available by writing the following query to the interface:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#ECEBE8">query MyQuery {</span></span>
<span class="line"><span style="color:#ECEBE8">  allButterPost {</span></span>
<span class="line"><span style="color:#ECEBE8">    nodes {</span></span>
<span class="line"><span style="color:#ECEBE8">      title</span></span>
<span class="line"><span style="color:#ECEBE8">      author {</span></span>
<span class="line"><span style="color:#ECEBE8">        first_name</span></span>
<span class="line"><span style="color:#ECEBE8">        last_name</span></span>
<span class="line"><span style="color:#ECEBE8">      }</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Now you should see the title of your posts and the author’s name in the right-side panel. Nice job! Gatsby and ButterCMS are now hooked up!</p>
<h3 id="step-3-rendering-data-in-gatsby"><strong>Step 3: Rendering data in Gatsby</strong></h3>
<p>Now, our app is sourcing data from Butter, but we are still not seeing it. Thankfully, this is the easy part!</p>
<p>For our proof-of-concept, we are going to create three pages:</p>
<ol>
<li>A home page, which will have no information from Butter;</li>
<li>A blog index, which will render the title of all posts and link to them;</li>
<li>A post template, which will be used to dynamically render every post added in Butter.</li>
</ol>
<p>Our goal, when debugging incremental builds, will be to assert the following:</p>
<ul>
<li>A code change triggers a rebuild for all pages;</li>
<li>A content change triggers a rebuild only for the pages that contain that content (the blog index and the corresponding post):</li>
<li>As a corollary, if I change post A, then the home page and post B shouldn’t be rebuilt.</li>
</ul>
<p>Create the blog index component:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Layout </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "../components/layout"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { useStaticQuery, graphql, Link } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "gatsby"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { content } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "./blog.module.css"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Blog</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">    allButterPost: { nodes: posts },</span></span>
<span class="line"><span style="color:#ECEBE8">  } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useStaticQuery</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">graphql</span><span style="color:#97CCAE">`</span></span>
<span class="line"><span style="color:#97CCAE">    query MyQuery {</span></span>
<span class="line"><span style="color:#97CCAE">      allButterPost {</span></span>
<span class="line"><span style="color:#97CCAE">        nodes {</span></span>
<span class="line"><span style="color:#97CCAE">          title</span></span>
<span class="line"><span style="color:#97CCAE">          slug</span></span>
<span class="line"><span style="color:#97CCAE">        }</span></span>
<span class="line"><span style="color:#97CCAE">      }</span></span>
<span class="line"><span style="color:#97CCAE">    }</span></span>
<span class="line"><span style="color:#97CCAE">  `</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Layout</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>My Blog&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">ul</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{content}></span></span>
<span class="line"><span style="color:#ECEBE8">          {</span><span style="color:#EDCC95">posts.map</span><span style="color:#ECEBE8">((post) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{post.slug}></span></span>
<span class="line"><span style="color:#ECEBE8">              &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{</span><span style="color:#97CCAE">`/blog/${</span><span style="color:#97CCAE">post.slug</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">}>{post.title}&#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          ))}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">Layout</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Blog;</span></span></code></pre></figure>
<p>And the post template:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { Link, graphql } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "gatsby"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Layout </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "./layout"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { container, back, body } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "./post.module.css"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> PostTemplate</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ data }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Layout</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{container}></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{back} </span><span style="color:#EDCC95">to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          ⇦ Go back</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>{data.butterPost.title}&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span></span>
<span class="line"><span style="color:#EDCC95">          className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{body}</span></span>
<span class="line"><span style="color:#EDCC95">          dangerouslySetInnerHTML</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ __html: data.butterPost.body }}</span></span>
<span class="line"><span style="color:#ECEBE8">        /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">Layout</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> query </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> graphql</span><span style="color:#97CCAE">`</span></span>
<span class="line"><span style="color:#97CCAE">  query ($slug: String!) {</span></span>
<span class="line"><span style="color:#97CCAE">    butterPost(slug: { eq: $slug }) {</span></span>
<span class="line"><span style="color:#97CCAE">      title</span></span>
<span class="line"><span style="color:#97CCAE">      body</span></span>
<span class="line"><span style="color:#97CCAE">    }</span></span>
<span class="line"><span style="color:#97CCAE">  }</span></span>
<span class="line"><span style="color:#97CCAE">`</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> PostTemplate;</span></span></code></pre></figure>
<p>For the sake of simplicity, I’m not going into Gatsby’s details in this tutorial, but you have access to the full code at <a href="https://github.com/ButterCMS/gatsby-incremental-builds" rel="noopener noreferrer" target="_blank"><strong>https://github.com/ButterCMS/gatsby-incremental-builds</strong></a>. A live example can be found at <a href="https://incremental-builds.netlify.app/" rel="noopener noreferrer" target="_blank"><strong>https://incremental-builds.netlify.app/</strong></a>.</p>
<p>If you follow through the repository (or clone it and switch the <em>authToken</em> with your own), you will see something like this:</p>
<figure class="image"><img alt="Blog page" loading="lazy" decoding="async" width="1033" height="803" src="https://rafaelquintanilha.com/_astro/incremental-builds-blog-page.DVz5j5Vq_ZtGCBb.webp"><figcaption>Blog page</figcaption></figure>
<p>See how the content of the post you added in ButterCMS is correctly rendered in your app? Congratulations, you have successfully combined Butter and Gatsby!</p>
<h3 id="step-4-deploying-to-netlify"><strong>Step 4: Deploying to Netlify</strong></h3>
<p>Now that our app is complete, it’s time to make it available to the world. <a href="https://app.netlify.com/" rel="noopener noreferrer" target="_blank"><strong>Log in to Netlify</strong></a> and click on “New site from git.”</p>
<p><em>Note: It’s a good time to create a repository for your own app. I recommend</em> <a href="https://github.com/" rel="noopener noreferrer" target="_blank"><em><strong>GitHub</strong></em></a><em>. Follow the instructions on their website to store your code in the cloud and get Git benefits.</em></p>
<p><em>Warning:</em> <em><strong>do</strong></em> <em><strong>not</strong></em> <em>commit your ButterCMS token to any Git provider. When using Netlify,</em> <a href="https://docs.netlify.com/configure-builds/environment-variables/" rel="noopener noreferrer" target="_blank"><em><strong>Netlify environment variables</strong></em></a> <em>are preferred instead.</em></p>
<p>When creating your new site, make sure to replace the <em>Build</em> command with:</p>
<p><code>gatsby build --verbose --log-pages</code></p>
<p>This will be necessary to gather more information about built pages. <a href="https://www.gatsbyjs.com/docs/debugging-incremental-builds/" rel="noopener noreferrer" target="_blank"><strong>Gatsby Docs</strong></a> have a dedicated page on how to debug incremental builds.</p>
<p>If all is good, you should be able to start a deploy for your app and see something like this in the logs:</p>
<figure class="image"><img alt="Deploy summary" loading="lazy" decoding="async" width="340" height="321" src="https://rafaelquintanilha.com/_astro/deploy-summary-1-1.B8fEYM7v_Z1re1co.webp"><figcaption>Deploy summary</figcaption></figure>
<figure class="image"><img alt="Deploy logs" loading="lazy" decoding="async" width="453" height="216" src="https://rafaelquintanilha.com/_astro/deploy-summary-2-1.BpxBaFOt_252NzP.webp"><figcaption>Deploy logs</figcaption></figure>
<p>Note how Netlify discerns all pages and assets built during that phase. If you scroll down the logs, you will be able to see more detailed information on the number of pages updated and how long it took for Gatsby to build them.</p>
<h3 id="step-5-hooking-netlify-deploys-to-content-changes"><strong>Step 5: Hooking Netlify deploys to content changes</strong></h3>
<p>The penultimate step remaining in your build puzzle is to “hook” every change in Butter’s content to a new deploy in Netlify. This way, every time a post is either published or updated in the Butter interface, we trigger a new build in Netlify. This build will generate new static assets (only if the content has changed) and then deploy them to the server. New visitors will be served with the updated content as soon as the deploy is complete.</p>
<p>In Netlify, go to “Site settings” and then “Build &#x26; deploy.” Scroll down to “Build hooks” and click on “Add build hook”. Give it a descriptive name and, in the end, you should see something like this:</p>
<figure class="image"><img alt="Netlify Build hooks" loading="lazy" decoding="async" width="922" height="327" src="https://rafaelquintanilha.com/_astro/netlify-build-hooks.BWDwJ5Tp_2jHQc7.webp"><figcaption>Netlify Build hooks</figcaption></figure>
<p>Copy the URL (the “hook”) and head to Butter’s panel. Go back to “Settings” again and, in the “Webhooks” tab, add the copied URL as the Target URL. Leave “Header” blank and select <em>post.published - blog post is published</em> in the Event field. Hit “Save” and we are done! Now, every time any post is published, a new build will be triggered.</p>
<p>In order to test that, go to your Blog posts and change something in one of the posts. Note that Netlify will automatically start a new build and that by the end of it only the affected pages (the post itself and the index with all posts) will be rebuilt!</p>
<figure class="image"><img alt="Deploy summary after changes" loading="lazy" decoding="async" width="372" height="221" src="https://rafaelquintanilha.com/_astro/deploy-summary-after-change-1.Cpit-Gif_2uS6dL.webp"><figcaption>Deploy summary after changes</figcaption></figure>
<figure class="image"><img alt="Deploy logs after changes" loading="lazy" decoding="async" width="442" height="128" src="https://rafaelquintanilha.com/_astro/deploy-summary-after-change-2.C-mKF-Kb_ccWDd.webp"><figcaption>Deploy logs after changes</figcaption></figure>
<p>Note how this build was faster (10s now vs 15s before). Now, imagine the difference if you had hundreds or thousands of pages of static content!</p>
<p><em>Note: Due to cache reasons it might be that the incremental builds kick in only after you have rebuilt your site at least once.</em></p>
<p>As a final test, change something in your Gatsby code and push it to your Git provider. As expected, <em>all</em> pages will be rebuilt, as mentioned in <a href="https://www.gatsbyjs.com/docs/debugging-incremental-builds/#expected-behaviors" rel="noopener noreferrer" target="_blank"><strong>Gatsby’s Docs as expected behavior</strong></a>. In short: incremental builds will be applied whenever <em>content</em> changes, but full builds are expected when your <em>code</em> changes.</p>
<h3 id="step-6-previewing-draft-content-before-publishing"><strong>Step 6: Previewing draft content before publishing</strong></h3>
<p>There is one last enhancement that can be done in order to streamline our process even more. In the previous step, we set up a webhook that rebuilds the website when a new post is <em>published</em> or <em>updated</em>. That’s really great, but in a working environment, the experience would be subpar. Oftentimes, content creators will want to double-check and preview their work before publishing it to a production environment.</p>
<p>Luckily, there’s a way to circumvent this limitation with ButterCMS! All we need to do is to set up a proper <em>staging</em> environment. I will walk you through how to do it in Netlify in a moment, but before that, create a <em>staging</em> branch in your repo:</p>
<p><code>$ git checkout -b staging</code></p>
<p>Now that you are in a different branch, the only code change needed is to tell <em>gatsby-source-buttercms</em> that you also want to source data in a <em>draft</em> state. Go to <em>gatsby-config.js</em> again and add the following line:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#ECEBE8">      resolve: </span><span style="color:#97CCAE">`gatsby-source-buttercms`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      options: {</span></span>
<span class="line"><span style="color:#ECEBE8">        authToken: YOUR_TOKEN,</span></span>
<span class="line"><span style="color:#ECEBE8">        preview: </span><span style="color:#97CCAE">1</span></span>
<span class="line"><span style="color:#ECEBE8">      },</span></span>
<span class="line"><span style="color:#ECEBE8">    },</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Surprisingly, that’s all you need code-wise! As a side note, you could try to use environment variables to spawn multiple environments based on the same code.</p>
<p>Let us now set up the <em>staging</em> environment. Hop back to Netlify and create a new site. Again, we are taking the simpler step here. If you have a custom domain registered with Netlify, you can leverage <a href="https://docs.netlify.com/domains-https/custom-domains/multiple-domains/#branch-subdomains" rel="noopener noreferrer" target="_blank"><strong>branch subdomains</strong></a> instead of setting up a new site.</p>
<p>Repeat the procedure done in Step 4, only this time selecting <em>staging</em> as the “Branch to deploy.” Your configuration should look similar to this:</p>
<figure class="image"><img alt="Branch subdomains configuration" loading="lazy" decoding="async" width="725" height="880" src="https://rafaelquintanilha.com/_astro/branch-to-deploy-configuration.B8Oj8217_ApLsF.webp"><figcaption>Branch subdomains configuration</figcaption></figure>
<p>Proceed to deploy and don’t forget to add your ButterCMS API key as an environment variable to the site recently created.</p>
<p>Next, repeat Step 5 and create a new webhook both in Netlify and ButterCMS. Make sure to add the URL generated by Netlify as the <em>Target URL</em> in Butter’s Webhooks tab and, this time, select <em>post.draft - draft post is saved</em> in the Event field. Your Butter’s webhooks should look like this:</p>
<figure class="image"><img alt="ButterCMS webhooks" loading="lazy" decoding="async" width="1345" height="543" src="https://rafaelquintanilha.com/_astro/buttercms-webhooks.CPDm10S7_2hwbKy.webp"><figcaption>ButterCMS webhooks</figcaption></figure>
<p>As is, our app already has a working preview environment: every time a new draft post is <em>created</em> or <em>saved</em>, a webhook will be triggered to rebuild our <em>staging</em> site in Netlify. This way, content creators can iterate and observe how it looks on the real page before actually publishing to the production site.</p>
<p>The only caveat is that previewing happens <em>outside</em> Butter — well, not anymore! The last step in this tutorial is to set up <em>Previews</em> in Butter’s settings, which means that ButterCMS will become the one-stop shop for your content creators.</p>
<p>Click on the “Previews” tab and add the template URL to the <em>Blog Posts</em> field. In our case, it will look like: https://your-staging-site-url.netlify.app/blog/&#x3C;slug>. The green part is what we defined in <em>gatsby-node.js</em>, only now using <em>&#x3C;slug></em> as the slug placeholder.</p>
<p>And that’s it! All technical details are done. Try your setup by creating a new post, but instead of clicking on “Publish,” select “Save draft.” Check that only your staging site was rebuilt, while the production site remained unchanged. Compare how the blog index is different in the <a href="https://staging-incremental-builds.netlify.app/blog" rel="noopener noreferrer" target="_blank"><strong>staging</strong></a> and live <a href="https://incremental-builds.netlify.app/blog" rel="noopener noreferrer" target="_blank"><strong>production</strong></a> environments.</p>
<p>Note that you can keep editing your content in Butter and, whenever “Save draft” is clicked, a new rebuild will be triggered. Click on the “Preview” button while editing to see your changes right inside Butter’s panel! Hopefully, once we are leveraging incremental builds, the rebuild will be really fast and the new content will be readily available.</p>
<figure class="image"><img alt="Previewing changes" loading="lazy" decoding="async" width="1744" height="1250" src="https://rafaelquintanilha.com/_astro/buttercms-preview-example--1-.iBsxC4M-_Zezb9s.webp"><figcaption>Previewing changes</figcaption></figure>
<h2 id="conclusion"><strong>Conclusion</strong></h2>
<p>Today, we learned the motivation behind incremental builds and the problems they are trying to solve. We gathered all information in a tutorial hooking up ButterCMS and Gatsby, which has incremental builds enabled for free by default since v3.</p>
<p>Incremental builds are and will no doubt continue to be beneficial for content creators, especially the ones leveraging a Gatsby-compatible <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><strong>headless CMS</strong></a> such as ButterCMS. By significantly decreasing build times, your website will be able to scale properly as new content is added for the enjoyment of your audience.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to Rebuild Static Sites at Fixed Intervals with Netlify and GitHub Actions]]></title>
<description><![CDATA[Learn how to schedule redeployments at regular intervals by building a simple application that fetches stock market data.]]></description>
<link>https://rafaelquintanilha.com/how-to-rebuild-static-sites-at-fixed-intervals-with-netlify-and-github-actions/</link>
<guid isPermaLink="false">6383a8f614168e003dd8f6e6</guid>
<category><![CDATA[Gatsby]]></category><category><![CDATA[Netlify]]></category><category><![CDATA[ButterCMS]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 15 Jun 2021 18:23:00 GMT</pubDate>

<content:encoded><![CDATA[<figure class="image"><img alt="Setting up cron jobs with GitHub Actions and Netlify" loading="lazy" decoding="async" width="600" height="600" src="https://rafaelquintanilha.com/_astro/illustration-edit-cron-jobs.CwrUK8wq_2bJdlY.webp"><figcaption>Setting up cron jobs with GitHub Actions and Netlify</figcaption></figure>
<p>Back in the old days, websites were all static. That meant that all content rendered on the page was fetched previously from the server and no change would take place until the files were updated. Time has passed and the need for <em>dynamic</em> data has increased — now users are demanding faster, timelier updates and the traditional model has become outdated.</p>
<p>Technologies like React, which can be used with our <a href="https://buttercms.com/react-cms/" rel="noopener noreferrer" target="_blank"><strong>React CMS</strong></a>, popularized the concept of client-side apps, where the browser would download the JavaScript from the server and render the whole app from there. If further data was needed, the application would issue as many HTTP requests as needed in order to get recent, up-to-date information.</p>
<p>The idea was great and people quickly adopted it. However, this approach had some shortcomings: because the application had to be constructed from scratch <em>after</em> the JavaScript was downloaded <em>and</em> parsed, larger apps could face performance issues. Moreover, SEO was a problem since web crawlers had less time to get available content to index your web page (only after <a href="https://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157" rel="noopener noreferrer" target="_blank"><strong>they got smart enough to crawl JavaScript</strong></a>).</p>
<p>In order to address these issues and retain the good from the dynamic approach, the concept of <em>server-side rendered</em> applications was introduced. Now, the app is rendered on the server during a phase called <em>build time</em>, which yields a bunch of static files to be served very much like the old days. During build time, data can be sourced from different places (e.g. a database, an external API, etc), which enables the static file to actually have dynamic information.</p>
<p>Now, considering that all data is fetched during build time, the app is as up-to-date as the last build. This means that if you don’t routinely <em>rebuild</em> it, your app won’t differ very much from the traditional model.</p>
<p>The goal of this article is to explain how you can easily set up and edit cron jobs to schedule a build for your static website at regular intervals, so you can use the latest cutting-edge tools for web development and still retain the ability to create SEO-friendly applications.</p>
<h2 id="what-is-a-cron-job"><strong>What is a cron job?</strong></h2>
<p>A <em>cron job</em> is simply a task scheduled to be executed at defined intervals. You can instruct a computer program to perform a routine at those intervals using a <em>crontab</em>.</p>
<p>Crontabs follow a specific structure that can be quickly learned. Fortunately, there are applications such as <a href="https://crontab.guru/" rel="noopener noreferrer" target="_blank"><strong>crontab guru</strong></a> that help you to edit cron jobs very easily. Diving into the specifics of crontabs is out of the scope of this article, but as a quick example, the following is the cron structure necessary to run a task at 8 pm every weekday:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="text"><code><span class="line"><span>0  20  *  *  1-5</span></span></code></pre></figure>
<p>The first position (0) is the <em>minute</em> that the task must be executed. The next one (20), is the hour. Combining both, we are instructing the computer to execute the task at minute 0 of the 20th hour (8 pm).</p>
<figure class="image"><img alt="Editing cron jobs illustration" loading="lazy" decoding="async" width="600" height="600" src="https://rafaelquintanilha.com/_astro/edit-cron-jobs.D60I0R_A_1udlbm.webp"><figcaption>Editing cron jobs illustration</figcaption></figure>
<p>The third position states the <em>day of the month,</em> while the fourth position is about the <em>month</em> itself. An asterisk means that <em>any</em> value is fine for both entries. Finally, the last value is the day of the week, where we are instructing the computer to only execute on days 1 to 5 (starting from 0, which is Sunday). Therefore, only days from Monday to Friday are included. We can view a nice, human-readable description of cron <a href="https://crontab.guru/#0_18_*_*_1-5" rel="noopener noreferrer" target="_blank"><strong>here</strong></a>.</p>
<h2 id="netlify-build"><strong>Netlify Build</strong></h2>
<p>Earlier we learned that <em>server-side rendered</em> applications render static files during their <em>build</em>. In a production environment, it is important that you are able to automatically <em>trigger</em> a build so you can set up a workflow for the deployment of your website.</p>
<p>One of the many tools available nowadays is <a href="https://www.netlify.com/products/build/" rel="noopener noreferrer" target="_blank"><strong>Netlify Build</strong></a>. Netlify Build is a modern way to go from code to deployment without too much of a hassle. As the name suggests, it takes care of building your website and deploying the output to the internet. There are several articles explaining how to use Netlify and its benefits (including <a href="https://buttercms.com/blog/what-is-serverless-and-how-to-use-it-in-practice/" rel="noopener noreferrer" target="_blank"><strong>What is Serverless and How to Use It in Practice</strong></a>) but if you haven’t used it yet, don’t worry — we are going to see how it works step by step.</p>
<figure class="image"><img alt="Netlify and GitHub communicating" loading="lazy" decoding="async" width="600" height="600" src="https://rafaelquintanilha.com/_astro/website-build.DYJAfqvI_Z2jKeYq.webp"><figcaption>Netlify and GitHub communicating</figcaption></figure>
<h3 id="build-hooks">Build hooks</h3>
<p>Considering that Netlify allows you to trigger builds, a natural question is how can you programmatically instruct Netlify that a build is due.</p>
<p>Fortunately, Netlify provides what are called <a href="https://docs.netlify.com/configure-builds/build-hooks/" rel="noopener noreferrer" target="_blank"><em><strong>build hooks</strong></em></a>. In their own words, <em>build hooks are URLs you can use to trigger new builds and deploys</em>. It means that every time you make a POST request to the provided URL, you are able to trigger a build.</p>
<p>We are getting closer to our goal: we know already that we can rebuild and deploy static websites using Netlify and that there is a unique URL that can be used to trigger a build programmatically. If we find a way to make POST requests at regular intervals, then we will be able to schedule builds for our static website.</p>
<h2 id="github-actions"><strong>GitHub Actions</strong></h2>
<p>The answer to this problem lies in a feature called <a href="https://github.com/features/actions" rel="noopener noreferrer" target="_blank"><strong>GitHub Actions</strong></a>. Actions are a very powerful service offered by GitHub that can leverage your application’s CI/CD (continuous integration and deployment) workflow. We are not getting into details of all the advantages that Actions can provide to you, but I suggest reading <a href="https://docs.github.com/en/actions" rel="noopener noreferrer" target="_blank"><strong>their docs</strong></a> in order to get a broader understanding of it.</p>
<p>For today, what is important is that GitHub Actions allow us to issue a cURL request at regular intervals. This fills the last piece of our puzzle. Here’s how our workflow looks:</p>
<ol>
<li>Host server-side rendered application on Netlify and generate unique build hook URL;</li>
<li>Set up a GitHub action to make a POST request to that URL at regular intervals;</li>
<li>Enjoy a fast, SEO-friendly application using cutting-edge technologies with data updated as scheduled.</li>
</ol>
<p>We are going to fit all the pieces together in a practical project, but before we get into it, let us discuss the implications and shortcomings of such an approach.</p>
<h2 id="limitations-of-scheduled-cron-jobs"><strong>Limitations of scheduled cron jobs</strong></h2>
<p>All looks very well but as with everything in life, there are some constraints.</p>
<p>Most importantly, even if we schedule builds at reduced intervals, our data will never be <em>real-time.</em> As always, it is part of the engineering job to decide the best tool for the task at hand, and if your application is very sensitive to real-time information, going server-side rendered might not be the best choice for you.</p>
<p>Moreover, if you significantly reduce the interval, you will perform more builds, which means that you are going to spend more <em>build minutes</em>. Many build tools charge by the minute, and even though most services will provide you a free tier, triggering too many builds can stack up minutes quickly and cost you a lot of money.</p>
<figure class="image"><img alt="Waiting for your code to execute" loading="lazy" decoding="async" width="600" height="600" src="https://rafaelquintanilha.com/_astro/performance-issues.B0xtYAea_Z1ecA4J.webp"><figcaption>Waiting for your code to execute</figcaption></figure>
<p>Also note that if your build is heavy, meaning that it fetches too much information or builds too many pages, every build will also take more time to complete. This will directly impact costs.</p>
<p>That said, setting up cron jobs to trigger static builds is a fairly elegant solution if your application can afford small delays (like updating once a day or every X hours). Remember that the ultimate goals for a static website are to be <em>fast</em> and <em>SEO-friendly</em>, and if you have dynamic, real-time pages, such as a social network feed, you probably won’t want it to be statically rendered anyway.</p>
<p>Enough talk. Let's learn how to implement all the concepts explained so far in a practical project.</p>
<h2 id="how-to-schedule-and-edit-cron-jobs"><strong>How to schedule and edit cron jobs</strong></h2>
<p>To illustrate the process, we will create a basic static stock price website. Our project will be very simple: we are going to build an application where users will be able to check how much the stock prices of FAANG companies have changed since the last trading day.</p>
<p>The application will be statically generated using <a href="https://www.gatsbyjs.com/" rel="noopener noreferrer" target="_blank"><strong>GatsbyJS</strong></a> and will fetch data from <a href="https://finance.yahoo.com/" rel="noopener noreferrer" target="_blank"><strong>Yahoo Finance’s API</strong></a>. On top of that, we will set up a GitHub Action to trigger a build every workday at the end of the regular trading session (4 pm ET or 8 pm UTC). You can check the source code at any point on the <a href="https://github.com/rafaelquintanilha/faang-variation" rel="noopener noreferrer" target="_blank"><strong>GitHub repo</strong></a>. The final version will look like <a href="http://faangvariation.netlify.app/" rel="noopener noreferrer" target="_blank"><strong>this</strong></a>.</p>
<h3 id="step-1-cloning-the-gatsby-repository">Step 1: Cloning the Gatsby repository</h3>
<p>In order to start with Gatsby, make sure you have <a href="https://www.gatsbyjs.com/docs/quick-start/" rel="noopener noreferrer" target="_blank"><strong>Gatsby’s CLI installed on your machine</strong></a>. Once you have it, run the following commands in your terminal to create a new project and start the default application:</p>
<figure class="code"><figcaption>shell</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="shell"><code><span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> gatsby</span><span style="color:#97CCAE"> new</span><span style="color:#97CCAE"> faang-variation</span></span>
<span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> cd</span><span style="color:#97CCAE"> faang-variation</span></span>
<span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> gatsby</span><span style="color:#97CCAE"> develop</span></span></code></pre></figure>
<p>Go to <a href="http://localhost:8000/" rel="noopener noreferrer" target="_blank"><strong>http://localhost:8000/</strong></a> and check that the app is up and running.</p>
<h3 id="step-2-fetching-data-from-the-api">Step 2: Fetching data from the API</h3>
<p>A server-side rendered application will typically fetch information from multiple sources. Today, we are going to use Yahoo Finance’s API to achieve our goal. The <a href="https://www.npmjs.com/package/yahoo-finance" rel="noopener noreferrer" target="_blank"><strong>yahoo-finance</strong></a> module is all we need:</p>
<figure class="code"><figcaption>shell</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="shell"><code><span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> yarn</span><span style="color:#97CCAE"> add</span><span style="color:#97CCAE"> yahoo-finance</span></span></code></pre></figure>
<p>With the module installed, it’s time to edit <em>gatsby-node.js</em>. <a href="https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/" rel="noopener noreferrer" target="_blank"><strong>Gatsby Node API</strong></a> is an interface provided by Gatsby that allows us to dynamically generate static pages, which is precisely what we need.</p>
<p>Add the following to your <a href="https://github.com/rafaelquintanilha/faang-variation/blob/master/gatsby-node.js" rel="noopener noreferrer" target="_blank"><strong>gatsby-node.js</strong></a>:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> yf </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> require</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"yahoo-finance"</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> path </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> require</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`path`</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">exports</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">createPages</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> ({ actions: { createPage } }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> homePageTemplate </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> path.resolve</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`src/components/Home.js`</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> symbols </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [</span><span style="color:#97CCAE">"FB"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"AMZN"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"AAPL"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"NFLX"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"GOOG"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> prices </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> yf.quote</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">   symbols,</span></span>
<span class="line"><span style="color:#ECEBE8">   modules: [</span><span style="color:#97CCAE">"price"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8"> })</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> buildTime </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> new</span><span style="color:#EDCC95"> Date</span><span style="color:#ECEBE8">()</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95"> createPage</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">   path: </span><span style="color:#97CCAE">`/`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">   component: homePageTemplate,</span></span>
<span class="line"><span style="color:#ECEBE8">   context: {</span></span>
<span class="line"><span style="color:#ECEBE8">     prices,</span></span>
<span class="line"><span style="color:#ECEBE8">     buildTime,</span></span>
<span class="line"><span style="color:#ECEBE8">   },</span></span>
<span class="line"><span style="color:#ECEBE8"> })</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>The code should be very straightforward: we are quoting prices for our desired stocks and recording the build time. Next, we use the <a href="https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/#createPages" rel="noopener noreferrer" target="_blank"><strong>createPage function</strong></a> to generate our home page using the Home component at <a href="https://github.com/rafaelquintanilha/faang-variation/blob/master/src/components/Home.js" rel="noopener noreferrer" target="_blank"><em><strong>src/components/Home.js</strong></em></a> as a template.</p>
<h3 id="step-3-create-the-home-component">Step 3: Create the Home component</h3>
<p>Now that we already have the stock information available at build time in Gatsby, the final piece of the app is to actually create the Home component, which we will use to render the content based on data.</p>
<p>Go ahead and delete the <em>pages</em> folder, which has a static <em>index.js</em> file that we won’t be using. Then, create <em>Home.js</em> in <em>src/components</em> and add the following:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Home</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ pageContext: { prices, buildTime } }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    /* Code here */</span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Home</span></span></code></pre></figure>
<p>The actual UI is not relevant. What really matters is that you can access the prices and buildTime variables generated in the previous step, using the pageContext prop of the component.</p>
<p>If you copy the code from GitHub and start the server again, you should be able to see our simple app up and running!</p>
<figure class="image"><img alt="FAANG Stock Price Variation Website" loading="lazy" decoding="async" width="611" height="379" src="https://rafaelquintanilha.com/_astro/image--25-.BIEZUyoB_v091U.webp"><figcaption>FAANG Stock Price Variation Website</figcaption></figure>
<h3 id="step-4-deploy-to-netlify">Step 4: Deploy to Netlify</h3>
<p>For this step, I am assuming you have your code hosted on a GitHub repository. Our app is ready, so it’s time to make it available to the world.</p>
<p>Make sure you have already signed up to Netlify. After this is done, go to <a href="https://app.netlify.com/start" rel="noopener noreferrer" target="_blank"><strong>https://app.netlify.com/start</strong></a> in order to connect your GitHub repository.</p>
<figure class="image"><img alt="Create a new site in Netlify" loading="lazy" decoding="async" width="615" height="470" src="https://rafaelquintanilha.com/_astro/image--26-.kZiCZFUo_ZmNbDn.webp"><figcaption>Create a new site in Netlify</figcaption></figure>
<p>Click on “GitHub” and authorize the integration. Next, select your repo and proceed to deploy:</p>
<figure class="image"><img alt="Configure site settings" loading="lazy" decoding="async" width="569" height="473" src="https://rafaelquintanilha.com/_astro/image--27-.Bp6MzxqY_LyLH6.webp"><figcaption>Configure site settings</figcaption></figure>
<p>It’s that simple. In a few minutes, your website will be available. Change the domain name if you want and it’s done! The live result <a href="https://faangvariation.netlify.app/" rel="noopener noreferrer" target="_blank"><strong>can be seen here</strong></a>.</p>
<h3 id="step-5-add-build-hook">Step 5: Add build hook</h3>
<p>The ultimate goal of today’s article is to set up a cron job that will trigger a build every weekday at 8 pm UTC. As discussed before, first we need to get a unique URL to which we will issue a POST request.</p>
<p>Go to Netlify > Site settings, then select “Build &#x26; deploy” and scroll to “Build hooks.” Click to add a new hook and fill it up with some descriptive information:</p>
<figure class="image"><img alt="Add Build hooks" loading="lazy" decoding="async" width="594" height="379" src="https://rafaelquintanilha.com/_astro/image--28-.d2hQ3XDT_1Lgcts.webp"><figcaption>Add Build hooks</figcaption></figure>
<p>After you save it, a unique URL will be available to you.</p>
<h3 id="step-6-schedule-curl-requests-with-github-actions">Step 6: Schedule cURL requests with GitHub Actions</h3>
<p>Finally, we are ready to integrate with GitHub Actions in order to schedule the builds. But before we jump into that, let’s make sure the build hook is working.</p>
<p>Open your terminal and run the following command, replacing BUILD_HOOK_URL with the URL you generated before.</p>
<figure class="code"><figcaption>shell</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="shell"><code><span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> curl</span><span style="color:#97CCAE"> -X</span><span style="color:#97CCAE"> POST</span><span style="color:#97CCAE"> -d</span><span style="color:#97CCAE"> {}</span><span style="color:#97CCAE"> BUILD_HOOK_URL</span></span></code></pre></figure>
<p>Go back to <em>Site overview</em> in Netlify and make sure you see something like this:</p>
<figure class="image"><img alt="Deploys in Netlify" loading="lazy" decoding="async" width="577" height="227" src="https://rafaelquintanilha.com/_astro/image--29-.DMz9a4EI_qDDX.webp"><figcaption>Deploys in Netlify</figcaption></figure>
<p>The hook is working! Now go to your GitHub repository, click on “Actions” and then on “set up a workflow yourself”.</p>
<figure class="image"><img alt="Configuring GitHub Actions" loading="lazy" decoding="async" width="618" height="438" src="https://rafaelquintanilha.com/_astro/image--30-.GUyTTXQb_ZMh2wz.webp"><figcaption>Configuring GitHub Actions</figcaption></figure>
<p>Finally, get rid of everything on the left side editor and add the following (again, replace BUILD_HOOK_URL with your own):</p>
<figure class="code"><figcaption>yaml</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="yaml"><code><span class="line"><span style="color:#A1C1E4">name</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">Trigger Netlify Build</span></span>
<span class="line"><span style="color:#A1C1E4">on</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">  schedule</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # “At 20:00 on every day-of-week from Monday through Friday.”</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # https://crontab.guru/#0_20_*_*_1-5</span></span>
<span class="line"><span style="color:#ECEBE8">    - </span><span style="color:#A1C1E4">cron</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">'0 20 * * 1-5'</span></span>
<span class="line"><span style="color:#A1C1E4">jobs</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">  build</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A1C1E4">    name</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">Build Hook</span></span>
<span class="line"><span style="color:#A1C1E4">    runs-on</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">ubuntu-latest</span></span>
<span class="line"><span style="color:#A1C1E4">    steps</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">      - </span><span style="color:#A1C1E4">name</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">Curl request</span></span>
<span class="line"><span style="color:#A1C1E4">        run</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">curl -X POST -d {} BUILD_HOOK_URL</span></span></code></pre></figure>
<p>Commit your changes and that’s it! You have now learned how to edit cron jobs in order to schedule builds for your static application.</p>
<h2 id="final-thoughts"><strong>Final thoughts</strong></h2>
<p>Static sites are very fast and <a href="https://buttercms.com/kb/seo-optimization" rel="noopener noreferrer" target="_blank"><strong>great for SEO</strong></a>, which makes them very appealing when designing your application. However, those benefits come with drawbacks, especially if you want data to be regularly updated.</p>
<p>Scheduling cron jobs is a viable solution assuming that you can afford some delay when triggering your rebuilds. Note that the smaller the delay, the more builds will run, and the more expensive it will be for you to adopt this strategy (however, most services will provide you some kind of free tier if you want to test it out).</p>
<p>This approach is very useful if you use a <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><strong>headless CMS</strong></a> such as ButterCMS with a javascript framework like React. Consider this strategy to regularly update the content on your page!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Converting Jupyter Notebooks Into Blog Posts with Gatsby]]></title>
<description><![CDATA[Learn how to bring your Data Science projects to life in easy steps.]]></description>
<link>https://rafaelquintanilha.com/converting-jupyter-notebooks-into-blog-posts-with-gatsby/</link>
<guid isPermaLink="false">63706c6c42a473003d9dcbbb</guid>
<category><![CDATA[Data Science]]></category><category><![CDATA[Gatsby]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Mon, 05 Oct 2020 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<figure class="image"><img alt="Converting Jupyter Notebooks Into Blog Posts With Gatsby" loading="lazy" decoding="async" width="730" height="487" src="https://rafaelquintanilha.com/_astro/cover--1-.HlWHM1hI_lBU2O.webp"><figcaption>Converting Jupyter Notebooks Into Blog Posts With Gatsby</figcaption></figure>
<p>Everyone acquainted with data science knows that Jupyter Notebooks are the way to go. They easily allow you to mix Markdown with actual code, creating a lively environment for research and learning. Code becomes user-friendly and nicely formatted — write about it and generate dynamic charts, tables, and images on the go.</p>
<p>Writing Notebooks is so good that it is only natural to imagine that you might want to share them on the internet. Surely, you can host it in GitHub or even in <a href="https://colab.research.google.com/" rel="noopener noreferrer" target="_blank">Google Colab</a>, but that will require a running kernel, and it’s definitely not as friendly as a good ol’ webpage.</p>
<p>Before we go any further, it’s important to understand that a Jupyter Notebook is nothing more than a collection of JSON objects containing inputs, outputs, and tons of metadata. It then constructs the outputs and can easily be <a href="https://github.com/jupyter/nbconvert/" rel="noopener noreferrer" target="_blank">converted into different formats</a> (such as HTML).</p>
<p>Knowing that Notebooks can become an HTML document is all we need — what remains is finding a way to automate this process so a <code>.ipynb</code> file can become a static page on the internet. My solution to this problem is to use GatsbyJS — notably, one of the best static site generators out there, if not the single best.</p>
<p>Gatsby easily sources data from different formats — JSON, Markdown, YAML, you name it — and statically generates webpages that you can host on the world wide web. The final piece then becomes: instead of transforming Markdown into a post, do the same with a <code>.ipynb</code> file. The goal of this post is to walk you through this process.</p>
<h2 id="technical-challenges">Technical challenges</h2>
<p>A quick search on the web will show you <a href="https://www.gatsbyjs.com/plugins/@gatsby-contrib/gatsby-transformer-ipynb/" rel="noopener noreferrer" target="_blank">gatsby-transformer-ipynb</a>. Basically, this is a Gatsby plugin that is able to parse the Notebook file in a way that we can access it later in our GraphQL queries. It’s almost too good to be true!</p>
<p>And, in fact, it is. The hard work was done by the fine folks of <a href="https://github.com/nteract/nteract" rel="noopener noreferrer" target="_blank">nteract</a>. However, the plugin hasn’t been maintained in a while, and things don’t simply work out of the box — not to mention the lack of customization that one would expect from a plugin.</p>
<p>I’ll spare you the boring stuff, but after fussing around the dark corners of GitHub, and with significant help from <a href="https://specific.solutions.limited/blog/rusty-jupyter/" rel="noopener noreferrer" target="_blank">this post</a> by Specific Solutions, I managed to <a href="https://www.npmjs.com/package/@rafaelquintanilha/gatsby-transformer-ipynb" rel="noopener noreferrer" target="_blank">create my own fork</a> of gatsby-transformer-ipynb, which solves my problems and will suffice for the purpose of this post.</p>
<p>Note, however, that I have no intention of become an active maintainer, and most of what I’ve done was solely to get what I need to work — use it at your own risk!</p>
<p>Enough with the preambles, let’s get to some code.</p>
<h2 id="creating-a-project">Creating a project</h2>
<p>Firstly, the source code for what we are going to build can be <a href="https://github.com/rafaelquintanilha/jupyter-blog" rel="noopener noreferrer" target="_blank">found here on GitHub</a>. We’ll start by creating a Gatsby project. Make sure you have <a href="https://www.gatsbyjs.com/docs/quick-start/" rel="noopener noreferrer" target="_blank">Gatsby installed</a>, and create a new project by running:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>gatsby new jupyter-blog</span></span>
<span class="line"><span>cd jupyter-blog</span></span></code></pre></figure>
<p>Run <code>gatsby develop</code> and go to <a href="http://localhost:8000/" rel="noopener noreferrer" target="_blank">http://localhost:8000/</a> to make sure everything is working fine.</p>
<h2 id="create-your-first-notebook">Create your first Notebook</h2>
<p>Since Jupyter Notebooks will be the data source for our brand-new blog, we need to start adding content. Within your project folder, go to <code>src</code> and create a <code>notebooks</code> folder. We’ll make sure to read from this folder later.</p>
<p>It’s time to create our first Notebook. For the purposes of this tutorial, I’ll use <a href="https://github.com/rafaelquintanilha/jupyter-blog/blob/master/src/notebooks/my-first-post.ipynb" rel="noopener noreferrer" target="_blank">this simple Notebook</a> as a base. You can see the dynamic output in GitHub, but feel free to use whichever you want.</p>
<p>In any case, it’s worth mentioning that some rich outputs such as dynamic charts generated by <a href="https://plotly.com/" rel="noopener noreferrer" target="_blank">Plotly</a> may need extra care — let me know if you want me to cover that in a later post! To keep this post short, however, we’ll handle only static images, tables, and Markdown.</p>
<p>Now that you have a Gatsby project with data, the next step is to query it using GraphQL.</p>
<h2 id="querying-data">Querying data</h2>
<p>One of the biggest advantages of Gatsby is flexibility when sourcing data. Virtually anything you want can become a data source that can be used to generate static content.</p>
<p>As mentioned above, we’ll be using my own version of the transformer. Go ahead and install it:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>yarn add @rafaelquintanilha/gatsby-transformer-ipynb</span></span></code></pre></figure>
<p>The next step is to configure the plugins. In <code>gatsby-config.js</code>, add the following to your <code>plugins</code> array (you can always <a href="https://github.com/rafaelquintanilha/jupyter-blog/blob/master/gatsby-config.js" rel="noopener noreferrer" target="_blank">check GitHub</a> when in doubt):</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#ECEBE8">  resolve: </span><span style="color:#97CCAE">`gatsby-source-filesystem`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">  options: {</span></span>
<span class="line"><span style="color:#ECEBE8">    name: </span><span style="color:#97CCAE">`notebooks`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">    path: </span><span style="color:#97CCAE">`${</span><span style="color:#97CCAE">__dirname</span><span style="color:#97CCAE">}/src/notebooks`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">    ignore: [</span><span style="color:#97CCAE">`**/.ipynb_checkpoints`</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8">  },</span></span>
<span class="line"><span style="color:#ECEBE8">},</span></span>
<span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#ECEBE8">  resolve: </span><span style="color:#97CCAE">`@rafaelquintanilha/gatsby-transformer-ipynb`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">  options: {</span></span>
<span class="line"><span style="color:#ECEBE8">    notebookProps: {</span></span>
<span class="line"><span style="color:#ECEBE8">      displayOrder: [</span><span style="color:#97CCAE">"image/png"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"text/html"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"text/plain"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8">      showPrompt: </span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">    },</span></span>
<span class="line"><span style="color:#ECEBE8">  },</span></span>
<span class="line"><span style="color:#ECEBE8">},</span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span></code></pre></figure>
<p>Let’s break it down.</p>
<p>First, we add a <code>gatsby-source-filesystem</code> option in the array. We are telling Gatsby to look for files in <code>src/notebooks</code>, where our <code>.ipynb</code> files live. Next, we are configuring the transformer and setting some props:</p>
<ul>
<li><code>displayOrder</code> – MIME type of the outputs we are displaying</li>
<li><code>showPrompt</code> – whether the prompt is displayed</li>
</ul>
<p>While prompts make sense in Notebooks, in static pages, they lose their purpose. For that matter, we will hide them in order to have clear content.</p>
<p>Time to check whether everything went according to plan. Open GraphiQL by going to <a href="http://localhost:8000/___graphql" rel="noopener noreferrer" target="_blank">http://localhost:8000/___graphql</a> and run the following query:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>query MyQuery {</span></span>
<span class="line"><span>  allJupyterNotebook {</span></span>
<span class="line"><span>    nodes {</span></span>
<span class="line"><span>      html</span></span>
<span class="line"><span>    }</span></span>
<span class="line"><span>  }</span></span>
<span class="line"><span>}</span></span></code></pre></figure>
<p>Success! Note how the HTML of our notebooks was generated. All that is left is to inject this HTML into a React component and our process will be complete.</p>
<h2 id="generating-posts-automatically">Generating posts automatically</h2>
<p>The worst is behind us now. The next step is to query this data in <code>gatsby-node.js</code> so we can generate static pages for each Notebook in <code>src/notebooks</code>.</p>
<p>Note, however, that we need to add additional metadata to our Notebook, e.g., author and post title. There are several ways of doing it, and the simplest is probably to take advantage of the fact that <code>.ipynb</code> files are JSON and use their own <code>metadata</code> field. Open the <code>.ipynb</code> and add the info you need:</p>
<figure class="code"><figcaption>json</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="json"><code><span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#A1C1E4"> "metadata"</span><span style="color:#ECEBE8">: {</span></span>
<span class="line"><span style="color:#A1C1E4">  "author"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"Rafael Quintanilha"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">  "title"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"My First Jupyter Post"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">  "language_info"</span><span style="color:#ECEBE8">: {</span></span>
<span class="line"><span style="color:#A1C1E4">   "codemirror_mode"</span><span style="color:#ECEBE8">: {</span></span>
<span class="line"><span style="color:#A1C1E4">    "name"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"ipython"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">    "version"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">3</span></span>
<span class="line"><span style="color:#ECEBE8">   },</span></span>
<span class="line"><span style="color:#A1C1E4">   "file_extension"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">".py"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">   "mimetype"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"text/x-python"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">   "name"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"python"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">   "nbconvert_exporter"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"python"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">   "pygments_lexer"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"ipython3"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">   "version"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"3.7.4-final"</span></span>
<span class="line"><span style="color:#ECEBE8">  },</span></span>
<span class="line"><span style="color:#A1C1E4">  "orig_nbformat"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">  "kernelspec"</span><span style="color:#ECEBE8">: {</span></span>
<span class="line"><span style="color:#A1C1E4">   "name"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"python3"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4">   "display_name"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"Python 3"</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8"> },</span></span>
<span class="line"><span style="color:#A1C1E4"> "nbformat"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">4</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4"> "nbformat_minor"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#A1C1E4"> "cells"</span><span style="color:#ECEBE8">: [</span></span>
<span class="line"><span style="color:#ECEBE8">  ...</span></span>
<span class="line"><span style="color:#ECEBE8"> ]</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p><em><strong>Pro tip:</strong> If you’re using VS Code, opening the file will probably launch the Jupyter kernel. You can disable it in the configs to edit the raw content, but I usually just open the file with another editor (such as gedit or Notepad++).</em></p>
<p>The process now is exactly the same for any data source with Gatsby. We’ll query the data in <code>gatsby-node.js</code> and pass the relevant info to a post template, which, in turn, will become a unique page in our domain.</p>
<p>Before getting to that, however, open <code>gatsby-node.js</code> and add the following:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">exports</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">onCreateNode</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ node, actions }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { createNodeField } </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> actions</span></span>
<span class="line"><span style="color:#A1C1E4">  if</span><span style="color:#ECEBE8"> (node.internal.type </span><span style="color:#A1C1E4">===</span><span style="color:#97CCAE"> 'JupyterNotebook'</span><span style="color:#ECEBE8">) {</span></span>
<span class="line"><span style="color:#EDCC95">    createNodeField</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">      name: </span><span style="color:#97CCAE">'slug'</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      node,</span></span>
<span class="line"><span style="color:#ECEBE8">      value: node.json.metadata.title</span></span>
<span class="line"><span style="color:#EDCC95">        .split</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">        .map</span><span style="color:#ECEBE8">(token </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> token.toLowerCase</span><span style="color:#ECEBE8">())</span></span>
<span class="line"><span style="color:#EDCC95">        .join</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'-'</span><span style="color:#ECEBE8">),</span></span>
<span class="line"><span style="color:#ECEBE8">    })</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>The above excerpt will, for every node created in GraphQL, check those that are a Jupyter Notebook and extend them with a new field, <code>slug</code>. We are using a naive approach here, but you can use a robust library such as <a href="https://www.npmjs.com/package/slugify" rel="noopener noreferrer" target="_blank">slugify</a>. The new field will be queried and used to generate the post path. In the same file, add the following:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> path </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> require</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`path`</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">exports</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">createPages</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> ({ graphql, actions: { createPage } }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> blogPostTemplate </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> path.resolve</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`src/templates/BlogPost.js`</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> results </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> graphql</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">    `</span></span>
<span class="line"><span style="color:#97CCAE">      {</span></span>
<span class="line"><span style="color:#97CCAE">        allJupyterNotebook() {</span></span>
<span class="line"><span style="color:#97CCAE">          nodes {</span></span>
<span class="line"><span style="color:#97CCAE">            fields {</span></span>
<span class="line"><span style="color:#97CCAE">              slug</span></span>
<span class="line"><span style="color:#97CCAE">            }</span></span>
<span class="line"><span style="color:#97CCAE">          }</span></span>
<span class="line"><span style="color:#97CCAE">        }</span></span>
<span class="line"><span style="color:#97CCAE">      }</span></span>
<span class="line"><span style="color:#97CCAE">    `</span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> posts </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> results.data.allJupyterNotebook.nodes</span></span>
<span class="line"><span style="color:#EDCC95">  posts.forEach</span><span style="color:#ECEBE8">(post </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    createPage</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">      path: post.fields.slug,</span></span>
<span class="line"><span style="color:#ECEBE8">      component: blogPostTemplate,</span></span>
<span class="line"><span style="color:#ECEBE8">      context: {</span></span>
<span class="line"><span style="color:#ECEBE8">        slug: post.fields.slug,</span></span>
<span class="line"><span style="color:#ECEBE8">      },</span></span>
<span class="line"><span style="color:#ECEBE8">    })</span></span>
<span class="line"><span style="color:#ECEBE8">  })</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>This basically queries data by slug and sends them to <code>BlogPost.js</code>. Let’s create it now:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { graphql } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'gatsby'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> SEO </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '../components/seo'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> BlogPost</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({</span></span>
<span class="line"><span style="color:#ECEBE8">  data: {</span></span>
<span class="line"><span style="color:#ECEBE8">    jupyterNotebook: {</span></span>
<span class="line"><span style="color:#ECEBE8">      json: { metadata },</span></span>
<span class="line"><span style="color:#ECEBE8">      html,</span></span>
<span class="line"><span style="color:#ECEBE8">    },</span></span>
<span class="line"><span style="color:#ECEBE8">  },</span></span>
<span class="line"><span style="color:#ECEBE8">}) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">SEO</span><span style="color:#EDCC95"> title</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{metadata.title} /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>{metadata.title}&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">>Written by {metadata.author}&#x3C;/</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> dangerouslySetInnerHTML</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ __html: html }} /></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> BlogPost</span></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> const</span><span style="color:#ECEBE8"> query </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> graphql</span><span style="color:#97CCAE">`</span></span>
<span class="line"><span style="color:#97CCAE">  query BlogPostBySlug($slug: String!) {</span></span>
<span class="line"><span style="color:#97CCAE">    jupyterNotebook(fields: { slug: { eq: $slug } }) {</span></span>
<span class="line"><span style="color:#97CCAE">      json {</span></span>
<span class="line"><span style="color:#97CCAE">        metadata {</span></span>
<span class="line"><span style="color:#97CCAE">          title</span></span>
<span class="line"><span style="color:#97CCAE">          author</span></span>
<span class="line"><span style="color:#97CCAE">        }</span></span>
<span class="line"><span style="color:#97CCAE">      }</span></span>
<span class="line"><span style="color:#97CCAE">      html</span></span>
<span class="line"><span style="color:#97CCAE">    }</span></span>
<span class="line"><span style="color:#97CCAE">  }</span></span>
<span class="line"><span style="color:#97CCAE">`</span></span></code></pre></figure>
<p>And that’s it! Hop over to <a href="http://localhost:8000/my-first-jupyter-post" rel="noopener noreferrer" target="_blank">http://localhost:8000/my-first-jupyter-post</a> and see your Notebook as a static HTML page.</p>
<h2 id="improvements">Improvements</h2>
<p>As you can see, a lot can be improved upon in terms of styling and design. This is beyond the scope of this post, but as a hint, you can use CSS Modules to enhance the layout and remove unnecessary <em>stdout</em> (text output that you don’t care about in a blog post). Create <code>BlogPost.module.css</code> and add the following:</p>
<figure class="code"><figcaption>css</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="css"><code><span class="line"><span style="color:#EDCC95">.content</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  max-width</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">900</span><span style="color:#A1C1E4">px</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  margin-left</span><span style="color:#ECEBE8">: auto;</span></span>
<span class="line"><span style="color:#A1C1E4">  margin-right</span><span style="color:#ECEBE8">: auto;</span></span>
<span class="line"><span style="color:#A1C1E4">  padding</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">40</span><span style="color:#A1C1E4">px</span><span style="color:#97CCAE"> 20</span><span style="color:#A1C1E4">px</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">.content</span><span style="color:#ECEBE8"> :global(</span><span style="color:#EDCC95">.nteract-display-area-stdout</span><span style="color:#ECEBE8">),</span></span>
<span class="line"><span style="color:#EDCC95">.content</span><span style="color:#ECEBE8"> :global(</span><span style="color:#EDCC95">.nteract-outputs</span><span style="color:#A1C1E4"> ></span><span style="color:#EDCC95"> .cell_display</span><span style="color:#A1C1E4"> ></span><span style="color:#A1C1E4"> pre</span><span style="color:#ECEBE8">) {</span></span>
<span class="line"><span style="color:#A1C1E4">  display</span><span style="color:#ECEBE8">: none;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">.content</span><span style="color:#ECEBE8"> :global(</span><span style="color:#EDCC95">.nteract-outputs</span><span style="color:#A1C1E4"> ></span><span style="color:#EDCC95"> .cell_display</span><span style="color:#A1C1E4"> ></span><span style="color:#A1C1E4"> img</span><span style="color:#ECEBE8">) {</span></span>
<span class="line"><span style="color:#A1C1E4">  display</span><span style="color:#ECEBE8">: block;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">.content</span><span style="color:#ECEBE8"> :global(</span><span style="color:#EDCC95">.input-container</span><span style="color:#ECEBE8">) {</span></span>
<span class="line"><span style="color:#A1C1E4">  margin-bottom</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">20</span><span style="color:#A1C1E4">px</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">.content</span><span style="color:#ECEBE8"> :global(</span><span style="color:#EDCC95">.input-container</span><span style="color:#A1C1E4"> pre</span><span style="color:#EDCC95">.input</span><span style="color:#ECEBE8">) {</span></span>
<span class="line"><span style="color:#A1C1E4">  border-radius</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">10</span><span style="color:#A1C1E4">px</span><span style="color:#A1C1E4"> !important</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  padding</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">1</span><span style="color:#A1C1E4">em</span><span style="color:#A1C1E4"> !important</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#EDCC95">.content</span><span style="color:#ECEBE8"> :global(</span><span style="color:#EDCC95">.input-container</span><span style="color:#A1C1E4"> code</span><span style="color:#ECEBE8">) {</span></span>
<span class="line"><span style="color:#A1C1E4">  line-height</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">1.5</span><span style="color:#A1C1E4"> !important</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  font-size</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">0.85</span><span style="color:#A1C1E4">rem</span><span style="color:#A1C1E4"> !important</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">.content</span><span style="color:#ECEBE8"> :global(</span><span style="color:#EDCC95">.input-container</span><span style="color:#A1C1E4"> code</span><span style="color:#EDCC95">:empty</span><span style="color:#ECEBE8">) {</span></span>
<span class="line"><span style="color:#A1C1E4">  display</span><span style="color:#ECEBE8">: none;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">@media</span><span style="color:#A1C1E4"> only</span><span style="color:#ECEBE8"> screen </span><span style="color:#A1C1E4">and</span><span style="color:#ECEBE8"> (</span><span style="color:#A1C1E4">max-width</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">940</span><span style="color:#A1C1E4">px</span><span style="color:#ECEBE8">) {</span></span>
<span class="line"><span style="color:#EDCC95">  .content</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    max-width</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">100</span><span style="color:#A1C1E4">%</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">    padding-left</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">20</span><span style="color:#A1C1E4">px</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">    padding-right</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">20</span><span style="color:#A1C1E4">px</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">    box-sizing</span><span style="color:#ECEBE8">: border-box;</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Now go back to <code>BlogPost.js</code> and add the class to our div:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> css </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "./BlogPost.module.css"</span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'content'</span><span style="color:#ECEBE8">]}></span></span>
<span class="line"><span style="color:#ECEBE8">     ...</span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">);</span></span></code></pre></figure>
<p>Note how much cleaner it looks now. The final result (with minor tweaks) is hosted in <a href="https://jupyter-blog.netlify.app/" rel="noopener noreferrer" target="_blank">Netlify</a>. All changes are in the <a href="https://github.com/rafaelquintanilha/jupyter-blog" rel="noopener noreferrer" target="_blank">source code</a>.</p>
<h2 id="final-thoughts">Final thoughts</h2>
<p>Transforming Jupyter Notebooks into HTML pages is not complicated but does involve a lot of small steps and adjustments. Hopefully, this post is a guide on how to get started with it.</p>
<p>There are tons of changes and improvements that can be done, like supporting rich outputs (such as a dynamic chart), improving the mobile experience, better metadata management, and more.</p>
<p>Notebooks are versatile and fun to work with, and automatically converting them into a webpage is a very nice feature of them.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Fixing Gatsby’s rehydration issue]]></title>
<description><![CDATA[Learn what a rehydration issue is in Gatsby, and the proper way to fix it.]]></description>
<link>https://rafaelquintanilha.com/fixing-gatsbys-rehydration-issue/</link>
<guid isPermaLink="false">638229c914168e003dd8f44f</guid>
<category><![CDATA[React]]></category><category><![CDATA[Gatsby]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Fri, 20 Mar 2020 14:59:00 GMT</pubDate>

<content:encoded><![CDATA[<figure class="image"><img alt="Gatsby cover" loading="lazy" decoding="async" width="730" height="412" src="https://rafaelquintanilha.com/_astro/gatsby-cover._9qe21yL_1uQcD9.webp"><figcaption>Gatsby cover</figcaption></figure>
<p>If you have been developing Gatsby applications recently, it is likely that this has bitten you at some point.</p>
<p>Consider the following scenario: your application stores some information in the client (the user’s browser), possibly in the <a href="https://developer.mozilla.org/en/docs/Web/API/Window/localStorage" rel="noopener noreferrer" target="_blank">Local Storage</a>.</p>
<p>The goal is straightforward — you want to quickly make UI changes based on individual data (e.g. theme preference, log-in details, etc).</p>
<p>You set everything up properly and it works locally, but as soon as you do the deploy things don’t look quite like what you expected.</p>
<p>What happened?</p>
<p>This is what we call a <strong>rehydration issue</strong>.</p>
<p>In other words, React and Gatsby are having trouble matching data that came from the server with the change you want to do in the client.</p>
<p>This happens because <a href="https://reactjs.org/docs/react-dom.html#hydrate" rel="noopener noreferrer" target="_blank">React does not expect</a> any mismatches between what was statically generated in the server and what was rendered by the client.</p>
<p>Before we dive deeper into what is going on, let’s first go over how Gatsby works.</p>
<h2 id="server-side-rendering"><strong>Server-side rendering</strong></h2>
<p>Gatsby has a magnificent set of server-side rendering (SSR) features.</p>
<p>That means that it is able to render complex pages in the server and send the full output (a compiled file) to the client (your browser).</p>
<p>This contrasts with regular React applications (such as the ones created by Create React App), which are completely generated in the client, i.e., everything you see on the page is dynamically created after the JavaScript is downloaded, parsed, and evaluated.</p>
<p>With SSR, you already send the rendered content.</p>
<p>The end result is that your page loads really fast.</p>
<p>Cool, huh?</p>
<p>In a typical client-server exchange in an application powered by Gatsby, the page is retrieved first and the JavaScript is evaluated later.</p>
<p>It allows for quicker page loads, <a href="https://developers.google.com/web/tools/lighthouse/audits/time-to-interactive" rel="noopener noreferrer" target="_blank">TTI values</a>, faster <a href="https://developers.google.com/web/tools/lighthouse/audits/first-meaningful-paint" rel="noopener noreferrer" target="_blank">first meaningful paint</a>, and several other performance metrics. By the time your JavaScript is ready to come into play, a lot has already happened on your user’s screen. Magic!</p>
<p>However, as you may have guessed, this has a caveat — if your page is server-side rendered, but you need information that is available only to the client to complete the UI, you have a lacuna.</p>
<p>Suppose that you need to display a login button for a visitor and a logout button for a user.</p>
<p>If the information that the user is logged in (for example, a token stored in the Local Storage) is in the client only, how can the server-side rendered page know which button to display before the JavaScript loads?</p>
<p>In fact, if the user is already logged in, you will experience an annoying event — the page will first display the login button (for there is no token available in the server whatsoever), and then it will revert to the logout button (as soon as the JavaScript code is evaluated and the token retrieved from the Local Storage).</p>
<p>This is annoying, but not the end of the world. It gets worse, though.</p>
<p>Suppose that the two buttons are in the same DOM tree and are conditionally rendered based on the information stored in the Local Storage.</p>
<p>Suppose also that they have different colors.</p>
<p>It is possible that their styles will be mixed up and you will end up with different colors than expected!</p>
<p>This is the end consequence of the so-called rehydration issue, where React will have trouble rehydrating the existing server-side rendered DOM with the dynamic content generated by the client.</p>
<p><a href="https://github.com/gatsbyjs/gatsby/issues/17914" rel="noopener noreferrer" target="_blank">This is a problem that has been troubling Gatsby’s users for a while now</a>. Fortunately, there is a simple way to overcome this problem and we’ll explore it.</p>
<h2 id="the-rationale"><strong>The rationale</strong></h2>
<p>As we’ve seen, this problem occurs because there is a mismatch between what the server renders and what the client generates.</p>
<p>We can mitigate this issue by holding off the particular element from rendering until we know for sure the client has fully loaded.</p>
<p>Bottom line is: why request the server to render if you can only guarantee the integrity after the client has acted?</p>
<p>Of course, you are looking at smaller pieces of UI, not a whole page, which would contradict the whole point of having SSR in the first place.</p>
<p>In fact, if you see yourself having this dilemma for a big chunk of your page, chances are you want to make it a <a href="https://www.gatsbyjs.org/docs/client-only-routes-and-user-authentication/" rel="noopener noreferrer" target="_blank">client-only page</a> instead of serving it directly from the server.</p>
<h3 id="deferring-to-the-client"><strong>Deferring to the client</strong></h3>
<p>Now that we understand that we don’t need to render the element until the client has loaded, how can we implement it? Fortunately, there is a very elegant way of doing it with React Hooks.</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState, useEffect } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Component</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [isClient, setClient] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    setClient</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">  }, []);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>I am in the {isClient </span><span style="color:#A1C1E4">?</span><span style="color:#97CCAE"> "client"</span><span style="color:#A1C1E4"> :</span><span style="color:#97CCAE"> "server"</span><span style="color:#ECEBE8">}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>The above Hook leverages <code>useEffect</code> in order to correctly detect whether the user is in the server or in the client.</p>
<p>The logic is as follows — <code>useEffect</code> with an empty dependency array runs only after the first render is committed to the screen (you can read more about it in the <a href="https://reactjs.org/docs/hooks-reference.html#useeffect" rel="noopener noreferrer" target="_blank">documentation</a>).</p>
<p>If you are on the server, there is no screen at all. As a result, the effect never runs and <code>isClient</code> will be always <code>false</code>.</p>
<p>On the other hand, for any application rendered in the client, after the first render, the effect will run and <code>isClient</code> will become <code>true</code>.</p>
<p>This simple snippet is enough for us to detect where the code is being run.</p>
<p>However, it doesn’t solve the potential issue with rehydration.</p>
<p>Consider the component below:</p>
<figure class="code"><figcaption>css</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="css"><code><span class="line"><span style="color:#EDCC95">.red</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    color</span><span style="color:#ECEBE8">: red;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#EDCC95">.blue</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    color</span><span style="color:#ECEBE8">: blue;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Component</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> [token, setToken] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useLocalStorage</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'token'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> isLoggedIn </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> token </span><span style="color:#A1C1E4">!==</span><span style="color:#97CCAE"> ""</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    /* Generate some fake token */</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#EDCC95"> onLogin</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setToken</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">Math.random</span><span style="color:#ECEBE8">()</span><span style="color:#EDCC95">.toString</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">36</span><span style="color:#ECEBE8">)</span><span style="color:#EDCC95">.substring</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">));</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#EDCC95"> onLogout</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setToken</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        {isLoggedIn </span></span>
<span class="line"><span style="color:#A1C1E4">         ?</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'red'</span><span style="color:#ECEBE8">]} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onLogout}>Logout&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">    	 :</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'blue'</span><span style="color:#ECEBE8">]} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onLogin}>Login&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    );</span></span>
<span class="line"><span style="color:#ECEBE8">}}</span></span></code></pre></figure>
<p>Now we are retrieving a token from the Local Storage (you can check how to do it with a Hooks approach <a href="https://usehooks.com/useLocalStorage/" rel="noopener noreferrer" target="_blank">here</a>) and rendering different components based on that information.</p>
<p>Due to the hydration issue, when the server first delivers the page to you, if you are logged in, you are going to see a blue Logout button!</p>
<p>Good luck debugging why this simple code isn’t working only in production.</p>
<p>Drama aside, now that we identified the problem, how can we solve it?</p>
<p>Well, the key is to use the <code>key</code> prop of the component.</p>
<p>In simpler terms, <code>key</code> tells React that whenever it changes, the component needs to re-render.</p>
<p>The updated version of the code becomes:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Component</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#ECEBE8"> [token, setToken] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useLocalStorage</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'token'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#ECEBE8"> isLoggedIn </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> token </span><span style="color:#A1C1E4">!==</span><span style="color:#97CCAE"> ""</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">      </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      /* Generate some fake token */</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#EDCC95"> onLogin</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setToken</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">Math.random</span><span style="color:#ECEBE8">()</span><span style="color:#EDCC95">.toString</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">36</span><span style="color:#ECEBE8">)</span><span style="color:#EDCC95">.substring</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">));</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#EDCC95"> onLogout</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setToken</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A1C1E4">      return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          {isLoggedIn </span></span>
<span class="line"><span style="color:#A1C1E4">            ?</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'red'</span><span style="color:#ECEBE8">]} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onLogout}>Logout&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">            :</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'blue'</span><span style="color:#ECEBE8">]} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onLogin}>Login&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      );</span></span>
<span class="line"><span style="color:#ECEBE8">    }}</span></span></code></pre></figure>
<p>Note that <code>key</code> changes when the component detects it now runs on the client, forcing the element to re-render and apply the correct style (adapted from <a href="https://github.com/gatsbyjs/gatsby/issues/14601#issuecomment-499922794" rel="noopener noreferrer" target="_blank">this comprehensive reply gave by Dustin Schau in GitHub</a>.)</p>
<p>Yet this only solves half of the problem.</p>
<p>Our styling mismatch issue was fixed, but there is still an annoying flickering due to the fact that the server renders first and then the client comes in and does its change.</p>
<p>Unfortunately, there is no way of fixing it without resorting to somehow letting the server knows beforehand if the user is logged in or not. However, a simple approach is to prevent the element from rendering at all whenever you detect that it is fully usable only in the client.</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Component</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [isClient, setClient] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> key </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> isClient </span><span style="color:#A1C1E4">?</span><span style="color:#97CCAE"> "client"</span><span style="color:#A1C1E4"> :</span><span style="color:#97CCAE"> "server"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [token, setToken] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useLocalStorage</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'token'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> isLoggedIn </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> token </span><span style="color:#A1C1E4">!==</span><span style="color:#97CCAE"> ""</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">      </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* Generate some fake token */</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> onLogin</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setToken</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">Math.random</span><span style="color:#ECEBE8">()</span><span style="color:#EDCC95">.toString</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">36</span><span style="color:#ECEBE8">)</span><span style="color:#EDCC95">.substring</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">));</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> onLogout</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setToken</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    setClient</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">  }, []);</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A1C1E4">  if</span><span style="color:#ECEBE8"> ( </span><span style="color:#A1C1E4">!</span><span style="color:#ECEBE8">isClient ) </span><span style="color:#A1C1E4">return</span><span style="color:#A1C1E4"> null</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{key}>      </span></span>
<span class="line"><span style="color:#ECEBE8">      {isLoggedIn         </span></span>
<span class="line"><span style="color:#A1C1E4">        ?</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'red'</span><span style="color:#ECEBE8">]} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onLogout}>Logout&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">>        </span></span>
<span class="line"><span style="color:#A1C1E4">        :</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'blue'</span><span style="color:#ECEBE8">]} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onLogin}>Login&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<h2 id="hooks-version"><strong>Hooks version</strong></h2>
<p>Adding the above logic to every component that suffers from rehydration can be very cumbersome.</p>
<p>Thankfully, there is a way to simplify the code with a straightforward Hook:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { useState, useEffect } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> useIsClient</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [isClient, setClient] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> key </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> isClient </span><span style="color:#A1C1E4">?</span><span style="color:#97CCAE"> "client"</span><span style="color:#A1C1E4"> :</span><span style="color:#97CCAE"> "server"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    setClient</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">  }, []);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> { isClient, key };</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> useIsClient;</span></span></code></pre></figure>
<p>The usage in our previous component would become:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Component</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { isClient, key } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useIsClient</span><span style="color:#ECEBE8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [token, setToken] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useLocalStorage</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'token'</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> isLoggedIn </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> token </span><span style="color:#A1C1E4">!==</span><span style="color:#97CCAE"> ""</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* Generate some fake token */</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> onLogin</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setToken</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">Math.random</span><span style="color:#ECEBE8">()</span><span style="color:#EDCC95">.toString</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">36</span><span style="color:#ECEBE8">)</span><span style="color:#EDCC95">.substring</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">));</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> onLogout</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setToken</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">""</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  if</span><span style="color:#ECEBE8"> ( </span><span style="color:#A1C1E4">!</span><span style="color:#ECEBE8">isClient ) </span><span style="color:#A1C1E4">return</span><span style="color:#A1C1E4"> null</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{key}></span></span>
<span class="line"><span style="color:#ECEBE8">      {isLoggedIn </span></span>
<span class="line"><span style="color:#A1C1E4">        ?</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'red'</span><span style="color:#ECEBE8">]} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onLogout}>Logout&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">        :</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{css[</span><span style="color:#97CCAE">'blue'</span><span style="color:#ECEBE8">]} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onLogin}>Login&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Which looks way cleaner and is ready to be reused across your codebase!</p>
<h3 id="visualizing-the-issue"><strong>Visualizing the issue</strong></h3>
<p>The rehydration problem and its workarounds can be easily observed in the following gif:</p>
<figure class="image"><img alt="Rehydration issue visualized" loading="lazy" decoding="async" width="730" height="588" src="https://rafaelquintanilha.com/_astro/Gatsby-hydration-issue-gif.cud3aqLa_2jDYhy.webp"><figcaption>Rehydration issue visualized</figcaption></figure>
<p>The first button has the rehydration problem. Notice how it displays the wrong color after we reload the page (i.e., when we ask the server to send the HTML).</p>
<p>The second button fixes the issue. However, you’ll notice it first displays the blue Login button.</p>
<p>Finally, the last button does not show up until the JavaScript is fully evaluated.</p>
<p>The last two effects are more noticeable in slow connections. Consider the following simulation of a user within a 3G network:</p>
<figure class="image"><img alt="Rehydration issue in a slow connection" loading="lazy" decoding="async" width="730" height="588" src="https://rafaelquintanilha.com/_astro/gatsby-hydration-issue-slowdown.Mi2AtgWp_Z1eVGLo.webp"><figcaption>Rehydration issue in a slow connection</figcaption></figure>
<p>The code for the above example is available <a href="https://github.com/rafaelquintanilha/rehydration-issue" rel="noopener noreferrer" target="_blank">in GitHub</a>.</p>
<p>There’s also a <a href="https://gatsby-rehydration-issue.netlify.com/" rel="noopener noreferrer" target="_blank">live version</a> if you want to check it for yourself.</p>
<h2 id="conclusion"><strong>Conclusion</strong></h2>
<p>Server-side rendering is a powerful concept and it really makes your application fast.</p>
<p>Gatsby knows how to best leverage it in order to enhance performance.</p>
<p>However, you need to be mindful when client and server need to talk. The main takeaways from this piece are:</p>
<ul>
<li>Use the <code>key</code> attribute whenever your component changes depending on what it is being rendered</li>
<li>Prevent the component from rendering until you acknowledge that the application is running in the client to avoid flicker</li>
<li>Adopt <code>useIsClient</code> in order to reuse the necessary logic for accomplishing the two points above</li>
</ul>]]></content:encoded>
</item>
</channel>
</rss>
