<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Briankaine on Medium]]></title>
        <description><![CDATA[Stories by Briankaine on Medium]]></description>
        <link>https://medium.com/@briankaine1604?source=rss-e7c572fc0a01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ALOGAyGG7rgoatMq</url>
            <title>Stories by Briankaine on Medium</title>
            <link>https://medium.com/@briankaine1604?source=rss-e7c572fc0a01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:05:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@briankaine1604/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why the Dot Product Isn’t Enough]]></title>
            <link>https://medium.com/@briankaine1604/why-the-dot-product-isnt-enough-0a1ddfefc5d1?source=rss-e7c572fc0a01------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a1ddfefc5d1</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dot-product]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Briankaine]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 12:35:54 GMT</pubDate>
            <atom:updated>2026-07-03T12:35:54.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDcNGYYYlTEOCsgpzCWAQA.png" /></figure><h3>Learning AI From First Principles — Part 4</h3><p>In the last article, we built one of the first mathematical tools that makes modern AI possible: the dot product.</p><p>For the first time, we had a way to compare two vectors.</p><p>It felt like we had solved the problem.</p><p>If two words, sentences, or documents are represented as vectors, then surely we can just calculate the dot product and see how similar they are.</p><p>Problem solved… right?</p><p>Not quite.</p><p>It turns out the dot product has a flaw.</p><p>And discovering that flaw naturally leads us to one of the most important ideas in modern AI: <strong>cosine similarity</strong>.</p><h3>The Goal Was Never Bigger Numbers</h3><p>Let’s remind ourselves what we’re actually trying to do.</p><p>Suppose an embedding model gives us these two vectors:</p><pre>A = [1, 1]<br>B = [2, 2]</pre><p>Using the dot product:</p><pre>1×2 + 1×2 = 4</pre><p>Now consider another vector.</p><pre>C = [100, 100]</pre><p>The dot product between <strong>A</strong> and <strong>C</strong> becomes:</p><pre>1×100 + 1×100 = 200</pre><p>At first glance, that looks amazing.</p><p>Two hundred is much larger than four.</p><p>But stop for a moment.</p><p>Have these vectors really become <strong>more similar</strong>?</p><p>Or has one of them simply become much longer?</p><p>That’s an important distinction.</p><p>Because our goal isn’t to reward bigger vectors.</p><p>Our goal is to answer a much simpler question:</p><blockquote><strong><em>Are these vectors pointing in the same direction?</em></strong></blockquote><p>That question changes everything.</p><h3>The Hidden Problem</h3><p>Imagine two people walking north.</p><p>One walks one kilometre.</p><p>The other walks one hundred kilometres.</p><p>Who walked further?</p><p>Obviously the second person.</p><p>But are they walking in different directions?</p><p>Not at all.</p><p>They’re both heading north.</p><p>The dot product mixes these two ideas together:</p><ul><li>direction</li><li>magnitude (length)</li></ul><p>Sometimes that’s useful.</p><p>But when we’re measuring semantic similarity, the length of a vector can distract us from what we actually care about.</p><p>We don’t want to know who walked the furthest.</p><p>We want to know whether they’re walking in the same direction.</p><h3>Measuring Length</h3><p>To separate direction from length, we first need to know how long a vector is.</p><p>For a vector like:</p><pre>[3, 4]</pre><p>its magnitude is calculated by:</p><ol><li>Squaring each component.</li><li>Adding them together.</li><li>Taking the square root.</li></ol><pre>3² + 4² = 9 + 16 = 25</pre><pre>√25 = 5</pre><p>Now we have a way to measure a vector’s length independently of its direction.</p><p>That turns out to be exactly what we need.</p><h3>The Missing Piece</h3><p>If the dot product combines:</p><ul><li>direction</li><li>and magnitude,</li></ul><p>what if we could somehow remove the effect of magnitude?</p><p>That’s exactly what cosine similarity does.</p><p>Instead of using the dot product by itself, we divide it by the product of the two vector magnitudes.</p><p>Suddenly something interesting happens.</p><p>Long vectors no longer receive larger scores simply because they’re long.</p><p>What’s left is a measurement that’s primarily about <strong>direction</strong>.</p><p>During my own journey through this topic, this was the moment everything finally clicked.</p><p>I stopped thinking of cosine similarity as “another formula.”</p><p>Instead, I started thinking of it like this:</p><blockquote><strong><em>We’re filtering out magnitude so that only direction remains.</em></strong></blockquote><p>Once I saw it that way, the formula no longer felt arbitrary.</p><p>It felt inevitable.</p><h3>Why This Matters for AI</h3><p>Imagine asking an AI:</p><blockquote><em>“What is machine learning?”</em></blockquote><p>Your question is converted into a vector.</p><p>Every document the AI could retrieve has also been converted into a vector.</p><p>The model now compares your query vector with thousands — or even millions — of document vectors.</p><p>If we relied only on the dot product, larger vectors could dominate the results even when they weren’t the closest match semantically.</p><p>Cosine similarity helps prevent that.</p><p>Instead of asking:</p><blockquote><em>“Which vector is biggest?”</em></blockquote><p>it asks:</p><blockquote><strong><em>“Which vector points most closely in the same direction?”</em></strong></blockquote><p>That small change is one of the reasons modern semantic search works so well.</p><h3>Looking Ahead</h3><p>So far, we’ve learned how to compare <strong>one vector with another</strong>.</p><p>But large language models don’t compare just two vectors.</p><p>They compare one query against thousands — or even millions — of embeddings.</p><p>Doing that one comparison at a time would quickly become inefficient.</p><p>In the next article, we’ll discover why matrices aren’t just grids of numbers from a mathematics textbook — they’re one of the key tools that let AI perform many vector comparisons efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a1ddfefc5d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When One Comparison Isn’t Enough]]></title>
            <link>https://medium.com/@briankaine1604/when-one-comparison-isnt-enough-26365499cb1e?source=rss-e7c572fc0a01------2</link>
            <guid isPermaLink="false">https://medium.com/p/26365499cb1e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Briankaine]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 10:26:08 GMT</pubDate>
            <atom:updated>2026-07-02T10:26:08.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_r8M_5wUwnz7BLlS8fXrA.png" /></figure><p><em>Learning AI From First Principles — Part 3</em></p><p>In the previous article, we learnt how computers compare two vectors using the dot product.</p><p>That answered one question, but it immediately raised another.</p><p><strong>What happens when there are more than two vectors?</strong></p><p>Suppose we have a simple sentence:</p><blockquote><em>The boy is good boy.</em></blockquote><p>If every word is represented as a vector, then every word can be compared with every other word.</p><p>At first, I imagined the computer picking one word, comparing all 768 of its features against another word, then moving on to the next pair.</p><p>That intuition wasn’t entirely wrong.</p><p>For two vectors, that’s exactly what happens.</p><p>Feature 1 is compared with Feature 1.</p><p>Feature 2 with Feature 2.</p><p>Feature 3 with Feature 3.</p><p>…</p><p>Feature 768 with Feature 768.</p><p>The products are summed together to produce a single similarity score.</p><p>But then I asked myself a much bigger question.</p><p>Who exactly is being compared?</p><p>Let’s label our sentence.</p><ul><li>W₁ = The</li><li>W₂ = boy</li><li>W₃ = is</li><li>W₄ = good</li><li>W₅ = boy</li></ul><p>Now imagine we’re trying to measure how similar every word is to every other word.</p><p>The comparisons suddenly explode.</p><ul><li>W₁ · W₁</li><li>W₁ · W₂</li><li>W₁ · W₃</li><li>W₁ · W₄</li><li>W₁ · W₅</li></ul><p>Then we repeat the process for W₂.</p><ul><li>W₂ · W₁</li><li>W₂ · W₂</li><li>W₂ · W₃</li><li>W₂ · W₄</li><li>W₂ · W₅</li></ul><p>And again for W₃.</p><p>Then W₄.</p><p>Then W₅.</p><p>Even in this tiny sentence, we’ve already computed <strong>25 dot products</strong>.</p><p>Nothing new has happened mathematically.</p><p>We’re simply repeating the same operation over and over again.</p><p>Then I realised something.</p><p>The computer isn’t really comparing <em>words</em>.</p><p>It’s comparing <strong>every vector with every other vector</strong>.</p><p>That distinction sounds small, but I think it’s important.</p><p>Once words become vectors, the computer no longer cares whether they’re nouns, verbs, or adjectives.</p><p>As far as the mathematics is concerned, they’re simply points in a high-dimensional space.</p><p>That also made me appreciate something I’d missed before.</p><p>The dot product isn’t the clever part.</p><p>The clever part is deciding <strong>which comparisons to perform</strong>.</p><p>A sentence with five words requires twenty-five comparisons.</p><p>A sentence with one hundred words requires ten thousand.</p><p>Suddenly, writing every comparison by hand doesn’t seem practical anymore.</p><p>Programmers usually have a response to moments like this.</p><p>Whenever we find ourselves repeating the same operation over and over, we start looking for a better abstraction.</p><p>I have a feeling that’s exactly where matrices enter the story.</p><p>Not because mathematicians wanted another topic to teach in school, but because they provide a natural way to organise thousands of comparisons at once.</p><p>That’s where we’ll continue next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26365499cb1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Computers Measure Similarity]]></title>
            <link>https://medium.com/@briankaine1604/how-computers-measure-similarity-e538506d2e53?source=rss-e7c572fc0a01------2</link>
            <guid isPermaLink="false">https://medium.com/p/e538506d2e53</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[similarity]]></category>
            <dc:creator><![CDATA[Briankaine]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 09:44:46 GMT</pubDate>
            <atom:updated>2026-07-02T09:44:46.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="An engineers notepad with vectors and RAG concepts" src="https://cdn-images-1.medium.com/max/1024/1*J-nx2riAsvjexxLVqHyv0Q.png" /></figure><h3>Learning AI From First Principles — Part 2</h3><p>In Part 1, we discovered that AI models don’t reason directly over words. They first convert them into vectors — a collection of numbers used to represent something.</p><p>That naturally led me to another question.</p><p>If everything is now just numbers…</p><p><strong>How does a computer know when two things are similar or different or comapare two things?</strong></p><p>My first instinct was subtraction.</p><p>Suppose we have two vectors.</p><pre>A = [3, 4]</pre><pre>B = [4, 5]</pre><p>Subtract them.</p><pre>B - A = [1, 1]</pre><p>The difference is small, so they must be similar.</p><p>That felt reasonable.</p><p>But then I started thinking about recommendation systems like Spotify.</p><p>Imagine one person listens to:</p><ul><li>Jazz = 3</li><li>Blues = 4</li></ul><p>Another person listens to:</p><ul><li>Jazz = 300</li><li>Blues = 400</li></ul><p>Subtraction tells us these people are very different.</p><p>But are they?</p><p>Not really.</p><p>One person simply listens to much more music.</p><p>Their <strong>taste</strong> is almost identical.</p><p>That’s when I realised something important.</p><p>Subtraction measures <strong>difference</strong>.</p><p>It doesn’t necessarily measure <strong>similarity</strong>.</p><p>Those are not always the same thing.</p><p>At this point another question came to mind.</p><p>What if similarity has less to do with <strong>how big</strong> two vectors are…</p><p>…and more to do with <strong>which direction they’re pointing</strong>?</p><p>Imagine two arrows.</p><pre>→<br>→</pre><p>Most of us would immediately say they’re pointing in the same direction.</p><p>Now imagine this.</p><pre>→<br>←</pre><p>They point in opposite directions.</p><p>Without doing any mathematics, your brain has already assigned a similarity score.</p><p>Same direction feels similar.</p><p>Opposite directions don’t.</p><p>That was the first clue that <strong>direction</strong> might matter more than <strong>magnitude</strong>.</p><p>This naturally led me to another question.</p><p>How do we measure direction?</p><p>That rabbit hole eventually took me back to trigonometry.</p><p>Like many people, I learned about sine, cosine and tangent because they appeared on an exam.</p><p>I don’t remember anyone explaining <em>why they existed</em>.</p><p>It turns out they weren’t invented for classrooms.</p><p>Imagine standing at the foot of a mountain.</p><p>You know how far away you are.</p><p>You can measure the angle between your line of sight and the ground.</p><p>The mountain, the ground and your line of sight naturally form a triangle.</p><p>The angle at your eye is usually represented by the Greek letter θ (theta).</p><p>Mathematicians discovered something remarkable.</p><p>Every right triangle with the same angle has the same relationships between its sides.</p><p>Those relationships became so useful that they were eventually given names.</p><ul><li>Sine</li><li>Cosine</li><li>Tangent</li></ul><p>Centuries later, those same ideas found another application.</p><p>Vectors.</p><p>One property of cosine makes it particularly interesting.</p><p>When two vectors point in exactly the same direction:</p><pre>cos(0°) = 1</pre><p>When they are perpendicular:</p><pre>cos(90°) = 0</pre><p>When they point in opposite directions:</p><pre>cos(180°) = -1</pre><p>If your goal is to measure alignment, those values are almost exactly what you’d hope for.</p><p>That brings us to the dot product.</p><p>Interestingly, there are two equally valid ways to think about it.</p><p>The first is geometric.</p><p>It tells us that the dot product depends on two things:</p><ul><li>the lengths of the vectors</li><li>how well they align</li></ul><p>The second is computational.</p><p>Instead of measuring angles directly, we compare corresponding features.</p><p>Suppose we have</p><pre>A = [3, 4]</pre><pre>B = [6, 8]</pre><p>We multiply matching features.</p><pre>3 × 6 = 18</pre><pre>4 × 8 = 32</pre><p>Then add the results.</p><pre>18 + 32 = 50</pre><p>That’s the dot product.</p><p>The beautiful part is that this simple computation produces exactly the same quantity as the geometric definition.</p><p>Computers don’t need to calculate angles.</p><p>They simply multiply corresponding features and add the results together.</p><p>At first I assumed this became much more complicated in AI because embeddings often have hundreds of dimensions.</p><p>In reality, nothing fundamentally changes.</p><p>If a vector has 768 dimensions, the computer simply repeats the exact same operation.</p><p>Feature 1 with Feature 1.</p><p>Feature 2 with Feature 2.</p><p>Feature 3 with Feature 3.</p><p>…</p><p>Feature 768 with Feature 768.</p><p>Every pair of matching features contributes a small vote.</p><p>Some reinforce similarity.</p><p>Others reduce it.</p><p>The final dot product is simply the sum of all those tiny agreements and disagreements.</p><p>I found that surprisingly elegant.</p><p>The algorithm never changed.</p><p>Only the number of features did.</p><p>That left me with one final question.</p><p>If a computer knows how to compare <strong>two</strong> vectors…</p><p>What happens when a sentence contains ten words?</p><p>Or one hundred?</p><p>Does every word compare itself with every other word?</p><p>As it turns out…</p><p>Yes.</p><p>And that simple idea opens the door to understanding how Transformers process language.</p><p>We’ll build that intuition in the next part.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e538506d2e53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning AI From First Principles]]></title>
            <link>https://medium.com/@briankaine1604/learning-ai-from-first-principles-090c7e43664e?source=rss-e7c572fc0a01------2</link>
            <guid isPermaLink="false">https://medium.com/p/090c7e43664e</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Briankaine]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 21:40:23 GMT</pubDate>
            <atom:updated>2026-06-29T21:41:27.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A jotter with technical draft notes" src="https://cdn-images-1.medium.com/max/1024/1*8lz-q8Um3g1d1zUjCG4zHQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@medbadrc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Med Badr Chemmaoui</a> on <a href="https://unsplash.com/photos/blue-ballpoint-pen-on-white-notebook-ZSPBhokqDMc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Part 1: Numbers and Vectors</h3><p>I want to begin by saying I am by no means an expert in this field. I am but a humble tinkerer, and with that in mind I’d like to share some of the concepts I’ve been learning as I try to understand AI from the ground up.</p><p>If you’re expecting deep mathematics or research-level explanations, this probably isn’t the article for you. This series is simply me documenting the questions I’ve asked, the mistakes I’ve made, and the mental pictures that have helped me along the way. If they help someone else too, then it was worth writing.</p><p>So let’s begin with a question that completely caught me off guard</p><blockquote>What is a number?</blockquote><p>Not AI.<br>Not Transformers.<br>Not embeddings.<br>Just… a number.<br>At first I thought it was a ridiculous place to begin.<br>But it turned out to be the right one.</p><p>A number describes one measurable quantity.</p><p>For example:</p><ul><li>Days in a week = <strong>7</strong></li><li>Horsepower = <strong>350 hp</strong></li><li>Temperature = <strong>28°C</strong></li></ul><p>Each number tells us exactly one thing.</p><p>Now imagine I asked you to describe a car using only one number.</p><pre>Car = 7</pre><p>That doesn’t tell us much.</p><p>Cars aren’t defined by one measurable property.</p><p>Instead, we naturally describe them using several numbers.</p><ul><li>Horsepower = 350 hp</li><li>Torque = 420 Nm</li><li>Weight = 1,500 kg</li><li>Fuel efficiency = 18 km/L</li></ul><p>Each number describes one aspect of the car.</p><p>Together, they begin to describe the car itself.</p><p>This is where vectors start to make sense.</p><blockquote>A vector is simply a collection of numbers used together to represent something that can’t be adequately described by a single number.</blockquote><p>Notice that nothing about this is unique to AI.</p><p>Vectors existed long before ChatGPT.</p><p>AI simply makes heavy use of them.</p><p>The next question is obvious.</p><p>If a car can be represented by a collection of numbers…</p><p>Could a word be represented the same way?</p><p>Modern AI models don’t reason directly over words. They first convert them into vector representations.</p><p>At first, that sounded bizarre to me.</p><p>How could a word like <strong>“dog”</strong> become numbers?</p><p>Up to this point, nothing we’ve discussed is unique to AI. Vectors have existed in mathematics and physics for a long time.</p><p>So why have they become such a big deal in machine learning?</p><p>That’s the question we’ll answer in Part 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=090c7e43664e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaffolding a Cloudflare Workers + React App: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@briankaine1604/scaffolding-a-cloudflare-workers-react-app-a-step-by-step-guide-3f15e700bd16?source=rss-e7c572fc0a01------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f15e700bd16</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Briankaine]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 20:51:14 GMT</pubDate>
            <atom:updated>2026-01-24T20:51:14.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUEeWUKVcCXKKv25FUev5w.jpeg" /><figcaption>Cover image courtesy of <a href="https://kaboompics.com/">Kaboompics</a></figcaption></figure><h3>1. Create the Project</h3><p>Run this command in your terminal:</p><pre>npm create cloudflare@latest -- my-react-app --framework=react</pre><blockquote>This automatically sets my-react-app as the project folder, so the CLI won’t ask you for a directory.</blockquote><h3>Step 1.1: Select Framework Variant</h3><p>You’ll be asked to pick a variant:</p><pre>Select a variant:<br>- TypeScript<br>- TypeScript + SWC<br>- JavaScript<br>- JavaScript + SWC</pre><blockquote>Choose <strong>TypeScript + SWC</strong> for type safety and faster builds.</blockquote><p>The CLI then scaffolds your React + Vite project:</p><pre>Continue with React via `npx create-vite@7.1.1 my-react-app --template react-swc-ts`<br>Scaffolding project in ./my-react-app ...</pre><p>It copies template files, installs dependencies, and prepares your environment.</p><h3>2. Cloudflare Configuration</h3><p>The CLI sets up <strong>Cloudflare Workers tooling</strong> automatically:</p><ul><li>Installs <strong>Wrangler</strong> (CLI for building &amp; deploying Workers).</li><li>Installs <strong>@cloudflare/vite-plugin</strong> for Vite + Workers integration.</li><li>Updates tsconfig.json for Worker compatibility.</li><li>Adds Wrangler-related files to .gitignore.</li><li>Adds scripts to package.json:</li></ul><h3>3. Git and Deployment</h3><p>You’ll be prompted:</p><pre>Do you want to use git for version control? Yes / No</pre><blockquote>Choose <strong>Yes</strong>. The CLI initializes a git repo and commits the scaffolded files.</blockquote><p>Next, the CLI asks if you want to <strong>deploy immediately</strong>:</p><pre>Do you want to deploy your application? Yes / No</pre><p>Choose <strong>Yes</strong>. If logged in to Cloudflare, the CLI selects your account and deploys automatically. If not it will prompt you to login before it can deploy. Also you can also choose no and deploy later it’s fully up to you.</p><p>After building and uploading assets, the CLI will print something like:</p><pre>✨ Success! Uploaded 5 files<br>Deployed test-app triggers<br>https://my-react-app.testdeploy-099.workers.dev</pre><p>Your React app is now live on Cloudflare Workers. 🎉</p><h3>4. Next Steps</h3><ul><li>Open the URL in your browser to see the default React page.</li><li>Continue developing locally:</li></ul><pre>cd my-react-app<br>npm run dev</pre><p>Redeploy or deploy if you didn’t the first time:</p><pre>npm run deploy</pre><p>Check your project in the <a href="https://dash.cloudflare.com/">Cloudflare Workers Dashboard</a>.</p><h3>Key Takeaways</h3><ol><li><strong>All-in-one scaffold</strong>: React + Vite + Workers + TypeScript ready to go.</li><li><strong>Edge deployment</strong>: Your app is served globally.</li><li><strong>Type-safe dev</strong>: TypeScript + SWC ensures safety and speed.</li><li><strong>Prepared for backend</strong>: Later you can integrate tRPC, D1, Drizzle, etc., without touching this setup.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*814ju_TrOVrncSCjnGBVWA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f15e700bd16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Escaping the useEffect Mess: A Better Way to Fetch Data with tRPC + React Query]]></title>
            <link>https://medium.com/@briankaine1604/escaping-the-useeffect-mess-a-better-way-to-fetch-data-with-trpc-react-query-4b357b28b4da?source=rss-e7c572fc0a01------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b357b28b4da</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Briankaine]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 12:42:25 GMT</pubDate>
            <atom:updated>2025-07-15T12:42:25.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJgd3-HPCHAhxxu9NFbYfQ.png" /></figure><h3>The useEffect Data Fetching Problem</h3><p><strong><em>Note:</em></strong><em> This guide focuses on full-stack TypeScript apps where you control both the frontend and backend. If you’re consuming external APIs or microservices, you’re better off using React Query with something like OpenAPI or GraphQL codegen.</em></p><p>You’ve been there.</p><p>You need to fetch some data when a component mounts — so naturally, you reach for useEffect. Seems simple enough, right?</p><pre>&quot;use client&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br><br>export const Bloglist = () =&gt; {<br>  const [blogs, setBlogs] = useState([]);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    let cancelled = false;<br><br>    async function fetchBlogs() {<br>      try {<br>        setLoading(true);<br>        const response = await fetch(&quot;/api/blogs&quot;);<br>        if (!response.ok) {<br>          throw new Error(&quot;Failed to fetch blogs&quot;);<br>        }<br>        const data = await response.json();<br>        if (!cancelled) {<br>          setBlogs(data);<br>        }<br>      } catch (err) {<br>        if (!cancelled) {<br>          setError(err.message || &quot;Unknown error&quot;);<br>        }<br>      } finally {<br>        if (!cancelled) {<br>          setLoading(false);<br>        }<br>      }<br>    }<br><br>    fetchBlogs();<br><br>    return () =&gt; {<br>      cancelled = true;<br>    };<br>  }, []);<br><br>  if (loading) return &lt;div&gt;Loading blogs...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error}&lt;/div&gt;;<br>  if (!blogs || blogs.length === 0) return &lt;div&gt;No blogs found.&lt;/div&gt;;<br><br>  return (<br>    &lt;div className=&quot;grid grid-cols-3 gap-5&quot;&gt;<br>      {blogs.map((blog) =&gt; (<br>        &lt;div className=&quot;border p-4&quot; key={blog.id}&gt;<br>          &lt;h2 className=&quot;font-bold text-lg&quot;&gt;{blog.title}&lt;/h2&gt;<br>          &lt;p className=&quot;text-sm text-gray-600&quot;&gt;<br>            {blog.content?.slice(0, 100)}...<br>          &lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Looks fine, right? But now you need blog data in three more components.<br>Your options?</p><ul><li>❌ Copy-paste</li><li>❌ Build a custom hook</li><li>❌ Lift state up and prop-drill like a maniac</li></ul><h3>The Problems Start Piling Up</h3><ul><li>Race conditions on component unmount</li><li>Manual cache invalidation after mutations</li><li>Repeating loading/error states everywhere</li><li>TypeScript types fall out of sync with the backend</li><li>40 lines of boilerplate… and you haven’t even handled optimistic updates</li></ul><p>That simple useEffect just turned into 40 lines of boilerplate. And you&#39;ll repeat it everywhere you need blog data.</p><p>There has to be a better way.</p><h3>Enter tRPC + React Query: A Different Approach</h3><p>What if I told you that same user profile component could look like this:</p><pre>&quot;use client&quot;;<br>import { useTRPC } from &quot;@/trpc/client&quot;;<br>import { useQuery } from &quot;@tanstack/react-query&quot;;<br><br>const Page = () =&gt; {<br>  const trpc = useTRPC();<br>  const { data, isLoading } = useQuery(trpc.blog.getAll.queryOptions());<br><br>  if (isLoading) {<br>    return &lt;div&gt;Loading...&lt;/div&gt;;<br>  }<br>  return (<br>    &lt;div className=&quot; grid grid-cols-3 gap-5&quot;&gt;<br>      {data?.map((blog) =&gt; (<br>        &lt;div className=&quot;border&quot; key={blog.id}&gt;<br>          {blog.title}<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Page;</pre><p>That’s it. No useEffect. No manual state management. No race conditions. No cache invalidation headaches.</p><h3>What Just Happened?</h3><ul><li>✅ <strong>Type Safety for Free</strong> — blog.title is fully typed. Change your backend? TypeScript shows you exactly what to fix.</li><li>✅ <strong>Automatic Caching</strong> — Fetch the same data in three places? Only one network request is made.</li><li>✅ <strong>Background Updates</strong> — Refetches automatically when the window regains focus.</li><li>✅ <strong>Global Error + Loading States</strong> — Consistent UX without duplicated boilerplate.</li><li>✅ <strong>Zero Manual Wiring</strong> — No fetch, no states, no try/catch.</li></ul><p>But the real magic isn’t in the individual features. It’s in how they work together to eliminate entire categories of bugs you didn’t even know you had.</p><h3>The tRPC Secret Sauce</h3><p>tRPC isn’t just another API client. It’s a contract between your frontend and backend that exists at the type level. When you define a procedure on your backend:</p><pre>// Backend<br><br>export const blogRouter = createTRPCRouter({<br>  getOne: baseProcedure<br>    .input(z.object({ id: z.string() }))<br>    .query(({ ctx, input }) =&gt; {<br>      return ctx.db.post.findUnique({<br>        where: { id: input.id },<br>      });<br>    }),<br>  getAll: baseProcedure.query(({ ctx }) =&gt; {<br>    return ctx.db.post.findMany();<br>  }),<br>});</pre><p>Your frontend automatically knows about it:</p><pre>// Frontend - fully typed, no manual API definitions<br>const trpc = useTRPC();<br>  const { data, isLoading } = useQuery(trpc.blog.getAll.queryOptions());</pre><p>Change the backend response? Your frontend TypeScript errors will guide you to update every affected component. It’s like having a compiler that understands your API.</p><h3>Real-World Example: Before and After</h3><p>Let’s look at something more realistic — a user dashboard that shows profile info, recent orders, and notifications. With useEffect, you&#39;d end up with something like this:</p><pre>&quot;use client&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br><br>const ReviewForm = ({ productId }: { productId: string }) =&gt; {<br>  const [review, setReview] = useState(null);<br>  const [loading, setLoading] = useState(true);<br><br>  useEffect(() =&gt; {<br>    fetch(`/api/reviews/${productId}`)<br>      .then((res) =&gt; res.json())<br>      .then((data) =&gt; {<br>        setReview(data);<br>        setLoading(false);<br>      })<br>      .catch(() =&gt; {<br>        alert(&quot;Error&quot;);<br>        setLoading(false);<br>      });<br>  }, [productId]);<br><br>  const submit = async () =&gt; {<br>    const method = review ? &quot;PUT&quot; : &quot;POST&quot;;<br>    await fetch(`/api/reviews${review ? `/${review.id}` : &quot;&quot;}`, {<br>      method,<br>      body: JSON.stringify({ productId, rating: 5, description: &quot;Nice&quot; }),<br>    });<br>  };<br><br>  if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br><br>  return &lt;button onClick={submit}&gt;{review ? &quot;Update&quot; : &quot;Post&quot;} Review&lt;/button&gt;;<br>};</pre><p>Look at all that boilerplate! And we haven’t even handled optimistic updates, error retry, or cache invalidation properly.</p><p><strong>The tRPC + React Query Version</strong></p><pre>&quot;use client&quot;;<br><br>import { useForm } from &quot;react-hook-form&quot;;<br>import { z } from &quot;zod&quot;;<br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;;<br>import { useTRPC } from &quot;@/trpc/client&quot;;<br>import { useQuery, useMutation } from &quot;@tanstack/react-query&quot;;<br><br>const schema = z.object({<br>  description: z.string().min(1),<br>  rating: z.number().min(1).max(5),<br>});<br><br>export const ReviewForm = ({ productId }: { productId: string }) =&gt; {<br>  const trpc = useTRPC();<br>  const utils = trpc.useUtils();<br><br>  const { data: review, isLoading } = useQuery(<br>    trpc.reviews.getOne.queryOptions({ productId })<br>  );<br><br>  const form = useForm({<br>    resolver: zodResolver(schema),<br>    defaultValues: {<br>      description: review?.description ?? &quot;&quot;,<br>      rating: review?.rating ?? 0,<br>    },<br>  });<br><br>  const mutation = useMutation(<br>    review<br>      ? trpc.reviews.update.mutationOptions({<br>          onSuccess: () =&gt; utils.reviews.getOne.invalidate({ productId }),<br>        })<br>      : trpc.reviews.create.mutationOptions({<br>          onSuccess: () =&gt; utils.reviews.getOne.invalidate({ productId }),<br>        })<br>  );<br><br>  const onSubmit = form.handleSubmit((values) =&gt; {<br>    if (review) {<br>      mutation.mutate({ reviewId: review.id, ...values });<br>    } else {<br>      mutation.mutate({ productId, ...values });<br>    }<br>  });<br><br>  if (isLoading) return &lt;p&gt;Loading...&lt;/p&gt;;<br><br>  return (<br>    &lt;form onSubmit={onSubmit}&gt;<br>      &lt;input {...form.register(&quot;rating&quot;)} type=&quot;number&quot; /&gt;<br>      &lt;textarea {...form.register(&quot;description&quot;)} /&gt;<br>      &lt;button type=&quot;submit&quot; disabled={mutation.isPending}&gt;<br>        {review ? &quot;Update&quot; : &quot;Post&quot;} Review<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};</pre><h3>Who Benefits Most (And When to Skip It)</h3><p><strong>You should definitely make the switch if you’re building:</strong></p><ul><li><strong>Dashboards</strong> with real-time data and frequent updates</li><li><strong>Finance apps</strong> where data consistency is critical</li><li><strong>Admin panels</strong> with complex forms and interdependent data</li><li><strong>Social apps</strong> with feeds, notifications, and user interactions</li><li><strong>Any highly interactive app</strong> where users expect snappy, consistent UX</li></ul><p><strong>Skip this approach if:</strong></p><ul><li>You’re building mostly static sites with minimal interactivity</li><li>You’re already happy with your current data fetching setup and it’s not causing pain</li><li>You’re working with external APIs you don’t control (stick with React Query + codegen)</li><li>Your team isn’t comfortable with TypeScript (tRPC’s benefits rely heavily on types)</li></ul><p>The sweet spot is full-stack TypeScript apps where you control both ends and need rich, interactive UIs. If you’re fighting useEffect race conditions and cache invalidation bugs weekly, tRPC + React Query will feel like magic.</p><p><strong>Ready to start using tRPC + React Query?</strong><br> The transformation might look dramatic, but the setup is surprisingly approachable — especially if you’re already working in a full-stack TypeScript environment.</p><p>In the <a href="https://medium.com/@briankaine1604/how-to-add-trpc-react-query-to-your-next-js-app-complete-setup-guide-7658b802a398">next article</a>, I’ll show you exactly how to wire it up from scratch:<br> ✅ tRPC backend setup<br> ✅ React Query client config<br> ✅ Smooth migration from useEffect to fully typed queries</p><p>Whether you’re refactoring an existing project or starting fresh, it’s the guide I wish I had when making the switch.</p><p>If you want to see more of my projects or get in touch, visit my portfolio at <a href="http://briankaine.com/">briankaine.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b357b28b4da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add tRPC + React Query to Your Next.js App (Complete Setup Guide)]]></title>
            <link>https://medium.com/@briankaine1604/how-to-add-trpc-react-query-to-your-next-js-app-complete-setup-guide-7658b802a398?source=rss-e7c572fc0a01------2</link>
            <guid isPermaLink="false">https://medium.com/p/7658b802a398</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[trpc]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Briankaine]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 20:11:06 GMT</pubDate>
            <atom:updated>2025-07-15T20:19:06.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKoDytsO_6ctlvAMaxdKKQ.png" /></figure><h3>Setting Up tRPC in Next.js: From Zero to First Query</h3><p>Ready to ditch those messy useEffect data fetching patterns? This guide walks you through setting up tRPC + React Query in your Next.js app, from initial install to your first type-safe query.</p><h3>Prerequisites</h3><p>Before we start, make sure you have:</p><ul><li>A Next.js 13+ project with App Router (we’ll use the app directory structure)</li><li>Node.js 18+ installed</li><li>TypeScript configured (tRPC’s magic relies on TypeScript)</li><li>Basic familiarity with React Query concepts</li></ul><p><strong>Optional but recommended</strong>: We’ll use Prisma as our ORM for the examples, but tRPC works with any database setup — raw SQL, Drizzle, TypeORM, or even external APIs. If you don’t have Prisma set up, just adapt the database calls to your preferred method.</p><h3>Install Dependencies</h3><p>First, let’s install all the packages we need:<br>In your terminal, run:</p><pre>npm install @trpc/server @trpc/client @trpc/tanstack-react-query @tanstack/react-query@latest zod client-only server-only</pre><p>Here’s what each package does:</p><ul><li>@trpc/server - Server-side tRPC utilities</li><li>@trpc/client - Client-side tRPC utilities</li><li>@trpc/react-query - React Query integration for tRPC</li><li>@tanstack/react-query - The actual React Query library</li><li>zod - Runtime type validation (tRPC&#39;s preferred validation library)</li><li>client-only &amp; server-only - Next.js utilities to prevent code from running in wrong environment</li></ul><p>With the packages installed, let’s start building our type-safe API layer.</p><h3>Create a tRPC Router</h3><p>Now we’ll initialize the tRPC backend and create our first router. We’ll start with a simple “hello world” example to make sure everything works before adding more complex logic.</p><p>1) Initialize tRPC<br>First, create a trpc folder, then create init.ts file in it like this trpc/init.ts to set up the tRPC instance:</p><pre>//Add this in trpc/init.ts<br><br>import { initTRPC } from &#39;@trpc/server&#39;;<br>import { cache } from &#39;react&#39;;<br>export const createTRPCContext = cache(async () =&gt; {<br>  /**<br>   * @see: https://trpc.io/docs/server/context<br>   */<br>  return { userId: &#39;user_123&#39; };<br>});<br>// Avoid exporting the entire t-object<br>// since it&#39;s not very descriptive.<br>// For instance, the use of a t variable<br>// is common in i18n libraries.<br>const t = initTRPC.create({<br>  /**<br>   * @see https://trpc.io/docs/server/data-transformers<br>   */<br>  // transformer: superjson,<br>});<br>// Base router and procedure helpers<br>export const createTRPCRouter = t.router;<br>export const createCallerFactory = t.createCallerFactory;<br>export const baseProcedure = t.procedure;<br></pre><p>Add this in trpc/routers/_app.ts, what this means is you create a routers folder in trpc and a file in the routers folder called _app.ts</p><pre>//Add in trpc/routers/_app.ts<br><br>import { z } from &#39;zod&#39;;<br>import { baseProcedure, createTRPCRouter } from &#39;../init&#39;;<br>export const appRouter = createTRPCRouter({<br>  hello: baseProcedure<br>    .input(<br>      z.object({<br>        text: z.string(),<br>      }),<br>    )<br>    .query((opts) =&gt; {<br>      return {<br>        greeting: `hello ${opts.input.text}`,<br>      };<br>    }),<br>});<br>// export type definition of API<br>export type AppRouter = typeof appRouter;</pre><p>Add the code below in this path app/api/trpc/[trpc]/route.ts</p><pre>// add in app/api/trpc/[trpc]/route.ts<br><br>import { fetchRequestHandler } from &#39;@trpc/server/adapters/fetch&#39;;<br>import { createTRPCContext } from &#39;@/trpc/init&#39;;<br>import { appRouter } from &#39;@/trpc/routers/_app&#39;;<br>const handler = (req: Request) =&gt;<br>  fetchRequestHandler({<br>    endpoint: &#39;/api/trpc&#39;,<br>    req,<br>    router: appRouter,<br>    createContext: createTRPCContext,<br>  });<br>export { handler as GET, handler as POST };</pre><p>2) Create a Query Client factory</p><p>In React Query, the QueryClient is like your app’s <strong>data warehouse manager</strong>. It stores all the data from your queries, knows when to refetch it, and handles caching, background updates, and more.</p><p>Instead of creating one manually each time, we define a makeQueryClient() function that builds one with sensible defaults.</p><p>Create it in this path <strong><em>trpc/query-client.ts</em></strong></p><pre>// add in trpc/query-client.ts<br><br>import {<br>  defaultShouldDehydrateQuery,<br>  QueryClient,<br>} from &quot;@tanstack/react-query&quot;;<br>// import superjson from &#39;superjson&#39;;<br>export function makeQueryClient() {<br>  return new QueryClient({<br>    defaultOptions: {<br>      queries: {<br>        staleTime: 30 * 1000,<br>      },<br>      dehydrate: {<br>        // serializeData: superjson.serialize,<br>        shouldDehydrateQuery: (query) =&gt;<br>          defaultShouldDehydrateQuery(query) ||<br>          query.state.status === &quot;pending&quot;,<br>      },<br>      hydrate: {<br>        // deserializeData: superjson.deserialize,<br>      },<br>    },<br>  });<br>}</pre><p>3) Create a tRPC client for Client Components</p><pre>// Add in trpc/client.tsx<br><br>&#39;use client&#39;;<br>// ^-- to make sure we can mount the Provider from a server component<br>import type { QueryClient } from &#39;@tanstack/react-query&#39;;<br>import { QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { createTRPCClient, httpBatchLink } from &#39;@trpc/client&#39;;<br>import { createTRPCContext } from &#39;@trpc/tanstack-react-query&#39;;<br>import { useState } from &#39;react&#39;;<br>import { makeQueryClient } from &#39;./query-client&#39;;<br>import type { AppRouter } from &#39;./routers/_app&#39;;<br>export const { TRPCProvider, useTRPC } = createTRPCContext&lt;AppRouter&gt;();<br>let browserQueryClient: QueryClient;<br>function getQueryClient() {<br>  if (typeof window === &#39;undefined&#39;) {<br>    // Server: always make a new query client<br>    return makeQueryClient();<br>  }<br>  // Browser: make a new query client if we don&#39;t already have one<br>  // This is very important, so we don&#39;t re-make a new client if React<br>  // suspends during the initial render. This may not be needed if we<br>  // have a suspense boundary BELOW the creation of the query client<br>  if (!browserQueryClient) browserQueryClient = makeQueryClient();<br>  return browserQueryClient;<br>}<br>function getUrl() {<br>  const base = (() =&gt; {<br>    if (typeof window !== &#39;undefined&#39;) return &#39;&#39;;<br>    if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;<br>    return &#39;http://localhost:3000&#39;;<br>  })();<br>  return `${base}/api/trpc`;<br>}<br>export function TRPCReactProvider(<br>  props: Readonly&lt;{<br>    children: React.ReactNode;<br>  }&gt;,<br>) {<br>  // NOTE: Avoid useState when initializing the query client if you don&#39;t<br>  //       have a suspense boundary between this and the code that may<br>  //       suspend because React will throw away the client on the initial<br>  //       render if it suspends and there is no boundary<br>  const queryClient = getQueryClient();<br>  const [trpcClient] = useState(() =&gt;<br>    createTRPCClient&lt;AppRouter&gt;({<br>      links: [<br>        httpBatchLink({<br>          // transformer: superjson, &lt;-- if you use a data transformer<br>          url: getUrl(),<br>        }),<br>      ],<br>    }),<br>  );<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;TRPCProvider trpcClient={trpcClient} queryClient={queryClient}&gt;<br>        {props.children}<br>      &lt;/TRPCProvider&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><blockquote>Note : Most of these code are boiler plate code and can easily be found in the tRPC documentation</blockquote><p>4) Create a tRPC caller for Server Components</p><p>To prefetch queries from server components, we create a proxy from our router. You can also pass in a client if your router is on a separate server.</p><pre>/trpc/server.tsx<br><br>import &quot;server-only&quot;; // &lt;-- ensure this file cannot be imported from the client<br>import { createTRPCOptionsProxy } from &quot;@trpc/tanstack-react-query&quot;;<br>import { cache } from &quot;react&quot;;<br>import { createTRPCContext } from &quot;./init&quot;;<br>import { makeQueryClient } from &quot;./query-client&quot;;<br>import { appRouter } from &quot;./routers/_app&quot;;<br>// IMPORTANT: Create a stable getter for the query client that<br>//            will return the same client during the same request.<br>export const getQueryClient = cache(makeQueryClient);<br>export const trpc = createTRPCOptionsProxy({<br>  ctx: createTRPCContext,<br>  router: appRouter,<br>  queryClient: getQueryClient,<br>});<br>// If your router is on a separate server, pass a client:<br>// createTRPCOptionsProxy({<br>//   client: createTRPCClient({<br>//     links: [httpLink({ url: &#39;...&#39; })],<br>//   }),<br>//   queryClient: getQueryClient,<br>// });</pre><p>5) Wrap your app in the TRPCReactProvider by updating your layout.tsx</p><pre>import { TRPCReactProvider } from &quot;@/trpc/client&quot;;<br>import &quot;./globals.css&quot;;<br>import { Navbar } from &quot;@/components/navbar&quot;;<br><br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;Navbar /&gt;<br>        &lt;TRPCReactProvider&gt;{children}&lt;/TRPCReactProvider&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>6) Now let’s add Prisma to the mix</p><p>In your terminal run these commands</p><pre>npm install prisma --save-dev<br>npm install @prisma/client @prisma/extension-accelerate</pre><pre>npx prisma init</pre><p>7) Next, we need to create a .env file if you don’t already have one — but you most likely will after running the previous commands.</p><p>Inside your .env, add the following line:</p><pre>DATABASE_URL=postgresql://postgres:password@localhost:5432/myapp</pre><p>Now you might be wondering how I got this connection string.<br> This is for a PostgreSQL instance running in Docker.</p><p>If you already have Docker Desktop installed, you can create a file named docker-compose.yml in the root of your project and add the following code:</p><pre>version: &quot;3.8&quot;<br><br>services:<br>  postgres:<br>    image: postgres:15<br>    container_name: local_postgres<br>    environment:<br>      POSTGRES_DB: myapp<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: password<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>      - ./init-scripts:/docker-entrypoint-initdb.d<br>    restart: unless-stopped<br><br>volumes:<br>  postgres_data:</pre><p>Then in your terminal, run:</p><pre>docker compose up -d</pre><p>This will start your local PostgreSQL server in the background, ready for your Prisma project to connect.</p><blockquote><strong><em>Note:</em></strong><em> Make sure the </em><strong><em>Docker Desktop app is running</em></strong><em> while you execute this command. It can stay minimized, but it must be running in the background — otherwise, the setup may fail.</em></blockquote><blockquote><em>Also, if the container doesn’t start automatically, you might need to </em><strong><em>manually press the “Start” (▶️) button</em></strong><em> in the Docker Desktop UI.</em></blockquote><p><strong>Next:</strong> If you don’t have Docker installed, you can get a <strong>free PostgreSQL instance</strong> from a service like <a href="https://neon.tech/"><strong>Neon</strong></a> or <a href="https://supabase.com/"><strong>Supabase</strong></a>.</p><p>These platforms offer <strong>free-tier hosted PostgreSQL databases</strong> with zero local setup. After creating an account and setting up a project, you’ll get a connection string like:</p><pre>DATABASE_URL=postgresql://username:password@your-db-url/project</pre><p>Paste in your .env and you’re good</p><p>8) Navigate to the prisma folder and locate the schema.prisma file. Replace its contents with the following example schema:</p><pre>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}<br><br>datasource db {<br>  provider = &quot;postgresql&quot;<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}<br><br>model User {<br>  id        String    @id @default(cuid())<br>  email     String    @unique<br>  name      String?<br>  posts     Post[]<br>  comments  Comment[]<br>  createdAt DateTime  @default(now())<br>}<br><br>model Post {<br>  id        String    @id @default(cuid())<br>  title     String<br>  content   String?<br>  published Boolean   @default(false)<br>  author    User      @relation(fields: [authorId], references: [id])<br>  authorId  String<br>  comments  Comment[]<br>  createdAt DateTime  @default(now())<br>}<br><br>model Comment {<br>  id        String   @id @default(cuid())<br>  content   String<br>  post      Post     @relation(fields: [postId], references: [id])<br>  postId    String<br>  author    User     @relation(fields: [authorId], references: [id])<br>  authorId  String<br>  createdAt DateTime @default(now())<br>}</pre><p>9) Next, run these commands in your terminal to generate the Prisma client and create your database tables:</p><pre>npx prisma generate<br>npx prisma migrate dev</pre><p>Here’s what they do:</p><ul><li>npx prisma generate: This creates the <strong>Prisma Client</strong>, a type-safe way to interact with your database in code. You’ll import this client to run queries like prisma.user.findMany() later on.</li><li>npx prisma migrate dev: This creates a new <strong>migration file</strong> based on your Prisma schema, applies it to your database, and updates the Prisma Client. It’s perfect for development because it keeps your database in sync with your schema changes.</li></ul><p>10) Now let’s set up a reusable Prisma Client instance to interact with the database.</p><p>In your project, create a new file at:</p><p>/lib/prisma.ts</p><p>Then add the following code:</p><pre>import { PrismaClient } from &quot;@prisma/client&quot;;<br>import { withAccelerate } from &quot;@prisma/extension-accelerate&quot;;<br><br>const globalForPrisma = global as unknown as {<br>  prisma: PrismaClient;<br>};<br><br>const prisma =<br>  globalForPrisma.prisma || new PrismaClient().$extends(withAccelerate());<br><br>if (process.env.NODE_ENV !== &quot;production&quot;) globalForPrisma.prisma = prisma;<br><br>export default prisma;</pre><p>11) Now that Prisma has been added, we need to make a small but important change to the first file we created: trpc/init.ts We’ll modify this file to inject the Prisma Client into our tRPC context, making it available in all procedures without manual imports.</p><p>It’s not a huge change, but it will <strong>save you a lot of code repetition</strong> later when writing procedures or queries.</p><pre>import prisma from &quot;@/lib/prisma&quot;;<br>import { initTRPC } from &quot;@trpc/server&quot;;<br>import { cache } from &quot;react&quot;;<br>export const createTRPCContext = cache(async () =&gt; {<br>  /**<br>   * @see: https://trpc.io/docs/server/context<br>   */<br>  return { userId: &quot;user_123&quot; };<br>});<br>// Avoid exporting the entire t-object<br>// since it&#39;s not very descriptive.<br>// For instance, the use of a t variable<br>// is common in i18n libraries.<br>const t = initTRPC.create({<br>  /**<br>   * @see https://trpc.io/docs/server/data-transformers<br>   */<br>  // transformer: superjson,<br>});<br>// Base router and procedure helpers<br>export const createTRPCRouter = t.router;<br>export const createCallerFactory = t.createCallerFactory;<br>export const baseProcedure = t.procedure.use(async ({ next }) =&gt; {<br>  return next({<br>    ctx: { db: prisma },<br>  });<br>});</pre><h3>Why this matters:</h3><ul><li>Now every procedure (query/mutation) that uses baseProcedure will automatically have access to ctx.db (your Prisma instance).</li><li>This avoids needing to import Prisma manually in every router file.</li><li>Keeps your tRPC layer <strong>clean, reusable, and testable</strong>.</li></ul><p>12) Now let’s update the trpc/routers/_app.ts file we created earlier.</p><p>Previously, it looked like this:</p><pre>// trpc/routers/_app.ts<br><br>import { z } from &quot;zod&quot;;<br>import { baseProcedure, createTRPCRouter } from &quot;../init&quot;;<br><br>export const appRouter = createTRPCRouter({<br>  hello: baseProcedure<br>    .input(<br>      z.object({<br>        text: z.string(),<br>      })<br>    )<br>    .query((opts) =&gt; {<br>      return {<br>        greeting: `hello ${opts.input.text}`,<br>      };<br>    }),<br>});<br><br>// Export type definition of API<br>export type AppRouter = typeof appRouter;</pre><p>Let’s replace this with a modular approach that organizes our API logic into dedicated router files (blog, auth, user, etc.) for better maintainability.</p><pre>// trpc/routers/_app.ts<br><br>import { blogRouter } from &quot;@/modules/blog/server/procedures&quot;;<br>import { createTRPCRouter } from &quot;../init&quot;;<br><br>export const appRouter = createTRPCRouter({<br>  blog: blogRouter,<br>});<br><br>// Export type definition of API<br>export type AppRouter = typeof appRouter;</pre><p>This sets up your main appRouter and pulls in the blogRouter — which handles all blog-related queries and mutations.</p><h3>Now Create the Blog Router</h3><p>In a new file (e.g. modules/blog/server/procedures.ts), add:<br>The file can be located in any folder of your choice just make sure you are importing it correctly</p><pre>import { baseProcedure, createTRPCRouter } from &quot;@/trpc/init&quot;;<br>import z from &quot;zod&quot;;<br><br>export const blogRouter = createTRPCRouter({<br>  getOne: baseProcedure<br>    .input(z.object({ id: z.string() }))<br>    .query(({ ctx, input }) =&gt; {<br>      return ctx.db.post.findUnique({<br>        where: { id: input.id },<br>      });<br>    }),<br><br>  getAll: baseProcedure.query(({ ctx }) =&gt; {<br>    return ctx.db.post.findMany();<br>  }),<br>});</pre><p><strong>14)</strong> Seed Your Database</p><p>Create a new file at the root of your project: /seed.ts <br>First, install the Faker library for generating test data:</p><pre>npm install @faker-js/faker</pre><pre>import { PrismaClient } from &quot;@prisma/client&quot;;<br>import { faker } from &quot;@faker-js/faker&quot;;<br><br>const prisma = new PrismaClient();<br><br>async function main() {<br>  console.log(&quot;🌱 Seeding...&quot;);<br><br>  // Optional: clear existing data<br>  await prisma.comment.deleteMany();<br>  await prisma.post.deleteMany();<br>  await prisma.user.deleteMany();<br><br>  for (let i = 0; i &lt; 5; i++) {<br>    const user = await prisma.user.create({<br>      data: {<br>        email: faker.internet.email().toLowerCase(),<br>        name: faker.person.fullName(),<br>      },<br>    });<br><br>    const postCount = faker.number.int({ min: 2, max: 3 });<br><br>    for (let j = 0; j &lt; postCount; j++) {<br>      const post = await prisma.post.create({<br>        data: {<br>          title: faker.lorem.sentence(),<br>          content: faker.lorem.paragraph(),<br>          published: faker.datatype.boolean(),<br>          authorId: user.id,<br>        },<br>      });<br><br>      const commentCount = faker.number.int({ min: 1, max: 4 });<br><br>      for (let k = 0; k &lt; commentCount; k++) {<br>        // Pick a random existing user to be the commenter<br>        const commenters = await prisma.user.findMany();<br>        const randomUser =<br>          commenters[faker.number.int({ min: 0, max: commenters.length - 1 })];<br><br>        await prisma.comment.create({<br>          data: {<br>            content: faker.lorem.sentence(),<br>            postId: post.id,<br>            authorId: randomUser.id,<br>          },<br>        });<br>      }<br>    }<br>  }<br><br>  console.log(&quot;✅ Seed complete&quot;);<br>}<br><br>main()<br>  .catch((e) =&gt; {<br>    console.error(e);<br>    process.exit(1);<br>  })<br>  .finally(() =&gt; prisma.$disconnect());</pre><p>Then in your package.json file at the root of your project add :</p><pre>&quot;scripts&quot;: {<br>  &quot;seed&quot;: &quot;ts-node prisma/seed.ts&quot;<br>}</pre><p>Make sure ts-node is installed:</p><pre>npm install -D ts-node</pre><p>Run the seed</p><pre>npm run seed</pre><h3>After This</h3><ul><li>Your DB has real data</li><li>Your blogRouter.getAll() should return some fake blog posts</li><li>You’re ready to move into <strong>frontend integration</strong> (e.g., use api.blog.getAll.useQuery())</li></ul><p>Now you can fetch data from your database using the following pattern:</p><pre>&quot;use client&quot;;<br>import { useTRPC } from &quot;@/trpc/client&quot;;<br>import { useQuery } from &quot;@tanstack/react-query&quot;;<br><br>const Page = () =&gt; {<br>  const trpc = useTRPC();<br>  const { data, isLoading } = useQuery(trpc.blog.getAll.queryOptions());<br><br>  if (isLoading) {<br>    return &lt;div&gt;Loading...&lt;/div&gt;;<br>  }<br>  return (<br>    &lt;div className=&quot; grid grid-cols-3 gap-5&quot;&gt;<br>      {data?.map((blog) =&gt; (<br>        &lt;div className=&quot;border&quot; key={blog.id}&gt;<br>          {blog.title}<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Page;</pre><p>This demonstrates the simplest form of data fetching using React Query (TanStack Query)</p><p>Thanks for following along with this complete setup guide to integrating tRPC and React Query in your Next.js app! 🎉</p><p>You now have a solid, type-safe foundation for building scalable full-stack applications without the headache of manual data fetching and boilerplate code.</p><p>While this guide focused on querying and fetching data, keep in mind that tRPC also fully supports <strong>mutations</strong> — allowing you to create, update, and delete data seamlessly. We just didn’t cover mutations here to keep things simple and focused.</p><p>If you found this guide helpful, be sure to follow me for more deep dives and hands-on tutorials, including:</p><ul><li>How to perform mutations and update your database with tRPC</li><li>Managing authentication and authorization</li><li>Real-time subscriptions and live updates</li><li>Advanced caching and query invalidation with React Query</li><li>And much more practical, production-ready tips</li></ul><p>Stay tuned and happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7658b802a398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed Routing Issues for My Next.js Static Site on cPanel]]></title>
            <link>https://medium.com/@briankaine1604/how-i-fixed-routing-issues-for-my-next-js-static-site-on-cpanel-23bb776da035?source=rss-e7c572fc0a01------2</link>
            <guid isPermaLink="false">https://medium.com/p/23bb776da035</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[cpanel]]></category>
            <dc:creator><![CDATA[Briankaine]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 00:48:18 GMT</pubDate>
            <atom:updated>2024-07-13T00:48:18.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zE_2lbgWSR3cTJwyHAODQ.jpeg" /></figure><p>Hosting a static site is a straightforward process, but sometimes unexpected issues arise and can be tricky to resolve. Recently, I encountered a routing issue while hosting my Next.js static site on cPanel.</p><p><strong>The problem?</strong> Whenever I refreshed a page or tried to navigate directly to a route other than the homepage, I was greeted with a dreaded 404 error. This indicated, that my site’s routing was broken, making it inaccessible beyond the homepage.</p><p>This article details the problem, the solutions I tried, and ultimately the fix. If you’re experiencing similar issues, this guide should help you get your Next.js static site running smoothly on cPanel.</p><h4>Identifying the Problem</h4><p>To fix the problem, I needed to understand how Next.js handles routing, especially in a static site. Static sites are pre-rendered, which means all routes must be known at build time. In contrast, a server with dynamic rendering handles routes on the fly. However, with static sites hosted on cPanel, the server doesn’t inherently know how to manage routes beyond the root. Next.js uses client-side routing, meaning that when you navigate to a different route, the content is fetched dynamically without reloading the entire page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHy0OetiGDnCP_kjfk8B7Q.png" /></figure><h4>Initial Attempts and Solutions</h4><p>My first thought was to modify the .htaccess file to handle the routing. However, this approach didn’t fully resolve the issue. While it prevented the 404 error, it redirected back to the homepage but left the URL unchanged, leading to a confusing user experience.</p><pre>&lt;IfModule mod_rewrite.c&gt;<br>  RewriteEngine On<br>  RewriteBase /<br>  RewriteRule ^index\.html$ - [L]<br>  RewriteCond %{REQUEST_FILENAME} !-f<br>  RewriteCond %{REQUEST_FILENAME} !-d<br>  RewriteCond %{REQUEST_FILENAME} !-l<br>  RewriteRule . /index.html [L]<br>&lt;/IfModule&gt;</pre><h4>Finding the Right Solution</h4><p>After some research, I discovered that Next.js offers a trailingSlash option in the next.config.js file. This option ensures that all routes are treated with a trailing slash, which aligns better with how static files are served.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCYkkL805uVT3qy0DAoKag.jpeg" /></figure><h4>Implementing the Solution</h4><p>To resolve the issue, I added the trailingSlash:true option to my next.config.js file and re-exported my project. This step-by-step guide will show you how to do the same</p><pre>/** @type {import(&#39;next&#39;).NextConfig} */<br>const nextConfig = {<br>  output: &quot;export&quot;,<br>  reactStrictMode: true,<br>  trailingSlash: true,<br>  images: {<br>    unoptimized: true,<br>  },<br>  exportPathMap: async function (<br>    defaultPathMap,<br>    { dev, dir, outDir, distDir, buildId }<br>  ) {<br>    return {<br>      &quot;/&quot;: { page: &quot;/&quot; },<br>      &quot;/about&quot;: { page: &quot;/about&quot; },<br>      &quot;/projects&quot;: { page: &quot;/&quot; },<br>    };<br>  },<br>};<br><br>export default nextConfig;</pre><h4>Exporting the Project</h4><p>Once the trailingSlash option was set, I needed to re-export my Next.js project and upload it to cPanel again. Here’s how to do it:</p><ol><li>Before you build the project ensure you have added output:&quot;export&quot; to the next config, this is a compulsory requirement for static hosting</li><li>Because you are doing an export, it does not support image optimization, you need to add<br>images: {<br> unoptimized: true<br> }</li><li>Additionally include this section too</li></ol><pre>  exportPathMap: async function (<br>    defaultPathMap,<br>    { dev, dir, outDir, distDir, buildId }<br>  ) {<br>    return {<br>      &quot;/&quot;: { page: &quot;/&quot; },<br>      &quot;/about&quot;: { page: &quot;/about&quot; },<br>      &quot;/projects&quot;: { page: &quot;/&quot; },<br>    };<br>  },</pre><p>This ensures that</p><ul><li>The root route (&quot;/&quot;) is correctly mapped to the home page component (&quot;/&quot;).</li><li>The /about route is correctly mapped to the about page component (&quot;/about&quot;).</li><li>The /projects route is mapped to the home page component (&quot;/&quot;) because the projects are also located on the homepage.</li></ul><p><strong>…..Finally</strong>, Run npm run build after ensuring you have added the above. You will notice an extra folder called out has appeared. This folder contains the files you will upload to the panel. Convert the out to a .zip folder (Some Cpanel’s do not support folder upload or .rar) and then upload to the public_html in your file manager or for some www depending on your service provider and unzip it and make sure the contents are directly in the public_html, not the out folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VosPqzuGFQQxI99ML6hQVA.png" /><figcaption>My Cpanel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtCkY40HARNQNptD4K_LWw.png" /><figcaption>Upload the out folder and unzip in the public_html</figcaption></figure><h4>Testing the Solution</h4><p>After deploying the updated project, it’s crucial to test by navigating to different routes and refreshing the pages to ensure the 404 error no longer appears.</p><h4>Conclusion</h4><p>By enabling the trailingSlash and other suggested options in next.config.js and properly configuring your .htaccess file, you can ensure smooth routing and avoid 404 errors when refreshing or directly accessing routes beyond the homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heK_l2_T2X_kxBeetECJUg.jpeg" /><figcaption>Problem fixed</figcaption></figure><p>If you’re facing similar routing issues with your Next.js static site, try implementing the solutions outlined in this article. To view the site I was working on check <a href="http://briankaine.com/"><strong><em>briankaine.com</em></strong></a>. Feel free to leave comments or reach out if you have any questions or need further assistance.</p><p>You can also follow me on Medium for more web development tips and tutorials, or connect with me on <a href="https://www.linkedin.com/in/brian-ikeogu-876023199/">LinkedIn</a>. Your feedback and questions are always welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23bb776da035" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>