<?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 Titus Efferian on Medium]]></title>
        <description><![CDATA[Stories by Titus Efferian on Medium]]></description>
        <link>https://medium.com/@titusefferian?source=rss-7d2073714e16------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MU-GrsbLtvjPzp9nwZhNlg.jpeg</url>
            <title>Stories by Titus Efferian on Medium</title>
            <link>https://medium.com/@titusefferian?source=rss-7d2073714e16------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:04:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@titusefferian/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[Rust vs JavaScript: Achieving 66% Faster Performance with WebAssembly]]></title>
            <link>https://levelup.gitconnected.com/rust-vs-javascript-achieving-66-faster-performance-with-webassembly-eea7e38266c8?source=rss-7d2073714e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea7e38266c8</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Titus Efferian]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 16:02:10 GMT</pubDate>
            <atom:updated>2024-09-12T16:02:10.514Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discover how Web Workers and WebAssembly can dramatically improve your JavaScript app’s performance, using the Fibonacci algorithm as a case study.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zSjVUr4hTwtr5Dt9IS0Ww.png" /><figcaption>Illustration showing a comparison between JavaScript and AssemblyScript versus Rust with WebAssembly</figcaption></figure><p>JavaScript typically runs on a single thread, often referred to as the <br>“main thread.” This means that JavaScript executes one task at a time in a synchronous manner. The main thread also handles rendering tasks such as painting and layout, along with user interactions, meaning that long-running JavaScript tasks can cause the browser to become unresponsive. This is why web pages may “freeze” when a heavy JavaScript function runs, blocking user interactions</p><p>We are going to demonstrate how to block the main thread by simulating heavy computation using the Fibonacci algorithm, and we will solve the blocked main thread using several approaches such as:</p><ul><li>multi-threaded (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Web Worker</a>),</li><li>WebAssembly using <a href="https://www.assemblyscript.org/">AssemblyScript</a>,</li><li>WebAssembly using <a href="https://www.rust-lang.org/what/wasm">Rust</a>.</li></ul><h4>Fibonacci Algorithm</h4><p>We are going to use the simple and very common Fibonacci algorithm with a time complexity of O(2^n) for all of our case studies in this article.</p><pre>const calculateFibonacci = (n: number): number =&gt; {<br>  if (n &lt;= 1) return n;<br>  return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);<br>};</pre><h4>Single Thread</h4><p>Now, let’s implement the Fibonacci algorithm directly on the main thread. Simply call the Fibonacci function when the button is clicked.</p><pre>&quot;use client&quot;;<br>import { useState } from &quot;react&quot;;<br><br>/**<br> * simulate loading animation<br> */<br>function Spinner() {<br>  return (<br>    &lt;div className=&quot;flex justify-center items-center&quot;&gt;<br>      &lt;div className=&quot;animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-blue-500&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default function Home() {<br>  const [result, setResult] = useState&lt;number | null&gt;(null);<br>  const [isLoading, setIsLoading] = useState&lt;boolean&gt;(false);<br><br>  const calculateFibonacci = (n: number): number =&gt; {<br>    if (n &lt;= 1) return n;<br>    return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);<br>  };<br><br>  const handleCalculate = () =&gt; {<br>    setIsLoading(true);<br>    /**<br>     * simulate a long-running calculation<br>     */<br>    const result = calculateFibonacci(42);<br>    setResult(result);<br>    setIsLoading(false);<br>  };<br><br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center min-h-screen bg-gray-900 text-white&quot;&gt;<br>      &lt;button<br>        onClick={handleCalculate}<br>        className=&quot;mb-8 px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition&quot;<br>      &gt;<br>        Calculate Fibonacci<br>      &lt;/button&gt;<br>      {isLoading ? &lt;Spinner /&gt; : &lt;p className=&quot;text-xl&quot;&gt;Result: {result}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now, let’s try clicking the ‘Calculate Fibonacci’ button while measuring performance. To measure the performance of our code, we can use the performance tools in Chrome DevTools.</p><p>As you can see in the UI, our spinner button doesn’t even appear and instead suddenly shows the calculation result. We can also see from the performance tools that our spinning animation is blocked by the heavy computation of the Fibonacci algorithm on the main thread for about <strong>2.06 seconds</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*RQkDZ2bPSJIMCpO8ypPblQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QoNlkcpM71ZrjkmmyupBA.png" /><figcaption>Performance tools showing the main thread being blocked for 2 seconds.</figcaption></figure><h4>Multi-Threaded (Web Worker)</h4><p>The common approach for offloading heavy computation from the main thread is using a Web Worker.</p><pre>/**<br> * move the fibonacci algorithm to web worker<br> */<br>self.addEventListener(&quot;message&quot;, function (e) {<br>  const n = e.data;<br><br>  const fibonacci = (n) =&gt; {<br>    if (n &lt;= 1) return n;<br>    return fibonacci(n - 1) + fibonacci(n - 2);<br>  };<br><br>  const result = fibonacci(n);<br>  self.postMessage(result);<br>});</pre><pre>&quot;use client&quot;;<br>import { useState } from &quot;react&quot;;<br><br>function Spinner() {<br>  return (<br>    &lt;div className=&quot;flex justify-center items-center&quot;&gt;<br>      &lt;div className=&quot;animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-blue-500&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default function Home() {<br>  const [result, setResult] = (useState &lt; number) | (null &gt; null);<br>  const [isLoading, setIsLoading] = useState &lt; boolean &gt; false;<br><br>  /**<br>   * instead of running the fibonacci function in the main thread,<br>   * we will run it in a web worker<br>   */<br>  const handleCalculate = () =&gt; {<br>    setIsLoading(true);<br><br>    const worker = new Worker(<br>      new URL(&quot;./fibonacci-worker.js&quot;, import.meta.url),<br>    );<br><br>    worker.postMessage(42);<br><br>    worker.onmessage = (e) =&gt; {<br>      setResult(e.data);<br>      setIsLoading(false);<br>      worker.terminate();<br>    };<br>  };<br><br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center min-h-screen bg-gray-900 text-white&quot;&gt;<br>      &lt;button<br>        onClick={handleCalculate}<br>        className=&quot;mb-8 px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition&quot;<br>      &gt;<br>        Calculate Fibonacci<br>      &lt;/button&gt;<br>      {isLoading ? &lt;Spinner /&gt; : &lt;p className=&quot;text-xl&quot;&gt;Result: {result}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now, if we try to measure, the spinner animation runs smoothly. This is because we offloaded the heavy computation to a worker thread, avoiding blocking the main thread.</p><p>As you can see, both the single-threaded and worker-threaded computations take a similar duration of around 2 seconds. The question now is, how can we improve this? The answer is by using WebAssembly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EVNGB6hPdl0GJX5CX8ZtNA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IoipxgZCaALdjluLLoBfPA.png" /><figcaption>Performance tools showing that heavy computation now runs on a worker.</figcaption></figure><h4>WebAssembly — AssemblyScript</h4><p>As a frontend engineer with limited experience in other languages who wants to try WebAssembly, we typically choose AssemblyScript because it offers a developer experience closest to TypeScript.</p><p>Here is the equivalent Fibonacci code written in AssemblyScript.</p><pre>export function fibonacci(n: i32): i32 {<br>  if (n &lt;= 1) return n;<br>  return fibonacci(n - 1) + fibonacci(n - 2);<br>}</pre><p>If we compile that code, it will generate a release.wasm file. We can then use this Wasm file in our JavaScript codebase.</p><pre>&quot;use client&quot;;<br>import { useState } from &quot;react&quot;;<br><br>function Spinner() {<br>  return (<br>    &lt;div className=&quot;flex justify-center items-center&quot;&gt;<br>      &lt;div className=&quot;animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-blue-500&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default function Home() {<br>  const [result, setResult] = (useState &lt; number) | (null &gt; null);<br>  const [isLoading, setIsLoading] = useState &lt; boolean &gt; false;<br><br>  const handleCalculate = async () =&gt; {<br>    setIsLoading(true);<br><br>    // Load and instantiate the WebAssembly module<br>    const wasmModule = await fetch(&quot;/release.wasm&quot;);<br>    const buffer = await wasmModule.arrayBuffer();<br>    const module = await WebAssembly.instantiate(buffer);<br>    const wasm = module.instance.exports;<br><br>    // Call the Fibonacci function from the WebAssembly module<br>    const fibResult = wasm.fibonacci(42);<br><br>    setResult(fibResult);<br>    setIsLoading(false);<br>  };<br><br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center min-h-screen bg-gray-900 text-white&quot;&gt;<br>      &lt;button<br>        onClick={handleCalculate}<br>        className=&quot;mb-8 px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition&quot;<br>      &gt;<br>        Calculate Fibonacci<br>      &lt;/button&gt;<br>      {isLoading ? &lt;Spinner /&gt; : &lt;p className=&quot;text-xl&quot;&gt;Result: {result}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now, if we measure this again, even though we are still on the main thread, the loading animation appears and is not blocked by the heavy computation. The Fibonacci algorithm now takes around <strong>950ms</strong>, which is <strong>53% faster than using only JavaScript</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Iphruoe6rwPXXgcpRyihNQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkKsFBT3gntDCpAnUp49Kg.png" /><figcaption>Performance tools showing AssemblyScript is 53% faster than JavaScript.</figcaption></figure><h4>WebAssembly — Rust</h4><p>Rust is one of the popular choices for WebAssembly, as highlighted by Mozilla’s official documentation. Let’s try to implement the same Fibonacci algorithm, but written in Rust.</p><pre>use wasm_bindgen::prelude::*;<br><br>// Expose the function to JavaScript through WebAssembly<br>#[wasm_bindgen]<br>pub fn fibonacci(n: u32) -&gt; u32 {<br>    match n {<br>        0 =&gt; 0,<br>        1 =&gt; 1,<br>        _ =&gt; fibonacci(n - 1) + fibonacci(n - 2),<br>    }<br>}</pre><pre>&quot;use client&quot;;<br>import { useState } from &quot;react&quot;;<br><br>function Spinner() {<br>  return (<br>    &lt;div className=&quot;flex justify-center items-center&quot;&gt;<br>      &lt;div className=&quot;animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-blue-500&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default function Home() {<br>  const [result, setResult] = (useState &lt; number) | (null &gt; null);<br>  const [isLoading, setIsLoading] = useState &lt; boolean &gt; false;<br><br>  const handleCalculate = async () =&gt; {<br>    setIsLoading(true);<br><br>    // Load and instantiate the WebAssembly module<br>    const wasmModule = await fetch(&quot;/pkg/rust_wasm_fibonacci_bg.wasm&quot;); // Use the actual wasm file<br>    const buffer = await wasmModule.arrayBuffer();<br><br>    const module = await WebAssembly.instantiate(buffer);<br>    const wasm = module.instance.exports;<br><br>    // Call the Fibonacci function from the WebAssembly module<br>    const fibResult = wasm.fibonacci(42); // Assuming the function is exported as &#39;fibonacci&#39;<br><br>    setResult(fibResult);<br>    setIsLoading(false);<br>  };<br><br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center min-h-screen bg-gray-900 text-white&quot;&gt;<br>      &lt;button<br>        onClick={handleCalculate}<br>        className=&quot;mb-8 px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition&quot;<br>      &gt;<br>        Calculate Fibonacci<br>      &lt;/button&gt;<br>      {isLoading ? &lt;Spinner /&gt; : &lt;p className=&quot;text-xl&quot;&gt;Result: {result}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now, let’s examine the result of using WebAssembly with Rust. We’re still using the main thread, but now with the Wasm. Similar to AssemblyScript, even though we’re running this Wasm on the main thread, the loading animation still appears and is not blocked. The amazing thing is that this heavy computation now takes only <strong>684ms</strong>, which is <strong>66% faster than using just JavaScript.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*osMLgSTVO4H1Ls09-ouW7A.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HFU1eXHdUk2C0z4uLzQPA.png" /><figcaption>Performance tools showing Rust is 66% faster than JavaScript.</figcaption></figure><h4>TL;DR and Conclusion</h4><ul><li>Heavy computation will block the main thread and stop all animations.</li><li>Heavy computation can be offloaded to a Web Worker.</li><li>Heavy computation can be improved by rewriting the logic in WebAssembly. Using the Fibonacci algorithm as a case study, we obtained the following results:<br>- JavaScript: 2s<br>- WebAssembly — AssemblyScript: 953ms<strong> (53% faster than JavaScript)</strong><br>- WebAssembly — Rust: 684ms<strong> (66% faster than JavaScript)</strong></li></ul><h4>References</h4><ul><li><a href="https://www.assemblyscript.org/">https://www.assemblyscript.org/</a></li><li><a href="https://www.rust-lang.org/what/wasm">https://www.rust-lang.org/what/wasm</a></li><li><a href="https://developer.mozilla.org/en-US/docs/WebAssembly">https://developer.mozilla.org/en-US/docs/WebAssembly</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea7e38266c8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/rust-vs-javascript-achieving-66-faster-performance-with-webassembly-eea7e38266c8">Rust vs JavaScript: Achieving 66% Faster Performance with WebAssembly</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tanstack Query as a synchronous state manager]]></title>
            <link>https://titusefferian.medium.com/tanstack-query-as-a-synchronous-state-manager-eb6c0db64c65?source=rss-7d2073714e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb6c0db64c65</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[react-query]]></category>
            <dc:creator><![CDATA[Titus Efferian]]></dc:creator>
            <pubDate>Wed, 29 May 2024 13:04:38 GMT</pubDate>
            <atom:updated>2024-05-29T13:04:38.436Z</atom:updated>
            <content:encoded><![CDATA[<h4>Should you do it, or should you not?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4gfpcVXEGsID6P_g4gH8g.png" /></figure><h4>Background and Motivation</h4><p>Tanstack Query is a powerful asynchronous state management tool for TypeScript and JavaScript projects. Although it is called <strong>‘asynchronous state management,’</strong> we can also utilize Tanstack Query to handle our synchronous state management, especially for global state management.</p><p>Personally, I usually use TanStack Query to handle API calls, so I do not manually manage refetching, caching, error handling, loading, etc., because TanStack Query handles these by default. However, I recently discovered an <a href="https://tkdodo.eu/blog/react-query-as-a-state-manager">article by the TanStack Query maintainer</a> that mentioned using React Query as a state manager. I wonder if I can use it to manage business logic state, similar to how we use useState, useReducer, Redux, Zustand, etc.</p><p>Then I decided to give it a try, and here are my trial results:</p><h4>Synchronous State Management</h4><p>For this example, we will try incrementing and decrementing state manipulation. Usually, we use useState, but now let’s try to implement increment and decrement functionality using TanStack Query. You can set it up like this, and it will work as expected. However, the numerical value will be stored in the TanStack Query cache management, allowing this number query key to be used anywhere in the app.</p><pre>// main.tsx<br>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import App from &#39;./App.tsx&#39;<br>import &#39;./index.css&#39;<br>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;<br><br>const client = new QueryClient();<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)!).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;QueryClientProvider client={client}&gt;<br>      &lt;App /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  &lt;/React.StrictMode&gt;,<br>)</pre><pre>// App.tsx<br>import { useQuery, useQueryClient } from &quot;@tanstack/react-query&quot;;<br>import &quot;./App.css&quot;;<br>interface NumberData {<br>  number: number;<br>}<br>const Action = () =&gt; {<br>  const client = useQueryClient();<br>  return (<br>    &lt;&gt;<br>      &lt;button<br>        onClick={() =&gt; {<br>          client.setQueryData&lt;NumberData&gt;([&quot;number&quot;], (prev) =&gt; {<br>            return {<br>              number: (prev?.number || 0) - 1,<br>            };<br>          });<br>        }}<br>      &gt;<br>        decrement<br>      &lt;/button&gt;<br>      &lt;button<br>        onClick={() =&gt; {<br>          client.setQueryData&lt;NumberData&gt;([&quot;number&quot;], (prev) =&gt; {<br>            return {<br>              number: (prev?.number || 0) + 1,<br>            };<br>          });<br>        }}<br>      &gt;<br>        increment<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>const Number = () =&gt; {<br>  const { data } = useQuery&lt;NumberData&gt;({<br>    queryKey: [&quot;number&quot;],<br>    initialData: {<br>      number: 0,<br>    },<br>  });<br>  return &lt;p&gt;{data?.number}&lt;/p&gt;;<br>};<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;Action /&gt;<br>      &lt;Number /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><h4>Synchronous State Management (with reducer)</h4><p>Okay, and what if we face more complex business logic and need to utilize a cleaner approach similar to useReducer or Redux? We can create a reducer function to handle this, providing a useReducer and Redux-like experience but with less boilerplate.</p><pre>// StateManager/index.tsx<br>import { useQuery, useQueryClient } from &quot;@tanstack/react-query&quot;;<br><br>interface NumberData {<br>  number: number;<br>}<br>type Action = { type: &quot;increment&quot; } | { type: &quot;decrement&quot; };<br><br>function reducer(state: NumberData, action: Action): NumberData {<br>  switch (action.type) {<br>    case &quot;increment&quot;:<br>      return { number: state.number + 1 };<br>    case &quot;decrement&quot;:<br>      return { number: state.number - 1 };<br>    default:<br>      throw new Error();<br>  }<br>}<br><br>const useNumber = () =&gt; {<br>  const { data } = useQuery&lt;NumberData&gt;({<br>    queryKey: [&quot;number&quot;],<br>  });<br>  return data;<br>};<br><br>const useNumberDispatch = () =&gt; {<br>  const client = useQueryClient();<br>  const dispatch = (action: Action) =&gt; {<br>    client.setQueryData([&quot;number&quot;], (oldState: NumberData) =&gt; {<br>      return reducer(oldState, action);<br>    });<br>  };<br>  return dispatch;<br>};<br><br>export { useNumber, useNumberDispatch };</pre><pre>// App.tsx<br>import &quot;./App.css&quot;;<br>import { useNumber, useNumberDispatch } from &quot;./StateManager&quot;;<br><br>const Action = () =&gt; {<br>  const numberDispatch = useNumberDispatch();<br>  return (<br>    &lt;&gt;<br>      &lt;button<br>        onClick={() =&gt; {<br>          numberDispatch({<br>            type: &quot;decrement&quot;,<br>          });<br>        }}<br>      &gt;<br>        decreament<br>      &lt;/button&gt;<br>      &lt;button<br>        onClick={() =&gt; {<br>          numberDispatch({<br>            type: &quot;increment&quot;,<br>          });<br>        }}<br>      &gt;<br>        increament<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>const Number = () =&gt; {<br>  const data = useNumber();<br>  return &lt;p&gt;{data?.number}&lt;/p&gt;;<br>};<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;Action /&gt;<br>      &lt;Number /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><h4>Summary</h4><p>In summary, yes, it actually works, and the rendering cycle is also optimized without any unnecessary re-renders. However, personally, I am still not sure if we can use this approach for large-scale business logic features. There are other opinions about this approach as well:</p><ul><li><a href="https://github.com/TanStack/query/discussions/2852">https://github.com/TanStack/query/discussions/2852</a></li><li><a href="https://blog.theodo.com/2021/06/newbie-guide-to-react-query/">https://blog.theodo.com/2021/06/newbie-guide-to-react-query/</a></li><li><a href="https://tanstack.com/query/v4/docs/framework/react/guides/does-this-replace-client-state">https://tanstack.com/query/v4/docs/framework/react/guides/does-this-replace-client-state</a></li><li><a href="https://thewebdev.info/2021/04/09/update-react-query-cache-with-the-setquerydata-method/">https://thewebdev.info/2021/04/09/update-react-query-cache-with-the-setquerydata-method/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb6c0db64c65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Auth0 and Discord Login in AWS Amplify Gen 2: A Step-by-Step Guide]]></title>
            <link>https://levelup.gitconnected.com/how-to-implement-auth0-and-discord-login-in-aws-amplify-gen-2-a-step-by-step-guide-a91ca2308b43?source=rss-7d2073714e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/a91ca2308b43</guid>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[amplify]]></category>
            <dc:creator><![CDATA[Titus Efferian]]></dc:creator>
            <pubDate>Tue, 21 May 2024 22:22:30 GMT</pubDate>
            <atom:updated>2024-05-21T22:22:30.209Z</atom:updated>
            <content:encoded><![CDATA[<p>Step-by-Step Implementation of Third-Party Authentication and Data Access Control in a Full-Stack TypeScript Environment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhEYcAK4DzO7kjK7Syy3_w.png" /><figcaption>Integrate Login with Discord Using Auth0 in AWS Amplify Gen 2</figcaption></figure><p>Recently, Amplify released their new version called Amplify Gen 2, which supports full-stack end-to-end development using TypeScript.</p><p>Now, let’s try to create an example project that is a bit more advanced and not explained in depth in the official documentation.</p><p>Amplify Gen 2 has <a href="https://docs.amplify.aws/react/build-a-backend/auth/concepts/external-identity-providers/">first-class support</a> for logging in with third-party providers such as Google, Facebook, Apple, and Amazon by default. However, additional configuration is required if we want to add another third-party provider that is not natively supported by Amplify.</p><p>We will demonstrate how to implement login with Auth0 using Discord as the social provider and then redirect back to the Amplify project with the user data.</p><h4>Create a new Amplify project</h4><p>We are going to use a simple React Vite template project provided by the Amplify documentation itself.</p><pre>git clone https://github.com/aws-samples/amplify-vite-react-template amplify-auth0-demo<br>cd amplify-auth0-demo<br>npm install<br><br># Push the template to your personal GitHub account, as we will need it later.<br>cd amplify-auth0-demo<br>git remote add amplify-auth0-demo<br>git push origin main</pre><p>After cloning the template from the Amplify GitHub repository, we will deploy it to Amplify to initialize the necessary cloud resources.</p><p>In the AWS Console, go to AWS Amplify, and you will see this landing page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hncru1_Vj-_FD_l3h5AlqQ.png" /><figcaption>Amplify Console Landing Page</figcaption></figure><p>Click “<strong>Create New App”</strong> and choose GitHub, since we previously used GitHub to clone and push the template to our account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDFlHUXLr4Dm-1WLGfmf5w.png" /><figcaption>Amplify Console Create New Project</figcaption></figure><p>Click <strong>“Next”</strong> and follow the instructions until you reach the review section.</p><p>Here, use all the default preconfigurations from Amplify. After that, click <strong>“Save and Deploy.”</strong> Wait until the deployment is complete, and then we are ready to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75wyThxA0lSercRlvXRpZg.png" /><figcaption>Amplify Console Review New Project Creation</figcaption></figure><h4>Create a new Auth0 project</h4><p>Since we are going to integrate Auth0 as the OIDC provider, we need to prepare the Auth0 configuration from the Auth0 dashboard. Go to the <a href="https://manage.auth0.com/">Auth0 dashboard</a> and create a new SPA application, as we are using React Vite at this moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYwEzFheBzMK3ElaWFE7Rw.png" /><figcaption>Auth0 Dashboard Create New Application</figcaption></figure><p>After creating a new application, go to the settings and add this value to the configuration:</p><ul><li>Allowed Callback URLs: We should fill this value with our AWS User Pool domain, which can be found in the amplify_outputs.jsonfile or in the AWS Console.</li><li>Allowed Logout URLs: For now, fill the value with localhost:5173.</li><li>Allowed Web Origins: For now, fill the value with localhost:5173.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uG-NP6LmCMKffBdBdhFu1w.png" /><figcaption>Auth0 Dashboard Settings</figcaption></figure><p>After that, go to the advanced settings, navigate to the OAuth tab, and make sure OIDC Conformant is toggled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPJ0njeKwgPMAtFRHXfHmg.png" /><figcaption>Auth0 Dashboard Advance Settings</figcaption></figure><h4>Add social provider</h4><p>After creating a new Auth0 project, we will try one of the social connections that Auth0 offers. There are many social connections available, with <strong>Google/Gmail being the default</strong>. For this demonstration, we will use <strong>Discord</strong>. Search for Discord and follow the instructions provided by Auth0. If you prefer to choose another option, that’s fine too; all the configurations will be similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mH7Svyp9zx7FOdBeyY_lRQ.png" /><figcaption>Auth0 Dashboard Social Provider Options</figcaption></figure><h4>Backend configuration for Auth0 OIDC provider</h4><p>Now let’s go back to our code and configure how to implement the OIDC external provider within Amplify Auth.</p><p>Amplify Gen 2 uses a TypeScript-based, code-first developer experience (DX) for defining backends, so you can copy and paste this configuration and it will run the same way as described in this article.</p><pre>// ./amplify/auth/resource.ts<br>import { defineAuth, secret } from &quot;@aws-amplify/backend&quot;;<br><br>export const auth = defineAuth({<br>  loginWith: {<br>    email: true,<br>    externalProviders: {<br>      oidc: [<br>        {<br>          name: &quot;auth0&quot;,<br>          /**<br>           * Since in Amplify, the TypeScript definition of <br>           * clientId and clientSecret is BackendSecret,<br>           * we need to store the values in Amplify&#39;s secret manager.<br>           */<br>          clientId: secret(&quot;authClient&quot;),<br>          clientSecret: secret(&quot;authSecret&quot;),<br>          issuerUrl: &quot;https://your-domain.jp.auth0.com&quot;,<br>          scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;, &quot;name&quot;], <br>        },<br>      ],<br>      logoutUrls: [<br>        &quot;http://localhost:5173&quot;,<br>        // your staging / production domain later<br>      ],<br>      callbackUrls: [<br>        &quot;http://localhost:5173&quot;,<br>        // your staging / production domain later<br>      ],<br>    },<br>  },<br>});</pre><p>As we wrote in the previous code, we have secret(&quot;authSecret&quot;);. We need to define the key value for this secret in the Amplify Secret Manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkUNKI-8FPv_MYRvLUePdQ.png" /><figcaption>Amplify Console Secret Manager Dashboard</figcaption></figure><p>Now let’s add a new table with owner authorization to demonstrate that only users who own the data based on their authorization can access it. We will define a TestingTablewith a contentfield and add ownerauthorization.</p><pre>// ./amplify/data/resource.ts<br>import { type ClientSchema, a, defineData } from &quot;@aws-amplify/backend&quot;;<br><br>const schema = a.schema({<br>  TestingTable: a<br>    .model({<br>      content: a.string().required(),<br>    })<br>    .authorization((allow) =&gt; [allow.owner()]),<br>});<br><br>export type Schema = ClientSchema&lt;typeof schema&gt;;<br><br>export const data = defineData({<br>  schema,<br>  authorizationModes: {<br>    defaultAuthorizationMode: &quot;apiKey&quot;,<br>    // API Key is used for a.allow.public() rules<br>    apiKeyAuthorizationMode: {<br>      expiresInDays: 30,<br>    },<br>  },<br>});</pre><h4>Deploy our backend configuration</h4><p>We are done setting up the backend. To deploy our configuration, the easiest way is to push a commit to GitHub, and Amplify will trigger the deployment based on the new commit to the main branch.</p><pre>git add .<br>git commit -m &quot;init auth0 integration&quot;<br>git push origin main</pre><h4>Frontend Integration</h4><p>After completing the deployment, we need to get the amplify_outputs.jsonfile from the console before doing any code on the frontend. The easiest way to get this is to go to the Amplify Console, download the amplify_outputs.jsonfile from the <strong>“Deployed Backend Resources”</strong> tab, and place it at the root level of the project we cloned previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZLalRh1TxRHXapiMKGABQ.png" /><figcaption>Amplify Console Dashboard Download JSON Output</figcaption></figure><p>We are going to do a simple demonstration in the frontend:</p><ul><li><strong>Sign In</strong>: This will demonstrate how to log in with Discord using the Auth0 provider.</li><li><strong>Sign Out</strong>: This will demonstrate how to log out of all sessions.</li><li><strong>Get Current User</strong>: This will demonstrate retrieving all user data from Auth0.</li><li><strong>Create Data</strong>: This will demonstrate inputting data into the TestingTablewith owner authorization, so users can only access their own data and can’t see other users’ data.</li><li><strong>Get Data</strong>: This will demonstrate reading user data based on their login identity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVwa-P5QEnchH8Wo_4_C7Q.png" /></figure><pre>import { generateClient } from &quot;aws-amplify/api&quot;;<br>import {<br>  fetchAuthSession,<br>  signInWithRedirect,<br>  signOut,<br>} from &quot;aws-amplify/auth&quot;;<br>import type { Schema } from &quot;../amplify/data/resource&quot;;<br>const client = generateClient&lt;Schema&gt;();<br><br>function App() {<br>  const handleSignInWithRedirect = () =&gt; {<br>    signInWithRedirect({<br>      provider: {<br>        // use the exact name we defined from the backend configuration<br>        custom: &quot;auth0&quot;,<br>      },<br>    });<br>  };<br><br>  const handleSignOut = () =&gt; {<br>    signOut({ global: true });<br>  };<br>  const handleGetCurrentUser = async () =&gt; {<br>    const session = await fetchAuthSession();<br>    console.log(session);<br>  };<br>  const handleCreateData = async () =&gt; {<br>    const data = await client.models.TestingTable.create(<br>      {<br>        content: &quot;hello world&quot;,<br>      },<br>      {<br>        // need to specify userPool because we are using owner authorization for this model<br>        authMode: &quot;userPool&quot;,<br>      },<br>    );<br>    console.log(data);<br>  };<br>  const handleGetAllData = async () =&gt; {<br>    // need to specify userPool because we are using owner authorization for this model<br>    const data = await client.models.TestingTable.list({<br>      authMode: &quot;userPool&quot;,<br>    });<br>    console.log(data);<br>  };<br>  return (<br>    &lt;main&gt;<br>      &lt;button onClick={handleSignInWithRedirect}&gt;signin&lt;/button&gt;<br>      &lt;button onClick={handleSignOut}&gt;signout&lt;/button&gt;<br>      &lt;button onClick={handleGetCurrentUser}&gt;get current user&lt;/button&gt;<br><br>      &lt;button onClick={handleCreateData}&gt;create data&lt;/button&gt;<br>      &lt;button onClick={handleGetAllData}&gt;get data&lt;/button&gt;<br>    &lt;/main&gt;<br>  );<br>}<br><br>export default App;</pre><h4>Demonstration</h4><h4><strong>SignIn</strong></h4><p>Click the <strong>“Sign In”</strong> button and try to log in with Discord from the available options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*q5uxXMfyx4xU9ffojDI-zA.gif" /></figure><h4><strong>Get Current User</strong></h4><p>If we click the <strong>“Get Current User”</strong> button, it will return this value. You can visit the <a href="https://docs.amplify.aws/react/build-a-backend/auth/concepts/tokens-and-credentials/">Amplify documentation</a> for a detailed explanation about access tokens vs. ID tokens.</p><pre>{<br>  &quot;tokens&quot;: {<br>    &quot;accessToken&quot;: {<br>      &quot;payload&quot;: {<br>        &quot;sub&quot;: &quot;xxx&quot;,<br>        &quot;cognito:groups&quot;: [<br>          &quot;ap-northeast-3_xxx_auth0&quot;<br>        ],<br>        &quot;iss&quot;: &quot;xxx&quot;,<br>        &quot;version&quot;: 2,<br>        &quot;client_id&quot;: &quot;xxx&quot;,<br>        &quot;origin_jti&quot;: &quot;0xxx&quot;,<br>        &quot;token_use&quot;: &quot;access&quot;,<br>        &quot;scope&quot;: &quot;aws.cognito.signin.user.admin phone openid profile email&quot;,<br>        &quot;auth_time&quot;: 1716097816,<br>        &quot;exp&quot;: 1716101416,<br>        &quot;iat&quot;: 1716097816,<br>        &quot;jti&quot;: &quot;xxx&quot;,<br>        &quot;username&quot;: &quot;auth0_oauth2|discord|xxx&quot;<br>      }<br>    },<br>    &quot;idToken&quot;: {<br>      &quot;payload&quot;: {<br>        &quot;at_hash&quot;: &quot;xxx&quot;,<br>        &quot;sub&quot;: &quot;xxx&quot;,<br>        &quot;cognito:groups&quot;: [<br>          &quot;ap-northeast-3_xxx_auth0&quot;<br>        ],<br>        &quot;email_verified&quot;: false,<br>        &quot;iss&quot;: &quot;https://cognito-idp.ap-northeast-3.amazonaws.com/ap-northeast-3_xxx&quot;,<br>        &quot;cognito:username&quot;: &quot;xxx&quot;,<br>        &quot;nonce&quot;: &quot;xxx&quot;,<br>        &quot;origin_jti&quot;: &quot;xxx&quot;,<br>        &quot;aud&quot;: &quot;xxx&quot;,<br>        &quot;identities&quot;: [<br>          {<br>            &quot;dateCreated&quot;: &quot;1716097789186&quot;,<br>            &quot;userId&quot;: &quot;oauth2|discord|xxx&quot;,<br>            &quot;providerName&quot;: &quot;auth0&quot;,<br>            &quot;providerType&quot;: &quot;OIDC&quot;,<br>            &quot;issuer&quot;: null,<br>            &quot;primary&quot;: &quot;true&quot;<br>          }<br>        ],<br>        &quot;token_use&quot;: &quot;id&quot;,<br>        &quot;auth_time&quot;: 1716097816,<br>        &quot;exp&quot;: 1716101416,<br>        &quot;iat&quot;: 1716097816,<br>        &quot;jti&quot;: &quot;xxx&quot;,<br>        &quot;email&quot;: &quot;myemail@gmail.com&quot;<br>      }<br>    }<br>  },<br>  &quot;credentials&quot;: {<br>    &quot;accessKeyId&quot;: &quot;xxx&quot;,<br>    &quot;secretAccessKey&quot;: &quot;xxx&quot;,<br>    &quot;sessionToken&quot;: &quot;xxx&quot;,<br>    &quot;expiration&quot;: &quot;2024-05-19T06:54:31.000Z&quot;<br>  },<br>  &quot;identityId&quot;: &quot;ap-northeast-3:xxx&quot;,<br>  &quot;userSub&quot;: &quot;xxx&quot;<br>}</pre><h4>Create Data</h4><p>Now let’s try to create data with the value hello world from discord.</p><pre>const handleCreateData = async () =&gt; {<br>  const data = await client.models.TestingTable.create(<br>    {<br>      content: &quot;hello world from discord&quot;,<br>    },<br>    {<br>      authMode: &quot;userPool&quot;,<br>    },<br>  );<br>  console.log(data);<br>};</pre><p>And it will return this value in the console log:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;id&quot;: &quot;xxx&quot;,<br>    &quot;content&quot;: &quot;hello world from discord&quot;,<br>    &quot;createdAt&quot;: &quot;2024-05-19T06:09:02.048Z&quot;,<br>    &quot;updatedAt&quot;: &quot;2024-05-19T06:09:02.048Z&quot;,<br>    // Now this data has been bound to this owner based on the access token.<br>    &quot;owner&quot;: &quot;auth0_discord-oauth2|xxx&quot;<br>  }<br>}</pre><h4>Get Data (Using the Same Account)</h4><p>Now, if you click the <strong>“Get Data”</strong> button using the same account you used to create the data, you will get this result:</p><pre>const handleGetAllData = async () =&gt; {<br>  const data = await client.models.TestingTable.list({ authMode: &quot;userPool&quot; });<br>  console.log(data);<br>};</pre><pre>{<br>    &quot;data&quot;: [<br>        {<br>            &quot;id&quot;: &quot;xxx&quot;,<br>            &quot;content&quot;: &quot;hello world from discord&quot;,<br>            &quot;createdAt&quot;: &quot;2024-05-19T06:09:02.048Z&quot;,<br>            &quot;updatedAt&quot;: &quot;2024-05-19T06:09:02.048Z&quot;,<br>            &quot;owner&quot;: &quot;auth0_oauth2|discord|xxx&quot;<br>        }<br>    ],<br>    &quot;nextToken&quot;: null<br>}</pre><h4>Get Data (Using a Different Account)</h4><p>Now let’s demonstrate what happens if we try to log in with a different account or if we are in an unlogged-in session. If we try to get the data, we will get this result.</p><pre>{<br>  &quot;data&quot;: [],<br>  &quot;nextToken&quot;: null<br>}</pre><p>This concept is called <strong>“per user owner / per owner data access,”</strong> meaning users can only access data that belongs to them. You can learn more about it in the <a href="https://docs.amplify.aws/react/build-a-backend/data/customize-authz/per-user-per-owner-data-access/#add-per-userper-owner-authorization-rule">Amplify documentation</a>.</p><h4>Conclusion</h4><ul><li>Amplify has released their new version called Amplify Gen 2, featuring a full-stack TypeScript experience, and you can try it out now.</li><li>Amplify is able to perform authentication with other OIDC providers, such as Auth0, for this example.</li><li>We can use Auth0 to enable any social login we want, which can help increase user acquisition through social login providers.</li><li>Even though we are logging in with Auth0, we can still utilize per-owner data access from Amplify AppSync and DynamoDB.</li></ul><h4>References and Resources</h4><ul><li><a href="https://docs.amplify.aws/react/build-a-backend/auth/concepts/external-identity-providers/">Amplify External Identity Provider</a></li><li><a href="https://docs.amplify.aws/react/build-a-backend/auth/concepts/tokens-and-credentials/">Access Token vs. ID Tokens</a></li><li><a href="https://docs.amplify.aws/react/build-a-backend/data/customize-authz/per-user-per-owner-data-access/#add-per-userper-owner-authorization-rule">Per Owner Data Access</a></li><li><a href="https://github.com/TitusEfferian/amplify-auth0-demo">Full Code Implementation</a></li><li><a href="https://github.com/aws-samples/amplify-vite-react-template">Amplify React Vite Template</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a91ca2308b43" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-implement-auth0-and-discord-login-in-aws-amplify-gen-2-a-step-by-step-guide-a91ca2308b43">How to Implement Auth0 and Discord Login in AWS Amplify Gen 2: A Step-by-Step Guide</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding React Rendering: Client, Server, or Stream?]]></title>
            <link>https://blog.stackademic.com/decoding-reactjs-rendering-client-server-or-stream-42c6a65319bb?source=rss-7d2073714e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c6a65319bb</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Titus Efferian]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 04:37:47 GMT</pubDate>
            <atom:updated>2023-11-20T03:09:25.681Z</atom:updated>
            <content:encoded><![CDATA[<p>A deep dive into rendering strategies for optimized performance and seamless user experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jOlDyLYPpZkiUbL0" /><figcaption>Photo by <a href="https://unsplash.com/@kaleidico?utm_source=medium&amp;utm_medium=referral">Kaleidico</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It has been one year since the release of Next.js 13, which introduced a new paradigm in its rendering concept.</p><p>I have been using Next.js since version 10, and I want to share information about the differences among the three rendering strategies currently available in the latest version of Next.js.</p><p>I also hope that this article can help anyone who has recently started using Next.js since version 13, and has little knowledge or experience with the previous versions. This way, you can understand the basic fundamentals and the reasons why React and Next.js introduced the streaming concept into these frameworks.</p><p>I created three production branches that I deployed on <a href="https://vercel.com/">Vercel</a>, so we can assume that anyone from around the world will access the assets from their nearest data center.</p><p>For all these renderings, I introduced a 2-second timeout before fetching data from the data sources. This allows us to simulate and observe the differences between the rendering strategies, because our example data source (<a href="https://pokeapi.co/">PokeAPI</a>) is quite fast. We need to mock a timeout to emulate a scenario where the data source experiences high traffic, so we can assess the differences.</p><h4>Client Side Rendering</h4><p>In traditional Client-Side Rendering, everything is usually rendered on the client. If we inspect using Chrome DevTools and look at the Preview tab, we will see something resembling blank white spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yrYNimpN4Ymvfs1_sbavw.png" /></figure><p>But from the user’s perspective, everything appears to work as expected; users can see the website’s content and interact with it as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFWIYMQBQN9kjo46UTwuww.png" /></figure><h4><strong>Server Side Rendering</strong></h4><p>On the other hand, server-side rendering fetches all the data on the server, waits until the server has received the data from the data sources, and then sends the HTML content to the client. If we inspect using Chrome DevTools, we can see that all the content sent by the server is visible, which is why we can preview it in Chrome DevTools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPsKb__eOa5RVcpOI9Oqhw.png" /></figure><h4><strong>Streaming</strong></h4><p>While using Streaming, you can choose which parts you want to be initially rendered by the server and which parts to stream from the server. Here, I’m simulating <strong>Bulbasaur as server-rendered</strong>, while <strong>the other Pokémon will be streamed from the server.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_dA8wwG0ouvgMWqSkNwww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDdNyk5OE6QvdX86Fy0Zjg.png" /></figure><h3><strong>Web Performance</strong></h3><p>Now, we are going to examine the differences between these three rendering strategies from a web performance perspective. I have used <a href="https://webpagetest.org/">WebPageTest</a> to simulate web performance.</p><h4><strong>Client Side Rendering</strong></h4><p>Time To First Byte: <strong>1.265s<br></strong>Overall Time: <strong>5.970s</strong></p><p>Here, in client-side rendering, the server responds quite quickly at 1.265 seconds, but the page will remain blank for a while until the JavaScript is ready to execute and perform client-side data fetching from the data sources. This is why data fetching starts after the JavaScript has finished executing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONUslGHLBs0hq1QJbEvzVw.png" /></figure><h4><strong>Server Side Rendering</strong></h4><p>Time To First Byte: <strong>6.074s<br></strong>Overall Time: <strong>9.235s</strong></p><p>While in server-side rendering, the user needs to wait until six seconds before they can see all the content sent by the server, because server-side rendering requires waiting until all the necessary data is received on the server before being sent to the client. This is why the React team has been working on <a href="https://nextjs.org/docs/app/building-your-application/rendering/server-components">React Server Components</a> and the concept of streaming for the past two years to address this issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHMYfY0xI70FPND1YqRKZw.png" /></figure><h4><strong>Streaming</strong></h4><p>Time To First Byte: <strong>1.052s<br></strong>Overall Time: <strong>3.408s</strong></p><p>While in streaming, we can breakdown which part we need to be initially rendered and later on stream to the server, that is why streaming can achieved 1.052s for the server to respond and overall time 3.408s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymgSFEiXmjHu5opyZTftZA.png" /></figure><h3>Conclusion</h3><p>Each rendering method has its own purpose and solves specific problems. Thus, it is important to understand the history of rendering strategies, from traditional ones like client-side rendering, to the new paradigm known as streaming, because each rendering method can be used to complement the others.</p><h3>Resources</h3><ul><li><a href="https://nextjs.org/docs/app/building-your-application/rendering">Nextjs documentation</a></li><li><a href="https://www.webpagetest.org/result/231106_AiDc5N_ADX/1/details/cached/#waterfall_view_step1">Webpage Test Results for Streaming</a></li><li><a href="https://www.webpagetest.org/result/231106_AiDcKE_ADY/1/details/#waterfall_view_step1">Webpage Test Results for Server Side Rendering</a></li><li><a href="https://www.webpagetest.org/result/231106_BiDc4T_AAS/1/details/#waterfall_view_step1">Webpage Test Results for Client Side Rendering</a></li><li><a href="https://pokemon-csr-vite.vercel.app/">Client Side Rendering Demo</a> (<a href="https://github.com/TitusEfferian/pokemon-medium-vite">github</a>)</li><li><a href="https://pokemon-app-ssr.vercel.app/">Server Side Rendering Demo</a> (<a href="https://github.com/TitusEfferian/pokemon-streaming-render/tree/ssr">github</a>)</li><li><a href="https://pokemon-app-router.vercel.app/">Streaming Demo</a> (<a href="https://github.com/TitusEfferian/pokemon-streaming-render">github</a>)</li></ul><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42c6a65319bb" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/decoding-reactjs-rendering-client-server-or-stream-42c6a65319bb">Decoding React Rendering: Client, Server, or Stream?</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remix: The React Framework Recommended by ReactJS Docs]]></title>
            <link>https://medium.com/better-programming/remix-the-react-framework-recommended-by-reactjs-docs-2c0fa94e3203?source=rss-7d2073714e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c0fa94e3203</guid>
            <category><![CDATA[remix]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Titus Efferian]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 17:58:16 GMT</pubDate>
            <atom:updated>2023-04-05T00:48:47.713Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Pokémon list fetch using the PokeAPI with the Remix Framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qLP6SdZwB6SB__VW" /><figcaption>Photo by <a href="https://unsplash.com/de/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://react.dev/">ReactJS documentation</a> just got a major upgrade a few weeks ago. This new documentation is improving with examples like diagrams, illustrations, challenges, and over 600 new interactive examples. This will be so useful for newcomers to ReactJS and for experienced ReactJS developers who want to sharpen their deep-dive knowledge of how React works.</p><p>While there are many great aspects of the new documentation, I’d like to focus on one thing: the <a href="https://react.dev/learn/start-a-new-react-project">“Starting a New React Project”</a> section.</p><p>The significant change in the “Starting a New React Project” section is that the official ReactJS documentation no longer mentions <a href="https://create-react-app.dev/">Create-React-App</a> (CRA). Instead, they recommend production-grade React frameworks like <a href="https://nextjs.org/">Next.js</a>, <a href="https://www.gatsbyjs.com/">Gatsby</a>, and <a href="https://remix.run/">Remix</a>.</p><p>In their previous <a href="https://legacy.reactjs.org/">legacy documentation</a>, the only React frameworks recommended were Next.js and Gatsby. However, in the new documentation, they have introduced a new recommended framework called Remix.</p><p>I will create a code snippet example in Remix and an equivalent example in Next.js. Since Next.js has been part of the frontend ecosystem for quite some time, many frontend engineers will be more familiar with its concepts.</p><h3><strong>What is Remix?</strong></h3><p>Remix is a full-stack React framework with nested routing<strong>.</strong> It lets you break your app into nested parts that can load data in parallel and refresh in response to the user&#39;s actions.</p><h3>Key Features of Remix</h3><p>I tried Remix for the first time to build a simple Pokémon list that fetches data from the PokeAPI. In this article, I will explain a few things about Remix and what I learned from using it for the first time.</p><p>You can view the final result of this <a href="https://pokelist-remix.vercel.app/">project at this link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eR1OQXiMXFxw3uIZo5IRw.png" /><figcaption>pokemon list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oF3_H-mWE4dJUuFP-crtLQ.png" /><figcaption>pokemon detail</figcaption></figure><h4><strong>Data loading</strong></h4><p>One of the primary features of Remix is simplifying interactions with the server to get data into components. This is equivalent to the <a href="https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props">getServerSideProps</a> feature in Next.js.</p><p>Here, I am handling two features for this website:</p><ol><li>Fetching a list of Pokémon for the initial render.</li><li>Fetching the next Pokémon for pagination.</li></ol><pre>export const loader = async ({ request }: LoaderArgs) =&gt; {<br>  // pagination handling<br>  const url = new URL(request.url);<br>  const query = url.searchParams.get(&quot;next&quot;);<br>  if (query) {<br>    const fetchPoke = await fetch(query);<br>    const fetchPokeJson = await fetchPoke.json();<br>    return json(fetchPokeJson);<br>  }<br>  // end of pagination handling<br><br>  // initial fetch<br>  const fetchPoke = await fetch(&quot;https://pokeapi.co/api/v2/pokemon&quot;);<br>  const fetchPokeJson = await fetchPoke.json();<br>  return json(fetchPokeJson);<br>  // end of initial fetch<br>};</pre><pre>interface LoaderData {<br> count: number;<br> next: string;<br> results: {<br>  name: string;<br>  url: string;<br> }[];<br>}<br><br>import { useLoaderData } from &quot;@remix-run/react&quot;;<br><br>export default function PokeList() {<br> // Obtain the data returned from the server using useLoaderData().<br> const pokeData = useLoaderData() as LoaderData;<br><br> return (<br>  &lt;SimpleGrid<br>   cols={4}<br>   breakpoints={[<br>    { maxWidth: &quot;sm&quot;, cols: 2 },<br>    { maxWidth: &quot;md&quot;, cols: 3 },<br>    { maxWidth: &quot;lg&quot;, cols: 4 },<br>   ]}<br>  &gt;<br>   {poke.results.map((x, y) =&gt; {<br>    return (<br>     &lt;Card key={x.name}&gt;<br>      &lt;Card.Section&gt;<br>       &lt;Center&gt;<br>        &lt;Image<br>         withPlaceholder<br>         width={120}<br>         height={120}<br>         src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${y + 1<br>          }.png`}<br>         alt={x.name}<br>        /&gt;<br>       &lt;/Center&gt;<br>      &lt;/Card.Section&gt;<br>      &lt;Text&gt;{x.name}&lt;/Text&gt;<br>     &lt;/Card&gt;<br>    );<br>   })}<br>  &lt;/SimpleGrid&gt;<br> );<br>}<br></pre><p>In Next.js, you may be familiar with a similar concept like this:</p><pre>function Page({ data }) {<br>  // Render data...<br>}<br><br>// This gets called on every request<br>export async function getServerSideProps() {<br>  // Fetch data from external API<br>  const res = await fetch(`https://.../data`)<br>  const data = await res.json()<br><br>  // Pass data to the page via props<br>  return { props: { data } }<br>}</pre><h4><strong>Routing</strong></h4><p>Remix also uses a file-based routing system, similar to other meta-frameworks in the current frontend ecosystem. However, Remix’s routing under the hood is built on top of <a href="https://reactrouter.com/en/main">react-router-dom</a>. Routing is possibly the most important concept to understand in Remix. Everything starts with your routes: the compiler, the initial request, and almost every user interaction afterward.</p><p>My top recommendation when starting to learn Remix is to first understand the core concepts of how their routing works before diving into other sections. However, if you come from a react-router-dom background, you may find similar concepts in Remix’s routing.</p><p>Here is an example of a routing structure in Remix. Every new file you create under the routes folder will be accessible through the page URL, which is why understanding the core concepts of Remix routing is essential.</p><pre>|--app<br>   |--routes<br>      |--$name.tsx -&gt; https://example.com/*<br>      |--index.tsx -&gt; https://example.com<br>      |--PokeList.tsx -&gt; https://example.com/pokelist</pre><p>Here is an equivalent routing structure in Next.js:</p><pre>|--pages<br>   |--index.tsx -&gt; https://example.com<br>   |--PokeList.tsx -&gt; https://example.com/pokelist<br>   |--[name]<br>      |--index.tsx -&gt; https://example.com/*</pre><p>As you can see here, we have two routes that can be combined into a single layout within one URL; this is called <a href="https://remix.run/docs/en/1.15.0/guides/routing#what-is-nested-routing">Nested Routing</a>. Nested Routing is the general idea of coupling URL segments to the UI&#39;s component hierarchy. In Remix, you will find that in almost every case, segments of the URL determine:</p><ul><li>The layouts to render on the page</li><li>The code-split JavaScript bundles to load</li><li>The data dependencies of those layouts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IwUtj9YQXeu0lMI_EgO0Q.png" /></figure><p>Since Pokelist is a route, yes, you can actually access the <a href="https://pokelist-remix.vercel.app/pokelist">URL through this link</a>.</p><p>In some cases, it may be acceptable for those routes to be accessed directly, but in my case, I prevent direct access to the URL because those routes will throw an error. The data loader for fetching the Pokémon list is located in routes/index.tsx.</p><pre>/**<br> * prevent direct access to the url<br> */<br>export const loader = async () =&gt; {<br> return redirect(&#39;/&#39;);<br>};<br><br>const PokeList = () =&gt; {<br> ...<br> ...<br>};<br><br>export default PokeList;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-kdQZnDJ2P07Rrb3dNPkw.png" /></figure><h4><strong>Rendering options</strong></h4><p>According to a <a href="https://twitter.com/mjackson/status/1585795441907494912?lang=en">Twitter thread</a> from the maintainer of Remix itself, Remix currently supports only Client-Side Rendering(CSR) and Server-Side Rendering(SSR), and it does not have features like Static Site Generation(SSG). As a result, it usually expects you to have a server.</p><h4><strong>Styling</strong></h4><p>In today’s ecosystem, there are dozens of approaches and frameworks for styling. Remix supports many of them out of the box, but the frameworks that require direct integration with the Remix compiler and expect Remix to inject styles onto the page automatically don’t work right now.</p><p>Remix is still researching how best to support, and be supported by, the various styling libraries without sacrificing the user’s network tab or creating a maintenance burden for Remix.</p><p>You need to be cautious when choosing a design system for use with Remix, as some features of your design system library may not work in Remix or vice versa.</p><p>One example is the Mantine library; when using Mantine in Remix, the streaming server rendering will not work. <a href="https://mantine.dev/guides/remix/#server-streaming-support">Here’s a guide for more information</a>.</p><h4>Error boundary</h4><p>In Remix, you can access the built-in API for handling error boundaries for every file in the subdirectories of the routes folder. You can use this to handle any errors related to your route components, including handling errors thrown from your loader.</p><pre>export const loader = async ({ params }: LoaderArgs) =&gt; {<br>    const fetchData = await fetch(`https://pokeapi.co/api/v2/pokemon/${params.name}`);<br>    if (fetchData.status !== 200) {<br>        throw new Error();<br>    }<br>    const fetchJson = await fetchData.json();<br>    return json(fetchJson);<br>}<br><br>// your error boundary<br>export function ErrorBoundary({ error }) {<br> // log your error <br> yourLogger(error);<br> return (<br>  &lt;Container&gt;<br>   &lt;Stack&gt;<br>    &lt;Alert color={&#39;red&#39;}&gt;<br>     Error<br>    &lt;/Alert&gt;<br>   &lt;/Stack&gt;<br>  &lt;/Container&gt;<br> );<br>}<br><br>const PokeDetail = () =&gt; {<br>  ...<br>  ...<br>}<br><br>export default PokeDetail;</pre><h3>Conclusion</h3><p>Remix is another meta-framework that has emerged in the ReactJS ecosystem. Now, we have three options recommended by the ReactJS documentation: Next.js, Gatsby, and Remix.</p><p>In my personal opinion, after trying Remix for the first time, I feel like this framework has a higher learning curve than Next.js.</p><p>If your project or company is currently building its own framework internally with react-router-dom dependencies, you should check out Remix, as it is now recommended by the ReactJS documentation for creating a new React app.</p><h3>Resources</h3><ul><li><a href="https://reactrouter.com/en/main">React Router</a></li><li><a href="https://remix.run/docs/en/main">Remix documentation</a></li><li><a href="https://github.com/TitusEfferian/poke-list-remix">My GitHub page with the poke list</a></li><li><a href="https://twitter.com/mjackson/status/1585795441907494912?lang=en">MJackson’s Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c0fa94e3203" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/remix-the-react-framework-recommended-by-reactjs-docs-2c0fa94e3203">Remix: The React Framework Recommended by ReactJS Docs</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amplify vs. Firebase: A Head-to-Head Comparison With My Real Product]]></title>
            <link>https://medium.com/better-programming/amplify-vs-firebase-a-head-to-head-comparison-with-a-real-product-b6fd76058416?source=rss-7d2073714e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6fd76058416</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Titus Efferian]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 00:53:35 GMT</pubDate>
            <atom:updated>2023-01-24T02:47:14.332Z</atom:updated>
            <content:encoded><![CDATA[<h4>Key differences and similarities</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3BVG_eSJCqibgoAh" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Over the past year, I built 2 products with real traffic and users. One used Amplify and the other one used Firebase. I am going to share my lessons learned and a head-to-head comparison between amplify and firebase.</p><p>I will divide this article into two parts. The first part will talk about Firebase, and the second part will talk about Amplify.</p><h3>Why Use Firebase or Amplify?</h3><p>In short, I am a front-end engineer with four years of experience. In my experience, I have rarely worked on production-quality backends, so you can assume that I only have a little knowledge of best practices for backend quality.</p><p>I want to focus on building a product and I want to release it as fast as possible without compromising the quality of the backend side, including authentication, database CRUD, asset storage, and of course, the backend security itself.</p><p>Both Amplify and Firebase solve the same problem, which is providing a complete solution that lets front-end web and mobile developers easily build and scale apps or games that users love.</p><h3>Here’s What I Built Using Firebase</h3><p>I built a <a href="https://wishlist.sekai.best/">community page</a> based on the <a href="https://pjsekai.sega.jp/">Project Sekai</a> game to collect all the song wishlists that players want to be released in the game from all over the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpIDdXN4t7rq9HAzKAt6Cg.png" /></figure><h3>Firebase Features I Used In My Project</h3><h4>Authentication</h4><p>I used Firebase Authentication to handle user authentication and authorization. There are a lot of authentication options, but for this project, I chose to use login with Google and log in with Twitter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*TULgT1wJS2iK4cLud0lxYA.png" /></figure><h4>Firestore</h4><p>I used Cloud Firestore as my database option. This is a NoSQL database with a document-based structure, similar to MongoDB. I used this database to handle:</p><ul><li>user votes with built-in real-time updates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*M2p6ze0fc5_byZaXdrVLVw.jpeg" /></figure><ul><li>User submission of their wishlist song</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fChBUzWZ_qWR8M1I9jiMhg.png" /></figure><ul><li>Manage songs that have already been released in the game.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUqjC7dI2L_3i0s46t5APw.png" /></figure><h4>Storage</h4><p>I used Cloud Storage with a simple use case, such as handling asset storage, like image banners.</p><h4>Security Rules</h4><p>I used security rules to handle validation, which users can manipulate to access specific data.</p><h4>Algolia</h4><p>Cloud Firestore comes with great data manipulation features, but there is one important thing that it can’t do: full-text and partial-text search. However, it has first-class support for integrating with Algolia search through its Firebase extension.</p><h3>Pros and Cons of Firebase</h3><h4>Pros</h4><ul><li><strong>Productivity </strong>— Firebase comes with great features for frontend engineers; it really helps us to launch products faster, scale automatically based on user traffic, and ensure security. They also have out-of-the-box real-time support. Under the hood of Firebase is GCP itself, so it can be easily extended to the capabilities of your Firebase project to Google Cloud Platform.</li><li><strong>Learning Curve</strong> — It has an easy learning curve because it is pretty straightforward to integrate with every Firebase feature.</li><li><strong>Authentication </strong>— Firebase Authentication has many built-in support for integrating with 3rd party services, such as <strong>Google</strong>, <strong>Apple</strong>, <strong>Facebook</strong>, <strong>Twitter</strong>, <strong>Microsoft</strong>, <strong>GitHub</strong>, and <strong>Yahoo</strong>.</li></ul><h4>Cons</h4><p><strong>No Admin Panel</strong> — Firebase does not come with a built-in admin panel. While users can directly manipulate data inside the Firebase console, the UI may be too technical for those without technical knowledge. In this case, an admin panel needs to be created separately</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sandy8B8Y1IdLC9Iz83Mtg.png" /></figure><p><strong>Full-Partial-Text Search</strong> — The lack of built-in features for performing a partial or full-text search means that integration with a 3rd party service, such as <strong>Algolia</strong>, <strong>Elasticsearch</strong>, or <strong>Typesense</strong>, is necessary.</p><p><strong>Database Object Modeling</strong> — When I was building this project, I was still using Firebase version 8.10.0, and I found it quite challenging to maintain consistency of data types between the cloud and the code. While databases like MongoDB have solutions like Mongoose for object modeling, I couldn&#39;t find a similar solution for Firestore. This leads to reduced productivity and code quality because I sometimes encounter typos in field names, or the field names may not be defined yet.</p><p>But in the latest version of Firebase, they have a feature to <a href="https://firebase.google.com/docs/firestore/manage-data/add-data#custom_objects">handle custom objects</a> which can fix this issue:</p><pre>class City {<br>    constructor (name, state, country ) {<br>        this.name = name;<br>        this.state = state;<br>        this.country = country;<br>    }<br>    toString() {<br>        return this.name + &#39;, &#39; + this.state + &#39;, &#39; + this.country;<br>    }<br>}<br><br>// Firestore data converter<br>const cityConverter = {<br>    toFirestore: (city) =&gt; {<br>        return {<br>            name: city.name,<br>            state: city.state,<br>            country: city.country<br>            };<br>    },<br>    fromFirestore: (snapshot, options) =&gt; {<br>        const data = snapshot.data(options);<br>        return new City(data.name, data.state, data.country);<br>    }<br>};</pre><h3>Here’s What I Built Using Amplify</h3><p>I built an <a href="https://fukunon.com/">end-to-end costume rental shop</a> dedicated to cosplay hobbies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cn3kNPjs1gZdEcvvfST5Hg.png" /></figure><h3>Amplify Features I Used In My Project</h3><ul><li><strong>Amazon Cognito</strong> — I used Amazon Cognito to handle user authentication and authorization. There are a lot of authentication options, but for this project, I chose to use <strong>login with Google</strong> and <strong>login with Facebook</strong>.</li><li><strong>Amazon CloudFormation</strong> — AWS CloudFormation lets you model, provision, and manage AWS and third-party resources by treating infrastructure as code. Because of CloudFormation, I can easily create branch environments such as staging and production.</li><li><strong>Amazon AppSync</strong> — AWS AppSync creates serverless GraphQL and Pub/Sub APIs that simplify application development through a single endpoint to securely query, update, or publish data.</li><li><strong>Amazon DynamoDB</strong> — In the previous section, we discussed Firestore, which uses a document-based concept. DynamoDB, on the other hand, uses a key-value schema similar to Redis. I used DynamoDB to handle all the data for my website, such as user data, product data, transaction data, payment data, etc.</li><li><strong>Amazon S3</strong> — S3 is an object storage built to retrieve any amount of data from anywhere. I used Amazon S3 to handle product images, website assets, and user assets.</li><li><strong>Amazon Pinpoint</strong> — Amazon Pinpoint is a targeted multichannel communication tool. It is the equivalent of Google Analytics, but for the AWS platform. I used Amazon Pinpoint to handle all tracking and analytics related to my website.</li><li><strong>Amazon Lambda</strong> — Amazon lambda is a serverless, event-driven compute service. I used AWS Lambda to handle all API communication with third-party vendors, such as payment gateways and courier gateways.</li></ul><h3>Pros and Cons of Amplify</h3><h4>Pros</h4><ul><li><strong>Amplify Studio</strong> — Unlike the Firebase version discussed in the previous section, AWS Amplify comes with a general admin panel called Amplify Studio. This Amplify Studio can handle data management, user management, and asset management. Here are some examples of what the capabilities of Amplify Studio look like.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqtfYwdXDRHWioL9cgw6qQ.png" /></figure><ul><li><strong>CloudFormation </strong>— With AWS CloudFormation, you can easily clone your environment, especially when building staging and production environments. This is one of the major advantages over Firebase.</li><li><strong>Database Object Modeling</strong> — Because of AWS AppSync, we can define our database schema using GraphQL schema types. This creates a ‘database as code’ approach, ensuring consistency in all data configuration. We can also configure data authorization using this schema.</li></ul><pre>type Products @model @auth(rules: [{allow: public}]) {<br>  id: ID!<br>  available_size: [AvailableSizeEnums!]!<br>  day_rent_price: Int!<br>  is_active: Boolean!<br>  minimum_rent_duration: Int!<br>  product_name: String!<br>  quantity: Int!<br>  weight: Int!<br>  s3_path: String!<br>  product_image: [String!]!<br>  product_description: String!<br>}</pre><p><strong>Full-Partial-Text Search</strong> — Amazon has a built-in feature for handling search with Amazon OpenSearch.</p><h4>Cons</h4><p><strong>Authentication</strong> — AWS Cognito has fewer social integration options compared to Firebase. It only has login options with <strong>Amazon</strong>, <strong>Facebook</strong>, <strong>Google</strong>, and <strong>Apple</strong>, but it can be extended with <strong>Auth0</strong>.</p><p><strong>Learning Curve</strong> — I feel like AWS Amplify has a steeper learning curve and is more difficult to understand for frontend engineers compared to Firebase. Amplify is just a building block and a CLI-guided command to manage AWS resources. So, you need to understand several AWS products to understand how Amplify works. For example, if I want to add new data fields to DynamoDB, I need to go through a few steps, unlike Firestore, where I can directly create new data on the Firebase console.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fjo_aaqchdNI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Djo_aaqchdNI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fjo_aaqchdNI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8cdedfa28b34f839f4d705ef6cca0bb/href">https://medium.com/media/a8cdedfa28b34f839f4d705ef6cca0bb/href</a></iframe><p><strong>Less Community Discussion</strong> — As I mentioned before, AWS Amplify has a higher learning curve. So, in case you encounter errors, issues, or something that you don’t know, the discussion and Q&amp;A on Stack Overflow or GitHub is fewer compared to Firebase. I even subscribed to the AWS Developer Support so I can get access to developer support from AWS itself if I have technical questions.</p><h3>Conclusion</h3><p>As front-end engineers, both Amplify and Firebase can solve complex problems related to the back end when building our own product. If asked which one I prefer, it depends.</p><p>If I want to build a non-serious product or something just for fun with the community, I would choose Firebase. However, if I want to build a serious product that will be my side income, I would choose Amplify.</p><h3>Resources</h3><ul><li><a href="https://docs.amplify.aws/">https://docs.amplify.aws/</a></li><li><a href="https://firebase.google.com/docs">https://firebase.google.com/docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6fd76058416" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/amplify-vs-firebase-a-head-to-head-comparison-with-a-real-product-b6fd76058416">Amplify vs. Firebase: A Head-to-Head Comparison With My Real Product</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expand Your Front End Skills With Machine Learning]]></title>
            <link>https://titusefferian.medium.com/expand-your-front-end-skills-with-machine-learning-f9780b99740f?source=rss-7d2073714e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9780b99740f</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[tensorflowjs]]></category>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Titus Efferian]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 08:20:09 GMT</pubDate>
            <atom:updated>2021-03-05T08:45:34.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*6OiWEap9JPEY_-66ZQk2_A.png" /></figure><p>As a software engineer especially in front end fields, we usually becomes an enabler for product and business to create things. As times goes on, front end not only do UI Layout and API integration, now we can do machine learning right on our client side.</p><p>Here I am going to share my experiment on how to create computer vision model to determine your hand sign with Alphabet ASL (American Sign Language). <br><strong>What i did here can also be done with any front end fields out there (iOS, Android, Web Platform)</strong>,<em> </em>but i will use web platform as example because currently I am active in javascript.</p><p><strong>Mandatory prerequisite to follow:</strong></p><ol><li>Basic understanding of project management on Google Cloud Platform.</li><li>Basic understanding of this Google Cloud Platform products:<br>- Cloud Storage<br>- AutoML Vision<br>- Cloud Shell</li><li>Strong understanding of your front end fields.</li><li>Strong understanding of ML library on your front end fields:<br>- TensorFlow JS (for web platform)<br>- TensorFlow Lite (for android)<br>- Core ML (for iOS)</li><li>Download the dataset here <a href="https://www.kaggle.com/grassknoted/asl-alphabet">https://www.kaggle.com/grassknoted/asl-alphabet</a></li></ol><p>In order to make it easy for you to follow this step by step, i’m going to use <a href="https://cloud.google.com/shell"><strong><em>Google Cloud Shell</em></strong></a><strong><em> </em></strong>so we will have the same environment no matter what your device is.</p><h3>Upload our dataset into cloud shell</h3><p>we need to upload our dataset and resources to cloud shell, so we can play on that environment. Just click the upload button and upload your file <strong>as a zip file.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OfmwSS4ctbdg7YFf-N-bg.png" /></figure><p>and unzip your file with basic linux command:</p><pre>unzip your_zip_name</pre><p>and you will see this folders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*A-R3OzYkGqD-qCHopDhjrg.png" /></figure><h3>Enable AutoML API</h3><p>We need to enable AutoML API, so we can use this products. Go to AI section and choose AI Platform &gt; Dashboard, and click the button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LtDCWXcwnSe1B04g8cNuQ.png" /></figure><p>choose what kind of output that we want to use, for this case we choose the Image Classification (Single-label)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnlbTSXJ61ctEp7zGqDKfA.png" /></figure><p>leave everything by default, and click <strong>create</strong>. And this process will auto create bucket on Cloud Storage for further use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*Rdv9EgwqQuwXvzPp_3QmCg.png" /></figure><h3>Upload our dataset to cloud storage</h3><p>Use <a href="https://cloud.google.com/storage/docs/gsutil"><strong>gsutil</strong></a><strong> </strong>to upload the test and train folders<strong> </strong>to cloud storage. Sample command will look like this, and adjust with your environment. <br>This will takes time because we are uploading 1000+ sample data :D. Go take a coffee break.</p><pre>gsutil -m cp -r ./asl_alphabet_train/asl_alphabet_train gs://cloud-ai-platform-xxxxxxxxxxx/train</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*VXMjFjI3GoTU-XtSfQMrzA.png" /></figure><h3>Labelling our dataset</h3><p>this will be the exhausting part, we need to give a label to all of our data set.</p><p>create a csv file, and do the Labelling with this kind of format:</p><pre>gs://path_to_your_file/A/A1.jpg,A<br>.<br>.<br>gs://path_to_your_file/A/A3000.jpg,A</pre><pre>gs://path_to_your_file/A/B1.jpg,B<br>.<br>.<br>gs://path_to_your_file/A/B3000.jpg,B</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-hksJmjzIb-BGTkURewbw.png" /></figure><p>and you need to create a csv files for all the alphabet (A — Z) and the edge case. Use any of your favourite programming language to make it automated 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*TB564YNmxS3E2ysM.jpg" /></figure><p>Upload all of those csv files to Cloud Storage with the gsutil. Back to AI Platform section, we need to fill all of our csv file location from Cloud Storage to AI Platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LW3VJez_uU6k7x4NZZnt_w.png" /></figure><p>Click continue and you will be redirected to preview process, if all of our previous steps was right, you will see something like this. All of the image with label. Next we click Train New Model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDe_3mLtheN13BmJCT-s8A.png" /></figure><h3>Train New Model</h3><p>After you click Train New Model, the configuration pop up will show. For the training method, choose <strong>AutoML Edge. </strong>AutoML Edge means, that our output will be compatible with any front end fields machine learning library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaNV3FKhlnmz8_gfgrJSig.png" /></figure><p>For the optimizer options, just choose whatever you want or fit your use case, the explanation and the tradeoff are written there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0D6UAlzI2GH_OQELQvG0aw.png" /></figure><p>For the training budget hours, just fill it 15 hours. I will explain later on the pricing section below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmxQMWMlzRyZcStLsVdFFg.png" /></figure><p>Start train your model, and go take another coffee break.</p><h3>Train Result</h3><p>After long wait of training time, you will see the training result and all the summary detail. If everything goes well, you will see high score accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNCj719CqdDVvqpKbISpHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1o8CBuR689AjNurTv8_MWQ.png" /></figure><h3>Export our model</h3><p>You will be given some options which platform you will be targeted. like i mentioned before, we can choose to any of front end fields out there. But for this part i’m going to choose <a href="https://www.tensorflow.org/js/"><strong>tensorflow.js</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Mouie63MMqG-n4cBOjTgQ.png" /></figure><h3>Implement on the web browser</h3><p>Time to code on the client side, i’m going to use nextjs + vercel to make it everything simple for code and deployment. Just create a new nextjs project, and install additional dependencies to implement our models.</p><pre>&quot;@tensorflow/tfjs&quot;: &quot;^2.8.6&quot;,    <br>&quot;@tensorflow/tfjs-automl&quot;: &quot;^1.0.0&quot;,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2azmNf-4ZDakj8J_L6uppw.png" /></figure><p>And the output will be look like this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FayxYY0h-1KA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DayxYY0h-1KA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FayxYY0h-1KA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/50cd0a32ca41a9b7e969067e756a8bc1/href">https://medium.com/media/50cd0a32ca41a9b7e969067e756a8bc1/href</a></iframe><h3>Pricing</h3><p>You need to be careful for this part, because to use Google Cloud Platform you need to bind your payment card into their billing. <strong>What i did here did not consume any money, because i used all the process within free tier.</strong></p><p>Let me breakdown one by one:</p><h4>Cloud AutoML</h4><p>Cloud AutoML have 15 node hours for edge training. The free node hour is issued at the time of the first batch prediction is initiated. You have up to one year to use them. As long as you stay within this range, you are safe.</p><h4>Cloud Storage</h4><p>Cloud Storage offers you this free quota:</p><ul><li>5 GB-months of Standard Storage</li><li>5,000 Class A Operations per month</li><li>50,000 Class B Operations per month</li><li>1 GB network egress from North America to all region destinations (excluding China and Australia) per month</li></ul><p>As long as you stay within this range, you are safe.</p><h4>Cloud Shell</h4><p>Cloud Shell is available at no additional cost for Google Cloud customers.</p><p>Full code implementation:</p><ul><li><a href="https://github.com/TitusEfferian/asl_alphabet">https://github.com/TitusEfferian/asl_alphabet</a></li></ul><p>References:</p><ul><li><a href="https://cloud.google.com/free">https://cloud.google.com/free</a></li><li><a href="https://cloud.google.com/shell">https://cloud.google.com/shell</a></li><li><a href="https://cloud.google.com/storage/docs/gsutil">https://cloud.google.com/storage/docs/gsutil</a></li><li><a href="https://cloud.google.com/vision/automl/docs/quickstart">https://cloud.google.com/vision/automl/docs/quickstart</a></li><li><a href="https://www.kaggle.com/grassknoted/asl-alphabet">https://www.kaggle.com/grassknoted/asl-alphabet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9780b99740f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy your react web apps with google cloud run]]></title>
            <link>https://titusefferian.medium.com/deploy-your-react-web-apps-with-google-cloud-run-d9f54d29708f?source=rss-7d2073714e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f54d29708f</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Titus Efferian]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 00:35:46 GMT</pubDate>
            <atom:updated>2019-12-25T12:00:28.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AATnQpkOXguXXwkc_X8hPA.png" /><figcaption>containerization a web apps using docker and deploy it to google cloud run services.</figcaption></figure><p>As a software engineer especially in a front end scope, not many engineers get their hands into the deployment process. Usually productivity engineer or DevOps already did the configuration in the pipeline, and we as front end engineer just focused on our code. Why don’t we try to learn how to deploy our code with cloud services?</p><p>Google Cloud Run is is a managed compute platform that automatically scales your stateless containers, so we are going to use docker in this step.</p><p><strong>Mandatory prerequisite to follow:<br></strong>1. Install Docker <br>2. Install Google Cloud SDK <a href="https://cloud.google.com/sdk/docs/">(https://cloud.google.com/sdk/docs/)</a><br>3. Create a new project in your dashboard (<a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a>)<br>4. node and npx</p><h4>1. Create a react app</h4><p>We are going to use a default <em>create-react-app </em>for this.</p><pre>npx create-react-app <em>yourProjectName<br></em>cd <em>yourProjectName<br></em>yarn start</pre><p>and make sure it does not throw any error.</p><h4>2. Create a dockerfile configuration</h4><p>We are going to use a simple configuration, here we are using <a href="https://github.com/zeit/serve">serve</a> that can handle client side routing for node environment. Here some useful link if you want to know detail about <a href="https://github.com/zeit/serve">serve</a>.<br><a href="https://create-react-app.dev/docs/deployment">https://create-react-app.dev/docs/deployment</a> <a href="https://github.com/zeit/serve">https://github.com/zeit/serve</a></p><p>And we need to expose 8080 port because Google Cloud Run listen on 8080 port by default.<br><a href="https://cloud.google.com/run/docs/reference/container-contract#port">https://cloud.google.com/run/docs/reference/container-contract#port</a></p><pre>FROM node:12-slim</pre><pre>RUN mkdir -p usr/src/app</pre><pre>WORKDIR /usr/src/app</pre><pre>COPY . .</pre><pre>RUN npm install -g serve</pre><pre>RUN npm install</pre><pre>RUN npm run build</pre><pre>EXPOSE 8080</pre><pre>CMD [&quot;serve&quot;, &quot;-s&quot;, &quot;-l&quot;, &quot;8080&quot;, &quot;./build&quot;]</pre><h4>3. Build and deploy a container</h4><p>We are going to build and deploy a container using google cloud sdk, make sure you are on the root directory of your project.</p><p><strong>Build a container:</strong></p><p>You can find project id in your google console dashboard.</p><pre>gcloud builds submit --tag gcr.io/<em>yourProjectId</em>/hello</pre><p>if it is success, it will looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyrcOCbfrH3bq5W-g5K11A.png" /></figure><p><strong>Deploy a container:</strong></p><pre>gcloud run deploy --image gcr.io/<em>yourProjectId</em>/hello --platform managed</pre><p>and choose some option that google offer for configuration. And if it is success, it will return something like this:</p><pre>Service [hello] revision [hello-00001-luv] has been deployed and is serving 100 percent of traffic at <a href="https://hello-wtjtziv4wq-an.a.run.app/">https://hello-wtjtziv4wq-an.a.run.app</a></pre><p>That’s it! for scaling and provisioning all has been handled by google itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f54d29708f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>