<?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[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/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>Rafael Quintanilha</title><link>https://rafaelquintanilha.com/</link></image>
<lastBuildDate>Wed, 18 Jun 2025 23:24:57 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[Why every programmer should write]]></title>
<description><![CDATA[The three levels of writing]]></description>
<link>https://rafaelquintanilha.com/why-every-programmer-should-write/</link>
<guid isPermaLink="false">68534645c84aa5000120e6e2</guid>
<category><![CDATA[Artificial Intelligence]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 18 Jun 2025 23:24:57 GMT</pubDate>

<content:encoded><![CDATA[<p>You might not have noticed, but a large portion of a programmer's day involves writing: code, comments, emails, messages — whether in Portuguese, English, Python, or JavaScript — we are constantly converting thoughts into characters. Or, as I prefer to see it, transforming <em>abstractions</em> into <em>concrete actions</em>.</p>
<p>You could argue that comparing writing code to writing text (i.e., natural language) is pushing it. I disagree. In fact, I repeatedly insist that the most readable code is as close as possible to how a <em>human</em> would read it: variable and function names, and even the logical hierarchy of a computer program, should resemble what we're accustomed to in non-technical texts.</p>
<p>In 2019, I published an article called <a href="https://rafaelquintanilha.com/how-to-become-a-bad-developer/">How to Become a Bad Developer</a>, which became my most-read text since then. In it, I list behaviors that negatively impact the quality of a programmer's work. The last — and most important — mistake listed perfectly illustrates my point: <strong>write for machines, not humans</strong>. Here’s the conclusion:</p>
<blockquote>
<p>Think about what makes a text enjoyable to you. It is usually concise, clear, direct, meaningful, and consistent. You won't enjoy reading when you can't understand the author, the narrative doesn't make sense, it's poorly written or weirdly formatted. Likewise, code that doesn't make sense and that you struggle to grasp is an excellent way to discourage readers. And just as an author who discourages readers is a bad author, a developer who discourages readers is a bad developer.</p>
</blockquote>
<p>But the need to write well goes beyond maintaining code that's readable, cohesive, and accessible to other humans. I'd like to explore other ways in which the habit of writing can not only boost your career but also make you a better person.</p>
<h2 id="writing-as-technical-validation">Writing as technical validation</h2>
<p>The first article I published online was on June 18, 2015, exactly 10 years ago (I swear it was a coincidence). It was a post about <a href="https://rafaelquintanilha.com/export-your-json-data-to-csv-format/">converting data from JSON format to CSV</a> using a framework called <a href="https://github.com/meteor/meteor" rel="noopener noreferrer" target="_blank">Meteor</a>. No one cares about this topic today — either because Meteor lost its appeal, any AI can solve this problem in 2 seconds, or the mentioned libraries no longer exist. The fact is that this text hardly fulfills its original purpose of <em>informing</em> the reader.</p>
<p>However, it serves another equally important role: validation, a <em>historical record</em> that I've been in the game for at least 10 years. Two months later, <a href="https://rafaelquintanilha.com/real-time-charts-with-meteor-react-and-d3-2/">I published my first article about React</a>. Thus, it's undeniable and easily verifiable that I have at least 10 years of experience with React, the most widely used library for building modern interfaces.</p>
<p>And why is it important to show online that you <em>know</em> what you <em>say you know</em>? Well, this detail can make a difference when getting hired, for example. As mentioned in my article <a href="https://codecapital.substack.com/p/por-que-todo-programador-deveria-escrever#:~:text=disse%20no%20artigo-,3%20conselhos%20pr%C3%A1ticos%20para%20crescer%20na%20carreira%20como%20programador,-%2C%20meu%20primeiro%20emprego" rel="noopener noreferrer" target="_blank">3 Practical Tips for Growing Your Career as a Programmer</a>" (<em>available in Portuguese)</em> my first job in the United States came from being cold-called by a company that found one of my articles online.</p>
<p>I've never been famous, and my texts never gained much traction (except for "How to Become a Bad Developer," which miraculously reached HackerNews front page), and this is not a case of natural selection in action (where someone successful teaches how to succeed in a niche where few can succeed). My texts had mediocre reach, were read by very few people, yet they still created an authority that qualified me for an international career.</p>
<p>You might think you have nothing interesting to say, but that's not true. As programmers, we solve puzzles every day. It's one of the few professions where we’re constantly learning something new. <em>Crystallize</em> this learning — it will benefit you, your career, and your readers (even if they are few).</p>
<h2 id="writing-as-a-form-of-communication">Writing as a form of communication</h2>
<p>Programming work is a collective effort — even if you're the only one writing code. If you have clients, you need to understand their difficulties and communicate solutions. If you have stakeholders, you must understand their demands and pain points, and argue the best way to address them. If you have teammates, you need to communicate your doubts, train new programmers, write documentation.</p>
<p>This necessity is further amplified if you work remotely. Without the <em>tête-à-tête</em> of a conventional office, you'll need to communicate more efficiently, often in writing (after all, remote collaboration is mostly asynchronous).</p>
<p>There’s a whole etiquette for remote work that’s essential for those who wish to excel in this mode: writing direct and concise messages, being clear in communication, not wasting others' time, etc. But the main aspect is what's known as <em>rubber duck debugging</em>.</p>
<figure class="image"><img alt="Get yourself a duck, but if lacking, any action figure will work." loading="lazy" decoding="async" width="1536" height="1024" src="https://rafaelquintanilha.com/_astro/ChatGPT-Image-Jun-18--2025--02_34_53-PM.BfglGzcG_Z17YW93.webp"><figcaption>Get yourself a duck, but if lacking, any action figure will work.</figcaption></figure>
<p>Rubber duck debugging is an extremely effective method for debugging code (i.e., understanding why it doesn't work properly), which literally involves explaining the problem to a rubber duck.</p>
<p>This method works because when we explain something to someone, we consciously organize our thoughts, often clearing our minds. It's as if a light turns on during the explanation, and the solution becomes obvious — but only after we <em>order</em> our thoughts to explain it.</p>
<p>That's why whenever someone asks me for a quick call, I ask them first to write down their question. This requirement serves to: 1) allow work to flow asynchronously, and 2) serve as a rubber duck, where the mere act of writing (and consequently organizing thoughts to ask a question) reveals the solution. I've lost count of how many times this method worked for me.</p>
<p>Therefore, writing will help you better understand your field. Don't worry about readers; you're writing for yourself. If someone else benefits, even better. But the main goal is to solidify that knowledge internally. It's no coincidence that most reading retention techniques involve summarizing in your own words what you understood from a given chapter (a technique famously shared in books like <a href="https://amzn.to/3Tw9BzG" rel="noopener noreferrer" target="_blank">How to Take Smart Notes</a>).</p>
<h2 id="writing-as-a-form-of-thinking">Writing as a form of thinking</h2>
<p>When I talked about writing as technical validation, we were at the most basic level of reasons to write: the utilitarian one, a kind of "advertisement" of your technical capabilities.</p>
<p>Then, we moved up to writing as communication. Here, this skill turns you into a valuable asset for those around you and a true team player. If the first level <em>gets</em> you a job, this one <em>keeps</em> you there.</p>
<p>Finally, at the highest level, writing develops your thinking ability. This skill transcends your job or mere programming and expands your understanding of the world, enabling you to see the reasons behind things, the best ways to organize a team, a company, and ultimately your own life. This is the stage that advances your career.</p>
<p>This is the real reason we should write: transforming the blob of data chaotically populating our minds into insights about the world, allowing us to work smarter.</p>
<p>If I haven't convinced you with this pseudo-philosophical argument, consider that in the age of AI, any model will ultimately code better than you. This is a competition we're doomed to lose. However, an AI will never <em>think</em> better than us — because it can't truly think. You don't have to believe me, though. A research team at Apple just released a paper named <a href="https://machinelearning.apple.com/research/illusion-of-thinking" rel="noopener noreferrer" target="_blank">The Illusion of Thinking</a> making the same claim (not really a breakthrough once this can be easily proved metaphysically, but let's not dive into that right now).</p>
<p>In this machine age, the winner will be whoever exercises their humanity — what only <em>we</em> can do. Thinking, creating, observing the world around us, identifying mechanisms behind things, concatenating ideas to solve problems — these are essentially human skills, as they emerge from human observation.</p>
<p>Writing trains your thinking. It's at this moment, alone with your thoughts, that you realize: do I <em>really know</em> what I <em>think</em> I know? Do I <em>know</em> what I want? <em>Why</em> do I want it? Practice not being an NPC, practice your understanding of the world, be humble enough to seek help from other texts, build your own knowledge network, and soon you’ll become indispensable not only at work but to everyone around you.</p>
<p>Write for yourself. Having an audience isn't essential for writing to be worthwhile. In some cases, readers might even hinder — write for others and you'll lose authenticity. Don’t fool yourself into thinking that just because programming is technical or boring, you’re excused from using words well.</p>
<p>Earlier this year, when I was setting up my <a href="https://substack.com/@rafaelquintanilha" rel="noopener noreferrer" target="_blank">Substack</a>, I struggled to find the right bio. Everything seemed wrong and without character. Finally, I settled on a sentence that ultimately captures the essence of today's article: <em>I write for humans and machines.</em></p>
<hr>
<p><a href="https://codecapital.substack.com/p/por-que-todo-programador-deveria-escrever" rel="noopener noreferrer" target="_blank"><em>Originally published in Portuguese at Code Capital.</em></a></p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Using Codex as a task inbox]]></title>
<description><![CDATA[A proposed workflow to clear your backlog.]]></description>
<link>https://rafaelquintanilha.com/using-codex-as-a-task-inbox/</link>
<guid isPermaLink="false">682e5f188e5e1c000163d75c</guid>
<category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[ChatGPT]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 21 May 2025 23:39:02 GMT</pubDate>

<content:encoded><![CDATA[<p>When <a href="https://openai.com/index/introducing-codex/" rel="noopener noreferrer" target="_blank">OpenAI first introduced Codex</a>, I must admit I wasn't very impressed. After all, <a href="https://rafaelquintanilha.com/is-claude-code-worth-the-hype-or-just-expensive-vibe-coding/">I've been a heavy user of Claude Code</a>, an AI model geared toward programming, which seems far superior. Moreover, with so many new tools popping up every other day, it becomes necessary to set boundaries and focus on just one thing.</p>
<p>However, I became slightly curious when they announced Codex was available on mobile. This was genuinely different. Claude Code is a CLI that runs on the terminal, while Cursor is an IDE requiring a reasonably decent computer. What could possibly be done on a phone?</p>
<p>Then I stumbled upon an <a href="https://zackproser.com/blog/openai-codex-review" rel="noopener noreferrer" target="_blank">excellent review of Codex by Zachary Proser</a>, highlighting its strengths and weaknesses. Finally, I was convinced — after all, what kind of hacker would I be if I didn't test all available tools? Besides, managing a blog and a <a href="https://www.youtube.com/c/quantbrasil" rel="noopener noreferrer" target="_blank">YouTube channel</a>, content creation is never too much...</p>
<p>But before diving into the strengths and weaknesses of this new tool, let's clarify: what <em>exactly</em> is Codex?</p>
<p>Let's start with OpenAI's own definition: <strong>Codex is a cloud-based software engineering agent</strong>. In other words, it's an agent capable of replicating the work of a software engineer (SWE).</p>
<p>This is where skepticism peaks. Recently, there have been numerous promises of AI replacing programmers. Despite this, such a scenario still feels distant. Indeed, models have improved significantly, and the speed of development combined with market competition makes optimists see this replacement as just a matter of time. But what does real-world practice tell us?</p>
<p>As mentioned, I've been a heavy user of AI tools. I'm also formally trained as a software engineer, working actively in the field, and thus deal with tasks beyond mere side projects where AI usually excels. Yet AI still doesn’t replace the formal work of a programmer in large-scale software teams.</p>
<p>The truth is, humans’ major advantage over machines is our capacity for abstract thinking — metaphysically speaking — which will always provide us with an edge over AI. Although over the course of its development, many who perform mediocrely — in the literal sense — might get left behind.</p>
<p>Therefore, I approach the promise of a software engineering agent with substantial skepticism. Sure, it can code. But can it abstract problems? Identify stakeholder preferences? Adhere to codebase standards? Suggest alternative approaches? Anticipate issues? The list goes on.</p>
<p>With all these considerations, I decided to test Codex, currently available only on ChatGPT's Pro plan (costing a modest $200/month), and ended up positively surprised. The entire testing process was documented on YouTube.</p>
<p><a href="https://youtu.be/79zBBZ2fLCo?si=npMbfmt6oWy1zkbm" rel="noopener noreferrer" target="_blank"><img alt="" loading="lazy" decoding="async" width="1280" height="720" src="https://rafaelquintanilha.com/_astro/ChatGPT-Codex---Primeiras-Impresso-es.BOIHpB3f_Z1RN3nT.webp"></a></p>
<h2 id="why-use-codex">Why use Codex?</h2>
<p>Straight to the point: what is Codex’s main advantage? In the article mentioned above, the author describes his ideal workday:</p>
<blockquote>
<p>"I'd like to start my morning in an office, launch a bunch of tasks, get some planning out of the way, and then step out for a long walk in nature."</p>
</blockquote>
<p>As a big advocate of reducing cognitive load at work, I completely understand his sentiment. Many everyday programming tasks are dull or mentally taxing: reading documentation, finding the correct file to fix a bug, adhering to unfamiliar standards, etc.</p>
<p>Additionally, anyone working on multiple projects (as I do with <a href="https://quantbrasil.com.br" rel="noopener noreferrer" target="_blank">QuantBrasil</a>, <a href="https://mmatrends.com.br" rel="noopener noreferrer" target="_blank">MMA Trends</a>, <a href="https://portalvasco.com.br" rel="noopener noreferrer" target="_blank">Portal Vasco</a>, and other toy projects) would appreciate being able to switch contexts without mental exhaustion. "<em>Context switching is the productivity killer,"</em> Elon Musk said.</p>
<p>Here's Codex's main advantage: as a <em>frictionless</em> cloud-based agent, you can delegate tasks to AI in parallel across multiple projects with minimal mental effort. With a generous limit of 60 tasks per hour (essentially unlimited), this tool acts as a <strong>brain dump</strong> or a <strong>task inbox</strong>, directly capturing ideas and transforming them immediately into actionable tasks.</p>
<h2 id="the-end-of-backlogs">The end of Backlogs</h2>
<p>Let me explain. When I have an idea for a feature, improvement, or bug fix, I typically need to record it somehow — usually using project management tools like Linear or Jira, or simply jotting it down in Obsidian or Notion. Later, this idea needs to become a task. But what if the act of recording <em>itself</em> became the task? That’s the world Codex promises.</p>
<p>You could dispatch multiple tasks and review them later, approving simpler ones quickly while dedicating more attention to the intricate ones. Obviously, this workflow depends on an AI competent in programming — and Codex’s <em>codex-1</em> model delivers.</p>
<p>However, the model used is fine-tuned to solve problems in one go, meaning iterating on a task isn't the most enjoyable experience. Each new iteration, if tested, becomes a new pull request — even within the same task. This makes the experience somewhat cumbersome, though I expect improvements soon.</p>
<h2 id="where-codex-excels">Where Codex excels</h2>
<p>So, the big question is: <em>where is Codex genuinely useful?</em> In its current form, the best use case is self-contained tasks with clear existing references in the codebase. For instance, adding a "last 90 days" filter to the <a href="https://mmatrends.com.br" rel="noopener noreferrer" target="_blank">MMA Trends</a> leaderboard was as simple as writing "add last 90 days to the leaderboard," and Codex identified and implemented the necessary changes.</p>
<figure class="image"><img alt="You don&#x27;t need to be a prompt master to leverage Codex." loading="lazy" decoding="async" width="1148" height="1432" src="https://rafaelquintanilha.com/_astro/image-2.r1T3nLvL_ZsWNpl.webp"><figcaption>You don't need to be a prompt master to leverage Codex.</figcaption></figure>
<p>Thus, minor additions, especially backend tasks or routine activities like refactoring components, adding unit tests, or making linter corrections, are excellent fits for this new agent.</p>
<h2 id="areas-for-improvement">Areas for improvement</h2>
<p>Naturally, there are many tasks not suitable for Codex. Particularly, elaborate frontend tasks don’t fit well since the agent doesn’t execute code, thus you are unable to see how it <em>looks</em> after the task is done. Consequently, creating PRs, checking out locally, requesting modifications, and iterating back-and-forth is cumbersome (forget about doing this in the woods).</p>
<p>Also, for security reasons, Codex doesn't have internet access after the environment setup, meaning updated documentation or interacting with external tools is out of scope. Thus, prompts must either be <em>precise</em> (which counters the promised practicality) or tasks <em>extremely simple</em> (like adding a button, moving text, or adding a filter).</p>
<h2 id="a-workflow-to-consider">A workflow to consider</h2>
<p>Finally, I'd like to propose a workflow designed to minimize cognitive load and still be practical for larger projects and complex features. Using Codex as a brain dump provides a starting point, albeit imperfect. Most tasks would still require refinement. But at this stage, there’s already existing code, context, and intention, making it easier to leverage a more appropriate model like Claude Code for further refinement.</p>
<p>I envision a scenario where I open Codex to find 5-10 tasks <em>ready for review</em> instead of facing a list of Jira tickets <em>to start from scratch</em>. The cognitive savings here are tremendous — <em>this</em> effectively transforms programmer productivity.</p>
<p>Ultimately, today isn’t the day AI replaces us. Is that day getting closer? Currently, Codex could competently replace an intern, handling small asynchronous tasks without much trouble. Tomorrow, its capabilities might extend to delegating even more complex problems.</p>
<p>Nevertheless, the ability to synthesize and abstract necessary to interact effectively with AI is increasingly valuable. Knowing how to express oneself, identify bottlenecks, and decide correctly when to use such tools remains crucial. Focus on these skills, and there's no need to fear Codex. On the contrary, when the day arrives when we no longer have to code, we can breathe a sigh of relief, finally liberated.</p>
<p><img alt="" loading="lazy" decoding="async" width="1080" height="1102" src="https://rafaelquintanilha.com/_astro/image-3.CQDbgOLA_1s5vLt.webp"></p>
<hr>
<p><a href="https://codecapital.substack.com/p/o-que-aprendi-usando-o-codex-o-agente-de-programacao-da-openai" rel="noopener noreferrer" target="_blank"><em>Originally published in Portuguese at Code Capital.</em></a></p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Not every programmer needs to be a professional]]></title>
<description><![CDATA[A lesson coming from the Alps.]]></description>
<link>https://rafaelquintanilha.com/not-every-programmer-needs-to-be-a-professional/</link>
<guid isPermaLink="false">67d20354e292a00001b41e27</guid>
<category><![CDATA[Artificial Intelligence]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 12 Mar 2025 22:00:28 GMT</pubDate>

<content:encoded><![CDATA[<p>If you wander into the northern mountains of the Italian Alps, you may find a 41-year-old Dutchman named Martijn Doolaard, working diligently and calmly in his stone cabin. Martijn, previously a graphic designer, now spends his days refurbishing an old alpine structure that once sheltered cows and other animals. With an eye for serene beauty, he captures and shares his daily tasks and surroundings on his <a href="https://www.youtube.com/@MartijnDoolaard" rel="noopener noreferrer" target="_blank">YouTube channel</a>.</p>
<p>To me, Martijn's channel is among the best things the internet has to offer. For years, my wife and I follow his Netflix-grade episodes, and it’s probably the “TV series” we are most anxious to watch. Ironically, there’s no anxiety at all in his videos—just a man barely talking, working meticulously, restoring and repairing a house in a beautiful setting.</p>
<p>Although Martijn used to work with computers, he does a completely different kind of work now. Need a septic system? He builds one. Cement work? Done. Chicken coop? Of course. Gardening and greenhouses? Easily managed. Even smaller projects, like crafting simple tools or a bench where he can quietly sip coffee on cold mornings, are within his scope. He's not striving for professional perfection or selling his services; he's fulfilling personal needs and finding joy in creation, searching for beauty in the tiniest details.</p>
<p>In software engineering, we could learn much from Martijn's approach. Today, especially as AI tools become ubiquitous, there's surprising hostility toward casual or amateur coding projects. Many professionals scoff at the idea of "<em>vibe coding</em>" or tinkering with tools without deep technical knowledge. But why should that bother us?</p>
<p>When someone builds a tool primarily for personal use—however imperfect—it's already a success. Who cares if it's not optimal or has vulnerabilities? The point is the joy and learning in the process itself. I always recall how I got into web development: I wanted to track a few chores I used to do for my former employer. What could have been easily the simplest spreadsheet became an excuse to build my first web app, which was later presented in a technical interview, where I landed my first job in the area.</p>
<p>Observing Martijn's serene craftsmanship, I realize how fortunate we are as software engineers. Our toolbox grows bigger every day, enabling us to attempt projects that would previously never get off the paper. I wish similar assistance existed in woodworking, masonry, or gardening. Why not encourage people to experiment freely with software? If they misuse or misunderstand AI, so be it. Imperfections are natural; over time, only truly useful products survive anyway.</p>
<p>I wish more people tried Martijn Doolaard’s philosophy in programming. I want people to have fun building tools for themselves. If they ship broken apps or sell shitty products, that’s fine. I’m the specialist they’ll come to when the toy project isn’t enough anymore—just like Martijn might consult someone who knows better how to properly level a floor. And I doubt anyone in construction is offended when amateurs try DIY.</p>
<p>I thereby advocate for a mindset shift in the current <em>Zeitgeist</em>: let people tinker freely. It’s better to have more people involved, more potential for collaboration, and more demand for expertise. If an amateur can do something decent with AI, imagine the advantage seasoned developers will gain from mastering them.</p>
<p>Let’s all rejoice in the power of software and AI, and be inspired by that calm, creative spirit Martijn Doolard demonstrates every day in the Alps.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Claude Code is expensive, reckless, and weirdly fun]]></title>
<description><![CDATA[An expensive way to vibe coding.]]></description>
<link>https://rafaelquintanilha.com/is-claude-code-worth-the-hype-or-just-expensive-vibe-coding/</link>
<guid isPermaLink="false">67cf03f8e218cc000126f7a8</guid>
<category><![CDATA[Artificial Intelligence]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Mon, 10 Mar 2025 15:27:05 GMT</pubDate>

<content:encoded><![CDATA[<p>When Anthropic announced their new CLI, <a href="https://docs.anthropic.com/en/docs/agents-and-tools/claude-code/overview" rel="noopener noreferrer" target="_blank">Claude Code</a>, I wasn't amused. In fact, I didn't see the point. Why use it in the CLI when we have it in a proper IDE like <a href="https://cursor.com" rel="noopener noreferrer" target="_blank">Cursor</a>?</p>
<p>However, after reading some interesting reviews, I decided to give it a shot. Here's what I learned over the last week (and after spending a few dollars along the way).</p>
<h2 id="comparison-with-cursor">Comparison with Cursor</h2>
<p>Let's start by addressing the elephant in the room. Why bother using Claude Code at around $5 per session when you can pay $20 for Cursor and use it indefinitely<a href=""><sup>[1]</sup></a>, while enjoying a fully-fledged IDE rather than a dull CLI?</p>
<p>In my experience, there are two distinct use-cases where each tool clearly shines.</p>
<h3 id="managing-big-contexts">Managing Big Contexts</h3>
<p>When precise context is crucial, Cursor is the clear winner. Its ability to control exactly what code is fed into the model helps tailor responses precisely. Suppose your code follows a specific pattern—maybe you organize your API layer into routers, services, and schemas. If you want to create a new service, it’s helpful to open related files, add them to the context, and prompt the model with instructions like "follow the pattern defined in X, Y, and Z."</p>
<p>In Claude Code, however, there's no practical way to tag files, only to describe them verbally. This approach is suboptimal, as it either requires a very small codebase or perfect memory of file paths—something I rarely have or think I should have.</p>
<h3 id="vibe-coding">Vibe Coding</h3>
<p>Ah yes, the term of the hour: <em>vibe coding</em>. It's essentially when you <em>interact</em> more than you <em>read or write</em> code. Development in this mode is somewhat reckless and, honestly, fun.</p>
<p>Claude Code surprisingly excels here. Operating outside the IDE helps get into the mood—you skim rather than deeply analyze code. While the loader runs, you can do something else. It makes mistakes but often self-corrects. You’re truly supervising, making coding feel as close to natural language as possible in 2025.</p>
<p>Pair it with a tool like <a href="https://superwhisper.com/" rel="noopener noreferrer" target="_blank">Superwhisper</a>, and the experience becomes even better. In <em>vibe coding</em>, precise prompts aren’t crucial—you simply open your mind and let the AI sort your thoughts.</p>
<p>It's genuinely fun: pressing a button to talk, standing up, walking around, mumbling ideas on how something should work or pitfalls to avoid, and shaping thoughts in your head while AI does the heavy lifting.</p>
<p>Of course, this approach can get expensive. <em>Vibe mode</em> tends to be imprecise—sometimes taking longer and inflating context, potentially confusing the model and leading to inefficiency.</p>
<p>Yet, there's a fascinating trade-off: this relaxed method is far less cognitively intense, which makes speed irrelevant. Like not trying to break personal records every gym session, there's a place in coding for simply focusing on consistent progress—and if it's enjoyable, even better.</p>
<h2 id="when-does-it-shine">When Does It Shine?</h2>
<p>Claude Code excels at tackling <em>boring</em> tasks. For instance, I successfully set up Pytest in minutes—a chore I'd procrastinated on due to sheer lack of enthusiasm. Quickly, I had tests ready, documentation drafted, and a new CI workflow established.</p>
<p>It's also great for extending features, especially when you allow for some creativity or don't have strong opinions about the solution. Need a reading mode for your news aggregator? Let the model handle it. Server-side search? Give it a spin.</p>
<p>However, due to lower supervision by design, it suits smaller or less critical projects best. If strict adherence to guidelines or best practices is required, Cursor’s superior context management typically provides better results.</p>
<h2 id="pricing">Pricing</h2>
<p>Let’s be clear—it’s <em>expensive</em>. Perhaps not so much in <em>absolute</em> terms, but definitely in <em>relative</em> terms.</p>
<p>If someone fixes your problem for $5, that seems reasonable. Over a month, that's akin to having a dedicated intern for $100—not bad, right?</p>
<figure class="image"><img alt="Anthropic charged me $5 for 32 minutes of work. Cheap in absolute, expensive in relative terms." loading="lazy" decoding="async" width="1202" height="310" src="https://rafaelquintanilha.com/_astro/image.CyG94kCf_Z39XY1.webp"><figcaption>Anthropic charged me $5 for 32 minutes of work. Cheap in absolute, expensive in relative terms.</figcaption></figure>
<p>Yet, relative to developers accustomed to around $20 monthly for comprehensive tools (OpenAI Plus, Claude AI, GitHub Copilot, Cursor), it can feel steep.</p>
<p>The enjoyment factor partly relies on reckless experimentation, suitable primarily for side or non-critical projects. But this sharply reduces ROI—are you willing to spend $20–$30 on a weekend side project likely generating $0 revenue, just for fun?<a href=""><sup>[2]</sup></a></p>
<p>Honestly, without my company’s carte blanche for experimentation, I'd likely use Claude Code far less (though I'd be less amused at work).</p>
<h2 id="is-it-the-future">Is It the Future?</h2>
<p>Probably not—and I don't particularly care. Currently, it's a valuable tool for self-contained tasks permitting creative freedom or mechanical chores where the implementation specifics don't matter.</p>
<p>There are obvious UX issues likely soon resolved—like unnecessary permission prompts for harmless tasks—but ironically, its simplicity contributes significantly to its charm.</p>
<p>Of course, underlying model quality matters greatly—and Claude 3.7 Sonnet (and its reasoning variant) are arguably the current SOTA for programming, greatly enhancing the overall experience.</p>
<p>I'll continue reporting my experiences. Until then, enjoy your <em>vibe coding</em> (if your wallet allows).</p>
<hr>
<ol>
<li>It's not really indefinitely as Cursor may throttle you, connection drops, there are fast and slow requests, etc. <a href="">↩︎</a></li>
<li>Not that I never regretted spending way more than that for things that are way less fun, but YMMV. <a href="">↩︎</a></li>
</ol>]]></content:encoded>
</item>
<item>
<title><![CDATA[Are AI Assistants Making Us Worse Programmers?]]></title>
<description><![CDATA[Perspectives on the rise of AI in programming and its effects on productivity.]]></description>
<link>https://rafaelquintanilha.com/are-ai-assistants-making-us-worse-programmers/</link>
<guid isPermaLink="false">67321368b9643c00017be1c5</guid>
<category><![CDATA[Artificial Intelligence]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Mon, 11 Nov 2024 14:33:45 GMT</pubDate>

<content:encoded><![CDATA[<p>They are everywhere now – from Copilot to Cursor, Zed to Aider – AI assistants have permeated IDEs and programming tools. Relying on an ever-changing ecosystem of models, many of them tuned to excel in programming tasks, it is safe to say one needs to make a <em>conscious</em> decision in order to <em>avoid</em> using AI during a typical day as a programmer.</p>
<p>I can tell from experience: I tested almost all of them and integrated them somehow into my workflow. I also have over 10 years of programming experience, so I know well how is to <em>not</em> use such assistants (the effect they can cause on a younger cohort intrigues me but I won't explore in this essay.)</p>
<p>I decided to reflect on this ubiquitous adoption trying to answer the question: <strong>is the usage of AI assistants making me a worse programmer</strong>?</p>
<p>Of course much of what I have to say is entirely personal, but I hope I can draw from fundamental principles that extend beyond programming, and therefore you can resonate with it giving your own experience.</p>
<h3 id="does-the-world-now-require-less-skills-than-in-the-past">Does the world now require less skills than in the past?</h3>
<p>Being born in the 90s in Brazil you can only imagine how fresh it was in every adult mind the figure of Ayrton Senna. One of the most talented racing drivers to date, obsessed with performance, Senna tragically but somewhat poetically died in an accident in San Marino's circuit in 1994.</p>
<p>Senna quickly became immortalized as one of the greatest of all time, and a recurring theme in generational debates about who was better – typically with an addendum that makes the exercise even more impossible to resolve – <em>in his peak.</em></p>
<p>For those who would pick the guys from the old-days, a typical argument is: <em>"nowadays pilots have it all automated, back in the day they had to know it all"</em>. Heck, I heard my father say countless times that they used to control the car <em>by hand</em>. I don't pretend to know Formula One enough to take sides here, but I think this argument has a point worth discussing.</p>
<p>In programming, high-level languages many times abstract the complexity away from you – something developers working with JavaScript, Python, Java, etc, know well. It seems clear that AI assistants introduce a <em>new</em> human-machine interface – natural language. Is that bad?</p>
<h3 id="distinguishing-core-skills-from-tool-specific-knowledge">Distinguishing core skills from tool-specific knowledge</h3>
<p>There is a heated debate about whether going to college to study Software Engineering or Computer Science is relevant in a world where you have access to countless courses either for free or for very cheap (relative to formal education).</p>
<p>I hold a degree in Computing Engineering and don't have a formal opinion. Why? Because in college I learned to <em>understand</em> computers. I studied the fundamentals, and they stuck. In contrast, 99% of the tools I had to learn are either outdated or simply useless.</p>
<p>However, those years honed my <em>core skills</em>, knowledge that is exterior to the specific tools you have at your disposal, principles that govern the activity of being a software engineer. And that <em>is</em> hard to get from crash courses and bootcamps.</p>
<p>Note that I'm not saying at all that bootcamps and crash courses are useless, just that by their own nature you won't have the time required to develop the core skills, trading this time for mastering <em>tool usage</em> at professional level (it's no wonder a lot of AI takeover doomists come from this space.)</p>
<p>Same as Senna knew things from racing cars that maybe the newer generation <em>doesn't have to</em>, we should ask: do I really need the specifics we <em>used</em> to know in the past? Especially when technologies are <em>so transient</em>?</p>
<p>I will give another example. I started working with Gatsby around 2018. Back then, it looked like a nice framework to build static sites, with a nice appeal to dynamic apps as well. I developed countless apps using Gatsby, engaged in public competitions and can safely say that I had at some degree mastered its usage.</p>
<p>Then... it was gone. Next.js and other frameworks like Astro took over and Gatsby became suddenly unmaintained. All the specifics I had to learn to operate the framework at a high-level are now useless for my current projects, and the herculean effort I had to put on to migrate all my apps were definitely painful.</p>
<p>What I <em>did</em> took from this episode, though? I learned about Server-Side Rendering and Static Site Generation ages ago – so when React 18 adopted server components as default I already had a mental model for it. Moving to Next.js app router was also easy, as I could relate to the reasoning behind it. But my knowledge of Gatsby plugins, gatsby-node, gatsby-config, and even GraphQL is now buried.</p>
<p>That's because knowing about Server-Side Rendering is a <em>core skill</em>, it is fundamentally tied to web development and how the internet operates. Should I build this page statically or dynamically? This is a judgement call that I – a human – need to make based on my knowledge. Once this decision is taken, AI can safely aid me with the implementation details – they won't matter for the most part.</p>
<h3 id="the-case-for-ai-assistance">The case for AI assistance</h3>
<p>Until now I'm taking a defensive stance on why leveraging AI assistants may not dwarf your skills. But I also want to offer a more positive view.</p>
<p>One thing that I always liked to do is to translate a business requirement into actionable pieces that can be taken by a developer. Therefore, I need to work on my abstraction capabilities whenever I am presented with a problem (that's why I like the term <em>software engineer</em>, as someone who uses software to model and solve real-world problems.)</p>
<p>Therefore, it comes really naturally to me to break down a problem into smaller steps, take them in the right order and assess the result in the end. Turns out this is a pretty decent framework to employ with AI assistants.</p>
<p>Anyone who has tried an AI assistant will recognize that their capability quickly deteriorates as you add more context, even if their context window is large. Hence, being able to feed them precisely what they need to figure out the <em>implementation details</em> is crucial (that's why I love Zed's approach to this problem.) Well, this is exactly what humans are good for. Sure, models like OpenAI's o1 are impressive in reasoning, but nowhere close being self-sufficient on the end to end process: reasoning, implementing, assessing.</p>
<p>Moreover, every programmer recognizes how context switching is a productivity killer. Regardless of how small the interruption can be, it will affect your ability to concentrate. In <a href="https://amzn.to/3Cor5sy" rel="noopener noreferrer" target="_blank">Deep Work</a>, Cal Newport mentions research that proposes that we have a limited amount of willpower available each day. Another concept explored by the author is the one of <em>attention residue</em>, the fact that changing activities too often will retain part of its context in our mind, effectively reducing our cognitive ability for the next tasks.</p>
<p>AI assistants are <em>context switch killers</em>, especially when integrated in the IDE. Don't recall a specific TypeScript syntax? Highlight the variable and ask the model to type it for you. Want to break down a large component into smaller ones? Ask for a file refactor and save some cognitive energy. Do you really recall by heart how to mock an API call in a unit test? I've been doing this for ages and never remember the syntax. The AI assistant thrives in such tasks and help you to stay in the flow.</p>
<p>Take UI animations, for instance. Is it really important to master the API of <em>framer-motion</em> or <em>react-spring</em>? As long as you can consciously employ animations on the right measure, without bloating the interface, you are good to go. And it is up to <em>you</em> – not the machine – to find the right balance.</p>
<p>When migrating away from Gatsby, I decided to move all files from JSX to TSX. The amount of time I saved by prompting the assistant to rewrite the components adding types is unprecedented. However, I <em>did</em> trade off honing my TypeScript skills for the sake of having it done quicker. Does that matter? I don't think so. In that case, TypeScript is a means to an end. Who knows if we'll have StaticScript or UberScript before long? I have seen enough.</p>
<h3 id="when-it-can-go-wrong">When it can go wrong</h3>
<p>Surely by now you believe I'm the captain of the hype train, over-excited with my NVDA shares (disclaimer: I don't hold any) and therefore ready to defend AI usage in all cases. Not quite: there are definitely problems that can arise from the abuse of AI in one's workflow.</p>
<p>The biggest one by and large is the <strong>over-reliance trap</strong>. This happens when you blindly delegate the work to the AI, and it fails to resolve the problem (ironically, this is usually very easy to spot right at the beginning.) Then you prompt it again. And again. The context window starts to blow up, you lose your manners... the apologies are enervating, you curse at the computer: "<em>are you the stupid machine that is supposed to take over the world?"</em></p>
<p>When this happens you lose way more than just your time (and temper). You risk depleting your willpower stock (in Newport's jargon) plus you now need to interact with code <em>you did not write</em>. The work that could have started as a clean slate now became a pair programming session with a junior developer who wrote bad code.</p>
<p>I've been trapped by that many times, and it usually ends with frustration when I realize that I spent more time than I would had I not used AI at all.</p>
<p>How to avoid that? Well, by being more <em>human</em>. By making better judgement calls on <em>when</em> is the right time to delegate to the AI; to make sure that you were able to break down the requirements into smaller, manageable tasks that an assistant could solve alone. This is the prompt engineering that I believe in. If AI assistants are a new interface, you will thrive if you learn how to interact with it.</p>
<h3 id="knowing-when-the-problem-is-solved">Knowing when the problem is solved</h3>
<p>I had a math teacher that, when explaining a tricky problem, would call our attention when the hardest part had been solved. The problem still had to be completed, but in his words, the only thing left was <em>bureaucracy</em>.</p>
<p>This is also the case with software engineering. Most of my work isn't particularly challenging. They just require abstraction, patience, order, and knowledge of the tools required to complete the task. It's important to <em>know</em> when a problem is solved, delegating to the AI the <em>bureaucratic</em> work. This frees us to deploy our best weapon – the human intellect – to solve the hardest piece of the puzzle.</p>
<p>For example, suppose that you are tasked with adding a dropdown that allows the user to select how a table is sorted. There is nothing challenging here: the sorting algorithm is basic, the UI is standard, if you are lucky there is even a common component to reuse... All you need to do is stitching things together, envisioning how they will interact, even though the actual implementation will vary depending on the framework. In other words, <em>it is a solved problem</em>. In such cases – which are far more common than many like to admit – the assistance of an AI model is not only handy, but likely <em>the best course of action</em>.</p>
<h3 id="conclusion">Conclusion</h3>
<p>There is a case to be made that using AI assistants can rust your programming skills. It is true that if used the wrong way it can also make you spend more time than you should, plus take a cut at your limited stock of willpower. And frankly, it won't replace humans nowhere near in the future.</p>
<p>However, it <em>is</em> an amazing tool – and as all tools, it is means to an end. The ultimate goal of a developer is to translate to a language that the computer can understand instructions to actions that will have impact in the real-world. And this ability requires constant fostering, which gives you an edge over the machine.</p>
<p>Assistants are incredibly useful when dealing with implementation details, the kind that don't affect your core skills, but are rather just requirements of transient technologies. Letting it type that HTML event variable for you, or create from scratch that pure function whose inputs and outputs are known, won't make you a bad developer – on the contrary, will preserve your mind to tackle the hardest problems, allowing you to focus on the right things, design comprehensive solutions, and ultimately become a more productive developer.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Reducing churn with Stripe and ChatGPT]]></title>
<description><![CDATA[Leverage ChatGPT to communicate with your customers.]]></description>
<link>https://rafaelquintanilha.com/reducing-churn-with-stripe-and-chatgpt/</link>
<guid isPermaLink="false">670e7da7d8bba20001d2b680</guid>
<category><![CDATA[ChatGPT]]></category><category><![CDATA[Pipedream]]></category><category><![CDATA[Automation]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Mon, 22 Jul 2024 14:38:00 GMT</pubDate>

<content:encoded><![CDATA[<p>Managing a SaaS is <em>hard</em>. Not only you need to develop an idea and battle for its adoption, constantly iterate and listen to user feedback, but also handle the back-office aspect of it. In particular, if you receive money in exchange of offered services, there is a plethora of zones to cover.</p>
<p>We tend to overspend efforts to attract new customers, while existing clients often overlooked. I, for one, am guilty of doing so. It may look counter-intuitive, but your existing customers are the ones you should be looking closer! Reducing churn is a guaranteed way to improve your compounded revenue over time.</p>
<p>Even if you have a customer hooked in a subscription model, the battle is not won. For one reason or another payments fail, and if you are not on top of your recurring customers, you are deemed to leave money in the table.</p>
<p>Automation is key for any small, fast-paced team, which is the standard in the SaaS industry. If you are able to offset boring back-office tasks to <a href="https://pipedream.com?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Pipedream</a>, you gain precious time to invest on your core product.</p>
<p>Today I want to guide you on how to build a pipeline that:</p>
<ol>
<li>Listens to any failed payment events from Stripe;</li>
<li>Uses ChatGPT to transform the often cryptic messages into friendly, human-readable emails;</li>
<li>Sends the email via Postmark.</li>
</ol>
<p>The goal is to give a personal touch to your customers, warming up the relationship when the unexpected happens, without losing the scalability that only an automated AI system can offer. Let's get to it!</p>
<h2 id="connecting-to-stripe">Connecting to Stripe</h2>
<p>For this guide we'll be connecting to Stripe, which is the leading platform for offering subscription-based products online.</p>
<p>Start by creating a new workflow and searching for <strong>Stripe</strong> as trigger. There are several interesting events that you can listen to, and today we'll select <strong>New Failed Payment.</strong></p>
<p><img alt="" loading="lazy" decoding="async" width="1856" height="998" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-15-at-16.49.35@2x.dghR9PGU_23FwT.webp"></p>
<p>Next, you will be prompted to connect your Stripe account. If you don't yet have one, now it's the time to go to the <a href="https://dashboard.stripe.com/apikeys" rel="noopener noreferrer" target="_blank">Developers section and select the API keys tab</a>. I recommend you start by checking the <strong>Test mode</strong> toggle at the top-right corner, so you can test with peace of mind.</p>
<p>Click <strong>Create restricted key</strong> and select the permissions you want to allow. It's always a good practice to make them as restrictive as possible, especially for sensitive matters. <em>Tip: if you are unsure on what to select, allow Read permission for the items on the Permissions column (the one in the left). It's not always clear what is needed for every webhook.</em></p>
<p>After you are done configuring your key, grab its value, add it to Pipedream, and once the connection is configured you will be greeted with a waiting screen.</p>
<p><img alt="" loading="lazy" decoding="async" width="1862" height="1018" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-15-at-17.00.02@2x.BWmtsP0g_1mKT6B.webp"></p>
<p>Great! The connection is successful and now Pipedream is listening to failed payment events.</p>
<h2 id="triggering-a-failed-payment">Triggering a failed payment</h2>
<p>There are several ways to trigger a failed payment, and thankfully it doesn't involve using a real card in production. The simplest solution is to configure a <a href="https://stripe.com/en-br/payments/payment-links" rel="noopener noreferrer" target="_blank">Payment Link</a>. Create one and you should see a portal like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="2258" height="1412" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-15-at-17.05.46@2x.te6Dm5T5_1udGvf.webp"></p>
<p><em>Fun fact</em>: even OpenAI uses Payment Links to manage ChatGPT subscriptions. You really don't need to build it yourself if you don't want to.</p>
<p>Now, Stripe conveniently provides several test card numbers that are wired to trigger specific errors (<a href="https://docs.stripe.com/testing#declined-payments" rel="noopener noreferrer" target="_blank">see the full list</a>). Make sure you pick a card associated with a payment failure, provide any 3-digit number as CVC and select a valid date (anyone in the future is fine). Try to pay and if all goes well the payment will be declined and you should see it show up in Pipedream.</p>
<p><img alt="" loading="lazy" decoding="async" width="1846" height="1648" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-15-at-17.12.05@2x.CRkqGdpr_HeN3.webp"></p>
<p>We have everything we need from Stripe, now onto leveraging AI to extract relevant information from the API.</p>
<h2 id="generating-a-human-friendly-message">Generating a human-friendly message</h2>
<p>Stripe returns a huge JSON with several relevant metadata, including fields like <code>failure_code</code> and <code>failure_message</code>. But it also returns billing details, which holds the user name, email and address.</p>
<p>Technically we could write a code to extract everything needed, but that's a great use-case for an AI model like GPT-4o! Instead of fighting with all possible return cases, we should be able to feed the whole payload to the model and ask for a nicely-formatted JSON output.</p>
<p>In order to do that let's <em>stringify</em> everything in the <code>event</code> object of the trigger step. It's very easy to do it: hook a new step to the trigger and select <strong>Python</strong>. Add the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Reference data from previous steps</span></span>
<span class="line"><span style="color:#ECEBE8">    event </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"trigger"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"event"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Return data for use in future steps</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> {</span><span style="color:#97CCAE">"event"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">str</span><span style="color:#EDCC95">(event)</span><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>This is all we need. The result will be a really long string, hard to parse for humans, but hopefully an easy task for an AI!</p>
<p>Let's move forward by hooking a new step: select <strong>OpenAI (ChatGPT)</strong> from the list and next the <strong>Chat</strong> option. Make sure you have your OpenAI API key at hand if you haven't connected to it already.</p>
<p>As of this writing, the most capable ChatGPT model is the GPT-4o. Select it from the dropdown. Next, in <strong>User Message</strong>, pick the <code>event</code> object returned in the previous step. That's how it should look like <code>{{steps.python.$return_value.event}}</code>.</p>
<p>Now, we want the AI to return 3 values:</p>
<ol>
<li>The <em>email address</em> of the user we will contact;</li>
<li>The <em>subject</em> of the email;</li>
<li>The <em>content</em> of the message.</li>
</ol>
<p>This is a great use-case for using the <code>json_object</code> <strong>Response Format</strong>. By selecting this option we <em>force</em> the AI to return a parseable JSON, which will be handy later on.</p>
<p>The only thing left in this step is to write the <strong>System Instructions</strong>, which will nudge the model to answer the way we want. That's what I came up with:</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>Your job is to receive a JSON string, which happens when a Stripe payment fails, and craft an email that should feel personal, mention the reason the payment failed, suggest ways to fix it.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>Extract the user email, create the subject, and the message, as it can be consumed by an API.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>The tone of the message should be friendly, without being too much.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>The response should also be in the JSON format and contain the fields: email, subject, message.</span></span></code></pre></figure>
<p><strong>Important:</strong> you need to <em>explicitly</em> say in the system instructions that you want the response as JSON whenever the response format is set to <code>json_object</code>.</p>
<p>Go ahead and test the integration. If all goes well, you can inspect the content:</p>
<p><img alt="" loading="lazy" decoding="async" width="1840" height="1542" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-16-at-10.30.48@2x.DyP5ey1P_23d4CL.webp"></p>
<p>This is a good time for you to adjust the tone of the message to better suit your use-case. You can also experiment with other failures and analyze how the model performs.</p>
<h2 id="parsing-the-ai-generated-json">Parsing the AI-generated JSON</h2>
<p>Once you are happy with the way the AI is crafting the message we are ready to finish the workflow by emailing the user.</p>
<p>Before we connect to <a href="https://pipedream.com/apps/postmark/actions/send-single-email?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Postmark</a>, which is my favorite email delivery service, we need to parse the JSON returned by the GPT model.</p>
<p>Add a new Python step (I named <em>python_json</em>) and paste the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> json</span></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Reference data from previous steps</span></span>
<span class="line"><span style="color:#ECEBE8">    content </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"chat"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"$return_value"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"original_messages_with_assistant_response"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"content"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Return data for use in future steps</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> json.</span><span style="color:#EDCC95">loads(content)</span></span></code></pre></figure>
<p>And now, as easy as that, the JSON is formatted and ready to be consumed by the email API.</p>
<p><img alt="" loading="lazy" decoding="async" width="1840" height="1210" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-16-at-10.36.20@2x.BpXXNAi__1ElvKC.webp"></p>
<h2 id="sending-the-email-with-postmark">Sending the email with Postmark</h2>
<p>Let's wrap up this guide by creating our final step: search for <strong>Postmark</strong> and then select <strong>Send Single Email</strong>. <em>Note: you can also choose Send Email With Template if you already have one configured.</em></p>
<p>The next steps are easy: connect to your Postmark account (you will need an <a href="https://account.postmarkapp.com/api_tokens" rel="noopener noreferrer" target="_blank">API token</a> for a server. It's also a good idea to have a dev server where you can experiment before going live). Finally, all required fields were generated in the previous step, with the exception of the <em>"From" email address</em>, which you should select from your <a href="https://account.postmarkapp.com/signature_domains" rel="noopener noreferrer" target="_blank">Sender Signatures</a> in Postmark.</p>
<p><img alt="" loading="lazy" decoding="async" width="1852" height="1422" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-16-at-10.43.00@2x.CbG9O4Dq_ZEmnc0.webp"></p>
<p>Go ahead and test the integration. The email with the custom AI-generated message will be visible in Postmark.</p>
<p><img alt="" loading="lazy" decoding="async" width="2202" height="1772" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-16-at-10.45.13@2x.CqhObnL9_2ngYMn.webp"></p>
<h2 id="next-steps">Next steps</h2>
<p>I hope that this guide sparks your creativity. While we barely touched all possible integrations made possible by Pipedream, a few follow-ups include:</p>
<ul>
<li>Use the same principle but do the reverse: <a href="https://pipedream.com/apps/stripe/triggers/new-subscription?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">contact every new subscriber</a> with a custom AI-generated message;</li>
<li><a href="https://pipedream.com/apps/stripe/triggers/canceled-subscription?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Connect with the user whenever a subscription is cancelled</a> offering a deal for them to come back;</li>
<li>If the user phone number is present in the Stripe payment form, <a href="https://pipedream.com/apps/twilio/actions/send-sms?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">send a SMS message using Twilio</a>.</li>
</ul>]]></content:encoded>
</item>
<item>
<title><![CDATA[Creating an out-of-office reminder system]]></title>
<description><![CDATA[Setup a Google Calendar + Slack workflow that notifies your team whenever someone is out-of-office.]]></description>
<link>https://rafaelquintanilha.com/creating-an-out-of-office-reminder-system/</link>
<guid isPermaLink="false">670e7cbad8bba20001d2b66f</guid>
<category><![CDATA[Pipedream]]></category><category><![CDATA[Automation]]></category><category><![CDATA[Python]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 21 May 2024 14:33:00 GMT</pubDate>

<content:encoded><![CDATA[<p>There are several ways to manage a team. In the modern start-up era, it is not uncommon to see HR departments replacing the old, stricter model, with a "responsible freedom" approach. Netflix popularized the principle of <a href="https://hbr.org/2014/01/how-netflix-reinvented-hr" rel="noopener noreferrer" target="_blank">treating employees as fully-formed adults</a>.</p>
<p>In order to have such autonomy in place, automations can be implemented, ensuring that your team is able to run independently without concealing relevant information from each other.</p>
<p>Consider an out-of-office system where each employee is responsible for picking their days off. Based on Netflix's principles, there is no need to strictly oversee such task, especially if some basic rules are respected (say, you should book your day off at least one week in advance, no more than X people from the team can be off at the same time, etc).</p>
<p>A simple system can be easily implemented with a shared Google Calendar, Slack notifications, and Pipedream as the automation engine. Today, I'll show how you can:</p>
<ol>
<li>Notify your team whenever someone book some time off;</li>
<li>Notify who is out for the day.</li>
</ol>
<p>Let's get started!</p>
<h2 id="notifying-new-entries-in-the-calendar">Notifying new entries in the calendar</h2>
<p>Start by creating a new workflow and searching for <em>Google Calendar</em> as trigger. A few options will show up, but for now let's select <strong>New Event Created.</strong></p>
<p><img alt="" loading="lazy" decoding="async" width="1906" height="1008" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-16.16.08@2x.D2j4gfGu_Z2tcRYx.webp"></p>
<p>You will need to connect your Google Calendar account (select the account which has access to the shared calendar).</p>
<p>Next, choose the frequency Pipedream will check if a new event has been created. Pick what works best for you, but as we are not aiming for real-time here, 15 minutes should be more than enough.</p>
<p>Finally, in <strong>Calendar ID</strong> you will be presented with a dropdown to select which calendar will be monitored. Pick the shared calendar and you are good to go!</p>
<p>After creating the source, you will be prompted to select a listened event in order to test the automation. Go ahead and create a new event in the calendar. Give it a few moments and the event should pop out! Select it and you will be able to inspect all the details.</p>
<p><img alt="" loading="lazy" decoding="async" width="1486" height="1738" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-16.23.42@2x.DCwSUo8u_2hPLsv.webp"></p>
<h3 id="generating-a-slack-message">Generating a Slack message</h3>
<p>The data from the trigger step is all we need to build the notification. In particular, we want to know <em>who</em> is out, <em>when</em> they will be out, and <em>how long</em> until they are out.</p>
<p>Let your creativity guide you through this step. All three values can be generated with a simple Python script – hence connect a new Python step to the trigger and add the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">from</span><span style="color:#ECEBE8"> datetime </span><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> datetime, timedelta, timezone</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> parse_datetime</span><span style="color:#ECEBE8">(date_str):</span></span>
<span class="line"><span style="color:#A1C1E4">    try</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        dt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">fromisoformat(date_str)</span></span>
<span class="line"><span style="color:#A1C1E4">    except</span><span style="color:#A1C1E4"> ValueError</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        dt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">fromisoformat(date_str </span><span style="color:#A1C1E4">+</span><span style="color:#97CCAE"> "T00:00:00+00:00"</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> dt.</span><span style="color:#EDCC95">astimezone(timezone.utc)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> count_weekdays</span><span style="color:#ECEBE8">(start_date, end_date):</span></span>
<span class="line"><span style="color:#ECEBE8">    days </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> (end_date </span><span style="color:#A1C1E4">-</span><span style="color:#ECEBE8"> start_date).days</span></span>
<span class="line"><span style="color:#ECEBE8">    weekdays </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0</span></span>
<span class="line"><span style="color:#ECEBE8">    last_weekday </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> start_date</span></span>
<span class="line"><span style="color:#A1C1E4">    for</span><span style="color:#ECEBE8"> i </span><span style="color:#A1C1E4">in</span><span style="color:#EDCC95"> range(days </span><span style="color:#A1C1E4">+</span><span style="color:#97CCAE"> 1</span><span style="color:#EDCC95">)</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        day </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> start_date </span><span style="color:#A1C1E4">+</span><span style="color:#EDCC95"> timedelta(days</span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95">i)</span></span>
<span class="line"><span style="color:#A1C1E4">        if</span><span style="color:#ECEBE8"> day.</span><span style="color:#EDCC95">weekday()</span><span style="color:#A1C1E4"> &#x3C;</span><span style="color:#97CCAE"> 5</span><span style="color:#ECEBE8">:  </span><span style="color:#A7A49E;font-style:italic"># Monday = 0, Friday = 4</span></span>
<span class="line"><span style="color:#ECEBE8">            weekdays </span><span style="color:#A1C1E4">+=</span><span style="color:#97CCAE"> 1</span></span>
<span class="line"><span style="color:#ECEBE8">            last_weekday </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> day</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> weekdays, last_weekday</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#ECEBE8">    event </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"trigger"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"event"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#ECEBE8">    creator </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"creator"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"email"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">    start </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"start"</span><span style="color:#ECEBE8">].</span><span style="color:#EDCC95">get(</span><span style="color:#97CCAE">"dateTime"</span><span style="color:#EDCC95">, event[</span><span style="color:#97CCAE">"start"</span><span style="color:#EDCC95">].get(</span><span style="color:#97CCAE">"date"</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#ECEBE8">    end </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"end"</span><span style="color:#ECEBE8">].</span><span style="color:#EDCC95">get(</span><span style="color:#97CCAE">"dateTime"</span><span style="color:#EDCC95">, event[</span><span style="color:#97CCAE">"end"</span><span style="color:#EDCC95">].get(</span><span style="color:#97CCAE">"date"</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#ECEBE8">    start_dt </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> parse_datetime(start)</span></span>
<span class="line"><span style="color:#ECEBE8">    end_dt </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> parse_datetime(end)</span></span>
<span class="line"><span style="color:#ECEBE8">    now </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">now(timezone.utc)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">    duration_days, last_weekday </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> count_weekdays(start_dt.date(), end_dt.date() </span><span style="color:#A1C1E4">-</span><span style="color:#EDCC95"> timedelta(days</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#ECEBE8">    days_until </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> (start_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#A1C1E4"> -</span><span style="color:#ECEBE8"> now.</span><span style="color:#EDCC95">date()</span><span style="color:#ECEBE8">).days</span></span>
<span class="line"><span style="color:#ECEBE8">    start_date_formatted </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> start_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%A, %B %d'</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#ECEBE8">    last_weekday_formatted </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> last_weekday.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%A, %B %d'</span><span style="color:#EDCC95">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> days_until </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        time_phrase </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "Today"</span></span>
<span class="line"><span style="color:#A1C1E4">    elif</span><span style="color:#ECEBE8"> days_until </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        time_phrase </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "Tomorrow"</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        time_phrase </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"In </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">days_until</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> days"</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#97CCAE"> "dateTime"</span><span style="color:#A1C1E4"> in</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"start"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">and</span><span style="color:#ECEBE8"> start_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#A1C1E4"> ==</span><span style="color:#ECEBE8"> end_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">        # Case 1: The creator is out only for some hours within the same day</span></span>
<span class="line"><span style="color:#A1C1E4">        if</span><span style="color:#ECEBE8"> days_until </span><span style="color:#A1C1E4">&#x3C;=</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">            slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office from </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC to </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">end_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC."</span></span>
<span class="line"><span style="color:#A1C1E4">        else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">            slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office on </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_date_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> from </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC to </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">end_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC."</span></span>
<span class="line"><span style="color:#ECEBE8">        event_type </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "only during the day"</span></span>
<span class="line"><span style="color:#ECEBE8">        duration </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 1</span></span>
<span class="line"><span style="color:#A1C1E4">    elif</span><span style="color:#97CCAE"> "dateTime"</span><span style="color:#A1C1E4"> not</span><span style="color:#A1C1E4"> in</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"start"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">and</span><span style="color:#ECEBE8"> start_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#A1C1E4"> ==</span><span style="color:#ECEBE8"> end_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#A1C1E4"> -</span><span style="color:#EDCC95"> timedelta(days</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">)</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">        # Case 2: The creator is out for a single full day</span></span>
<span class="line"><span style="color:#ECEBE8">        slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office."</span></span>
<span class="line"><span style="color:#ECEBE8">        event_type </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "only during the day"</span></span>
<span class="line"><span style="color:#ECEBE8">        duration </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 1</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">        # Case 3: The creator is out for more than one day</span></span>
<span class="line"><span style="color:#A1C1E4">        if</span><span style="color:#97CCAE"> "dateTime"</span><span style="color:#A1C1E4"> in</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"start"</span><span style="color:#ECEBE8">]:</span></span>
<span class="line"><span style="color:#ECEBE8">            slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office from </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_date_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> at </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC to </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">last_weekday_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> at </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">end_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC (</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">duration_days</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> days)."</span></span>
<span class="line"><span style="color:#A1C1E4">        else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">            slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office from </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_date_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> to </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">last_weekday_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> (</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">duration_days</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> days)."</span></span>
<span class="line"><span style="color:#ECEBE8">        event_type </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "more than one day"</span></span>
<span class="line"><span style="color:#ECEBE8">        duration </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> duration_days</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">    output </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#97CCAE">        "creator"</span><span style="color:#ECEBE8">: creator,</span></span>
<span class="line"><span style="color:#97CCAE">        "start"</span><span style="color:#ECEBE8">: start,</span></span>
<span class="line"><span style="color:#97CCAE">        "end"</span><span style="color:#ECEBE8">: end,</span></span>
<span class="line"><span style="color:#97CCAE">        "duration"</span><span style="color:#ECEBE8">: duration,</span></span>
<span class="line"><span style="color:#97CCAE">        "days_until"</span><span style="color:#ECEBE8">: days_until,</span></span>
<span class="line"><span style="color:#97CCAE">        "event_type"</span><span style="color:#ECEBE8">: event_type,</span></span>
<span class="line"><span style="color:#97CCAE">        "slack_message"</span><span style="color:#ECEBE8">: slack_message</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> output</span></span></code></pre></figure>
<p>Although the code is slightly big, there is nothing complicated going on. We are basically just formatting the message in a friendly manner so we highlight if the event is near. For example, we say <em>"Today, <a href="mailto:john@company.com">john@company.com</a> is out of the office"</em>, or <em>"Tomorrow, <a href="mailto:jane@company.com">jane@company.com</a> is out of the office"</em>. If the event is farther away, the output is <em>"In X days, <a href="mailto:mary@company.com">mary@company.com</a> will be out of the office"</em>.</p>
<p>The script also handles the cases when the person will be out for only part of the day, and when they will be out for many days in a row. Take some time to read through the code and make sure to adjust the wording to your needs!</p>
<h3 id="sending-the-slack-message">Sending the Slack message</h3>
<p>The Python step conveniently returns a dictionary with relevant values allowing for a finer control of the next steps. For now, let's simply add a new step, search for <em>Slack</em>, click on <strong>Send Message to a Public Channel,</strong> connect your Slack Account, select the Channel ID and add the message generated in the previous step.</p>
<p><img alt="" loading="lazy" decoding="async" width="1862" height="1040" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-17.43.27@2x.BMRNLB-t_1E3mjv.webp"></p>
<p>And that's it! Publish your workflow, create a new event in the shared calendar and in up to 15 minutes you will see the notification in Slack.</p>
<p>There are many enhancements to be made. For example, the <code>days_until</code> variable returned by the Python step can be used to conditionally trigger a new workflow. Suppose you have a hard rule that no time off can be booked with less than 5 days in advance. Then you can leverage the <strong>Continue based on condition</strong> step to send a warning, or even to delete the event from the calendar.</p>
<h2 id="listing-everyone-out-for-the-day">Listing everyone out for the day</h2>
<p>Notifying when someone book time off is progress, but it's not uncommon that a long-planned trip will be forgotten by the time it takes place (suppose you book a week off with two months in advance. When it's finally time, nobody will remember you are out).</p>
<p>Let's build another workflow, this time triggered at a fixed time on workdays. It will list all events in the calendar for that day and send a Slack message informing who is out. You can set it to run at the beginning of the day, so by the time your team show up to work there is a message letting them know who is unavailable.</p>
<h3 id="triggering-the-workflow">Triggering the workflow</h3>
<p>Start by creating a new workflow and selecting <strong>Custom Interval</strong> as trigger. Next, select the time that better suits your team schedule.</p>
<p><img alt="" loading="lazy" decoding="async" width="1852" height="788" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-17.58.05@2x.jxxNn9w__1UEqdt.webp"></p>
<p>In <em>Results</em> you can see the output, in particular the exact timestamp of when the workflow was triggered – this will be useful to restrict the search within Google Calendar's API.</p>
<h3 id="generating-the-boundaries">Generating the boundaries</h3>
<p>We don't want to list <em>all</em> events in the calendar, just the ones for that day. For example, if the event triggered on 2024-04-26T09:00:00+00, we want to list entries between 2024-04-26 and 2024-04-27 (we'll talk about timezones in a moment).</p>
<p>Let's use a Python script to get those values. Hook up a new step to the trigger and add the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">from</span><span style="color:#ECEBE8"> datetime </span><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> datetime, timedelta, timezone</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Get the timestamp from the trigger event</span></span>
<span class="line"><span style="color:#ECEBE8">    timestamp </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"trigger"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"event"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"timezone_configured"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"iso8601"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"timestamp"</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">    # Parse the timestamp into a datetime object</span></span>
<span class="line"><span style="color:#ECEBE8">    dt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">fromisoformat(timestamp)</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Convert the datetime to GMT (UTC)</span></span>
<span class="line"><span style="color:#ECEBE8">    dt_gmt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> dt.</span><span style="color:#EDCC95">astimezone(timezone.utc)</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Get the current day at midnight GMT</span></span>
<span class="line"><span style="color:#ECEBE8">    min_time </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> dt_gmt.</span><span style="color:#EDCC95">replace(hour</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">0</span><span style="color:#EDCC95">, minute</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">0</span><span style="color:#EDCC95">, second</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">0</span><span style="color:#EDCC95">, microsecond</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">0</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Get the next day at midnight GMT</span></span>
<span class="line"><span style="color:#ECEBE8">    max_time </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> min_time </span><span style="color:#A1C1E4">+</span><span style="color:#EDCC95"> timedelta(days</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Format the min_time and max_time as ISO 8601 strings</span></span>
<span class="line"><span style="color:#ECEBE8">    min_time_str </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> min_time.</span><span style="color:#EDCC95">isoformat()</span></span>
<span class="line"><span style="color:#ECEBE8">    max_time_str </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> max_time.</span><span style="color:#EDCC95">isoformat()</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Return the dictionary with min_time and max_time</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#97CCAE">        "min_time"</span><span style="color:#ECEBE8">: min_time_str,</span></span>
<span class="line"><span style="color:#97CCAE">        "max_time"</span><span style="color:#ECEBE8">: max_time_str</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span></code></pre></figure>
<p>The code is simply getting the timestamp of the triggered event, converting it to UTC, setting it to midnight (lower boundary) and then adding 1 day to it (upper boundary).</p>
<h3 id="listing-all-events">Listing all events</h3>
<p>Add a new step and, as before, search for <em>Google Calendar.</em> This time, however, select <strong>List events</strong>.</p>
<p><img alt="" loading="lazy" decoding="async" width="1850" height="1424" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.07.16@2x.DPCWlPwS_Z1N4ftP.webp"></p>
<p>Note that the values returned in the previous step are used as <strong>Min time</strong> and <strong>Max time</strong>, and that the <strong>Time Zone</strong> matches the one used during the data transformation.</p>
<p>Click to test and, if there is any event for the current day in the calendar, you will be able to see it.</p>
<p><img alt="" loading="lazy" decoding="async" width="1852" height="1214" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.12.27@2x.D88d58Bj_2qgJDC.webp"></p>
<h3 id="generating-the-slack-message">Generating the Slack message</h3>
<p>Let's use the same principle of the first example and use another Python script to generate a Slack message. Add a new step, select <strong>Python</strong> and add the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#ECEBE8">    events </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"list_events"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"$return_value"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"items"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#ECEBE8">    people_off </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [event[</span><span style="color:#97CCAE">"creator"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"email"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">for</span><span style="color:#ECEBE8"> event </span><span style="color:#A1C1E4">in</span><span style="color:#ECEBE8"> events]</span></span>
<span class="line"><span style="color:#ECEBE8">    num_people_off </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> len(people_off)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> num_people_off </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        message </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "Good morning! No one is out today."</span></span>
<span class="line"><span style="color:#A1C1E4">    elif</span><span style="color:#ECEBE8"> num_people_off </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"Good morning! Today </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">people_off[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">]</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> is out."</span></span>
<span class="line"><span style="color:#A1C1E4">    elif</span><span style="color:#ECEBE8"> num_people_off </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 2</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"Good morning! Today </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">people_off[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">]</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> and </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">people_off[</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">]</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> are out."</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"Good morning! Today </span><span style="color:#97CCAE">{</span><span style="color:#97CCAE">', '</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">join(people_off[:</span><span style="color:#A1C1E4">-</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">])</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, and </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">people_off[</span><span style="color:#A1C1E4">-</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">]</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> are out."</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> {</span><span style="color:#97CCAE">"num_people_off"</span><span style="color:#ECEBE8">: num_people_off, </span><span style="color:#97CCAE">"message"</span><span style="color:#ECEBE8">: message}</span></span></code></pre></figure>
<p>This short script is all you need to generate a helpful message to your teammates!</p>
<h3 id="conditionally-sending-a-slack-notification">Conditionally sending a Slack notification</h3>
<p>Finally, let's notify the team, but only if there is people off. Fortunately, the <code>num_people_off</code> return value can be used for it.</p>
<p>Select the option <strong>Continue based on condition</strong> for the next step and configure it like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="1864" height="908" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.16.35@2x.D7WNJsIO_GuQ8v.webp"></p>
<p>Now, any subsequent step will <em>only</em> run if the condition is met. That's exactly what we need, and the final act is to send another message to a public channel.</p>
<p><img alt="" loading="lazy" decoding="async" width="1858" height="956" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.17.41@2x.TDT88Ese_Z1nicMx.webp"></p>
<p>And that's it! Test the workflow and you should receive a message like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="1188" height="668" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.21.18@2x.QgZNXHgc_27AXru.webp"></p>
<p>There are <a href="https://pipedream.com/apps?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">several other calendar apps</a> that can be integrated using Pipedream. They are just a few clicks away from powering your automated workflows.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Classifying bug reports with ChatGPT]]></title>
<description><![CDATA[Integrate Airtable + ChatGPT + Slack using the power of Pipedream.]]></description>
<link>https://rafaelquintanilha.com/classifying-bug-reports-with-chatgpt/</link>
<guid isPermaLink="false">670e7b27d8bba20001d2b65b</guid>
<category><![CDATA[ChatGPT]]></category><category><![CDATA[Automation]]></category><category><![CDATA[Pipedream]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 28 Mar 2024 14:26:00 GMT</pubDate>

<content:encoded><![CDATA[<p>There is nothing dreaded more by programmers than bugs. Well, actually it's probably either <a href="https://martinfowler.com/bliki/TwoHardThings.html" rel="noopener noreferrer" target="_blank">naming things or cache invalidation</a>, but you see my point. Bugs show up at unwelcome times, perhaps when you are deep on a totally different problem.</p>
<p>If not properly handled, bugs can slow down an engineering team considerably. Context switching is expensive for any cognitive task. If you code, you know what I'm talking about. And if you haven't, then listen to Elon Musk.</p>
<figure class="embed embed-twitter" data-url="https://platform.twitter.com/embed/Tweet.html?creatorScreenName=webquintanilha&#x26;dnt=false&#x26;embedId=twitter-widget-0&#x26;features=eyJ0ZndfdGltZWxpbmVfbGlzdCI6eyJidWNrZXQiOltdLCJ2ZXJzaW9uIjpudWxsfSwidGZ3X2ZvbGxvd2VyX2NvdW50X3N1bnNldCI6eyJidWNrZXQiOnRydWUsInZlcnNpb24iOm51bGx9LCJ0ZndfdHdlZXRfZWRpdF9iYWNrZW5kIjp7ImJ1Y2tldCI6Im9uIiwidmVyc2lvbiI6bnVsbH0sInRmd19yZWZzcmNfc2Vzc2lvbiI6eyJidWNrZXQiOiJvbiIsInZlcnNpb24iOm51bGx9LCJ0ZndfZm9zbnJfc29mdF9pbnRlcnZlbnRpb25zX2VuYWJsZWQiOnsiYnVja2V0Ijoib24iLCJ2ZXJzaW9uIjpudWxsfSwidGZ3X21peGVkX21lZGlhXzE1ODk3Ijp7ImJ1Y2tldCI6InRyZWF0bWVudCIsInZlcnNpb24iOm51bGx9LCJ0ZndfZXhwZXJpbWVudHNfY29va2llX2V4cGlyYXRpb24iOnsiYnVja2V0IjoxMjA5NjAwLCJ2ZXJzaW9uIjpudWxsfSwidGZ3X3Nob3dfYmlyZHdhdGNoX3Bpdm90c19lbmFibGVkIjp7ImJ1Y2tldCI6Im9uIiwidmVyc2lvbiI6bnVsbH0sInRmd19kdXBsaWNhdGVfc2NyaWJlc190b19zZXR0aW5ncyI6eyJidWNrZXQiOiJvbiIsInZlcnNpb24iOm51bGx9LCJ0ZndfdXNlX3Byb2ZpbGVfaW1hZ2Vfc2hhcGVfZW5hYmxlZCI6eyJidWNrZXQiOiJvbiIsInZlcnNpb24iOm51bGx9LCJ0ZndfdmlkZW9faGxzX2R5bmFtaWNfbWFuaWZlc3RzXzE1MDgyIjp7ImJ1Y2tldCI6InRydWVfYml0cmF0ZSIsInZlcnNpb24iOm51bGx9LCJ0ZndfbGVnYWN5X3RpbWVsaW5lX3N1bnNldCI6eyJidWNrZXQiOnRydWUsInZlcnNpb24iOm51bGx9LCJ0ZndfdHdlZXRfZWRpdF9mcm9udGVuZCI6eyJidWNrZXQiOiJvbiIsInZlcnNpb24iOm51bGx9fQ%3D%3D&#x26;frame=false&#x26;hideCard=false&#x26;hideThread=false&#x26;id=1728213431201792492&#x26;lang=en&#x26;origin=https%3A%2F%2Fpipedream.com%2Fblog%2Fclassifying-bug-reports-with-chatgpt%2F&#x26;sessionId=d1d5a63c61277d4529493336dc9b58cbee19c41c&#x26;siteScreenName=pipedream&#x26;theme=light&#x26;widgetsVersion=2615f7e52b7e0%3A1702314776716&#x26;width=550px">
<blockquote class="twitter-tweet"><a href="https://twitter.com/i/status/1728213431201792492" rel="noopener noreferrer" target="_blank">https://twitter.com/i/status/1728213431201792492</a></blockquote>
</figure>
<p>So there are two problems to reconcile: 1) context switching kills developer productivity, but 2) bugs happen. How can we deal with this reality?</p>
<p>One way to tackle this is by enforcing proper prioritization. This is certainly easier said than done, but modern tooling and Pipedream can help.</p>
<p>In this post, we'll create an automated workflow that will:</p>
<ol>
<li>Trigger on new bug reports</li>
<li>Use ChatGPT to classify the report based on the user description</li>
<li>Update the priority accordingly</li>
<li>Send a Slack notification <em>if and only if</em> the bug is deemed as <strong>Urgent</strong>.</li>
</ol>
<p>That's a lot of unpack, so let's get started!</p>
<h3 id="configuring-airtable">Configuring Airtable</h3>
<p>For this example we'll use Airtable as our database. Airtable lets us create public forms, shareable with anyone on the Internet. It also provides its own automation framework, which we'll use to trigger the <a href="https://pipedream.com/new?h=tch_1AfMbY&#x26;via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Pipedream workflow</a>.</p>
<p>Start by creating a new base and a table inside it. I chose the fields <em>Title, Description, Name, Email</em> and <em>Priority</em>. <em>Priority</em> will be a <a href="https://support.airtable.com/docs/single-select-field" rel="noopener noreferrer" target="_blank">Single Select</a> field, holding a set of values that we'll pass to ChatGPT as the options for the classification.</p>
<p><img alt="" loading="lazy" decoding="async" width="3024" height="1868" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-15.17.38@2x-2.Be2tRW58_Z89MsU.webp"></p>
<p>Now, there are two possible approaches for adding new records.</p>
<p>First, you can add a custom <a href="https://support.airtable.com/docs/button-field" rel="noopener noreferrer" target="_blank">Button</a> to the table (see our post on how to <a href="https://pipedream.com/blog/sharp-js-compatibility/?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Slice and dice images with Sharp.js</a>). Here, Airtable sends an HTTP <code>GET</code> request to a Pipedream-generated URL, passing the record ID as query parameter. While it works beautifully, this means the workflow can be triggered only from <em>within</em> Airtable. In this post, we want to allow <em>anyone</em> to submit a report, e.g. a user affected by the bug.</p>
<p>You can also create a <a href="https://support.airtable.com/docs/building-and-sharing-forms-in-airtable" rel="noopener noreferrer" target="_blank">Form</a>. This can be shared publicly, sending an event when any user submits a bug.</p>
<p><a href="https://support.airtable.com/docs/building-and-sharing-forms-in-airtable" rel="noopener noreferrer" target="_blank">Create a form in Airtable</a> and adjust it to your use case. Don't forget to hide the <em>Priority</em> field, as it will be filled by the AI. You should end up with something like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="2000" height="1204" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-18.04.30@2x.HKqJzxxK_Z1ujQF8.webp"></p>
<p>Great, now we have a working form storing bug reports. Now, let's configure our trigger.</p>
<h3 id="triggering-the-workflow">Triggering the workflow</h3>
<p>We want form submissions to trigger our workflow. To do that, we need to configure a <em>webhook</em>.</p>
<p>In Pipedream, create a new workflow and select <strong>HTTP / Webhook > HTTP Requests with a Body</strong>. Data from the form sent by Airtable will be available in the body of the HTTP request in Pipedream. You don't need to change anything in the configuration — clicking <strong>Save and continue</strong> and you'll receive a URL like <a href="https://eoqb6ojri6uulck.m.pipedream.net/" rel="noopener noreferrer" target="_blank">https://eoabc123def456.m.pipedream.net</a>.</p>
<p>Head back to Airtable and create a new automation. Similar to Pipedream, Airtable also requires a trigger, which here will be <strong>When a form is submitted</strong>. Next, select the table and the recently-created form.</p>
<p>The next step is the only coding necessary in this tutorial. Click on <strong>Add advanced logic or action > Run script</strong>. On the panel on the left, click on <strong>Add input variable</strong> and name and select all fields submitted via the form. Don't forget to also add the <em>Airtable record ID</em>, once it will be needed later.</p>
<p>Add the following in the code editor, replacing the content of <code>WEBHOOK_URL</code> with the URL provided before:</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"> WEBHOOK_URL </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 'https://your-endpoint.m.pipedream.net'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">fetch</span><span style="color:#ECEBE8">(WEBHOOK_URL, {</span></span>
<span class="line"><span style="color:#ECEBE8">  method: </span><span style="color:#97CCAE">'POST'</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">  headers: {</span></span>
<span class="line"><span style="color:#97CCAE">    'Content-Type'</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">'application/json'</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">  },</span></span>
<span class="line"><span style="color:#ECEBE8">  body: </span><span style="color:#EDCC95">JSON.stringify</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">input.config</span><span style="color:#ECEBE8">()),</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>Great! You can click on <strong>Test action</strong>, and, if a record has been previously selected, you'll receive its content in Pipedream.</p>
<p><img alt="" loading="lazy" decoding="async" width="1864" height="1366" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-18.23.32@2x.DNh_RTXA_Z1LQtK4.webp"></p>
<p>Let's recap what we did so far.</p>
<ol>
<li>We created a Pipedream workflow whose trigger is a webhook which provides a unique URL;</li>
<li>We created a form in Airtable that inserts records into a table called <em>Bug Reports;</em></li>
<li>We added an <em>Airtable automation</em> triggered on form submissions;</li>
<li>This automation runs a script that sends a <code>POST</code> request along with the submitted data to the webhook URL generated in step 1.</li>
</ol>
<p><img alt="" loading="lazy" decoding="async" width="1548" height="1055" src="https://rafaelquintanilha.com/_astro/image-1.C5PNpbn4_20D17T.webp"></p>
<h3 id="classifying-the-priority-of-the-bug">Classifying the priority of the bug</h3>
<p>Now we're ready to classify the priority of the bug. Let's remember the goal: we want to classify the content of the bug report and notify the developers only when OpenAI detects urgency.</p>
<p>Back in Pipedream, create a new step in your workflow and select the <strong>OpenAI (ChatGPT)</strong> app. Conveniently, Pipedream has an action to <strong>Classify Items into Categories</strong>, which will work for simple classification use cases. Here, we'll use the <strong>Chat</strong> action instead; this gives us more control over the API request, which is key here.</p>
<p>If you don't have one, you'll need an <a href="https://platform.openai.com/api-keys" rel="noopener noreferrer" target="_blank">OpenAI API key</a>. In Pipedream, click the button to add a new <strong>OpenAI (ChatGPT)</strong> account and add the API key there.</p>
<p>Next, select the <em>Model</em> you want to use for classifications. If bug reports are not <em>so</em> frequent in your application, then we recommend choosing <code>gpt-4-turbo-preview</code>, the most-accurate model for classifications as of this post.</p>
<p>In the <em>User Message</em> field, pick the <code>description</code> sent in the body of the request.</p>
<p>Finally, we'll set the <em>System Instructions</em>. System instructions guide how the AI answers prompts. Add the following:</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>Your tasks is to receive a bug report from a user and classify into ONE of the following categories:</span></span>
<span class="line"><span></span></span>
<span class="line"><span>Urgent</span></span>
<span class="line"><span>High</span></span>
<span class="line"><span>Medium</span></span>
<span class="line"><span>Low</span></span>
<span class="line"><span></span></span>
<span class="line"><span>You should ONLY output the chosen category, and nothing else.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>Notice that an "Urgent" report is anything that prevents users from:</span></span>
<span class="line"><span>- Accessing their account;</span></span>
<span class="line"><span>- Paying, subscribing, or generally taking revenue-impacting actions.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>This is the description of the bug reported by the user:</span></span></code></pre></figure>
<p>Notice that the categories provided match the priorities expected in Airtable. The instruction explicitly asks the model to return the category and <em>only</em> the category. We also give examples of urgent requests in order to nudge the AI to our specific use-case. Feel free to adjust the instructions with examples pertinent to your application.</p>
<p><em>Note: the pre-made Classify Items into Categories will instruct the LLM to output a JSON, which is very convenient when parsing the output in a code context, but not necessary here.</em></p>
<p>Because of the stochastic character of any AI, we cannot guarantee it will always return one of the 4 categories, though more powerful models are significantly better at adhering to the prompt. There's an extra trick we can do, too. The <a href="https://platform.openai.com/tokenizer" rel="noopener noreferrer" target="_blank">Tokenizer</a> app allows us to simulate how many tokens a given text is expected to yield. It happens that <em>Urgent</em> takes 3 tokens, while all other categories are successfully encoded with a single one. Hence, we can <em>limit</em> the maximum number of tokens allowed in the completion.</p>
<p>Finally, adjust <strong>Temperature</strong> to 0 (we want as little randomness as possible in the outcome) and <strong>N</strong> to 1, and the step is complete.</p>
<p><img alt="" loading="lazy" decoding="async" width="1264" height="1636" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-19.20.28@2x.BzPjv24S_1cW1yD.webp"></p>
<p>Click on <strong>Test</strong> to run the step, and if all is well, you should see the category selected by the LLM.</p>
<p><img alt="" loading="lazy" decoding="async" width="1776" height="1412" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-19.24.35@2x.DLF9S18j_ZXONXA.webp"></p>
<h3 id="updating-the-airtable-record">Updating the Airtable record</h3>
<p>Now that the classifier works, let's update the record in Airtable.</p>
<p>Add a new step to the workflow, search for "<em>airtable</em>", and select the <strong>Airtable (OAuth)</strong> app. Click the <strong>Update Record</strong> action. The configuration is straightforward – connect your account and select your <em>Base</em> and <em>Table</em>.</p>
<p>For <em>Record ID</em>, we will need the <code>id</code> from the trigger step. The field we want to update is <em>Priority,</em> and the content is the generated message from the previous step.</p>
<p>The <em>update_record</em> step should look like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="1868" height="1392" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-25-at-09.00.05@2x.DawIrEZa_1K6d6J.webp"></p>
<h3 id="conditionally-send-slack-message">Conditionally send Slack message</h3>
<p>Finally, we'll send a message to Slack. Recall that we want to send notifications <em>only if</em> on <em>Urgent</em> issues. Luckily, Pipedream makes this process a breeze by providing a <strong>Continue based on condition</strong> step: the workflow will only continue if the configured condition is met, else it ends.</p>
<p>You'll need to configure three fields: <em>Initial value, Condition,</em> and <em>Second value.</em></p>
<p>For <em>Initial value</em>, select the same output used when updating Airtable – this will be the category. The <em>Second value</em> is the target priority, i.e., <em>Urgent</em>. Finally, select <em>TEXT_EQUALS</em> as the condition. In order to prevent unnecessary misclassifications, make sure <em>Case sensitive</em> is False as well.</p>
<p><img alt="" loading="lazy" decoding="async" width="1864" height="1140" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-25-at-09.13.21@2x.2xVJJon4_1CXYCh.webp"></p>
<p>Now the workflow will only continue if the AI classifies the report exactly as <em>Urgent</em> (case insensitive). Let's wrap this tutorial up by creating the final step: <strong>Slack > Send Message to a Public Channel</strong>. Connect your account, select the <em>Channel ID</em> from the list, and use the data sent from Airtable to craft a message to your beloved developers.</p>
<p><img alt="" loading="lazy" decoding="async" width="1396" height="698" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-25-at-09.17.50@2x.DDhnoAFz_9wdME.webp"></p>
<p>And that's it! Deploy the Pipedream workflow and don't forget to turn on the Airtable automation. Open the publicly-shareable Airtable form and submit a desperate request in order to receive the notification.</p>
<h3 id="next-steps">Next steps</h3>
<p>A great enhancement to this workflow is to send an automatic email to the user, letting them know that the report has been received.</p>
<p>Pipedream has a convenient <a href="https://pipedream.com/apps/gmail?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Gmail integration</a> that can be used for this purpose. For a more custom experience, you can leverage the <a href="https://pipedream.com/apps/postmark/actions/send-email-with-template?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Postmark</a> integration (my go-to platform for sending templated emails).</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Scraping market data with Python]]></title>
<description><![CDATA[Web scraping with the BeautifulSoup Python library.]]></description>
<link>https://rafaelquintanilha.com/scraping-market-data-with-python/</link>
<guid isPermaLink="false">670e78a1d8bba20001d2b645</guid>
<category><![CDATA[Web Scraping]]></category><category><![CDATA[Python]]></category><category><![CDATA[Pipedream]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 19 Mar 2024 14:17:00 GMT</pubDate>

<content:encoded><![CDATA[<p>For many investors, <em>timing</em> is extremely important. We've seen the market be irrational (despite some arguing that it is <a href="https://www.investopedia.com/terms/e/efficientmarkethypothesis.asp" rel="noopener noreferrer" target="_blank">efficient</a>) countless times, which often translates into great investment opportunities.</p>
<p>The combination of <em>quantitative analysis</em> and <em>software engineering</em> can be extremely useful for exploiting such moments. Having access to real-time data, executing some computation, and plugging it into a decision-making algorithm is a workflow that you can start benefitting today. And the good news – it's never been easier to start.</p>
<p>There is a problem, though. While there are plenty of data sources available, they are usually restricted to specific markets, rate-limited, throttled, or flat out expensive. Outside of the American market and crypto assets, chances are you won't have access to good, reliable APIs.</p>
<p>Thankfully, Pipedream allows you to run JavaScript or Python code as part of your workflows. This unlocks every website as a data source for your project — that's what we'll explore today.</p>
<p>We'll build a workflow that:</p>
<ol>
<li>Runs at fixed intervals</li>
<li>Launches a Python code to scrape data from a website containing market data of unusual assets.</li>
<li>Sends the <a href="https://en.wikipedia.org/wiki/Open-high-low-close_chart" rel="noopener noreferrer" target="_blank">OHLC</a> values to Slack</li>
</ol>
<p>You can copy the <a href="https://pipedream.com/new?h=tch_ovfybN&#x26;via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">final workflow</a> at any time and use it in your own Pipedream account.</p>
<p>With that all said, let's get started!</p>
<h3 id="create-the-workflow">Create the workflow</h3>
<p>When you create a workflow, you'll be presented with a list of settings. Depending on what you're scraping, it's important to pay attention to the workflow's <strong>Timeout</strong>.</p>
<p>By default, Pipedream will set a 30-second timeout on workflow executions, which should be enough for our example. You may need to raise it or <a href="https://pipedream.com/docs/workflows/settings?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">take advantage of other settings</a> for more complex workflows.</p>
<p><img alt="" loading="lazy" decoding="async" width="1306" height="1396" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-14-at-08.37.02@2x.BNFlZSDv_Z1FtVSJ.webp"></p>
<h3 id="add-a-custom-interval-trigger">Add a Custom Interval trigger</h3>
<p>We need a <a href="https://pipedream.com/docs/workflows/triggers?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">trigger</a> to launch our web scraper. As we want to constantly monitor the security we're interested on, a <strong>Custom Interval</strong> is the best choice. Select it from the list of triggers.</p>
<p>You'll be asked to set a <em>Schedule</em>, i.e., when the action will be triggered. Typically, a fixed interval like "once every hour" is enough. But for this example I'll be scraping IBOV data, the Brazilian benchmark index. The Brazilian market opens from Monday to Friday, during working hours. Fortunately, Pipedream supports custom <a href="https://en.wikipedia.org/wiki/Cron" rel="noopener noreferrer" target="_blank">cron expressions</a>, which we can leverage in order to avoid triggering the action unnecessarily.</p>
<p>I never remember the cron syntax, so that's a great use-case for your LLM of choice to help you (I'm using <a href="https://www.raycast.com/" rel="noopener noreferrer" target="_blank">Raycast</a>'s built-in <strong>Ask AI</strong> feature to get quick answers like that).</p>
<p><img alt="" loading="lazy" decoding="async" width="1204" height="668" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-14-at-08.48.07@2x.COKxE9MX_1LHs1b.webp"></p>
<p>Great! We can then set that schedule and get a human-friendly description that confirms it's what we wanted:</p>
<p><img alt="" loading="lazy" decoding="async" width="1860" height="884" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-14-at-08.49.45@2x.BZEKK6gP_Z1jTw7m.webp"></p>
<h3 id="configure-the-scraper">Configure the scraper</h3>
<p>Now that the trigger is configured, we're ready to build the scraper. Pipedream will prompt you to connect a <a href="https://pipedream.com/docs/workflows/steps?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">step</a>, i.e., an action to be performed after the workflow triggers.</p>
<p>Select <strong>Python > Run Python code</strong> to open the editor.</p>
<p>You'll be greeted with a functional editor where you can start running Python code or add third-party dependencies without the fuss of dealing with package managers like <code>pip</code> or <code>poetry</code>. Pretty neat.</p>
<p>We'll scrape the Polish website <a href="https://stooq.com/q/g/?s=%5Ebvp" rel="noopener noreferrer" target="_blank">Stooq.com</a>, passing the Brazilian index ticker as the query parameter (try adjusting it to use your ticker of choice).</p>
<p>Replace the content of the editor with the following:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> requests</span></span>
<span class="line"><span style="color:#A1C1E4">from</span><span style="color:#ECEBE8"> bs4 </span><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> BeautifulSoup</span></span>
<span class="line"><span style="color:#A1C1E4">from</span><span style="color:#ECEBE8"> datetime </span><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> datetime</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#A1C1E4">  try</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # The base URL</span></span>
<span class="line"><span style="color:#ECEBE8">    url </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "https://stooq.com/q/g/?s=^bvp"</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Sending a GET request</span></span>
<span class="line"><span style="color:#ECEBE8">    response </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> requests.</span><span style="color:#EDCC95">get(url)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # If the GET request is successful, the status code will be 200</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> response.status_code </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 200</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Get the content of the response</span></span>
<span class="line"><span style="color:#ECEBE8">      page_content </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> response.content</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Create a BeautifulSoup object and specify the parser</span></span>
<span class="line"><span style="color:#ECEBE8">      soup </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> BeautifulSoup(page_content, </span><span style="color:#97CCAE">"html.parser"</span><span style="color:#EDCC95">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Find the tables</span></span>
<span class="line"><span style="color:#ECEBE8">      tables </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> soup.</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"table"</span><span style="color:#EDCC95">, {</span><span style="color:#97CCAE">"id"</span><span style="color:#EDCC95">: </span><span style="color:#97CCAE">"t1"</span><span style="color:#EDCC95">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Initialize a dictionary to hold the data</span></span>
<span class="line"><span style="color:#ECEBE8">      data </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Iterate through the rows in the first table</span></span>
<span class="line"><span style="color:#A1C1E4">      for</span><span style="color:#ECEBE8"> row </span><span style="color:#A1C1E4">in</span><span style="color:#ECEBE8"> tables[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"tr"</span><span style="color:#EDCC95">)</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">          cells </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> row.</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"td"</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#A1C1E4">          if</span><span style="color:#ECEBE8"> cells[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].text </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> "Otwarcie"</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"open"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> float</span><span style="color:#EDCC95">(cells[</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">].text.replace(</span><span style="color:#97CCAE">","</span><span style="color:#EDCC95">, </span><span style="color:#97CCAE">""</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#A1C1E4">          elif</span><span style="color:#ECEBE8"> cells[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].text </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> "Kurs"</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"close"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> float</span><span style="color:#EDCC95">(cells[</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">].text.replace(</span><span style="color:#97CCAE">","</span><span style="color:#EDCC95">, </span><span style="color:#97CCAE">""</span><span style="color:#EDCC95">))</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Iterate through the rows in the second table</span></span>
<span class="line"><span style="color:#A1C1E4">      for</span><span style="color:#ECEBE8"> row </span><span style="color:#A1C1E4">in</span><span style="color:#ECEBE8"> tables[</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">].</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"tr"</span><span style="color:#EDCC95">)</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">          cells </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> row.</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"td"</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#A1C1E4">          if</span><span style="color:#ECEBE8"> cells[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].text </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> "Max/min"</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">              high, low </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> cells[</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">].text.</span><span style="color:#EDCC95">split(</span><span style="color:#97CCAE">" / "</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"high"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> float</span><span style="color:#EDCC95">(high.replace(</span><span style="color:#97CCAE">","</span><span style="color:#EDCC95">, </span><span style="color:#97CCAE">""</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"low"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> float</span><span style="color:#EDCC95">(low.replace(</span><span style="color:#97CCAE">","</span><span style="color:#EDCC95">, </span><span style="color:#97CCAE">""</span><span style="color:#EDCC95">))</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">      dt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">now()</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">"%Y-%m-%d"</span><span style="color:#EDCC95">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">      data </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [</span></span>
<span class="line"><span style="color:#ECEBE8">          (</span></span>
<span class="line"><span style="color:#ECEBE8">              dt,</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"open"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"high"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"low"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"close"</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">      return</span><span style="color:#ECEBE8"> data</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#EDCC95">      print(</span><span style="color:#97CCAE">"Error fetching data!"</span><span style="color:#EDCC95">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Raise a network error so we can retry the task again</span></span>
<span class="line"><span style="color:#A1C1E4">      raise</span><span style="color:#ECEBE8"> requests.exceptions.RequestException</span></span>
<span class="line"><span style="color:#A1C1E4">  except</span><span style="color:#A1C1E4"> Exception</span><span style="color:#A1C1E4"> as</span><span style="color:#ECEBE8"> e:</span></span>
<span class="line"><span style="color:#EDCC95">    print(</span><span style="color:#A1C1E4">f</span><span style="color:#97CCAE">"Error scraping data: </span><span style="color:#97CCAE">{</span><span style="color:#EDCC95">repr(e)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">"</span><span style="color:#EDCC95">)</span></span></code></pre></figure>
<p>The code should be pretty straightforward (though admittedly easier if you happen to know Polish), and the only thing you need to change in order to scrape other assets is the URL:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#ECEBE8">url </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "https://stooq.com/q/g/?s=^bvp"</span></span></code></pre></figure>
<p>Go ahead and test the code. If successful, you'll see something like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="1874" height="1384" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-16-at-10.38.36@2x.BU7kbxbd_1frGPK.webp"></p>
<p><em>Note: If you run into timeout issues, consider increasing the Timeout value in Settings (shortcut: press M then S).</em></p>
<p>Great! The <em>Exports</em> tab exposes all data that will be available in future steps. Let's take advantage of it next.</p>
<h3 id="connect-to-slack">Connect to Slack</h3>
<p>The last step of this proof-of-concept is to send the results of the scraper to Slack.</p>
<p>Click on the plus button to add a new step and select <strong>Slack > Send Message to a Public Channel</strong>.</p>
<p>The wizard is also straightforward. Click on <strong>Slack Account</strong> and allow Pipedream to connect to your workspace. Next select the <strong>Channel ID</strong> you want the messages to be sent. Finally, format the <strong>Text</strong> as you like, using the floating dropdown menu to help you integrate variables returned from prior steps.</p>
<p><img alt="" loading="lazy" decoding="async" width="1880" height="1302" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-16-at-10.58.39@2x.C_EIGJ6-_2tIewx.webp"></p>
<p>Notice how I plugged data from the previous two steps:</p>
<ol>
<li>A nicely-formatted timestamp pulled from the trigger step</li>
<li>The actual return of the Python function pulled from the scraping step.</li>
</ol>
<p>Now, we are able to test our integration! Click on <strong>Test</strong> and within a moment you shall receive a message in the selected channel:</p>
<p><img alt="" loading="lazy" decoding="async" width="1416" height="914" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-16-at-10.57.53@2x.C73l0YZ9_20zjgI.webp"></p>
<p>That's it! You successfully hooked an end-to-end automation capable to power your quantitative analysis!</p>
<h3 id="next-steps">Next steps</h3>
<p>Hopefully this article serves as a base for further exploration. Here are some follow-up suggestions:</p>
<ul>
<li>Notify how much the asset price has <em>changed.</em> It's usually useful to know the variation in percentage points. Sharpen your Python (and Polish) skills to scrape this information from <a href="https://pipedream.com/blog/scraping-market-data-with-python/stooq.com" rel="noopener noreferrer" target="_blank">Stooq.com</a>, or store previously scraped data elsewhere (can be as simple as a <a href="https://pipedream.com/apps/pipedream/integrations/google-sheets" rel="noopener noreferrer" target="_blank">Google Sheet</a>).</li>
<li>Go to the next level by storing the data in a <strong>database</strong> (e.g. <a href="https://pipedream.com/apps/pipedream/integrations/supabase?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Supabase</a>). This will unlock a world of automated possibilities, including running your own data analysis, allowing you to generate real-time notifications based on historical data.</li>
</ul>]]></content:encoded>
</item>
<item>
<title><![CDATA[React Best Practices: How to Write Better React Apps]]></title>
<description><![CDATA[A summary of modern React best practices, with tips that can be applied to real-world applications.]]></description>
<link>https://rafaelquintanilha.com/react-best-practices-how-to-write-better-react-apps/</link>
<guid isPermaLink="false">6383c14a14168e003dd8f7a8</guid>
<category><![CDATA[React]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Best Practices]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 07 Sep 2022 19:58:00 GMT</pubDate>

<content:encoded><![CDATA[<h2 id="what-is-react-and-why-use-it"><strong>What is React and why use it?</strong></h2>
<p>While web development isn’t <em>new</em>, some aspects of it are. In particular, frontend engineering is somewhat of a new term. Back in the day, you would see “web designers” and “webmasters”, but rarely <em>frontend developers</em>.</p>
<p>There’s a good reason for it - there was no need! Websites were simple, mostly static, and the bigger complexity was around designs, not functionality.</p>
<p>Needless to say, we are way past that now. Websites evolved into web apps, browsers became more powerful and the era of desktop applications is over, disrupted by the eruption of mobile devices. While it took some time for the consensus to establish in web apps and not in mobile apps, it seems to be fairly understandable now that web apps provide better availability, portability, and ease of use than native applications. And as mobile devices become more powerful, and optimizing for the web becomes a sexy engineering problem, the end result is an outburst of well-engineered, optimized, and resourceful applications right here, on the web.</p>
<p>But as we have learned from the history books, there’s no power vacuum. The web was set to reign, but who shall be the king? Enter <a href="https://reactjs.org/" rel="noopener noreferrer" target="_blank"><strong>React – a JavaScript library for building user interfaces</strong></a>.</p>
<p>This library maintained by the fine folks at Facebook took the market share and ended once and for all the <a href="https://medium.com/@ericclemmons/javascript-fatigue-48d4011b6fc4" rel="noopener noreferrer" target="_blank"><strong>JavaScript fatigue</strong></a>: that feeling everyone around in 2015 had. Every day a new frontend framework is competing for the top spot. Then eventually React appeared, people liked it, and the problem was settled.</p>
<p>This (not so) short introductory story is the answer to <em>what</em> React is and <em>why</em> you need it. Because React is a JavaScript library for the ever-growing frontend environment, you need it because it is popular, way maintained, liked, and used throughout the globe, in FAANGs and local shops. You can’t go wrong choosing React.</p>
<h2 id="what-makes-react-hard-to-learn-for-beginners"><strong>What makes React hard to learn for beginners?</strong></h2>
<p>React doesn’t have a particularly hard abstraction or technical conception. On the contrary, its single source of truth mantra has been a breeze for seasoned web developers.</p>
<p>However, this change in paradigm (for the better) can hit harder if you are used to using vanilla JavaScript or the last king, jQuery. Communication is rarely event-based, as opposed to what JavaScript typically enforces by design or with its backend counterpart, NodeJS.</p>
<p>Componentization is a concept that is easy to grasp but demands time to master. <a href="https://buttercms.com/blog/learn-react-hooks-by-writing-your-first-hook/" rel="noopener noreferrer" target="_blank"><strong>Hooks brought the functional flavor</strong></a> that seems to be the current trend, despite component lifecycles that may be more familiar to Java developers.</p>
<p>In short, what makes React hard for beginners is that <em>it is React</em>, not an adaption, a fork of a known framework, or an abuse of the JavaScript language. It’s a new paradigm, focused on User Interfaces, simplicity, and opinionated state management.</p>
<h2 id="react-best-practices"><strong>React best practices</strong></h2>
<p>Every language and framework has the so-called “best practices”, i.e., a community-accepted set of practices when using the tool. The following isn’t an exhaustive list of them, but an attempt to list the ones that typically concern the average developer.</p>
<h2 id="security"><strong>Security</strong></h2>
<p>Every software engineer that had code shipped to production had to go over this drill. Is the code secure? Are there flaws? Are they exploitable? Given the architecture of the web, this matter is even more flagrant.</p>
<p>However, I’d argue that React doesn’t pose any special security threat that any web application doesn’t have. Be aware of XSS attacks; store authentication tokens safely; sanitize HTML, and so forth.</p>
<h3 id="sanitize-html">Sanitize HTML</h3>
<p>By having its own <em>templating engine</em> that allows dynamic variables to be inserted into HTML, React exposes a security issue that every web developer should be aware of: injecting malicious code in HTML.</p>
<p>As the classical example goes, we don’t want users to pass any kind of script that can be rendered on an HTML page. Because of that, there’s a process called <em>sanitization</em>, where we allow only specific tags to be rendered on a page.</p>
<p>Imagine you have a CMS like ButterCMS and render the content generated by the content creator without any kind of filter. Well, <a href="https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml" rel="noopener noreferrer" target="_blank"><strong>React exposes the property</strong> <em><strong>dangerouslySetInnerHTML</strong></em></a> that serves this very purpose: get a raw HTML for an API, and render it in an element.</p>
<p>But the API isn’t named like that for nothing. Suppose this content contains a valid script that collects user information and posts it back to the attacker database: you’re essentially adding a trojan horse to your website!</p>
<p>In order to prevent such cases, you can use libraries like <a href="https://www.npmjs.com/package/sanitize-html" rel="noopener noreferrer" target="_blank"><strong>sanitize-html</strong></a> to allow only specific tags to be rendered. For example, if your goal is to render a blog post, you can allow only the traditional &#x3C;div>, &#x3C;p>, &#x3C;b>, &#x3C;i>, &#x3C;img>, etc tags, and block suspicious ones like &#x3C;script>.</p>
<h3 id="secure-apis">Secure APIs</h3>
<p>Although this isn’t a problem specific to React, this is a common problem faced by any front-end developer. We typically need to connect to our brothers in blood, the backend engineers, who have carefully crafted an interface for us to communicate.</p>
<p>However, this API often is <em>secured</em>, meaning that you need proper credentials to access it. The authentication process occurs mostly in the backend but is the front-end's job to keep the access token safe and sound.</p>
<p>There is a lot of <a href="https://stackoverflow.com/questions/3220660/local-storage-vs-cookies/3220802#3220802" rel="noopener noreferrer" target="_blank"><strong>debate about whether you should store it in the Local Storage or in cookies</strong></a>, and this matter warrants a post in itself. But while this is a personal choice and both can be used under the right circumstances, I find it crucial that you, as a developer, understand what the tradeoffs of each solution are.</p>
<p>I have used both, and suggest using cookies if you can. They provide more security layers and control, and if used with a compatible library in the backend, like <a href="https://flask-jwt-extended.readthedocs.io/en/stable/" rel="noopener noreferrer" target="_blank"><strong>Python’s Flask</strong></a>, the implementation is a breeze.</p>
<p>In any case, before judging your friend who stores a JWT in the Local Storage, try to understand where the flaw is. Saying “if your app JavaScript is compromised you are screwed” isn’t really an argument; once you’re compromised, well, you are screwed anyway. Understand your app’s needs first, and the rest should come naturally.</p>
<h3 id="install-linters">Install linters</h3>
<p>I mentioned before how good practices are nothing more than a community set of accepted practices, but as you have probably thought, this is subjective and hard to enforce.</p>
<p>Linters come to the rescue. There are awesome linters that will encapsulate a set of JavaScript or React-oriented best practices and complain whenever you drift off. This is great for ending an argument – people will often disagree on how to best handle a particular scenario. A linter, or a programmatic way to warn about an unexpected code usage, will act as the mighty judge, settling the matter once and for all (you need to agree on the linter first though).</p>
<p>Linters are also great for big teams, where many people touch a single file repeatedly. If everybody uses a linter, you cut off most of the inconsistencies, save development time and make reviewing code a breeze.</p>
<p>When coding, you shouldn’t focus too much on aesthetics. Sure, they are nice. But the less you need to worry about it, the better. Let developers focus on what they like, namely, code.</p>
<h2 id="testing"><strong>Testing</strong></h2>
<p>Think about that: you are already a developer, why would you do something manually? Programmers of course thought about that, and resisting the temptation of overengineering, also agreed on writing code for testing their own code. Isn’t it beautiful?</p>
<h3 id="leverage-react-debugging-utilities">Leverage React debugging utilities</h3>
<p>There are a set of React practices that are often neglected. <a href="https://reactjs.org/docs/error-boundaries.html" rel="noopener noreferrer" target="_blank"><strong>Error Boundaries</strong></a> are one of them.</p>
<p>When developing React applications, an interface is typically composed of several components in a tree that can escalate quickly. For that reason, if there’s an error in the application, it’s common to be lost in the hierarchy of components.</p>
<p>Error Boundaries can help you by raising the red flag on the exact node that experienced the flaw. More modern frameworks like <a href="https://buttercms.com/blog/what-is-react-remix/" rel="noopener noreferrer" target="_blank"><strong>React Remix</strong></a> leverage this concept to enhance user and developer experience. Give them a shot and caught the issues in the act.</p>
<p>Another way to add better-debugging tooling to your web app is to convert to TypeScript. Fortunately, TypeScript is widely adopted and integrated into the React ecosystem now. With TypeScript, you get top-notch auto-complete, caught errors on the act, and reduce runtime errors by leveraging features like type-checking. Pairing the typed JavaScript version with a good text editor like VSCode is a game changer for serious web development.</p>
<h3 id="invest-in-test-driven-development">Invest in test-driven development</h3>
<p>Beware when getting into the world of testing – you risk becoming addicted to it. In fact, some people like it so much that they develop backward! First, they create the test, <em>then</em> they write the code.</p>
<p>While this coding style isn’t for everyone, this is particularly interesting when developing a functional application or library. Suppose that you are working on a calculator. There are some well-defined cases that you want to handle, and it’s just fair that you work from there: you start by checking that addition works, then you move to multiplication, and handle edge cases.</p>
<p>For more complex applications, <a href="https://rafaelquintanilha.com/writing-tests-as-user-stories-in-react"><strong>I suggest treating your tests as user stories</strong></a>. Suppose you are working on a feature that needs to do X, Y, and Z. They are valid, strict metrics that you will be testing against. Once you established all the roadblocks, traps, and edge cases, it becomes way easier to just sit down and do what you already know.</p>
<p>Don’t know if this is for you? Well, <em>test</em> first, and then let me know (pun intended).</p>
<h3 id="install-react-testing-library">Install React Testing Library</h3>
<p>Everything I mentioned before about React taking over the power void can be applied to <a href="https://testing-library.com/docs/react-testing-library/intro/" rel="noopener noreferrer" target="_blank"><strong>React Testing Library</strong></a> or RTL. Designed for React and later adapted to other frameworks, the Testing Library took over hacky approaches like Enzyme, where developers would spend more time fixing tests than actually testing their applications.</p>
<p>React Testing Library has a simple API, a big community, and good principles, and should be your go-to library when unit testing your code.</p>
<h3 id="configure-user-events">Configure user events</h3>
<p>One of the main advantages of React Testing Library is abstracting away user events in single lines of code. For example: what if a user presses a specific key? Or if they move their mouse out of the window? Or focus on an input?</p>
<p>All those are events that can happen in a real app and oftentimes have a direct impact on what should happen next. For example, you can assert that a bouncing modal pops up if the user tries to leave the screen (it’s annoying but effective… what are you gonna do?). <a href="https://github.com/testing-library/user-event" rel="noopener noreferrer" target="_blank"><strong>A clear and simple API like the user events API</strong></a> from RTL is all you need in order to test like <em>user stories.</em></p>
<h2 id="components"><strong>Components</strong></h2>
<p>The heart of React, components are the best friend of the frontend developer. They encapsulate logic, UI blocks, and functionality. But how should you approach designing them?</p>
<h3 id="keep-component-creation-to-a-minimum">Keep component creation to a minimum</h3>
<p>Component creation should be understood as building a LEGO. You design the parts and glue them together. You start small, where each part is focused on its own job. It’s the UI equivalent to functional programming, where each function has a single purpose. In fact, components are functions! So the comparison holds even stronger.</p>
<p>When designing an interface, it’s often useful to draw it on a piece of paper. Using the same principle as in the test-driven approach, you have a <em>component-driven approach</em>. Start by designing your interface and what constitutes each part of it – maybe you have a side panel, a list of results in which every result has a call-to-action button… design them as an architect would design a living room, and the rest will flow naturally.</p>
<h3 id="introduce-state">Introduce state</h3>
<p>Using React for building user interfaces is nice, but if they are <em>static</em> there is nothing really exciting about them. Or at least nothing our predecessors, web designers, wouldn’t do with tools like Photoshop.</p>
<p>What transforms React into a really powerful library is its power to, well, <em>react</em> to users' interactions. That’s the heart and soul of frontend engineering – develop a nice UI, sure, but what good is a sleek-looking UI that isn't easy to use?</p>
<p>What solution does React brings to the table? The app or component <em>state</em> will dictate how your UI should behave. For example, it can display an error message for invalid input, disable a button for an incomplete form, share context and variables across many parts of the app, count how many times you have performed an action, tell whether you should render a modal or not… there are endless possibilities that are exactly the reason why frontend development is so exciting: the user input is a new dimension in your variable matrix.</p>
<p>A <em>stateful</em> component is a component that renders differently based on its state. An input component that renders an error message or is disabled is a good example. On the other hand, a <em>stateless</em> component is a plain static UI, but is still useful. Suppose you want to render your website footer. Instead of duplicating code left and right, you can develop it once and call it anywhere, pretty much like a function, generating one source of truth, best for maintainability and consistency.</p>
<h3 id="use-props-to-pass-data-to-a-children-component">Use Props to pass data to a children component</h3>
<p>Sometimes your component is not stateful but still depends on outside variables. Think about a template, for example. It has a recipe, a specific form, but with “gaps” that are dynamically filled (variables).</p>
<p>Properties, or props, are precisely a way to customize a component that should always behave the same but can accept different data. Think about your driving license: everyone has the same, they look the same, and their layout is the same, but the name, number, expiration date, and whatnot are different. Those are the props filling up the gaps.</p>
<p>In React, props are always passed from father to child. We saw already that componentization transforms your app into a huge tree of code, and the communication needs to be direct, and top-down (there are some exceptions like contexts, though).</p>
<p>While this can be annoying occasionally, it really gives predictability to your code. If a variable is such, it <em>must be</em> because it is like so in the parent. And hence you can trace back that value to its origin, helping to debug a lot.</p>
<p>I remember my old days working on CakePHP where I would spend hours trying to decipher where that variable had come from. It was hard because communication wasn’t direct, top-down. It was buried somehow in contexts and controllers. Call it pragmatic, but it will make your life easier.</p>
<h3 id="use-different-component-patterns">Use different component patterns</h3>
<p>As always, there is never one single way to tackle a problem. Before hooks took off on the 16th version of React, there was a famous React pattern called <a href="https://reactjs.org/docs/higher-order-components.html" rel="noopener noreferrer" target="_blank"><strong>HOC, or Higher-Order Components</strong></a>.</p>
<p>In this pattern, you encapsulate a particular component with another one, like a sandwich. But this gives it superpowers, or in less exciting terms, new props for it to use. For example, you could wrap your component in a HOC that would monitor the screen size in order to pass to your child component the width and height as props.</p>
<p>In some sense, Higher-Order Components worked as <em>decorators</em>, injecting logic into a given component. As mentioned, though, React Hooks was a great breakthrough and replaced this behavior with a nicer, more reusable API. Hooks work similarly to plugins, where you call them in your component to get a specific behavior.</p>
<p>Also before hooks, React components would be class-based, bringing more of the objected-oriented world to the frontend community. They would provide lifecycle hooks instead, where you could act when a specific event occurred, like the component mounting, or a specific prop changing.</p>
<p>The React team replaced this paradigm with a new one, using hooks, called <a href="https://reactjs.org/docs/hooks-effect.html" rel="noopener noreferrer" target="_blank"><strong>useEffect</strong></a>. Now, you can monitor everything that makes a component re-render, the act of being updated because something in the tree changed. It’s up to you to monitor and act accordingly to whatever state or prop change happened.</p>
<p>While more flexible, arguably some developers miss the straightness of <em>componentDidMount</em> or <em>componentWillUpdate</em>. If that’s who you are, you should check class-based components.</p>
<h2 id="styling"><strong>Styling</strong></h2>
<p>A hot topic with a myriad of alternatives, styling a web app is never a consensus. Constructed on top of a controversial piece of technology, we shall explore how you can approach styling in your React applications.</p>
<h3 id="try-inline-css">Try inline CSS</h3>
<p>The simples solution, by and large, is to embrace tradition and use an inline style like everyone was doing with HTML in the 90s. There’s nothing really wrong with it – with the exception that is hard to reuse.</p>
<p>React will handle style pretty much like a JSON object, and this will be the source behind the multiple CSS-in-JS frameworks that emerged. In any case, inline CSS is good, simple, and efficient. They will lack performance improvements (like being able to cache a separate CSS file), and maybe software engineering best practices. But they will work just fine.</p>
<h3 id="import-styled-components-as-an-object">Import styled-components as an object</h3>
<p>Using JavaScript to style your components has the unbeatable advantage of being able to control the style dynamically. Suppose you are building a component that changes its color based on a given input. JavaScript and React will make your life a breeze because you can just conditionally use the input to render the desired color.</p>
<p>Of course, people wouldn’t stop there: if you can use JavaScript in such cases, you can also use them to control other aspects of your styling. For example, font size, brand colors, default line height, etc. Using technology like <a href="https://www.styled-components.com/" rel="noopener noreferrer" target="_blank"><strong>styled-components</strong></a> allows you to write CSS-in-JS while creating a hierarchy of values that programmers so often like.</p>
<p>And as I mentioned before, the <em>style</em> property is nothing more than a JSON object. So you can leverage JavaScript constants to build your style schema, inherit from it, and write your component’s style as you would write code. Neat.</p>
<h3 id="abstract-style-components">Abstract style components</h3>
<p>Styles are good and a simple solution, but as a project grows it won’t scale. Think about how many primary buttons you have in your application and you will know what I mean.</p>
<p>As I mentioned in the previous section, styled-components help you to create a basic structure and build from there, with basic properties being set as constants. You can then combine them and create more complex structures, like buttons, paragraphs, headers, heroes, inputs, and so on.</p>
<p>In fact, React creates the perfect ecosystem for you to design your own component library. Forget about Bootstrap, Semantic UI, and their peers – with React, you please any designer you work with consistency and accuracy.</p>
<h3 id="use-css-and-sass-stylesheets">Use CSS and SASS stylesheets</h3>
<p>Everything I said thus far is great but some freaks insist on using plain old CSS files. Why? Well, I can tell (I’m one of those freaks). CSS is a technique on its own, and I prefer the separation of concerns of having a file dedicated to styling. It’s easier to review, change and adapt. Also, it can be cached when performance is at stake.</p>
<p>With the surge of frameworks that allow CSS Modules, the typical problem of classes clashing with each other is over. Plus, it generates a fingerprint that helps developers debug by targeting the precise component with that particular style.</p>
<p>And if you want the option to add parameters to your classes, like a brand color or semantic font size, SASS can help you. Pair both and you will get the best of two worlds, while still looking cool by using a time-tested fool-proof technology like cascading stylesheets.</p>
<h2 id="project-structure"><strong>Project structure</strong></h2>
<p>React is definitely not an opinionated library. As Uncle Ben would recall, “with great powers come great responsibilities”. I would also say, in a poetic tone, that you are free to do whatever you want, but a prisoner of the consequences.</p>
<p>With that in mind, let us take a look at how you can structure your React project.</p>
<h3 id="split-components-into-separate-tsx-files">Split components into separate .tsx files</h3>
<p>We already mentioned the power of componentization and treating components as you would treat functions in a functional paradigm. But in React this is even better if you enforce that only one component should exist per file.</p>
<p>First, files become smaller, and easier to tweak and review. Secondly, the <em>separation of concerns</em> buzzword rings again. By having a single file handling a single part, it’s very easy to spot and tackle eventual changes. Finally, if working on a larger team, will reduce conflicts and make collaboration a breeze.</p>
<h3 id="give-each-component-single-responsibilities">Give each component single responsibilities</h3>
<p>I’m a big fan of small, self-contained files, functions, and components. Think of them as small building blocks that are combined and used to create something bigger, like the pyramids, or a computer processor.</p>
<p>By assigning single responsibilities to each component, you are essentially functioning as a factory, with ultra-specialized employees that handle one thing and that thing only. Therefore, if <em>X</em> goes south, you know immediately that you need to talk with the one responsible for <em>X</em>. If each component has a single responsibility, it follows that it must exist only one component for it.</p>
<p>Combine multiple components with single responsibilities and you get your own production line.</p>
<h3 id="group-files-by-structures-or-routes">Group files by structures or routes</h3>
<p>We have already learned that React won’t enforce any file structure. Some people will circumvent this freedom but enforcing their own strict rules. I disagree. I believe React is better experienced if you leverage this freedom.</p>
<p>I explain: a successful folder structure is one you don’t need to think about. Frankly, the less you need to think about those petty things, the better. On that note, I like to group files <em>semantically</em>, or when they belong to a specific chunk of the app.</p>
<p>Have a route that renders a specific view? Add all your components there. Created a new page? Create also a new folder and add the corresponding components there as well. Simples structure. Not much thought is needed.</p>
<p>I oftentimes see people trying to be smart and breaking down components in multiple folders, with technical characteristics attached to them, like calling them <em>atomic</em>. I don’t like it. This means creating a new file or folder is no longer a no-brainer, and should be actively reviewed at the expense of having inconsistent file structures across the board. If you don’t care about the inconsistencies, then why create a rule in the first place? Moreover, you really don’t gain much (if anything) by adding a custom file structure to your projects. Developers aren’t supposed to be navigating in folders anyway. Components are small and self-contained, which means you potentially have a lot of files, so what’s the use of manually looking for them? Hence my proposal: group files by routes or pages, and forget about it.</p>
<h3 id="avoid-too-much-nesting">Avoid too much nesting</h3>
<p>React is a big tree of components as discussed, and this is fine. However, if you are nesting too much, you probably are doing it wrong.</p>
<p>There are so many levels that you can descend. You have a list, a CRUD, a modal… you can’t nest forever. If possible, favor the horizontal spread of components, in its own routes, shallow enough that you are not lost in the abstraction and easy enough for a developer to find his or her way through the code.</p>
<h2 id="using-react-with-a-headless-cms"><strong>Using React with a headless CMS</strong></h2>
<p>React is a library for building user interfaces, as we have seen. But it has some interesting integrations. For example, you might want to have your app’s content set somewhere else but render it in your shiny, fast, and efficient React app.</p>
<p>For such cases, content management systems like ButterCMS are a breeze. I spoke already about the separation of concerns, but this isn’t only related to code. In fact, the more you can separate areas of expertise, leaving people to their bread and butter, the better.</p>
<p>If you have a team of content creators, you can give them the freedom to put their creativity to work, generating content that will later be consumed and rendered in your application. Your developers shouldn’t need to have additional work if content changes – the own project structure should be able to do it.</p>
<p>Connecting a CMS provider with a React framework like GatsbyJS will empower you to do exactly that – <a href="https://buttercms.com/blog/leveraging-gatsby-incremental-builds/" rel="noopener noreferrer" target="_blank"><strong>connect to the content being generated, listen to changes, and rebuild your site with fresh content</strong></a>.</p>
<p>Server-side rendering applications like NextJS will also be valuable by fetching data from the CMS and serving to the user as requested.</p>
<p>In short, the JavaScript ecosystem for content management has evolved to the point where having blazing-fast, <a href="https://buttercms.com/blog/react-seo-how-to-build-search-friendly-pages-in-react/" rel="noopener noreferrer" target="_blank"><strong>SEO-friendly web apps</strong></a> can be achieved with both great content and developer experiences.</p>]]></content:encoded>
</item>
<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[What Is React Remix? Should It Be Your Next Framework?]]></title>
<description><![CDATA[Understand the pros and cons of adopting this new technology, with code examples.]]></description>
<link>https://rafaelquintanilha.com/what-is-react-remix-and-should-it-be-your-next-framework/</link>
<guid isPermaLink="false">6383878f14168e003dd8f608</guid>
<category><![CDATA[React]]></category><category><![CDATA[Remix]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 24 Mar 2022 15:51:00 GMT</pubDate>

<content:encoded><![CDATA[<p>We’ve all seen it happen before: something new becomes old until it eventually becomes new again. Trends appear, vanish, and come back again, maybe reinvented, probably with improvements, but the gist will be there. This is the wheel of life.</p>
<p>React <a href="https://remix.run/" rel="noopener noreferrer" target="_blank"><strong>Remix</strong></a> is the “back to basics” strategy for web developers: a toast to the golden era (for some people) of web development—where everything was HTML, and PHP provided the extra spice.</p>
<p>Whether people miss the HTML + PHP combo or not is debatable, but the principles behind it still stand, as we are going to see in a moment. <a href="https://buttercms.com/blog/react-seo-how-to-build-search-friendly-pages-in-react/" rel="noopener noreferrer" target="_blank"><strong>I’ve discussed at length</strong></a> the evolution of web development from static files, to dynamic content, then back to static plus dynamic. Now, React Remix is a new approach, revitalizing the quest for server-side generated content. In this article we will learn what Remix is trying to solve, how it is doing it, what are the consequences (good and bad) of the choices made, and, in the end, will create a small project to outline some of the principles discussed in practice.</p>
<h2 id="back-to-basics"><strong>Back to Basics</strong></h2>
<p>Let us understand how websites were created before, so we can better understand what React Remix is trying to solve. In the early days, web pages (nobody dared to call them “applications” back then) would be a collection of plain HTML. If data needed to change, developers would add a <em>form</em> that would be responsible for sending that data to the server.</p>
<p>Eventually, however, this data would need to be displayed. In order to do that, frameworks were created to allow developers to insert pieces of <em>dynamic</em> data into a <em>static</em> template. This way, users would have up-to-date information and developers would sleep tight at night without needing to manually refresh the content.</p>
<p>PHP was one of the go-to languages for this technique, and anyone who created websites up until the early 2010s probably had to deal with the infamous PHP tags in an HTML file, where dynamic content would be inserted after being read from an external source like a database or API.</p>
<p>However, things started to go south in PHP-land as developers started to praise a pattern called “separation of concerns”. Apparently, mixing PHP, HTML, JavaScript, and CSS in the same file became a burden at some point, and using PHP for templating lost its appeal, as other JavaScript frameworks like <a href="https://buttercms.com/blog/how-to-overcome-the-5-biggest-nodejs-mistakes/" rel="noopener noreferrer" target="_blank"><strong>Node</strong></a> and React became more popular, and <a href="https://buttercms.com/blog/best-skills-for-junior-developers-job-success/" rel="noopener noreferrer" target="_blank"><strong>new professions like front-end</strong></a> and back-end developer surged.</p>
<figure class="image"><img alt="Separation of Concerns" loading="lazy" decoding="async" width="1201" height="629" src="https://rafaelquintanilha.com/_astro/seperation-of-concerns-diagram.D4SFoAtN_2q13yW.webp"><figcaption>Separation of Concerns</figcaption></figure>
<p>But the wheel of life (or should I say “web development”) spun and developers started to think that splitting a single page into multiple files is too cumbersome, and why not add <a href="https://buttercms.com/blog/how-to-take-your-css-to-the-next-level/" rel="noopener noreferrer" target="_blank"><strong>CSS</strong></a>-in-JS and have loaders to load the dynamic information and actions to mutate data. And in this spirit, React Remix emerged.</p>
<p>In short, React Remix is a modern attempt—using newer techniques and an opinionated framework—to rescue the basics of web development. It is less dependent on JavaScript, semantically groups code, and prioritizes performance.</p>
<h2 id="is-it-really-necessary"><strong>Is it really necessary?</strong></h2>
<p>A fair question is if we really need to make this U-turn pattern-wise, especially now that React has conquered its space as the frontend framework king. Here it’s important to know that React Remix, if you haven’t noticed yet, is built on top of React and therefore not a total disruption of the current patterns.</p>
<p>However, it does change some paradigms as we are going to explore further in a moment. But while React is an unopinionated frontend-only library, React Remix (as other competitors like <a href="https://nextjs.org/" rel="noopener noreferrer" target="_blank"><strong>Next.js</strong></a> and <a href="https://www.gatsbyjs.com/" rel="noopener noreferrer" target="_blank"><strong>Gatsby</strong></a>) aims to bring React to the server-side rendering (SSR) realm, and therefore it needs to be analyzed under the assumption that this is something that you want.</p>
<p>In other words, React Remix helps developers who want the benefits of server-side rendering. React started as the “V” of the MVC (Model-View-Controller). React Remix is the whole package, reshaped as an evolution of the old ASP.net and PHP frameworks.</p>
<p>For a more formal definition, according to <a href="https://bejamas.io/blog/guide-to-remix-framework/" rel="noopener noreferrer" target="_blank"><strong>Bejamas</strong></a>, Remix is a server-side rendering JavaScript framework built on React that allows us to build full-stack web applications due to its frontend and server-side capabilities.</p>
<h2 id="why-pick-react-remix"><strong>Why pick React Remix?</strong></h2>
<p>We already discussed how React Remix is different from a plain React application. But as a developer, why would you decide to pick React Remix for your next project over another framework?</p>
<p>Here it’s important to say that if all you are looking for is SSR, there are senior frameworks such as Next.js and Gatsby on the block. And if what you need is <a href="https://buttercms.com/blog/6-of-the-best-static-site-generators-in-2020/" rel="noopener noreferrer" target="_blank"><strong>static site generation</strong></a> (SSG), then React Remix is probably not for you.</p>
<h3 id="ssr-vs-ssg">SSR vs SSG</h3>
<p>Right, but what the heck are all those acronyms anyway? I won’t go too deep, but SSR stands for <a href="https://buttercms.com/blog/leveraging-gatsby-incremental-builds#server-side-components/" rel="noopener noreferrer" target="_blank"><strong>server-side rendering</strong></a>, whereas SSG means static site generation. Both are alternatives to SPAs, or single-page applications, which React is by default.</p>
<p>In SSR applications, pages are templated like PHP in the golden days, and upon request, fresher information is inserted – or in more technical terms, data is added at <em>run time</em>. SSG, however, fills the templates at <em>build time</em>, i.e., when the HTML page is being generated. By doing that, delivery time becomes way faster, although you need to spend more time building your application.</p>
<p>Which approach to choose will depend on your requirements, but as of today, I’d argue that Remix won’t probably be a fit for SSG applications, but is a contender for SSR. But does it win the contest?</p>
<figure class="image"><img alt="SSR vs SSG" loading="lazy" decoding="async" width="1201" height="629" src="https://rafaelquintanilha.com/_astro/ssr-vs-ssg.DaADDetP_ZlwKcN.webp"><figcaption>SSR vs SSG</figcaption></figure>
<p>As always, it depends. Bear in mind that the framework is very new and subject to change, and also that it tries to do <em>less things</em> and therefore you can eventually hit a roadblock. But if you have a defined scope and a clear understanding of your requirements, by all means, give it a shot. It has some fun paradigms, as we are going to see.</p>
<h2 id="react-remix-key-features--benefits"><strong>React Remix key features &#x26; benefits</strong></h2>
<p>Alright, up until now we have discussed what React Remix is and what it tries to solve from a conceptual standpoint. It’s time for us to understand what all this fuss means <em>in practice</em>, and later, to see some code in action.</p>
<h3 id="nested-routes">Nested Routes</h3>
<p>The creators of React Remix were also the minds behind <a href="https://reactrouter.com/" rel="noopener noreferrer" target="_blank"><strong>react-router</strong></a>, a well-known library for routing applications. Remix has a very clever scheme of nested routes where you can compose routes pretty much like you can compose components. This is very convenient for the traditional “list-view” application, where you select an item of a list in order to inspect its details.</p>
<h3 id="error-boundaries">Error Boundaries</h3>
<p>It has happened to all of us – a web application tries to load, something goes south, and the whole page crashes. React Remix argues it doesn’t need to be this way. Would you short-circuit the whole component if a child breaks? Then why do that in your application? With <a href="https://remix.run/docs/en/v1/guides/errors#nested-error-boundaries" rel="noopener noreferrer" target="_blank"><strong>Error Boundaries</strong></a>, you have localized points of failure, so you don’t disrupt the functioning of your app because only one thing went wrong.</p>
<h3 id="loaders">Loaders</h3>
<p>Static sites became dynamic for a reason, and that was because static is boring. However, fetching all data dynamically compromises your app’s performance, impacts SEO, and so on. Remember how SSR websites fill the gaps (the templates) at <em>run time</em>? React Remix makes this work by using <em>loaders</em>, special functions that load the dynamic information from somewhere (a database, an <a href="https://buttercms.com/blog/webhook-vs-api-whats-the-difference/#what-is-an-api/" rel="noopener noreferrer" target="_blank"><strong>API</strong></a>) when the page is served. Loaders are added in your route file, so you know exactly what information is being retrieved at the time. A handy <code>useLoaderData</code> hook is provided, so your component is shielded from the extra complexity.</p>
<h3 id="actions">Actions</h3>
<p>Actions are the hyperactive brothers of loaders, the ones responsible for <em>mutating data</em>. We give the name of “mutation” to every action that changes data, like inserting, editing, or deleting. Like loaders, you can add an action function in your Remix routes in order to intercept <em>form</em> data, and handle them as you please.</p>
<h3 id="javascript-free-zone">JavaScript-free zone</h3>
<p>Because actions are HTML forms and Remix can handle loading states for you, JavaScript becomes henceforth a luxury. That means that you can have a modern framework, using the latest technologies, and still be resilient to JavaScript not being available. In an era of JavaScript abuse, it is truly remarkable.</p>
<h3 id="full-stack-framework">Full-stack framework</h3>
<p>React Remix does an awesome job in closing the gap between frontend and backend, to the point that it becomes really fuzzy where one ends and the other starts. This has drawbacks, but also great advantages. Your codebase is unique, code is relatively grouped together, and development is smooth.</p>
<h2 id="criticism-of-react-remix"><strong>Criticism of React Remix</strong></h2>
<p>React Remix is an opinionated framework and, as such, has benefits and drawbacks. Although drawbacks can be objective or subjective, some points are not debatable. For example, the fact that Remix doesn’t support SSG out-of-the-box and therefore shouldn’t be used if that’s your primary goal. However, because this is an opinionated article, I’ll lay down what I think are the crucial points when deciding whether React Remix is the right tool for the job.</p>
<figure class="image"><img alt="React Remix criticism" loading="lazy" decoding="async" width="1201" height="629" src="https://rafaelquintanilha.com/_astro/react-remix-criticisim-positive-negative.C_PqRCyw_1RjAfp.webp"><figcaption>React Remix criticism</figcaption></figure>
<h3 id="nested-routes-for-whom">Nested routes for whom?</h3>
<p>Let’s be honest: nested routes are nice, but do you really need them? How many times are they useful enough that it warrants the choice? Granted, being able to preload chunks of your app is a nice addition, but you need to think if this is a feature applicable to your application.</p>
<h3 id="do-you-need-error-boundaries">Do you need Error Boundaries?</h3>
<p>It is nice that your app doesn’t explode when a tiny chunk fails, but the question is: how often does a tiny chunk fail and your user is still able to pull some value out of it? It’s definitely important in critical parts of your app, but let’s face it, most of the time when something fails on a web page, the whole thing will need to be refreshed.</p>
<h3 id="not-very-restful">Not very RESTful</h3>
<p>If you come from a RESTful framework like Express, you probably will be a bit shocked that traditional verbs like PUT, PATCH, and DELETE are not encouraged. That’s because HTML forms only support GET and POST verbs, and therefore you lose a bit of Remix’s magic by using them (and it looks a bit hacky anyway). Personally, I think this is one of the main disadvantages, as it goes against API development best practices.</p>
<h3 id="do-you-really-i-mean-really-expect-to-be-functional-without-javascript">Do you really (I mean, really) expect to be functional without JavaScript?</h3>
<p>Oftentimes I see people bragging that they browse the web with JavaScript disabled and can’t help but wonder from what planet they come from. Jokes aside, do you really want to account for those freaks extra sensitive people?</p>
<p>I understand the argument that too much JavaScript is bad, and often unnecessary, but <em>zero</em> seems a bit drastic to me. If that’s not a must for you, probably all the “we work without JavaScript” propaganda won’t make a difference for you anyway.</p>
<h3 id="rip-separation-of-concerns">RIP Separation of Concerns</h3>
<p>I’m old enough to remember people praising “<a href="https://dev.to/suspir0n/soc-separation-of-concerns-5ak7" rel="noopener noreferrer" target="_blank"><strong>separation of concerns</strong></a>” as some sort of holy grail of web development. You have small, self-contained files, each doing its own job, like bees in a beehive. What’s so wrong with that? If you are like me and like everything in its own file, React Remix may not be for you.</p>
<h3 id="css-is-cumbersome">CSS is cumbersome</h3>
<p><a href="https://remix.run/docs/en/v1/guides/styling" rel="noopener noreferrer" target="_blank"><strong>The approach for styling used in Remix</strong></a> is a bit odd, but not unexpected (remember we post requests using a form). In their API, you need to add a <code>&#x3C;link></code> tag, as you typically do with HTML. One of the benefits is that you can “control your network tab” and improve performance by importing only the required CSS in the most efficient manner. I then reply: do you want to control your network tab?</p>
<p>Also, your favorite CSS framework might not be supported just yet. Be mindful of that before you migrate all your codebase.</p>
<h2 id="react-remix-in-practice"><strong>React Remix in practice</strong></h2>
<p>The time has come for us to quit the babble and start what is really important: the code. The goal here is not to go in-depth on all React Remix features, but rather to provide a brief overview of the features discussed so far.</p>
<p>To achieve that, we are going to build a simple app called <a href="https://github.com/rafaelquintanilha/remix-lotr" rel="noopener noreferrer" target="_blank"><strong>Remix LotR</strong></a> (code available in GitHub), leveraging this awesome <a href="https://the-one-api.dev/" rel="noopener noreferrer" target="_blank"><strong>Lord of the Rings API</strong></a>. I chose this example because it is (arguably) not only fun but also helps us understand some of the fundamentals of the framework. I hope that by using this project as a starting point, you can continue your React Remix studies and decide whether it is the right framework for you.</p>
<h3 id="one-remix-app-to-rule-them-all">One Remix app to rule them all</h3>
<p>If you want to follow along with this tutorial, head over to the LotR API website and claim your key. There are some rate limits but it should be more than enough for our project.</p>
<p>Also, make sure that you have React Remix set up and a new project created as described in their <a href="https://remix.run/docs/en/v1/tutorials/blog#quickstart" rel="noopener noreferrer" target="_blank"><strong>Quickstart guide.</strong></a> To make things simple, select <em>when prompted since deploying is out of the scope of today’s project.</em></p>
<p>We will build a tree-view-like app where the Lord of the Rings characters will be listed and, upon selection, their details will show up. When a character is “opened”, you will also be able to load their quotes (if any). Although a bit silly, this is a clear way to understand how nested routes work and how you can use loaders to serve data to the client.</p>
<h3 id="your-first-route">Your first route</h3>
<p>If you have already created a Remix project, you will see the framework has created some boilerplate for us. The most important piece is the folder <em>app/routes,</em> where all pages live. Open <strong>index.jsx</strong> and add a <code>Link</code> to the page we are going to create soon.</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"> { Link } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "remix"</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:#A1C1E4"> function</span><span style="color:#EDCC95"> Index</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"> style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ fontFamily: </span><span style="color:#97CCAE">"system-ui, sans-serif"</span><span style="color:#ECEBE8">, lineHeight: </span><span style="color:#97CCAE">"1.4"</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">>Welcome to Remix!&#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:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        {</span><span style="color:#A7A49E;font-style:italic">/* code */</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">          &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/characters"</span><span style="color:#ECEBE8">>Characters&#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">      &#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">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>The highlighted portion is what we need to add. Feel free to remove the rest if you want. For now, the important piece is that, when linking to an <em>internal page</em>, we need to import the <code>Link</code> component from <code>remix</code>. This is important because this way Remix can preload the next route and improve your app’s performance.</p>
<p>Alright, we added a link but the route doesn’t exist yet. Let’s fix this by creating a file <strong>characters.jsx</strong> in <em><strong>app/routes</strong></em>. This should be enough for now:</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">export</span><span style="color:#A1C1E4"> default</span><span style="color:#A1C1E4"> function</span><span style="color:#EDCC95"> Characters</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">main</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">>Characters&#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">main</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>Save your work, then start the server by running <code>npm run dev</code> and notice that the link works. Congratulations, you have created your first route from scratch!</p>
<h3 id="listing-all-characters">Listing all characters</h3>
<p>Our app is rather lame so far. Fear not, we are going to spice things up a little right now.</p>
<p>The goal of this page is to list all characters in the Lord of the Rings series as cataloged by the API. Looking at the docs, you see that the <em><strong>/characters</strong></em> endpoint is what we want.</p>
<p>The way React Remix adopts to <em>load</em> data into a route is called… well, <em>loaders</em>. You can easily test it by adding a function called <em>loader</em> in the route:</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"> { useLoaderData } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "remix"</span><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:#EDCC95"> loader</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</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"> data </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [“Gandalf”, “Frodo”, “Aragorn”];</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> data;</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:#A1C1E4"> function</span><span style="color:#EDCC95"> Characters</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useLoaderData</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#EDCC95">  console.log</span><span style="color:#ECEBE8">(data);</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">main</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">>Characters&#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">main</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>Add the highlight pieces and check how the data variable defined inside the loader function becomes available in the route component through the <code>useLoaderDat</code>a hook. This is one of the magical things about Remix: the data source and the actual component using it are coupled together.</p>
<p>Now, let’s scrap the dummy data and actually make the API connection. For that, make sure you have the API key and the base path set. In order to make things cleaner, create a <strong>.env</strong> file at the root and add the following data:</p>
<figure class="code"><figcaption>c</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="c"><code><span class="line"><span style="color:#ECEBE8">BASE_PATH</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"insert API base path"</span></span>
<span class="line"><span style="color:#ECEBE8">API_KEY</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"insert an API key from https://the-one-api.dev/"</span></span></code></pre></figure>
<p>Now you will be able to safely use the variables using <code>process.env</code>. Cool, right?</p>
<p>Let’s then get back to the loader function and hook it properly:</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">export</span><span style="color:#A1C1E4"> const</span><span style="color:#EDCC95"> loader</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</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"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> fetch</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">    `${</span><span style="color:#97CCAE">process.env.BASE_PATH</span><span style="color:#97CCAE">}/character?sort=name:asc`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">    {</span></span>
<span class="line"><span style="color:#ECEBE8">      headers: {</span></span>
<span class="line"><span style="color:#ECEBE8">        Authorization: </span><span style="color:#97CCAE">`Bearer ${</span><span style="color:#97CCAE">process.env.API_KEY</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>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> response.json</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> data;</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span></code></pre></figure>
<p>And that’s it! Check how the actual data is available in your route component.</p>
<h3 id="adding-a-nested-route">Adding a nested route</h3>
<p>Everything is going according to the plan. Now, we want a character’s details to be expanded by clicking on their name. Notice that the route right now is <em><strong>/characters</strong></em> so we’ll need a nested route in the format <em><strong>/characters/$id</strong></em>.</p>
<p>Let us then get back to <em><strong>characters.jsx</strong></em> and link them properly:</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 } </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, Outlet, useLoaderData } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "remix"</span><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:#EDCC95"> loader</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* code */</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:#A1C1E4"> function</span><span style="color:#EDCC95"> Characters</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useLoaderData</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [filter, setFilter] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">""</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">main</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">>Characters&#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">hr</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"> style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ display: </span><span style="color:#97CCAE">"flex"</span><span style="color:#ECEBE8">, marginTop: </span><span style="color:#97CCAE">"40px"</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">label</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">>Filter:&#x3C;/</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">label</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#97CCAE">          &#x26;nbsp;</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">input</span><span style="color:#EDCC95"> value</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{filter} </span><span style="color:#EDCC95">onChange</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{(e) </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setFilter</span><span style="color:#ECEBE8">(e.target.value)} /></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">            {data.docs</span></span>
<span class="line"><span style="color:#EDCC95">              .filter</span><span style="color:#ECEBE8">((d) </span><span style="color:#A1C1E4">=></span></span>
<span class="line"><span style="color:#ECEBE8">                filter </span><span style="color:#A1C1E4">===</span><span style="color:#97CCAE"> ""</span></span>
<span class="line"><span style="color:#A1C1E4">                  ?</span><span style="color:#A1C1E4"> true</span></span>
<span class="line"><span style="color:#A1C1E4">                  :</span><span style="color:#EDCC95"> d.name.toLowerCase</span><span style="color:#ECEBE8">()</span><span style="color:#EDCC95">.includes</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">filter.toLowerCase</span><span style="color:#ECEBE8">())</span></span>
<span class="line"><span style="color:#ECEBE8">              )</span></span>
<span class="line"><span style="color:#EDCC95">              .map</span><span style="color:#ECEBE8">((d) </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">Link</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{d._id} </span><span style="color:#EDCC95">to</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{d._id} </span><span style="color:#EDCC95">style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ display: </span><span style="color:#97CCAE">"block"</span><span style="color:#ECEBE8"> }}></span></span>
<span class="line"><span style="color:#ECEBE8">                  {d.name}</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">              ))}</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">div</span></span>
<span class="line"><span style="color:#EDCC95">          style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{</span></span>
<span class="line"><span style="color:#ECEBE8">            position: </span><span style="color:#97CCAE">"sticky"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">            top: </span><span style="color:#97CCAE">"20px"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">            marginLeft: </span><span style="color:#97CCAE">"20px"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">            alignSelf: </span><span style="color:#97CCAE">"flex-start"</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">          &#x3C;</span><span style="color:#A1C1E4">Outlet</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">main</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>We added a client-side filter to help while looking for a specific character. Notice how it’s React plain and simple. Also, we added a <code>Link</code> component for every character, using the variable <code>_id</code> as an identifier. The <code>Outlet</code> component is what houses the nested component that will be created next.</p>
<p>We can interpret routes’ chunks as variables as long as we prefix them with a $. That’s what we are going to do now – create a new folder <em><strong>/app/routes/characters</strong></em> and inside it a file <em><strong>$id.jsx</strong></em>. This will be enough for Remix to understand that a route like <em><strong>/characters/123</strong></em> will expose a variable called <code>id</code> whose value will be <code>123</code>.</p>
<p>Open <strong>$id.jsx</strong> 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"> { useLoaderData } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "remix"</span><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:#EDCC95"> loader</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> ({ params: { id } }) </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"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> fetch</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`${</span><span style="color:#97CCAE">process.env.BASE_PATH</span><span style="color:#97CCAE">}/character/${</span><span style="color:#97CCAE">id</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">, {</span></span>
<span class="line"><span style="color:#ECEBE8">    headers: {</span></span>
<span class="line"><span style="color:#ECEBE8">      Authorization: </span><span style="color:#97CCAE">`Bearer ${</span><span style="color:#97CCAE">process.env.API_KEY</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:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> response.json</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> data;</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:#A1C1E4"> function</span><span style="color:#EDCC95"> Character</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useLoaderData</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> character </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> data.docs[</span><span style="color:#97CCAE">0</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"> style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ display: </span><span style="color:#97CCAE">"flex"</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"> style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ minWidth: </span><span style="color:#97CCAE">"300px"</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">>{character.name}&#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 style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>Birth&#x3C;/</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>: {character.birth}</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>Death&#x3C;/</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>: {character.death}</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>Gender&#x3C;/</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>: {character.gender}</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>Hair&#x3C;/</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>: {character.hair}</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>Height&#x3C;/</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>: {character.height}</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>Race&#x3C;/</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>: {character.race}</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>Realm&#x3C;/</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>: {character.realm}</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>Spouse&#x3C;/</span><span style="color:#A1C1E4">b</span><span style="color:#ECEBE8">>: {character.spouse}</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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">a</span><span style="color:#EDCC95"> href</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{character.wikiUrl}>Wiki URL&#x3C;/</span><span style="color:#A1C1E4">a</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">div</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>Notice how we destructured <code>{ params: { id } }</code> in order to have access to the id <em>in the server</em>. Then, we used the API the same way as before to get the details, and <code>useLoaderData</code> again to access them in the component. Note that because <code>wikiUrl </code>is an <em>external link</em>, we didn’t use the <code>Link</code> component but rather a plain old anchor tag.</p>
<p>Play a bit with what we have right now. Notice how clicking on a character name instantly opens their details, and how hitting back in the browser changes the URL and also the content. This is the magic of nesting routes, rendered from the <code>Outlet</code> component.</p>
<figure class="image"><img alt="Filtering characters" loading="lazy" decoding="async" width="770" height="484" src="https://rafaelquintanilha.com/_astro/characters.DCR1Xpi4_Z1gzGHf.webp"><figcaption>Filtering characters</figcaption></figure>
<h3 id="how-much-nesting-is-too-much-nesting">How much nesting is too much nesting?</h3>
<p>Let’s explore a bit further by adding <em>another</em> nesting level. Is that even possible? Of course, it is! And the good news is that there’s nothing new to us.</p>
<p>The next goal is to create a link that will open the quotes for a given character. The route will be <em><strong>/characters/123/quotes</strong></em> and this suggests that we follow the same pattern as before: create a folder with the name of the parent route (in this case <strong>app/routes/characters/$id</strong>) and inside a file with the name of the desired route: <em><strong>quotes.jsx</strong></em>.</p>
<p>Open <em><strong>quotes.jsx</strong></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"> { useLoaderData } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "remix"</span><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:#EDCC95"> loader</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> ({ params: { id } }) </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"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> fetch</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">    `${</span><span style="color:#97CCAE">process.env.BASE_PATH</span><span style="color:#97CCAE">}/character/${</span><span style="color:#97CCAE">id</span><span style="color:#97CCAE">}/quote`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">    {</span></span>
<span class="line"><span style="color:#ECEBE8">      headers: {</span></span>
<span class="line"><span style="color:#ECEBE8">        Authorization: </span><span style="color:#97CCAE">`Bearer ${</span><span style="color:#97CCAE">process.env.API_KEY</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>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> response.json</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> data;</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:#A1C1E4"> function</span><span style="color:#EDCC95"> Character</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useLoaderData</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">h3</span><span style="color:#ECEBE8">>Quotes&#x3C;/</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {data.docs.length </span><span style="color:#A1C1E4">></span><span style="color:#97CCAE"> 0</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">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          {</span><span style="color:#EDCC95">data.docs.map</span><span style="color:#ECEBE8">((q) </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">{q._id}>{q.dialog}&#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">      ) </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">div</span><span style="color:#ECEBE8">>No quotes found.&#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">    &#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>Alright! Nothing new to see here. Go back to <strong>$id.jsx</strong> and add the missing link:</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"> { useLoaderData, Link } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "remix"</span><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:#EDCC95"> loader</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> ({ params: { id } }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  {</span><span style="color:#A7A49E;font-style:italic">/* code */</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">export</span><span style="color:#A1C1E4"> default</span><span style="color:#A1C1E4"> function</span><span style="color:#EDCC95"> Character</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#ECEBE8">        {</span><span style="color:#A7A49E;font-style:italic">/* code */</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"> style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ marginTop: </span><span style="color:#97CCAE">"20px"</span><span style="color:#ECEBE8"> }}></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:#97CCAE">"quotes"</span><span style="color:#ECEBE8">>See quotes&#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">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">      &#x3C;/</span><span style="color:#ECEBE8">div</span><span style="color:#A1C1E4">></span></span>
<span class="line"><span style="color:#A1C1E4">    &#x3C;/</span><span style="color:#ECEBE8">div</span><span style="color:#A1C1E4">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Save your work, click on the Link, and… something’s off. Nothing is showing up!</p>
<p>Why is that happening? Well, every time we want to make a <em>nested</em> route, we need to use the <code>Outlet</code> component. And as you can see, a single <code>Outlet</code> component is not enough – you need one for each desired nested level.</p>
<p>Let’s fix the issue by adding another Outlet component, this time in <strong>$id.jsx</strong>:</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"> { useLoaderData, Link, Outlet } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "remix"</span><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:#EDCC95"> loader</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> ({ params: { id } }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  {</span><span style="color:#A7A49E;font-style:italic">/* code */</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">export</span><span style="color:#A1C1E4"> default</span><span style="color:#A1C1E4"> function</span><span style="color:#EDCC95"> Character</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#ECEBE8">      {</span><span style="color:#A7A49E;font-style:italic">/* code */</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">        style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{</span></span>
<span class="line"><span style="color:#ECEBE8">          position: </span><span style="color:#97CCAE">"sticky"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">          top: </span><span style="color:#97CCAE">"20px"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">          marginLeft: </span><span style="color:#97CCAE">"20px"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">          alignSelf: </span><span style="color:#97CCAE">"flex-start"</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">        &#x3C;</span><span style="color:#A1C1E4">Outlet</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:#A1C1E4">    &#x3C;/</span><span style="color:#ECEBE8">div</span><span style="color:#A1C1E4">></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Try again and see how it works!</p>
<figure class="image"><img alt="Nested characters" loading="lazy" decoding="async" width="1022" height="1178" src="https://rafaelquintanilha.com/_astro/nested-characters--1-.BPvkAg9L_Z1SbJfd.webp"><figcaption>Nested characters</figcaption></figure>
<h3 id="error-boundaries-in-action">Error boundaries in action</h3>
<p>The last thing that I’d like to go over today is called <em>Error Boundaries.</em> Simply put, if something breaks in your app, the closest boundary will “intercept” it, preventing a deeply nested mistake from bubbling up the whole application. Once we are talking about a two-level nested route, it’s important that we prevent an issue in the <em>quotes</em> route, for example, from blowing up the whole experience.</p>
<p>Let’s test it by adding a function called <em>ErrorBoundary</em> and by simulating an error in our code:</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"> { useLoaderData } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "remix"</span><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:#EDCC95"> loader</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> ({ params: { id } }) </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"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> fetch</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">    `${</span><span style="color:#97CCAE">process.env.BASE_PATH</span><span style="color:#97CCAE">}/character/${</span><span style="color:#97CCAE">id</span><span style="color:#97CCAE">}/quote`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">    {</span></span>
<span class="line"><span style="color:#ECEBE8">      headers: {</span></span>
<span class="line"><span style="color:#ECEBE8">        Authorization: </span><span style="color:#97CCAE">`Bearer ${</span><span style="color:#97CCAE">process.env.API_KEY</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>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> response.json</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">/</span><span style="color:#97CCAE"> 1000</span><span style="color:#ECEBE8">; </span><span style="color:#A7A49E;font-style:italic">// Generate some random error</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:#A1C1E4"> function</span><span style="color:#EDCC95"> Character</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#ECEBE8">  {</span><span style="color:#A7A49E;font-style:italic">/* code */</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">export</span><span style="color:#A1C1E4"> function</span><span style="color:#EDCC95"> ErrorBoundary</span><span style="color:#ECEBE8">({ error }) {</span></span>
<span class="line"><span style="color:#EDCC95">  console.error</span><span style="color:#ECEBE8">(error);</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"> style</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ color: </span><span style="color:#97CCAE">"red"</span><span style="color:#ECEBE8"> }}></span></span>
<span class="line"><span style="color:#ECEBE8">      Something went wrong: &#x3C;</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">>{error.message}&#x3C;/</span><span style="color:#A1C1E4">strong</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>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Now, select a character, click on “See quotes”, and check how only the quotes part is broken.</p>
<figure class="image"><img alt="Error boundaries in action" loading="lazy" decoding="async" width="1018" height="460" src="https://rafaelquintanilha.com/_astro/character-error-boundaries--1-.vhquiUzt_Z11cXqd.webp"><figcaption>Error boundaries in action</figcaption></figure>
<h2 id="conclusion"><strong>Conclusion</strong></h2>
<p>React Remix is definitely an interesting framework and a new paradigm, at least for modern standards. It brings back some old web development principles, which is by no means a bad thing.</p>
<p>That said, the technology is fairly new and things are subject to change. Therefore, I’d be cautious in adopting this stack in production. Nonetheless, it’s worth keeping an eye on it and how it will develop in the future.</p>
<p>One more quick thing to note, being an SSR framework Remix isn’t an ideal choice for a production app like ours. This is because every page hit will ping the API again, with data that won’t change often, and therefore stress the API server unnecessarily (on the peril of being rate-limited). An SSG framework like Gatsby or Next would probably be a better choice. However, had our data been more dynamic (a stock price, for example), this approach would work better. Thus understanding the business needs of your app is crucial when determining whether React Remix is adequate for you.</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[React SEO: How to Build Search-Friendly Pages in React]]></title>
<description><![CDATA[How to boost your React app SEO ranking with many practical tips.]]></description>
<link>https://rafaelquintanilha.com/react-seo-how-to-build-search-friendly-pages-in-react/</link>
<guid isPermaLink="false">6383abfb14168e003dd8f748</guid>
<category><![CDATA[React]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Best Practices]]></category><category><![CDATA[ButterCMS]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 21 Jan 2021 18:27:00 GMT</pubDate>

<content:encoded><![CDATA[<p>Digital advertising is a multi-billionaire industry that has been rising sharply. In fact, the money spent worldwide on it has <a href="https://www.statista.com/statistics/237974/online-advertising-spending-worldwide/" rel="noopener noreferrer" target="_blank"><strong>nearly doubled</strong></a> since 2016. The motive for this is clear: companies want to be seen on the Internet.</p>
<p>On the one hand, you can pay a large number of dollars to have your ad featured; on the other hand, you can be seen for free. That’s due to SEO, or Search Engine Optimization. Attracting organic traffic to your website is one of the most profitable actions a business can take, and this is by no means a trivial thing to achieve.</p>
<p>In this article, I’ll guide you on how to build SEO-friendly pages using React, the most popular framework for building modern websites. I'll also show you how these methods can be applied to dynamic content with the help of a <a href="https://buttercms.com/react-cms/" rel="noopener noreferrer" target="_blank"><strong>good React CMS</strong></a>.</p>
<h2 id="the-importance-of-seo"><strong>The Importance of SEO</strong></h2>
<p>Google owns 92% of the search engine market share worldwide and this number has been fairly <a href="https://gs.statcounter.com/search-engine-market-share#yearly-2009-2020" rel="noopener noreferrer" target="_blank"><strong>steady since 2009</strong></a>. It makes sense, then, to target Google and what it considers good practice when developing your SEO strategy.</p>
<figure class="image"><img alt="Search Engine Market Share (2020)" loading="lazy" decoding="async" width="1200" height="628" src="https://rafaelquintanilha.com/_astro/react-seo-search-engine-market-share.iKYtaES7_ZePX6C.webp"><figcaption>Search Engine Market Share (2020)</figcaption></figure>
<p>The core concept is that the higher your website ranks on the Search Results Page (SERP), the higher the likelihood that users will click on it. While this is fairly intuitive, what might surprise you is how large the gap is in click-through rates (CTR) in the first positions — <a href="https://www.smartinsights.com/search-engine-optimisation-seo/seo-analytics/comparison-of-google-clickthrough-rates-by-position/" rel="noopener noreferrer" target="_blank"><strong>recent studies</strong></a> have found that the combined click-through rates for positions 1 and 2 on a SERP are approximately double the combined click-through rates for positions 3 and 4! In other words, your effectiveness in being seen is exponentially affected by how well you fare on the results page.</p>
<h2 id="how-google-ranks-your-website"><strong>How Google Ranks Your Website</strong></h2>
<p>Before we learn how to enhance React SEO, we must understand how the process works. Simply put, Google uses a bot called Googlebot (how creative!) to crawl your application. This robot is called a <em>web crawler</em>.</p>
<p>The crawler will load your application, analyze it, and rank it by a set number of criteria. While exactly how each criterion is evaluated is unknown, one should target as many features as possible. An application optimized for SEO will enforce some rules to increase the likelihood of being highly ranked.</p>
<figure class="image"><img alt="Meta tags" loading="lazy" decoding="async" width="1146" height="584" src="https://rafaelquintanilha.com/_astro/react-seo-meta-tags.zMQ_VCok_Z2vb5iD.webp"><figcaption>Meta tags</figcaption></figure>
<h3 id="crawling-budget">Crawling Budget</h3>
<p>We live in an era of limited resources, and this will always be true. The same concept applies to search engines and their crawlers — they need to spend their time wisely. The result of this policy is what is called a <em>crawling budget</em>, or how much time a crawler will spend analyzing your website. As you might guess, how efficiently Google will parse your application is severely impacted by your app speed. Any effort to improve load time is welcome, which can become a problem for React apps.</p>
<h3 id="accessible-urls">Accessible URLs</h3>
<p>It is imperative for React SEO to have an SEO-friendly URL. In Google’s words: <em>“URLs with words that are relevant to your site's content and structure are friendlier for visitors navigating your site.”</em> The full set of <a href="https://developers.google.com/search/docs/beginner/seo-starter-guide?hl=en&#x26;visit_id=637438582413772187-2328543862&#x26;rd=1#best-practices_6" rel="noopener noreferrer" target="_blank"><strong>best practices can be seen here</strong></a>. This factor turns out to be one of the major problems with Single Page Applications (SPA), such as regular React applications. Once SPAs are evaluated on the client side, the whole application can live within a single URL.</p>
<p>Several other factors affect React SEO. However, the above are the most flagrant shortcomings of a React application and will be the object of discussion for the next sections.</p>
<h2 id="react-seo-the-problem-with-react-applications"><strong>React SEO: The Problem with React Applications</strong></h2>
<p>So far we have learned that search engines use robots called crawlers to parse your website and rank them accordingly in their SERP. Unfortunately, several of the aspects that are valuable to search engines are not found in standard React applications. We will now analyze what exactly React’s limitations are and, later on, learn how we can overcome them.</p>
<h3 id="static-vs-dynamic-sites">Static vs Dynamic Sites</h3>
<p>Back in the day, all web pages were called <em>static.</em> The process is as follows: the user makes a request to a server for a given URL. The server then returns a set of HTML, JavaScript, and CSS files that are served on-demand and rendered on the user’s browser.</p>
<p>This old-fashioned process is ideal for robots — they have all assets for that web page when they access it. However, things changed and web applications became more complex. The content is many times <em>dynamic</em>, meaning that it changes constantly. Think about your Twitter feed: all content is in constant motion, even though the URL remains the same.</p>
<p>Dynamic content is a problem for crawlers once the data might not be available during their crawling time (remember the crawling budget?). Also, it is loaded via JavaScript, meaning the browser needs to <em>render</em> and <em>parse</em> the code before anyone can see anything. This substantially increases the time a crawler needs to parse the content, hence affecting your SEO.</p>
<h3 id="how-spas-work">How SPAs Work</h3>
<p>As mentioned before, React is a Single Page Application. This means that your whole app lives on a single page, even though you can simulate different routes and pages.</p>
<p>While SPAs are very convenient for dynamic applications, they lack good SEO support. For starters, if all you have is a single page, your meta tags will hardly describe accurately each part of your application. Moreover, you won’t be able to generate unique URLs out-of-the-box, resorting to a <em>client-side routing</em> library like <a href="https://reactrouter.com/" rel="noopener noreferrer" target="_blank"><strong>react-router</strong></a>.</p>
<p>And finally, an SPA is a single webpage where JavaScript is responsible for updating the content on the screen. That usually means that the JavaScript code is bulky, which leads to a higher parse time by the browser. Ultimately, your application will load slower (due to the time needed to download + parse a larger JavaScript file) and your crawling budget will run out quickly.</p>
<p>It all looks like React applications are doomed to rot on the dark corners of the SERP, but it doesn’t need to be that way. Next, we will learn how to overcome the aforementioned issues.</p>
<h2 id="server-side-rendering"><strong>Server-Side Rendering</strong></h2>
<p>Server-side rendering (SSR), also known as <em>isomorphic applications</em>, is a clever solution to the SPAs shortcomings.</p>
<p>In order to avoid the single page with bulky JavaScript, the React community evolved to a model where the application is rendered on the server during <em>build time</em>. That means that instead of sending a large JavaScript file to the client and letting it figure out what to render, a compiler will analyze the code on the server and generate multiple pages. These pages will then be served on their specific routes, in the good ol’ static website model.</p>
<p>The advantage of such a model is that you can keep working with a cutting-edge library such as React and still retain the biggest advantage of static websites — blazing-fast load times!</p>
<p>However, it is a product decision to understand if SSR is ideal for your project. As a rule of thumb, if your application has content that changes <em>too</em> often, client-side applications should be the best option. Now, if your content is mostly static, and you have many web pages that would benefit from being found on a search engine (such as a product landing page or a blog post), SSR is the way to go.</p>
<h2 id="implementing-an-ssr-application-in-react"><strong>Implementing an SSR Application in React</strong></h2>
<p>The most famous frameworks for developing SSR applications are <a href="http://gatsbyjs.com/" rel="noopener noreferrer" target="_blank"><strong>Gatsby</strong></a> and <a href="https://nextjs.org/" rel="noopener noreferrer" target="_blank"><strong>Next.js</strong></a>. Although there are differences between them, their main goal is similar: to allow next-generation web applications to remain blazing-fast.</p>
<p>It is beyond the scope of this article to compare both technologies, but I will use Gatsby as an example of how the framework addresses the React SEO dilemma.</p>
<h3 id="react-helmet">React-helmet</h3>
<p><a href="https://github.com/nfl/react-helmet" rel="noopener noreferrer" target="_blank"><strong>React-helmet</strong></a> is the industry standard for meta tags optimization. It allows every page to have its own custom meta tags, what we have seen is a major victory for React SEO. The library also allows for the addition of <a href="https://ogp.me/" rel="noopener noreferrer" target="_blank"><strong>Open Graph</strong></a>, which directly impacts the shareability of your content on potentially highly viral spaces such as social networks.</p>
<figure class="image"><img alt="React Helmet SEO plugin" loading="lazy" decoding="async" width="906" height="309" src="https://rafaelquintanilha.com/_astro/react-helmet-react-seo-plugin.DD9nj6S2_Z1fHjqM.webp"><figcaption>React Helmet SEO plugin</figcaption></figure>
<p>Fortunately, Gatsby provides a wide set of plugins that can be used to simplify your life as a developer. The <a href="https://www.gatsbyjs.com/plugins/gatsby-plugin-react-helmet/" rel="noopener noreferrer" target="_blank"><strong>gatsby-plugin-react-helmet</strong></a> repository is one of the most used and widely maintained plugins in the ecosystem.</p>
<p>If you haven’t tried it already, <a href="https://www.gatsbyjs.com/tutorial/seo-and-social-sharing-cards-tutorial/#reach-skip-nav" rel="noopener noreferrer" target="_blank"><strong>this comprehensive tutorial</strong></a> will help you get up on your feet with Gatsby and react-helmet.</p>
<h3 id="gatsby-image">Gatsby-image</h3>
<p>We have repeatedly insisted on how harmful to your React SEO score large JavaScript files are. However, I have never found a potential performance threat as strong as images.</p>
<p>Developers often optimize too much of what is in their control — dependencies, code splitting, etc. But many overlook that a large image loaded on your website can severely impact its performance. While code is under control, static assets are often not. They are provided by content creators, marketers, authors, and others. Therefore, we need a plan to mitigate the potential impacts.</p>
<p>My favorite solution for this problem is <a href="https://www.gatsbyjs.com/plugins/gatsby-image/" rel="noopener noreferrer" target="_blank"><strong>gatsby-image</strong></a>, another plugin meant to save your life. Gatsby-image takes care of, among several other things, optimizing your images and serving them in the most efficient and responsive format. It enhances the look and feel of your app, not to mention the performance and ultimate SEO gain.</p>
<h3 id="other-plugins">Other Plugins</h3>
<p>Gatsby has a <a href="https://www.gatsbyjs.com/plugins" rel="noopener noreferrer" target="_blank"><strong>vast library of plugins</strong></a>. Many of them are zero-config, meaning that you gain React SEO without much more effort than an <em>npm install</em>. As an example, <a href="https://www.gatsbyjs.com/plugins/gatsby-plugin-sitemap" rel="noopener noreferrer" target="_blank"><strong>gatsby-plugin-sitemap</strong></a> will generate sitemaps for your web page, helping bots to crawl your content in the right way.</p>
<figure class="image"><img alt="Gatsby Plugin Library" loading="lazy" decoding="async" width="1228" height="767" src="https://rafaelquintanilha.com/_astro/gatsby-plugin-library.lIQC1Oxu_1n8NW8.webp"><figcaption>Gatsby Plugin Library</figcaption></figure>
<h3 id="route-based-code-splitting">Route-based Code Splitting</h3>
<p>Another great feature of Gatsby is the ability to serve static pages in their own URL (thus addressing the <em>Accessible URLs</em> point) and be wise about what should be included in that particular page.</p>
<p>Remember how SPAs are penalized by having large chunks of JavaScript being loaded at all times? With route-based code splitting, the only JavaScript code sent from the server to the client will be necessary to render whatever is on that particular page. <a href="https://www.gatsbyjs.com/blog/2019-04-02-behind-the-scenes-what-makes-gatsby-great/#route-based-code-splitting" rel="noopener noreferrer" target="_blank"><strong>The following article describes in detail</strong></a> how it works.</p>
<h3 id="do-i-need-a-static-site-generator">Do I Need a Static Site Generator?</h3>
<p>By all means, every advantage listed in the previous topics can be achieved with vanilla JavaScript and other tools. However, <a href="https://buttercms.com/blog/6-of-the-best-static-site-generators-in-2020/" rel="noopener noreferrer" target="_blank"><strong>SSGs like Gatsby and Next.js</strong></a> will abstract the hassle from you to the point that the standard Gatsby application is born with a 100 SEO score on <a href="https://developers.google.com/web/tools/lighthouse" rel="noopener noreferrer" target="_blank"><strong>Lighthouse</strong></a>, Google’s performance analyzer.</p>
<p>More than recommending framework A or B, the goal of this post is to outline the importance of SEO, the shortcomings of barebone React applications, and which tools can be used to overcome them. Don’t feel pressured to switch and adopt a new technology tomorrow — but be aware that different businesses have different needs and it is your job to find the right tool.</p>
<h2 id="static-sites-can-be-dynamic"><strong>Static Sites Can Be Dynamic</strong></h2>
<p>The last point worth mentioning is that, in fact, static sites can have dynamic content. Yes, I know I said before that they are two different kinds of applications, but bear with me for a moment.</p>
<p>If you opt for a Server Side Rendering strategy, your deployment process will include a <em>building time</em>. During this period, the framework will fetch the most up-to-date data available and construct the static page. That means that the <em>source</em> of data can constantly be changing!</p>
<p>This ends up being one of the main advantages of such a process, given that it allows the leverage of a <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><em><strong>headless CMS</strong></em></a> such as ButterCMS. Using this strategy, you can have your Gatsby application connected to ButterCMS and fetch all content from an external admin panel. The main advantage is the possibility to offload the need to constantly edit static content onto professionals better suited for such actions, like marketers and copywriters.</p>
<p>Every time a change is made to static content, or in defined intervals, a new build will be triggered, and once it is finished your content will be updated. The process is highly SEO-friendly and, when properly designed, will allow content creators to choose the best features for the web crawler carefully.</p>
<p>ButterCMS is a leading <a href="https://buttercms.com/gatsbyjs-cms/" rel="noopener noreferrer" target="_blank"><strong>Gatsby CMS</strong></a>, and you can set up the integration with your Gatsby application in minutes!</p>]]></content:encoded>
</item>
</channel>
</rss>
