<?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 Farasat Ali on Medium]]></title>
        <description><![CDATA[Stories by Farasat Ali on Medium]]></description>
        <link>https://medium.com/@faraasat?source=rss-51f7a2ca7b50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UPXassyZs4KLyZwsk5jUkg.jpeg</url>
            <title>Stories by Farasat Ali on Medium</title>
            <link>https://medium.com/@faraasat?source=rss-51f7a2ca7b50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:11:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@faraasat/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[Configuring Environments for iOS in React Native Using Xcode — Clean, Clear & Concise]]></title>
            <link>https://blog.stackademic.com/configuring-environments-for-ios-in-react-native-using-xcode-clean-clear-concise-6e80166d6235?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e80166d6235</guid>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 07:52:06 GMT</pubDate>
            <atom:updated>2025-07-27T19:25:09.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>Configuring Environments for iOS in React Native Using Xcode — Clean, Clear &amp; Concise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btBc8qPeGX8lSXS2KEQE3A.jpeg" /><figcaption>Configuring Environments for iOS in React Native Using Xcode — Clean, Clear &amp; Concise</figcaption></figure><p>In this guide, we’ll walk you through a clean, clear, and concise approach to configuring multiple environments — Development, UAT, and Production — without the chaos. Whether you’re managing different APIs, feature flags, or app names, this setup ensures your iOS builds stay organized, scalable, and easy to maintain.</p><p>If you also want to configure for Android, check out this article:</p><p><a href="https://blog.stackademic.com/configuring-environments-for-android-in-react-native-clean-clear-concise-c75b332c55f1">Configuring Environments for Android in React Native — Clean, Clear &amp; Concise</a></p><p>You will be able to set the environment in 7 simple and easy steps:</p><h3>Step 1 — Install Config Library:</h3><p>If you do not have react-native-config already installed, then use one of the following commands according to your package manager:</p><pre># for npm<br>npm install react-native-config<br><br># for yarn<br>yarn add react-native-config<br><br># for pnpm<br>pnpm install react-native-config<br><br># for bun<br>bun add react-native-config</pre><h3>Step 2 — Update Podfile:</h3><p>Now, go to &lt;project&gt;/ios/Podfile and add the following code under the target ‘app’ do line:</p><pre>project &#39;app&#39;, {<br>    &#39;Staging Debug&#39; =&gt; :debug,<br>    &#39;Staging Release&#39; =&gt; :release,<br>    &#39;UAT Debug&#39; =&gt; :debug,<br>    &#39;UAT Release&#39; =&gt; :release,<br>    &#39;Production Debug&#39; =&gt; :debug,<br>    &#39;Production Release&#39; =&gt; :release<br>}</pre><p>The Podfile will look something like:</p><figure><img alt="Podfile code" src="https://cdn-images-1.medium.com/max/1024/1*Cwr6WkajVmAF_NAjkpIj0g.png" /><figcaption>Podfile code</figcaption></figure><p>Now, go to the &lt;project&gt;/ios path and run the following command:</p><pre>pod install</pre><h3>Step 3 — Add New Configurations for the app:</h3><p>Open your project in Explorer and double-click app.xcodeproj to open it in Xcode. You will find this file under &lt;project&gt;/ios .</p><figure><img alt="Opening the project in Xcode" src="https://cdn-images-1.medium.com/max/1024/1*T0CqYtVQMw31G3vjml1fHA.gif" /><figcaption>Opening the project in Xcode</figcaption></figure><p>After the project is open in Xcode as follows, click the <strong>app</strong>, and in configuration and select <strong>app</strong> under the <strong>PROJECT</strong>.</p><figure><img alt="Xcode window" src="https://cdn-images-1.medium.com/max/1024/1*3DGeiHUBkj5pqiUu9Fs8Lg.png" /><figcaption>Xcode window</figcaption></figure><p>You can duplicate the Debug and Release to create a new configuration as you like, and I will create the following new configurations:</p><ul><li>Uat Debug</li><li>Staging Debug</li><li>Uat Release</li><li>Staging Release</li></ul><p>All new Debug configurations will be duplicated from the main Debug configuration, and the same goes for the new Release configurations.</p><p>The default Debug and Release configuration will be for production.</p><figure><img alt="Adding Configurations for Environments" src="https://cdn-images-1.medium.com/max/1024/1*djFjDfDPCGGXqC0CZdKbFg.gif" /><figcaption>Adding Configurations for Environments</figcaption></figure><h3>Step 4 — Add New Schemes:</h3><p>Now, we will be adding New schemes for the environments as shown in the image. On the top bar, click the drop-down and then click <strong>New Scheme</strong>. Name the new scheme and click <strong>Ok</strong>.</p><p>I will be creating 2 new schemes:</p><ul><li>app staging</li><li>app uat</li></ul><p>The default <strong>app</strong> scheme will be used for production.</p><figure><img alt="Adding Configurations for Environments" src="https://cdn-images-1.medium.com/max/1024/1*qMbTtRc2f5gMjs2lIC_LyA.gif" /><figcaption>Adding Schemes for Environments</figcaption></figure><p>Now we edit our recently created schemes and configure the <strong>Run</strong>, <strong>Test</strong>, <strong>Profile</strong>, <strong>Analyze</strong>, and <strong>Archive</strong> according to the configuration we have created. For Example:</p><p>In the <strong>app staging</strong> scheme, we will set the <strong>Staging Debug</strong> configuration for <strong>Run</strong>, <strong>Test</strong>, and <strong>Analyze</strong>, and the <strong>Staging Release</strong> configuration for <strong>Profile</strong> and <strong>Archive</strong>. The same goes for the other schemes, like <strong>app</strong> and <strong>app uat</strong> with their matching configuration.</p><figure><img alt="Editing and Configuring Schemes for Environments" src="https://cdn-images-1.medium.com/max/1024/1*HzMFXXDtvJCi6JVeAa8KvQ.gif" /><figcaption>Editing and Configuring Schemes for Environments</figcaption></figure><h3>Step 5 — Update the Configuration File in the Configurations:</h3><p>Now we will update the configuration files in the configurations, and if you do not see these files, close Xcode and run pod install in the ios folder and again open Xcode.</p><p>The configuration files will be mapped as follows:</p><ul><li><strong>Debug</strong> -&gt; Pods-app.uat.xcconfig</li><li><strong>Release</strong> -&gt; Pods-app.uat.xcconfig</li><li><strong>Uat Debug</strong> -&gt; Pods-app.uat debug.xcconfig</li><li><strong>Uat Release</strong> -&gt; Pods-app.uat release.xcconfig</li><li><strong>Staging Debug </strong>-&gt; Pods-app.staging debug.xcconfig</li><li><strong>Staging Release </strong>-&gt; Pods-app.staging release.xcconfig</li></ul><figure><img alt="Updating the Configuration File in the Configurations" src="https://cdn-images-1.medium.com/max/1024/1*R_AFISpXZkW-PPj7fTfbfQ.gif" /><figcaption>Updating the Configuration File in the Configurations</figcaption></figure><h3>Step 6 — Add User-Defined Config in Build Settings:</h3><p>In the app, click <strong>Build Settings</strong>. You will see a small + sign near Basic and Combined and click <strong>Add User-Defined Setting</strong>. Doing this will add a field in the User-Defined configuration. Name that field as <strong>ENVFILE</strong> and press <strong>ENTER</strong>.</p><p>Now open the ENVFILE dropdown and the path for the related environment file containing the environment variables. For example, we will connect the env files with the config as follows:</p><ul><li><strong>Debug</strong> -&gt; .env</li><li><strong>Release</strong> -&gt; .env</li><li><strong>Staging Debug</strong> -&gt; .env.staging</li><li><strong>Staging Release</strong> -&gt; .env.staging</li><li><strong>Uat Debug</strong> -&gt; .env.uat</li><li><strong>Uat Release</strong> -&gt; .env.uat</li></ul><figure><img alt="Add User-Defined Config in Build Settings" src="https://cdn-images-1.medium.com/max/1024/1*igkkGQ-T4sZ1Q4MbHOla1g.gif" /><figcaption>Add User-Defined Config in Build Settings</figcaption></figure><h3>Step 7 — Add the Script in Schemes:</h3><p>Now, click on the <strong>Schemes</strong> drop-down and click <strong>Edit Scheme</strong>. Open the <strong>Build</strong> drop-down and in <strong>Pre-Actions</strong>, click the + symbol and then the New run script action. After the box for code appears, add the script given below:</p><pre>env_file=&quot;$ENVFILE&quot;<br><br>if [ &quot;$env_file&quot; ]; then<br>    echo &quot;$env_file&quot; &gt; /tmp/envfile<br>else<br>    echo &quot;.env&quot; &gt; /tmp/envfile<br>fi</pre><p>On line 6, echo &quot;.env&quot; &gt; /tmp/envfile you will give the env file relevant to the scheme you opened, for example, <strong>env.staging</strong> for the <strong>Staging Scheme</strong>,<strong> </strong>and so on.</p><figure><img alt="Adding the Script in Schemes" src="https://cdn-images-1.medium.com/max/1024/1*KGNea5vhF7dP1nIsjKc3AA.gif" /><figcaption>Adding the Script in Schemes</figcaption></figure><p>Now what’s remaining is to run your app, your environment variable will be accessible to you according to the selected environment.</p><p>And that’s it, Happy Coding! 😊</p><p>If you liked my story, you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>View Other Related Articles:</p><p><a href="https://blog.stackademic.com/configuring-environments-for-android-in-react-native-clean-clear-concise-c75b332c55f1">Configuring Environments for Android in React Native — Clean, Clear &amp; Concise</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e80166d6235" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/configuring-environments-for-ios-in-react-native-using-xcode-clean-clear-concise-6e80166d6235">Configuring Environments for iOS in React Native Using Xcode — Clean, Clear &amp; Concise</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[Configuring Environments for Android in React Native — Clean, Clear & Concise]]></title>
            <link>https://blog.stackademic.com/configuring-environments-for-android-in-react-native-clean-clear-concise-c75b332c55f1?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/c75b332c55f1</guid>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 09:44:57 GMT</pubDate>
            <atom:updated>2025-07-15T07:53:58.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Configuring Environments for Android in React Native — Clean, Clear &amp; Concise</h3><figure><img alt="Configuring Environments for Android in React Native — Clean, Clear &amp; Concise" src="https://cdn-images-1.medium.com/max/1024/1*2OT2-WP-PqeXNgnr1PUkbg.jpeg" /><figcaption>Configuring Environments for Android in React Native — Clean, Clear &amp; Concise</figcaption></figure><p>In this guide, we’ll walk you through a clean, clear, and concise approach to configuring multiple environments — Development, UAT, and Production — without the chaos. Whether you’re managing different APIs, feature flags, or app names, this setup ensures your Android builds stay organized, scalable, and easy to maintain.</p><p>If you also want to configure for iOS, check out this article:</p><p><a href="https://faraasat.medium.com/configuring-environments-for-ios-in-react-native-using-xcode-clean-clear-concise-6e80166d6235">Configuring Environments for iOS in React Native Using Xcode — Clean, Clear &amp; Concise</a></p><p>You will be able to set the environment in 4 easy steps:</p><h3>Step 1 — Install Config Library:</h3><p>If you do not have react-native-config already installed, then use one of the following commands according to your package manager:</p><pre># for npm<br>npm install react-native-config<br><br># for yarn<br>yarn add react-native-config<br><br># for pnpm<br>pnpm install react-native-config<br><br># for bun<br>bun add react-native-config</pre><h3>Step 2 — Env Files:</h3><p>Create named environment variable files if you do not have any. As for this tutorial, we will create three environments: staging, UAT, and production, with file names env.staging , env.uat , and env respectively on the root directory.</p><pre># you can put your variables in each file as follows<br>URL=&lt;URL_HERE&gt;</pre><h3>Step 3 — Update Build Gradle File:</h3><p>Now open the file /android/app/build.gradle on the following path and make the given changes to it.</p><p>Add the custom environment configuration file declaration at the top of the file, and make sure the project.ext.envConfigFiles declaration must be before the apply command:</p><pre>// android/app/build.gradle<br><br>project.ext.envConfigFiles = [<br>    Production:&#39;.env&#39;,<br>    Staging:&#39;.env.staging&#39;,<br>    Uat: &#39;.env.uat&#39;,<br>]<br><br>apply from: project(&#39;:react-native-config&#39;).projectDir.getPath() + &#39;/dotenv.gradle&#39;</pre><p>Under android &gt; defaultConfig, write the following code:</p><pre>// replace com.medium.example with your package name<br><br>resValue &#39;string&#39;, &#39;build_config_package&#39;, &#39;com.medium.example&#39;</pre><p>Now, in Android, add the following code:</p><pre>flavorDimensions &#39;default&#39;<br>productFlavors {<br>    Staging {<br>        resValue &#39;string&#39;, &#39;app_name&#39;, &#39;\&quot;Medium Example Staging\&quot;&#39;<br>    }<br>    Uat {<br>        resValue &#39;string&#39;, &#39;app_name&#39;, &#39;\&quot;Medium Example UAT\&quot;&#39;<br>    }<br>    Production {<br>        resValue &#39;string&#39;, &#39;app_name&#39;, &#39;\&quot;Medium Example\&quot;&#39;<br>    }<br>}</pre><p>Your build.gradle will finally look like this:</p><figure><img alt="build.gradle config 1" src="https://cdn-images-1.medium.com/max/1024/1*dZ_fCsJJ5MNDXwlwSDw5HQ.png" /><figcaption>build.gradle config 1</figcaption></figure><figure><img alt="build.gradle config 2" src="https://cdn-images-1.medium.com/max/1024/1*FizBkQ__1atPp5_VDPRdAg.png" /><figcaption>build.gradle config 2</figcaption></figure><h3>Step 4 — Update Package.json:</h3><p>Now, as per your convenience, update the package.json and add the following commands:</p><pre>{<br>  // ...<br><br>  &quot;scripts&quot;: {<br>    // ...<br>    &quot;androidRelease&quot;: &quot;cd android &amp;&amp; ./gradlew assembleProductionRelease &amp;&amp; cd ..&quot;,<br>    &quot;androidStagingRelease&quot;: &quot;cd android &amp;&amp; ./gradlew assembleStagingRelease &amp;&amp; cd ..&quot;,<br>    &quot;androidStaging&quot;: &quot;react-native run-android --mode=stagingDebug&quot;,<br>    &quot;androidProduction&quot;: &quot;react-native run-android --mode=productionDebug&quot;<br>  },<br><br>  // ...<br>}</pre><p>And that’s it, Happy Coding! 😊</p><p>If you liked my story, you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>View Other Related Articles:</p><p><a href="https://faraasat.medium.com/configuring-environments-for-ios-in-react-native-using-xcode-clean-clear-concise-6e80166d6235">Configuring Environments for iOS in React Native Using Xcode — Clean, Clear &amp; Concise</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c75b332c55f1" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/configuring-environments-for-android-in-react-native-clean-clear-concise-c75b332c55f1">Configuring Environments for Android in React Native — Clean, Clear &amp; Concise</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[Basics of Blockchain Everyone Should Know — Part 1A: The Fundamentals]]></title>
            <link>https://blog.cubed.run/basics-of-blockchain-everyone-should-know-part-1a-the-fundamentals-187d07755f63?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/187d07755f63</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[technology-trends]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 20:23:13 GMT</pubDate>
            <atom:updated>2024-11-04T08:33:56.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basics of Blockchain Everyone Should Know For Interviews — Part 1A: The Fundamentals</h3><figure><img alt="Basics of Blockchain Everyone Should Know — Part 1A: The Fundamentals" src="https://cdn-images-1.medium.com/max/1024/1*9ghCkhTb9d7lfxF0Ta25wA.jpeg" /><figcaption>Basics of Blockchain Everyone Should Know — Part 1A: The Fundamentals</figcaption></figure><h3>1) Journey of Web:</h3><p>The web didn’t start as the vibrant, chaotic playground we know today. Initially, it was more like a dusty library — plain pages, no comments, no likes, and definitely no memes.</p><h4><strong>i) Web 1.0 (1989–2005):</strong></h4><p><strong>Web 1.0 </strong>refers to the early “read-only” phase of the Internet when the focus was on delivering information with minimal interactivity and limited web design. More importantly, advertising was not allowed.</p><h4><strong>ii) Web 2.0 (2005 — Present):</strong></h4><p><strong>Web 2.0</strong> is the current phase of the Internet. It introduced social media, dynamic websites, and a greater emphasis on user interaction and experience. It popularized technologies like AJAX and JavaScript, but intermediaries controlled data, limiting privacy.</p><h4><strong>iii) Web 3.0 (The Future):</strong></h4><p><strong>Web 3.0</strong> envisions an internet focused on Blockchain, Artificial Intelligence, large backend systems, Ledgers, and databases.</p><h3>2) Centralization vs Decentralization (With Comparison):</h3><p><strong>Centralization</strong> involves the concentration of control under a single organization or entity, such as banks, governments, or corporations, such as Google, Facebook, JP Morgan, etc.</p><p><strong>Decentralization</strong> transfers control or decision-making to a distributed network with no central authority. Examples include Bitcoin, Ethereum, Solana, etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4f5075b53623685c085c7cdadbf819c/href">https://medium.com/media/b4f5075b53623685c085c7cdadbf819c/href</a></iframe><h3>3) Trustlessness:</h3><p>Trustlessness means that participants in a system don’t need to rely on a central authority or trust any single entity to verify transactions or operations. Instead, the system’s rules and mechanisms ensure security and reliability.</p><p><strong>Scenario: </strong>In a centralized bank, users trust the bank to process and validate transactions. In a decentralized blockchain like Bitcoin, trustlessness is achieved because the network’s consensus mechanism verifies transactions without needing to trust a single authority.</p><h3>4) What is Blockchain:</h3><p>Blockchain is a <em>Distributed</em>, <em>Decentralized</em>, <em>Immutable</em>, <em>publicly-available</em> <strong><em>ledger</em></strong> that can be verified. A <strong>ledger</strong> is simply a collection of financial records. Following are some of the Properties of the Blockchain:</p><ul><li><strong>Decentralization:</strong> Blockchain operates without a central authority, relying on a distributed network of participants (nodes) for validation.</li><li><strong>Transparency &amp; Public Availability: </strong>All transactions are visible to all network participants, ensuring openness and accountability.</li><li><strong>Immutability:</strong> Once a transaction is recorded on the blockchain, it cannot be altered or deleted, ensuring data integrity.</li><li><strong>Security:</strong> Blockchain uses cryptographic algorithms to secure data, making it highly resistant to hacking or fraud.</li><li><strong>Chronological Order:</strong> Transactions are recorded in a time-stamped sequence, creating a clear and verifiable history of all activities on the blockchain.</li><li><strong>Irrevocability:</strong> Once a block is added to the blockchain, it becomes permanent and cannot be reversed or tampered with, ensuring the finality of all transactions.</li><li><strong>Consensus Mechanism:</strong> Blockchain relies on consensus algorithms (e.g., Proof of Work, Proof of Stake) to validate transactions and maintain network integrity.</li><li><strong>Trustlessness:</strong> Blockchain eliminates the need for intermediaries, as the system relies on the rules of the network rather than trusted third parties.</li><li><strong>Programmability:</strong> Smart contracts can be embedded into blockchains, allowing automated execution of predefined conditions.</li><li><strong>Distributed Ledger:</strong> The blockchain acts as a shared ledger that is replicated across all participants, ensuring uniform access to data.</li><li><strong>Anonymity/Pseudonymity:</strong> Users can participate in blockchain networks with public addresses instead of personal identification, preserving their privacy.</li></ul><h3>5) Types of Blockchains:</h3><p>There are four main types of Blockchains:</p><h4>i) Public Blockchain</h4><p>Open and decentralized networks where anyone can participate, verify transactions, and maintain the blockchain. No single entity controls the network. Example: Bitcoin, Ethereum.</p><p><strong>Use Case</strong>: Cryptocurrency, decentralized applications (dApps), peer-to-peer transactions</p><p><strong>Current Uses: Bitcoin</strong> facilitates global, borderless, peer-to-peer payments without needing intermediaries like banks. <strong>Ethereum</strong> supports decentralized finance (DeFi) applications such as <strong>Uniswap</strong>, where users can trade cryptocurrencies without relying on centralized exchanges.</p><h4><strong>ii) Private Blockchain</strong></h4><p>Permissioned and centralized networks where only specific participants can join. Controlled by a single organization, they offer privacy and are used for internal operations. An example is Hyperledger Fabric.</p><p><strong>Use Case</strong>: Supply chain management, internal data sharing, and asset tracking</p><p><strong>Current Uses:</strong> <strong>Walmart</strong> uses Hyperledger Fabric to track the origin and movement of food products from farm to store. It provides real-time data on product status, enhances transparency, reduces fraud, and ensures faster recalls when necessary.</p><h4><strong>iii) Consortium Blockchain</strong></h4><p>Semi-decentralized networks managed by a group of organizations rather than a single entity, enabling collaboration across an industry. Example: Corda, Quorum.</p><p><strong>Use Case</strong>: Cross-organization collaboration in banking, supply chain, and healthcare</p><p><strong>Current Uses:</strong> <strong>M</strong>ultiple banks use R3’s Corda for trade finance solutions. It allows secure, real-time sharing of transaction records between banks and customers, speeding up the payment settlement process and reducing reconciliation errors.</p><h4><strong>iv) Hybrid Blockchain</strong></h4><p>Combines features of both public and private blockchains. Data can be selectively made public or kept private, offering flexibility in control and transparency. Example: Dragonchain.</p><p><strong>Use Case</strong>: Use cases requiring privacy with selective transparency, such as enterprise applications</p><p><strong>Current Uses:</strong> <strong>Dragonchain</strong> was developed by Disney to securely handle internal enterprise processes and public verification. Sensitive information like identity management can remain private while allowing public access to verify certain records when needed.</p><h3>6) Basic Cryptography:</h3><h4><strong>i) Private Key</strong></h4><p>A private key functions like a password for a blockchain account. Whoever possesses the private key can access and manage the account’s funds. It’s crucial to store private keys securely, ideally in multiple locations, and never share them online. A private key is a 64-digit hexadecimal number and can be encrypted using a password, resulting in an Encrypted Private Key (EPK).</p><h4><strong>ii) Public Key</strong></h4><p>The public key, derived from the private key, acts as the account’s identifier. It allows nodes in the network to validate signed transactions. It’s safe to share, as it’s also a 64-digit hexadecimal number. While longer than an address, it’s less convenient for frequent use.</p><h4><strong>iii) Address</strong></h4><p>An address on Ethereum is a more compact version of a public key, consisting of 20 bytes (160 bits or 40 hex characters). Multiple addresses can be derived from a single public key, all pointing to the same account. Example: 0x5FaBa0a090a65744EE9D799c1108e1E2DD1cA33A.</p><pre>Private Key -&gt; H(X) -&gt; Public Key -&gt; H(X) -&gt; Address</pre><h4><strong>iv) Hash Function</strong></h4><p>Hash functions are “one-way” cryptographic algorithms with no known inverse. They are fast, produce uniform outputs, and are deterministic, ensuring the same output for the same input. Hash collisions are extremely rare.</p><h4><strong>v) Seed Phrase</strong></h4><p>A seed phrase is a sequence of 12 or 24 words selected from a predefined list of 2048 words, with the order being crucial. It can be used to recover the private key by regenerating it, following the BIP39 standard</p><h4>vi) Encryption vs Digital Signature:</h4><p><strong>Encryption</strong> is a process that transforms data into a secure format, ensuring only authorized parties can access it. It uses a key to convert plaintext into ciphertext, which can only be decrypted back into readable form by those who possess the corresponding decryption key. The main goal of encryption is to protect the confidentiality of data.</p><pre>To Encrypt: Msg + Key -&gt; E(X) -&gt; Encrypted Msg<br>To Decrypt: Encrypted Msg + Key -&gt; D(X) -&gt; Decrypted Msg</pre><p><strong>A Digital Signature</strong> is a cryptographic method used to verify the authenticity and integrity of digital data or transactions. It works by generating a unique signature based on the sender’s private key and the message’s contents. The recipient can then use the sender’s public key to confirm that the message hasn’t been altered and that it was indeed sent by the correct person.</p><pre>To Sign: Msg + Private Key -&gt; S(X) -&gt; Signed Msg<br>To Verify: Signed Msg + Public Key -&gt; V(X) -&gt; Msg</pre><h3>7) Transaction in Blockchain:</h3><p>A blockchain transaction transfers value or data between accounts, recorded on a distributed ledger. It involves creating a digital record verifiable by nodes in the network, ensuring accuracy and immutability. Transactions can include sending cryptocurrency, executing smart contracts, or storing information.</p><h4><strong>i) Fees/Gas</strong></h4><p>In blockchain networks, transaction fees (often called “gas” in Ethereum) are required to process and validate transactions. Gas fees compensate miners or validators for their computational work, with the cost depending on network demand and transaction complexity. Higher fees often result in faster transaction processing.</p><h4><strong>ii) Nonce</strong></h4><p>A nonce is a unique number that tracks the number of transactions sent from an account. It prevents double-spending by ensuring that each transaction is processed in the correct order. It is only used in Proof-of-Work (PoW), and it has nothing to do with the Proof-of-Stake (PoS) Consensus Algorithm.</p><h4><strong>ii) Block Confirmation</strong></h4><p>After submitting a transaction, the network must include it in a block and validate it. The more block confirmations a transaction receives, the more secure and irreversible it becomes.</p><h3>7) What Bitcoin &amp; Ethereum Transactions Look Like?</h3><h4>i) General Idea:</h4><p>A transaction consists of To and From accounts that transact an Amount between them, which is then secured by a Digital Signature and requires Gas/Fee. A Transaction Hash or Tx Hash is the hash that contains all the transaction information hashed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFJBL9tEVy7Og_49hqayXg.jpeg" /><figcaption>Transaction in Blockchain (Generalized Overview)</figcaption></figure><p>When the transaction is being created, the inputs to the transactions are all previous transactions, and the output includes <strong>From Address</strong>, <strong>To Address</strong>, <strong>Fee/Gas</strong> &amp; <strong>Change</strong>.</p><figure><img alt="Transaction Inputs &amp; Ouputs" src="https://cdn-images-1.medium.com/max/1024/1*Lh_w2BpUFlgJtGgxHW7VCQ.jpeg" /><figcaption>Transaction Inputs &amp; Ouputs</figcaption></figure><h4>ii) Detailed Overview:</h4><p>A transaction in Bitcoin &amp; Ethereum contains the following:</p><p><strong>Common Fields in Both Transactions:</strong></p><ul><li><strong>To Address</strong>: The recipient’s address.</li><li><strong>From Address</strong>: The sender’s address.</li></ul><p><strong>Distinct Fields in Bitcoin Transaction:</strong></p><ul><li><strong>Inputs</strong>: References previous unspent transaction outputs (UTXOs).</li><li><strong>Outputs</strong>: The destination address(es) where the Bitcoin is being sent.</li><li><strong>Amount</strong>: The value of Bitcoin being transferred.</li><li><strong>Signature</strong>: Digital signature to authorize the transaction.</li><li><strong>Transaction ID (TXID)</strong>: A unique identifier for the transaction.</li><li><strong>Fee</strong>: The transaction fee paid to miners.</li></ul><p><strong>Distinct Fields in Ethereum Transaction:</strong></p><ul><li><strong>Value</strong>: Amount of Ether being sent.</li><li><strong>Gas Limit</strong>: Maximum amount of gas the transaction can consume.</li><li><strong>Gas Price</strong>: The amount the sender is willing to pay per unit of gas.</li><li><strong>Nonce</strong>: A unique number to ensure the transaction is processed in order.</li><li><strong>Data</strong>: Optional field for interacting with smart contracts or sending additional info.</li><li><strong>Signature</strong>: Digital signature to verify the sender’s identity.</li><li><strong>Transaction Hash (Tx Hash)</strong>: Unique identifier of the transaction, which is generated by hashing all the fields in the transaction.</li></ul><h3><strong>8) Transaction Lifecycle:</strong></h3><p>When a transaction is initiated, it first enters a holding area known as the <strong>Transaction Pool</strong> (or mempool). This is essentially a waiting room where all pending transactions reside before being validated and added to the blockchain. From here, <strong>miners</strong> (in proof-of-work systems) or <strong>validators</strong> (in proof-of-stake systems) pick up these transactions for processing.</p><p>The next step involves verifying the transaction’s authenticity. This includes checking critical elements such as the digital signature, ensuring that the sender has sufficient funds, and confirming that the transaction complies with the protocol’s rules.</p><p>Once validated, miners or validators begin bundling verified transactions into blocks. After a block is fully assembled, it is added to the blockchain, thereby making the transaction officially recorded and irreversible. This final step ensures the transaction is permanently embedded within the decentralized ledger, completing its lifecycle.</p><figure><img alt="Transaction Lifecycle for Bitcoin and Ethereum" src="https://cdn-images-1.medium.com/max/1024/1*Vvto3jFtL6deq4mVwjuHpQ.jpeg" /><figcaption>Transaction Lifecycle for Bitcoin and Ethereum</figcaption></figure><h3>9) Empty Transaction &amp; Why It Happens?</h3><p>When a miner receives a transaction and begins creating a new block, they may encounter a situation where they receive another block to review. In this scenario, the miner must assess the new block and determine which transactions must be removed from the transaction pool. However, the miner cannot know which transactions will be removed in advance, which temporarily halts their ability to create a new block.</p><p>To continue the process, the miner might opt to create an empty block, as they know the previous block&#39;s hash and can work to find a nonce that will generate a valid block hash. If they successfully meet the necessary conditions, they will submit this empty block. It’s important to note that the blockchain protocol does not consider the number of transactions contained within a block; both empty and filled blocks have the same probability of successfully finding a nonce.</p><h3>10) Cyber Attacks On Blockchain:</h3><p>Some Basic Attacks on Blockchain include:</p><h4><strong>i) Sybil Attack</strong></h4><p>In this attack, a single entity creates multiple fake identities (nodes) to take control of the blockchain network and disrupt its functioning by flooding it with malicious activity.</p><h4><strong>ii) 51% Attack</strong></h4><p>When an attacker gains control of over 50% of a blockchain’s mining power or network hash rate, they can manipulate it by reversing transactions and double-spending coins.</p><h4><strong>iii) Double-Spending Attack</strong></h4><p>This occurs when a malicious actor tries to spend the same cryptocurrency more than once by altering the blockchain, leading to financial loss for those who accept invalid transactions.</p><h4><strong>iv) Replay Attack</strong></h4><p>An attacker duplicates a transaction on another blockchain that shares the same or similar codebase, tricking the receiver into accepting a payment that was only meant for a different network.</p><h4><strong>v) Eclipse Attack</strong></h4><p>In an eclipse attack, the attacker isolates a node by controlling or spoofing all the node’s incoming and outgoing connections, making it believe it’s connected to the actual blockchain when it’s not.</p><h4><strong>vi) Routing Attack</strong></h4><p>Attackers intercept network traffic and delay or manipulate the blockchain’s propagation process, leading to discrepancies in transaction validation across the network.</p><h4><strong>vii) Smart Contract Exploits</strong></h4><p>Malicious actors find vulnerabilities in smart contract code, exploiting logic flaws or bugs to drain funds or cause the smart contract to behave unintendedly.</p><h4><strong>viii) Timejacking Attack</strong></h4><p>The attacker manipulates the network’s sense of time by broadcasting incorrect timestamps, which can cause miners to waste resources on the wrong chain or cause a temporary blockchain split.</p><h4><strong>ix) Phishing Attack</strong></h4><p>Attackers trick users into revealing private keys or login credentials through fake websites or communication, leading to the theft of cryptocurrencies from wallets or exchanges.</p><h4><strong>x) Dusting Attack</strong></h4><p>Tiny amounts of cryptocurrency (dust) are sent to numerous wallet addresses. When the victim uses these small amounts, attackers track and analyze transactions to de-anonymize wallet owners.</p><h3>* Stay Tuned for Following Topics in Part 2:</h3><ul><li>Block &amp; Genesis Block</li><li>Mining Process</li><li>Consensus Algorithms</li><li>Forks and Chain Resolution</li><li>Mining Strategy &amp; Difficulty</li><li>Node</li><li>Merkle Tree</li><li>Scalability Trilemma</li><li>Stable Coins &amp; Types</li><li>and much more…</li></ul><p>If you liked my story you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>View Other Related Articles:</p><ul><li><a href="https://faraasat.medium.com/how-i-reduced-my-solidity-smart-contract-size-practical-guide-59cfe1ad3c7d">How I Reduced My Solidity Smart Contract Size - Practical Guide</a></li><li><a href="https://coinsbench.com/comprehensive-guide-tips-and-tricks-for-gas-optimization-in-solidity-5380db734404">Comprehensive Guide: Tips and Tricks for Gas Optimization in Solidity</a></li><li><a href="https://coinsbench.com/an-analytical-look-at-eip-1559-and-eip-3529-e1463725a300">An Analytical Look at EIP-1559 and EIP-3529</a></li><li><a href="https://coinsbench.com/exploring-ethereum-transaction-fees-an-in-depth-analysis-of-eip-1559-and-costing-96a9bc6127ec">Exploring Ethereum Transaction Fees: An In-Depth Analysis of EIP-1559 and Costing</a></li><li><a href="https://coinsbench.com/web-evolution-navigating-the-difference-between-web3-and-web-3-0-982b26c4a891">Web Evolution: Navigating the Difference Between Web3 and Web 3.0!</a></li></ul><h3>Cubed</h3><p><em>Thank you for being a part of the community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>Visit our platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://venturemagazine.net/"><strong>Venture</strong></a> | <a href="https://cubed.run/"><strong>Cubed</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=187d07755f63" width="1" height="1" alt=""><hr><p><a href="https://blog.cubed.run/basics-of-blockchain-everyone-should-know-part-1a-the-fundamentals-187d07755f63">Basics of Blockchain Everyone Should Know — Part 1A: The Fundamentals</a> was originally published in <a href="https://blog.cubed.run/">Cubed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Puppeteer/Chromium on AWS Lambda with Node.js 20+ — Working Guide]]></title>
            <link>https://blog.stackademic.com/running-puppeteer-chromium-on-aws-lambda-with-node-js-20-working-guide-4ab26510e91b?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ab26510e91b</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 06:01:57 GMT</pubDate>
            <atom:updated>2024-10-14T06:24:35.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>Running Puppeteer/Chromium on AWS Lambda with Node.js 20+ — Working Guide</h3><figure><img alt="Running Puppeteer/Chromium on AWS Lambda with Node.js 20+ — Working Guide" src="https://cdn-images-1.medium.com/max/1024/1*JfPu00W8xI1XFXtPnBD-CA.jpeg" /><figcaption>Running Puppeteer/Chromium on AWS Lambda with Node.js 20+ — Working Guide</figcaption></figure><p>Last time, I was working with PDF generation using Puppeteer. It worked fine when we were using AWS Linux 2 and Node.js 18. However, we started getting different issues when we moved to AWS Linux 2023 and upgraded our node version to 20. We solved these various issues, and in the end, we succeeded in generating the PDF, but alas, the PDF generated was corrupted.</p><p>After discussing it with our team, we decided to move the Puppeteer to AWS Lambda so that whatever we change in our instance does not impact our PDF-generation functionality. This also helped us cut costs, as generating PDF reports was the functionality for our admins. We used The following steps to migrate our Puppeteer to AWS Lambda successfully.</p><h3>1) Preparing Code for AWS Lambda:</h3><p>Create a folder with any name; in my case, I have to create puppeteer-lambda . After that, initialize the npm package using:</p><pre>npm init --y</pre><p>Install the following packages and make sure to install the exact versions. To install, run the following command:</p><pre>yarn add @sparticuz/chromium@122.0.0 puppeteer-core@22.5.0</pre><p>After installing packages and doing some editing, my package.json looks as follows:</p><pre>{<br>  &quot;name&quot;: &quot;puppeteer-lambda&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.mjs&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@sparticuz/chromium&quot;: &quot;122.0.0&quot;,<br>    &quot;puppeteer-core&quot;: &quot;22.5.0&quot;<br>  }<br>}</pre><p>Now, create a file with the name of index.mjsand paste the following code:</p><pre>import chromium from &quot;@sparticuz/chromium&quot;;<br>import puppeteer from &quot;puppeteer-core&quot;;<br><br>export const handler = async (event, _context, _callback) =&gt; {<br>  let browser = null;<br>  let result = null;<br><br>  // await chromium.font(&quot;/var/task/fonts/NotoColorEmoji.ttf&quot;);<br>  // Recommended if using url<br>  // await chromium.font(<br>  //   &quot;https://raw.githack.com/googlei18n/noto-emoji/master/fonts/NotoColorEmoji.ttf&quot;<br>  // );<br><br>  try {<br>    // Extracting the HTML from the event object<br>    const html = event.body.html;<br>    const args = [...chromium.args, &quot;--disable-gpu-sandbox&quot;];<br><br>    // creating puppeteer browser instance<br>    browser = await puppeteer.launch({<br>      args: args,<br>      defaultViewport: chromium.defaultViewport,<br>      executablePath: await chromium.executablePath(),<br>      headless: chromium.headless,<br>      ignoreHTTPSErrors: true,<br>      dumpio: true,<br>    });<br><br>    // Create a new page<br>    const page = await browser.newPage();<br><br>    // setting the html content<br>    await page.setContent(html, { waitUntil: &quot;domcontentloaded&quot; });<br><br>    // To reflect CSS used for screens instead of print<br>    await page.emulateMediaType(&quot;screen&quot;);<br><br>    // If you are using custom fonts<br>    await page.evaluateHandle(&quot;document.fonts.ready&quot;);<br><br>    // configurations for generating pdfs<br>    const pdf = await page.pdf({<br>      // path: &quot;result.pdf&quot;,<br>      margin: { top: &quot;100px&quot;, right: &quot;50px&quot;, bottom: &quot;100px&quot;, left: &quot;50px&quot; },<br>      printBackground: true,<br>      format: &quot;A4&quot;,<br>    });<br><br>    // converting pdf to base64<br>    result = pdf.toString(&quot;base64&quot;);<br>  } catch (error) {<br>    console.log(&quot;-----handler---&quot;, error);<br>  } finally {<br>    if (browser !== null) {<br>      await browser.close();<br>    }<br>  }<br><br>  return result;<br>};</pre><p>Your folder structure would look like as follows:</p><pre>.<br>└── puppeteer-lambda/<br>    ├── fonts  (only when you want to upload font file)/<br>    │   └── NotoNaskhArabic-VariableFont_wght.ttf   (Any font file)<br>    ├── node_modules<br>    ├── index.mjs<br>    ├── package.json<br>    └── yarn.lock   (depends upon your package manager)</pre><p>Now go into the folder and compress all files in the folder: <strong><em>(Note: node_modules will also be the part of compressed folder)</em></strong></p><figure><img alt="Compressing the files (Mac) — Same procedure for Windows" src="https://cdn-images-1.medium.com/max/1024/1*41aUrVkcuqtbbzYsbQfuiQ.gif" /><figcaption>Compressing the files (Mac) — Same procedure for Windows</figcaption></figure><h3>2) Deploying Code on AWS Lambda</h3><p>Visit <a href="https://console.aws.amazon.com/">https://console.aws.amazon.com/</a> and log in to your account. In the search bar, search for Lambda and then click on it. After that, click on Create Lambda Function.</p><figure><img alt="Searching for Lambda in AWS Console" src="https://cdn-images-1.medium.com/max/1024/1*0DUpb4x_vRvdJXXbDBqrsg.jpeg" /><figcaption>Searching for Lambda in AWS Console</figcaption></figure><p>Now configure your Lambda in the creation pane. I have named mine as puppeteer-lambd ; you can name it whatever you want. Optionally, enable the function URL if you require it. Lambda creation looks as follows:</p><figure><img alt="Lambda Creation Screen Section 1" src="https://cdn-images-1.medium.com/max/951/1*2_gA2zkM5HEKS8j2iGq-Cg.jpeg" /><figcaption>Lambda Creation Screen Section 1</figcaption></figure><figure><img alt="Lambda Creation Screen Section 2" src="https://cdn-images-1.medium.com/max/914/1*ACltlU3miRL41KDxwOPZyw.jpeg" /><figcaption>Lambda Creation Screen Section 2</figcaption></figure><p>After creating the Lambda, you will see the following screen; click on the configuration to update the configuration:</p><figure><img alt="After Lambda Creation Screen" src="https://cdn-images-1.medium.com/max/1024/1*aN22g3bVCQqVhXSY6yiX-w.jpeg" /><figcaption>After Lambda Creation Screen</figcaption></figure><p>Now, you can update the memory (RAM), Ephemeral Storage, and Timeout accordingly:</p><figure><img alt="Lambda Configuration Pane" src="https://cdn-images-1.medium.com/max/1024/1*AP8jYtBqYYbSUp6UseK3Jw.jpeg" /><figcaption>Lambda Configuration Pane</figcaption></figure><p>Now, you can upload the compressed folder in two ways: using the direct method if the compressed file is less than 50MB. Otherwise, you will require your file to be uploaded to S3, and then you have to copy the URL to the input.</p><figure><img alt="Uploading Compressed File" src="https://cdn-images-1.medium.com/max/1024/1*Nl_RUZ5zPBAHKxvQqIxUqg.jpeg" /><figcaption>Uploading Compressed File</figcaption></figure><p>Now, to test your code, you can do the following in the Tests tab:</p><figure><img alt="Testing the Lambda Function" src="https://cdn-images-1.medium.com/max/1024/1*mD7p7vs7Q26PmS4W73Aujw.jpeg" /><figcaption>Testing the Lambda Function</figcaption></figure><p>Now, you can publish the new version by clicking the button in Versions tab:</p><figure><img alt="Publishing a New Version" src="https://cdn-images-1.medium.com/max/1024/1*z1UNsr-UyN5hlzP3WcuQiw.jpeg" /><figcaption>Publishing a New Version</figcaption></figure><h3>3) Adding Code on Your Backend:</h3><p>Now you can add the code in your backend, and you can call this utility function in your route to get pdf:</p><pre>// index.js<br><br>const AWS = require(&quot;aws-sdk&quot;);<br><br>AWS.config.loadFromPath(`./aws.config.json`);<br><br>exports.generatePdfFile = async ({ html }) =&gt; {<br>  try {<br>    const lambda = new AWS.Lambda({});<br><br>    // Invoke the Lambda function<br>    const lambdaResult = await lambda<br>      .invoke({<br>        FunctionName: &quot;puppeteer-lambd&quot;,<br>        Payload: JSON.stringify({<br>          body: {<br>            html: html,<br>          },<br>        }),<br>      })<br>      .promise();<br><br>    if (lambdaResult.StatusCode === 200) {<br>      // The body contains the base64 encoded PDF<br>      const pdfBase64 = JSON.parse(lambdaResult.Payload);<br><br>      // Convert base64 string back to a buffer (binary data)<br>      const pdfBuffer = Buffer.from(pdfBase64, &quot;base64&quot;);<br><br>      // Send the PDF buffer to the client<br>      return pdfBuffer;<br>    } else {<br>      console.log(responsePayload);<br>      throw Error(&quot;Error generating PDF&quot;);<br>    }<br>  } catch (error) {<br>    console.error(&quot;Error invoking Lambda:&quot;, error);<br>    throw Error(&quot;Error generating PDF&quot;);<br>  }<br>};</pre><p>Add a configuration file for AWS credentials:</p><pre>{<br>  &quot;accessKeyId&quot;: &quot;&lt;your-access-key&gt;&quot;,<br>  &quot;secretAccessKey&quot;: &quot;&lt;your-secret-access-key&gt;&quot;,<br>  &quot;region&quot;: &quot;&lt;your-region&gt;&quot;<br>}</pre><p>And that’s it, Happy Coding! 😊</p><p><strong>Access the Code at:</strong></p><p><a href="https://github.com/faraasat/running-puppeteer-on-aws-lambda">GitHub - faraasat/running-puppeteer-on-aws-lambda: Example Code for Article - Running Puppeteer/Chromium on AWS Lambda with Node.js 20+ - Working Guide</a></p><p>If you liked my story you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>View Other Related Articles:</p><ul><li><a href="https://blog.stackademic.com/scaling-node-js-express-app-using-worker-threads-clusters-simple-guide-ac997614aa12">Scaling Node.js/Express App Using Worker Threads &amp; Clusters — Simple Guide</a></li><li><a href="https://blog.stackademic.com/optimizing-3d-model-rendering-in-next-js-by-reducing-blocking-time-using-react-fiber-offscreen-11bd39ca7a67">Optimizing 3D Model Rendering in Next.js by Reducing Blocking Time Using React Fiber Offscreen</a></li><li><a href="https://blog.stackademic.com/creating-animated-avatar-for-your-portfolio-website-using-ready-player-mixamo-next-js-fd4405747b81">Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js</a></li><li><a href="https://blog.stackademic.com/optimizing-your-next-js-app-by-offloading-compute-intensive-tasks-from-main-thread-to-web-workers-bc2fe8e95a6d">Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers</a></li><li><a href="https://blog.stackademic.com/activating-pwa-in-next-js-13-app-directory-using-serwist-simple-guide-b84d2a29da9c">Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide</a></li><li><a href="https://blog.stackademic.com/syncing-tabs-in-next-js-13-using-redux-toolkit-redux-state-sync-simple-guide-f953329c6beb">Syncing Tabs in Next.js 13+  using Redux Toolkit &amp; Redux State Sync— Simple Guide</a></li><li><a href="https://blog.stackademic.com/how-to-generate-blur-image-in-next-js-server-components-using-blur-hash-e032b74c0ebb">How to Generate Blur Image in Next.js Server Components using Blur Hash</a></li><li><a href="https://blog.stackademic.com/adding-pwa-to-next-js-with-app-directory-simple-guide-73284be7b7c1">Adding PWA to Next.js with App Directory — Simple Guide</a></li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ab26510e91b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/running-puppeteer-chromium-on-aws-lambda-with-node-js-20-working-guide-4ab26510e91b">Running Puppeteer/Chromium on AWS Lambda with Node.js 20+ — Working Guide</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[Scaling Node.js/Express App Using Worker Threads & Clusters — Simple Guide]]></title>
            <link>https://blog.stackademic.com/scaling-node-js-express-app-using-worker-threads-clusters-simple-guide-ac997614aa12?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac997614aa12</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 11:22:40 GMT</pubDate>
            <atom:updated>2024-07-15T00:47:04.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaling Node.js/Express App Using Worker Threads &amp; Clusters — Simple Guide</h3><figure><img alt="Scaling Node.js/Express App Using Worker Threads &amp; Clusters — Simple Guide" src="https://cdn-images-1.medium.com/max/1024/1*GBH4fW_5fYoWz4n863C4nQ.jpeg" /><figcaption>Scaling Node.js/Express App Using Worker Threads &amp; Clusters — Simple Guide</figcaption></figure><p>Node.js is a popular JavaScript Runtime based on Google’s V8 Engine and is well-known for its non-blocking, event-driven architecture that makes it fast, efficient, and lightweight. Nowadays, the complexity of applications is increasing, and while building scalable applications, handling multiple tasks concurrently becomes crucial. This is where Node.js Threads and Node.js Clusters come into play, making applications more concurrent and scalable.</p><p>In this article, we will compare them and then see how to code create threads and clusters in Node.js.</p><h3>Node.js Threads:</h3><p>Node.js is a single-threaded runtime and everything runs on the main thread, as a result, when we have a long-running operation it blocks this main thread, and as a result whole application gets stuck. V8 engine implements a library called libuv which lets the node application to spawn up some thread workers. Some of these threads are reserved for garbage collection and others will respond when needed for example an I/O operation.</p><p>To offload some operations, we can spawn up some threads on demand which will shift blocking operations from the main thread to these worker threads. These threads have the ability to communicate back and forth with the main thread.</p><p>You can use the following example code:</p><pre>// thread_example.js (main file)<br><br>const express = require(&quot;express&quot;);<br>const { Worker } = require(&quot;node:worker_threads&quot;);<br><br>const PORT = 5050; // port number to run the server<br>const THREAD_COUNT = 4; // number of threads to run (we will use them in custom threads route)<br><br>const app = express();<br><br>// This route will block the event loop and<br>// will not allow other requests to be processed<br>app.get(&quot;/blocking&quot;, (req, res) =&gt; {<br>  let i = 1;<br>  while (i &lt; 10_000_000_000) {<br>    i++;<br>  }<br>  return res.status(200).send(`Calculation Total is ${i}`);<br>});<br><br>// This route will not block the event loop and<br>// will allow other requests to be processed<br>app.get(&quot;/non-blocking&quot;, (req, res) =&gt; {<br>  // Create a new worker thread<br>  const worker = new Worker(&quot;./worker.js&quot;);<br><br>  // it will listen to the message event from the worker thread<br>  worker.on(&quot;message&quot;, (data) =&gt; {<br>    return res.status(200).send(`Result is ${data}`);<br>  });<br><br>  // it will listen to the error event from the worker thread<br>  worker.on(&quot;error&quot;, (err) =&gt; {<br>    console.error(&quot;Worker error:&quot;, err);<br>    return res.status(404).send(`Error Occurred: ${err.message}`);<br>  });<br><br>  // it will listen to the exit event from the worker thread<br>  worker.on(&quot;exit&quot;, (code) =&gt; {<br>    if (code !== 0) {<br>      console.error(`Worker stopped with exit code ${code}`);<br>    }<br>  });<br>});<br><br>// This route will create multiple worker threads and<br>// will not block the event loop and will allow<br>// other requests to be processed<br>const createWorker = () =&gt; {<br>  // return a promise which will resolve the result<br>  return new Promise((resolve, reject) =&gt; {<br>    // Create a new worker thread<br>    const worker = new Worker(&quot;./worker-custom-threads.js&quot;, {<br>      workerData: { thread_count: THREAD_COUNT },<br>    });<br><br>    // it will listen to the message event from the worker thread<br>    worker.on(&quot;message&quot;, (data) =&gt; {<br>      resolve(data);<br>    });<br><br>    // it will listen to the error event from the worker thread<br>    worker.on(&quot;error&quot;, (err) =&gt; {<br>      reject(err);<br>    });<br><br>    // it will listen to the exit event from the worker thread<br>    worker.on(&quot;exit&quot;, (code) =&gt; {<br>      if (code !== 0) {<br>        console.error(`Worker stopped with exit code ${code}`);<br>      }<br>    });<br>  });<br>};<br><br>// This route will create multiple worker threads and<br>// will not block the event loop and will allow<br>app.get(&quot;/non-blocking-custom-threads&quot;, async (req, res) =&gt; {<br>  try {<br>    // To store Promises from all threads<br>    const workerPromises = [];<br><br>    // Create multiple worker threads<br>    for (let i = 0; i &lt; THREAD_COUNT; i++) {<br>      workerPromises.push(createWorker());<br>    }<br><br>    // Wait for all threads to complete<br>    const threadResult = await Promise.all(workerPromises);<br><br>    // Calculate the result from all threads<br>    const result = threadResult.reduce((acc, val) =&gt; acc + val, 0);<br><br>    // Send the result to the client<br>    return res.status(200).send(`Result is ${result}`);<br>  } catch (error) {<br>    // Handle the error if any<br>    console.error(&quot;Error in non-blocking-custom-threads:&quot;, error);<br>    return res.status(500).send(`Error Occurred: ${error.message}`);<br>  }<br>});<br><br>// Start the server<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}`);<br>});</pre><pre>// worker.js<br><br>const { parentPort } = require(&quot;node:worker_threads&quot;);<br><br>let i = 0;<br>while (i &lt; 10_000_000_000) {<br>  i++;<br>}<br><br>parentPort.postMessage(i);</pre><pre>// worker-custom-threads.js<br><br>const { workerData, parentPort } = require(&quot;node:worker_threads&quot;);<br><br>// workerData is the data passed to the worker thread<br>let i = 0;<br>while (i &lt; 10_000_000_000 / workerData.thread_count) {<br>  i++;<br>}<br><br>parentPort.postMessage(i);</pre><h3>Node.js Clusters:</h3><p>When we run a node.js application, it is assigned to a process in a core. To increase concurrency we can make clusters to make use of other cores.</p><p>Node.js provides out-of-the-box application layer clustering which can also perform load-balancing and is good for small projects. In the case of Clusters, it isolates each node.js process and if this isolation is not required, worker threads are better to use.</p><p>When we create a cluster all secondary node instances span each core while the primary node.js instance load balances the traffic between other node.js instances using Round-Robin Algorithm.</p><p>You can use the following example code:</p><pre>// cluster_example.js<br><br>import cluster from &quot;cluster&quot;;<br>import os from &quot;os&quot;;<br>import { dirname } from &quot;path&quot;;<br>import { fileURLToPath } from &quot;url&quot;;<br><br>// Get the directory path<br>const __dirname = dirname(fileURLToPath(import.meta.url));<br>// Get the number of logical CPU cores<br>const CPU_COUNT = os.cpus().length;<br><br>console.log(`Total Number of CPUs: ${CPU_COUNT}`);<br>console.log(`Primary pid=${process.pid}`);<br><br>// Setup the primary cluster<br>cluster.setupPrimary({<br>  exec: __dirname + &quot;/cluster.js&quot;,<br>});<br><br>// spawn a new worker process for each CPU core<br>for (let i = 0; i &lt; CPU_COUNT; i++) {<br>  cluster.fork();<br>}<br><br>// if a worker dies, spawn another worker<br>cluster.on(&quot;exit&quot;, (worker, code, signal) =&gt; {<br>  console.log(<br>    `Worker ${worker.process.pid} died, code=${code}, signal=${signal}`<br>  );<br>  console.log(`Starting Another Worker...`);<br>  cluster.fork();<br>});</pre><pre>// cluster.js<br><br>import express from &quot;express&quot;;<br><br>const PORT = 5050; // port number to run the server<br><br>const app = express();<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  let total = 0;<br>  for (let i = 0; i &lt; 50_000_000; i++) {<br>    total++;<br>  }<br>  res.send(`The result of task is ${total}\n`);<br>});<br><br>// Start the server<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}`);<br>  console.log(`worker pid is ${process.pid}`);<br>});</pre><p>If you want to have much easier control, you can use the following NPM package:</p><pre>npm i pm2</pre><p>To start a cluster, run the following command:</p><pre>pm2 start app.js</pre><p>Other useful commands are:</p><pre># list clusters<br>pm2 list<br># stop cluster<br>pm2 stop     &lt;app_name|namespace|id|&#39;all&#39;|json_conf&gt;<br># restart cluster<br>pm2 restart  &lt;app_name|namespace|id|&#39;all&#39;|json_conf&gt;<br># delete cluster<br>pm2 delete   &lt;app_name|namespace|id|&#39;all&#39;|json_conf&gt;</pre><h3>Thread vs Clusters:</h3><p>Threads are best to use when we want to have:</p><ul><li>Shared Memory Access</li><li>Real-Time Processing</li><li>Parallel Processing</li></ul><p>Cluster Modules are better to use when we want load balancing and multiple servers running on the same port. They are best when we use them for:</p><ul><li>Handling Concurrent HTTP Request</li><li>CPU Bound Task</li><li>Isolating Task</li></ul><h3>References:</h3><ul><li><a href="https://nodejs.org/api/worker_threads.html">Worker threads | Node.js v25.9.0 Documentation</a></li><li><a href="https://nodejs.org/api/cluster.html">Cluster | Node.js v25.8.1 Documentation</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6lHvks6R6cI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6lHvks6R6cI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6lHvks6R6cI%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/2945dc471b8def5220944f814df955ae/href">https://medium.com/media/2945dc471b8def5220944f814df955ae/href</a></iframe><p>And that’s it, Happy Coding! 😊</p><p><strong>Access the Code at:</strong></p><p><a href="https://github.com/faraasat/nodejs-clusters-and-threads">GitHub - faraasat/nodejs-clusters-and-threads: Example Code for Article - Scaling Node.js/Express App Using Worker Threads &amp; Clusters - Simple Guide</a></p><p>If you liked my story you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>View Other Related Articles:</p><ul><li><a href="https://blog.stackademic.com/optimizing-3d-model-rendering-in-next-js-by-reducing-blocking-time-using-react-fiber-offscreen-11bd39ca7a67">Optimizing 3D Model Rendering in Next.js by Reducing Blocking Time Using React Fiber Offscreen</a></li><li><a href="https://blog.stackademic.com/creating-animated-avatar-for-your-portfolio-website-using-ready-player-mixamo-next-js-fd4405747b81">Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js</a></li><li><a href="https://blog.stackademic.com/optimizing-your-next-js-app-by-offloading-compute-intensive-tasks-from-main-thread-to-web-workers-bc2fe8e95a6d">Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers</a></li><li><a href="https://blog.stackademic.com/activating-pwa-in-next-js-13-app-directory-using-serwist-simple-guide-b84d2a29da9c">Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide</a></li><li><a href="https://blog.stackademic.com/syncing-tabs-in-next-js-13-using-redux-toolkit-redux-state-sync-simple-guide-f953329c6beb">Syncing Tabs in Next.js 13+  using Redux Toolkit &amp; Redux State Sync— Simple Guide</a></li><li><a href="https://blog.devops.dev/using-next-js-13-app-directory-with-hot-reload-enabled-in-docker-simple-guide-60de42840d7e">Using Next.js 13+  App Directory with Hot-Reload Enabled in Docker — Simple Guide</a></li><li><a href="https://blog.stackademic.com/how-to-generate-blur-image-in-next-js-server-components-using-blur-hash-e032b74c0ebb">How to Generate Blur Image in Next.js Server Components using Blur Hash</a></li><li><a href="https://blog.stackademic.com/adding-pwa-to-next-js-with-app-directory-simple-guide-73284be7b7c1">Adding PWA to Next.js with App Directory — Simple Guide</a></li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac997614aa12" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/scaling-node-js-express-app-using-worker-threads-clusters-simple-guide-ac997614aa12">Scaling Node.js/Express App Using Worker Threads &amp; Clusters — Simple Guide</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[Optimizing 3D Model Rendering in Next.js by Reducing Blocking Time Using React Fiber Offscreen]]></title>
            <link>https://blog.stackademic.com/optimizing-3d-model-rendering-in-next-js-by-reducing-blocking-time-using-react-fiber-offscreen-11bd39ca7a67?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/11bd39ca7a67</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[react-three-fiber]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 10:45:16 GMT</pubDate>
            <atom:updated>2024-03-05T01:17:15.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JYGvYhO7qWvIYXf0iE0zA.jpeg" /><figcaption>Optimize 3D Model Rendering in Next.js by Reducing Blocking Time Using React Fiber Offscreen</figcaption></figure><p>Whenever we use CPU-intensive operation on the Web, it becomes sluggish and un-interactable for some time. Rendering a 3D model directly affects the initial loading time of the Web, so we can use Web Workers to load them behind the scenes.</p><p>In this article, we will optimize the loading time of our model which we built in the following article:</p><p><a href="https://blog.stackademic.com/creating-animated-avatar-for-your-portfolio-website-using-ready-player-mixamo-next-js-fd4405747b81">Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js</a></p><p>If you want to study Web Workers in general, you can visit the following article:</p><p><a href="https://blog.stackademic.com/optimizing-your-next-js-app-by-offloading-compute-intensive-tasks-from-main-thread-to-web-workers-bc2fe8e95a6d">Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers</a></p><p>Now without further ado, let&#39;s start our tutorial!</p><h3>1) Install React Three Fiber:</h3><p>To render your model in Web Worker you can install the following dependency using:</p><pre>npm install @react-three/offscreen</pre><h3>2) Moving all the Children of Canvas into Another File:</h3><p>In the previous “Animated Avatar” tutorial we had our model rendered something like this:</p><pre>// components/avatar-renderer.tsx<br><br>&quot;use client&quot;;<br><br>import { Suspense } from &quot;react&quot;;<br><br>import { Canvas } from &quot;@react-three/fiber&quot;;<br>import { Environment, OrbitControls } from &quot;@react-three/drei&quot;;<br><br>import Avatar from &quot;@/Avatar&quot;;<br><br>const ModelRenderer = () =&gt; {<br>  return (<br>    &lt;div className=&quot;w-full h-auto aspect-[24/25]&quot;&gt;<br>      &lt;Suspense<br>        fallback={<br>          &lt;div className=&quot;w-full flex items-center justify-center h-[calc(100vh-300px)] font-bold text-[30px] font-mono text-white&quot;&gt;<br>            loading...<br>          &lt;/div&gt;<br>        }<br>      &gt;<br>        &lt;Canvas<br>          shadows=&quot;basic&quot;<br>          // adjust camera parameters according to your needs<br>          camera={{<br>            position: [0, -5, 1.5],<br>            fov: 50,<br>            castShadow: true,<br>            zoom: 1.3,<br>          }}<br>          className=&quot;w-full h-full&quot;<br>        &gt;<br>          &lt;OrbitControls /&gt;<br>          &lt;ambientLight intensity={1.5} /&gt;<br>          &lt;Environment preset=&quot;sunset&quot; /&gt;<br>          &lt;directionalLight intensity={0.8} /&gt;<br>          &lt;Avatar /&gt;<br>        &lt;/Canvas&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ModelRenderer;</pre><p>Now we will divide this into different files.</p><p>First, we will create scence.tsx which will contain our scene as follows:</p><pre>// scene.tsx<br><br>&quot;use client&quot;;<br><br>import Avatar from &quot;@/Avatar&quot;;<br><br>import { Environment, OrbitControls } from &quot;@react-three/drei&quot;;<br><br>const Scene = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;OrbitControls /&gt;<br>      &lt;ambientLight intensity={1.5} /&gt;<br>      &lt;Environment preset=&quot;sunset&quot; /&gt;<br>      &lt;directionalLight intensity={0.8} /&gt;<br>      &lt;Avatar /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Scene;</pre><p>Now we will create a worker named worker.tsx which will import the scene as follows:</p><pre>// worker.tsx<br><br>&quot;use client&quot;;<br><br>import { render } from &quot;@react-three/offscreen&quot;;<br><br>import Scene from &quot;./scene&quot;;<br><br>render(&lt;Scene /&gt;);</pre><p>Now, in the model-renderer.tsx , rather than importing Canvas from @react-three/fiber now we will import from @react-three/offscreen and configure our components as follows:</p><pre>// components/avatar-renderer.tsx<br><br>&quot;use client&quot;;<br><br>import { Suspense, lazy } from &quot;react&quot;;<br>import { Canvas } from &quot;@react-three/offscreen&quot;;<br><br>const Scene = lazy(() =&gt; import(&quot;./scene&quot;));<br><br>const worker = new Worker(new URL(&quot;./worker.tsx&quot;, import.meta.url), {<br>  type: &quot;module&quot;,<br>});<br><br>const ModelRenderer = () =&gt; {<br>  return (<br>    &lt;div className=&quot;w-full h-auto aspect-[24/25]&quot;&gt;<br>      &lt;Suspense<br>        fallback={<br>          &lt;div className=&quot;w-full flex items-center justify-center h-[calc(100vh-300px)] font-bold text-[30px] font-mono text-white&quot;&gt;<br>            loading...<br>          &lt;/div&gt;<br>        }<br>      &gt;<br>        &lt;Canvas<br>          worker={worker}<br>          fallback={&lt;Scene /&gt;}<br>          shadows=&quot;basic&quot;<br>          camera={{<br>            position: [0, -5, 1.5],<br>            fov: 50,<br>            castShadow: true,<br>            zoom: 1.3,<br>          }}<br>          className=&quot;w-full h-full&quot;<br>        /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ModelRenderer;</pre><p>Make sure to import ModelRenderer dynamically as follows:</p><pre>import dynamic from &quot;next/dynamic&quot;;<br><br>const ModelRenderer = dynamic(() =&gt; import(&quot;@/components/model-renderer&quot;), {<br>  ssr: false,<br>});<br><br>const Page = () =&gt; {<br>  return &lt;&gt;<br>    {/* ... any other code */}<br>    &lt;ModelRenderer /&gt;<br>  &lt;/&gt;<br>}<br><br>export default Page;</pre><h3>Testing Blocking Time:</h3><p>Now we will test for blocking time. The rendered model without the Web Worker is deployed at: <a href="https://next-with-animated-avatar.vercel.app/">https://next-with-animated-avatar.vercel.app/</a>, and it gave the following results:</p><figure><img alt="Model Blocking Time" src="https://cdn-images-1.medium.com/max/1024/1*l010ytw5HRTy7xj5bismXA.png" /><figcaption>Model Blocking Time Without Web Worker</figcaption></figure><p>The model rendered using Web Worker can be found at <a href="https://next-with-animated-avatar-offload.vercel.app/">https://next-with-animated-avatar-offload.vercel.app/</a>. It gave the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7tiXabttx11biy9QNdgDw.png" /><figcaption>Model Blocking Time Web Worker</figcaption></figure><p>And that’s it, Happy Coding! 😊</p><p><strong>Access the Code at:</strong></p><p><a href="https://github.com/faraasat/next-with-animated-avatar-offload">GitHub - faraasat/next-with-animated-avatar-offload: Example code for article - Optimize 3D Model Rendering in Next.js by Reducing Blocking Time Using React Fiber Offscreen</a></p><p><strong>Visit the Live version at: </strong><a href="https://next-with-animated-avatar-offload.vercel.app/">https://next-with-animated-avatar-offload.vercel.app/</a></p><p>If you liked my story you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>You can also explore the following related articles:</p><ul><li><a href="https://blog.stackademic.com/creating-animated-avatar-for-your-portfolio-website-using-ready-player-mixamo-next-js-fd4405747b81">Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js</a></li><li><a href="https://blog.stackademic.com/creating-animated-avatar-for-your-portfolio-website-using-ready-player-mixamo-next-js-fd4405747b81">Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js</a></li><li><a href="https://blog.stackademic.com/how-to-generate-blur-image-in-next-js-server-components-using-blur-hash-e032b74c0ebb">How to Generate Blur Image in Next.js Server Components using Blur Hash</a></li><li><a href="https://blog.devops.dev/using-next-js-13-app-directory-with-hot-reload-enabled-in-docker-simple-guide-60de42840d7e">Using Next.js 13+  App Directory with Hot-Reload Enabled in Docker — Simple Guide</a></li><li><a href="https://faraasat.medium.com/simple-guide-on-deploying-next-js-app-on-heroku-using-cli-27d7465791eb">Simple Guide on Deploying Next.js App on Heroku using CLI</a></li><li><a href="https://blog.stackademic.com/syncing-tabs-in-next-js-13-using-redux-toolkit-redux-state-sync-simple-guide-f953329c6beb">Syncing Tabs in Next.js 13+  using Redux Toolkit &amp; Redux State Sync— Simple Guide</a></li><li><a href="https://blog.stackademic.com/activating-pwa-in-next-js-13-app-directory-using-serwist-simple-guide-b84d2a29da9c">Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide</a></li><li><a href="https://blog.stackademic.com/optimizing-your-next-js-app-by-offloading-compute-intensive-tasks-from-main-thread-to-web-workers-bc2fe8e95a6d">Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers</a></li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11bd39ca7a67" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/optimizing-3d-model-rendering-in-next-js-by-reducing-blocking-time-using-react-fiber-offscreen-11bd39ca7a67">Optimizing 3D Model Rendering in Next.js by Reducing Blocking Time Using React Fiber Offscreen</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[Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js]]></title>
            <link>https://blog.stackademic.com/creating-animated-avatar-for-your-portfolio-website-using-ready-player-mixamo-next-js-fd4405747b81?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd4405747b81</guid>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 09:56:00 GMT</pubDate>
            <atom:updated>2024-03-02T09:32:38.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js &amp; React Three Fiber</h3><figure><img alt="Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js &amp; React Three Fiber" src="https://cdn-images-1.medium.com/max/1024/1*2QBrJAhdoWUNAp-6ionmxg.jpeg" /><figcaption>Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js &amp; React Three Fiber</figcaption></figure><p>In today’s competitive world, a portfolio website is more than just a collection of pretty pictures and code snippets. It’s your virtual business card, a creative playground, and a personal brand ambassador. Whether you’re a designer, developer, writer, or any other creative professional, having a well-crafted portfolio can open doors you never knew existed.</p><h3>Why Does Your Portfolio Matter?</h3><ol><li>First Impression is the Last Impression.</li><li>Give a Platform to Showcase Your Skills.</li><li>Allows you to Tell Your Story Creatively.</li><li>Helps you Stand Out from the Crowd.</li></ol><h3>Creativity and Uniqueness:</h3><p>Creativity and Uniqueness are the two ingredients that can transform an ordinary portfolio into something extraordinary:</p><ol><li><strong>Creativity: </strong>Think beyond the conventional. Experiment with layouts, colors, and interactions. Surprise your visitors. Maybe add a playful animation or an unexpected hover effect. Creativity isn’t about following trends; it’s about setting them.</li><li><strong>Uniqueness: </strong>Your portfolio should scream “you.” Inject your personality into every pixel. Share your process, your inspirations, and your passion projects. Remember, there’s only one you, and that’s your superpower.</li></ol><h3>Ready to Create Your Animated Avatar for Your Portfolio Website?</h3><p>Now we will explore how to breathe life into your portfolio using Ready Player, Mixamo, Next.js, and React Three Fiber.</p><p>without further ado, we will let&#39;s start our tutorial!</p><h4>Step 1 — Initialize Project:</h4><p>To create a new Next.js Project run the following command:</p><pre>npx create-next-app@latest</pre><p>Choose the prompts accordingly:</p><pre>What is your project named? next-with-animated-avatar<br>Would you like to use TypeScript? Yes<br>Would you like to use ESLint? Yes<br>Would you like to use Tailwind CSS? Yes<br>Would you like to use `src/` directory? Yes<br>Would you like to use App Router? (recommended) Yes<br>Would you like to customize the default import alias (@/*)? No</pre><p>If you already have a Next project go to the next step.</p><h4>Step 2 — Generate Avatar using Ready Player:</h4><p>To create an avatar for yourself, you can visit <a href="https://readyplayer.me/">https://readyplayer.me/</a>. After logging in click Create New Avatar. Your screen may look different as I already have one avatar.</p><figure><img alt="Creating your Avatar" src="https://cdn-images-1.medium.com/max/1024/1*PB6CZDkATn7M6w0CR1cf6Q.png" /><figcaption>Creating your Avatar</figcaption></figure><p>I have selected a random avatar and I will continue with the defaults. You can do the customizations as you like. Click “Next” after you have done all styling.</p><figure><img alt="Create Avatar Screen" src="https://cdn-images-1.medium.com/max/1024/1*GpswOkbdzseXXHtChcBiFg.png" /><figcaption>Create Avatar Screen</figcaption></figure><p>Now click the download button and it will download the .glb file.</p><figure><img alt="Downloading Your 3D Avatar" src="https://cdn-images-1.medium.com/max/1024/1*Co_tBAV829ThEAWNC4LULg.png" /><figcaption>Downloading Your 3D Avatar</figcaption></figure><h4>Step 3 — Convert your .glb model file into .fbx using Blender:</h4><p>Import your .glb model in Blender:</p><figure><img alt="Importing Model in Blender" src="https://cdn-images-1.medium.com/max/1024/1*e8KEuvh_VJ4dPVsJcdtwGg.png" /><figcaption>Importing Model in Blender</figcaption></figure><p>Now export your model as .fbx file:</p><figure><img alt="Exporting the model as .fbx" src="https://cdn-images-1.medium.com/max/696/1*Mg5yEsNzgpaemP5lXxWEHw.png" /><figcaption>Exporting the model as .fbx</figcaption></figure><p>This conversion from .glb to .fbx is important because to animate it we have to do it in Mixamo which does not support a .glb file.</p><h4>Step 4 — Find Animation to Add to Your Model:</h4><p>Go to <a href="https://www.mixamo.com/">https://www.mixamo.com/</a> and after signing in click “Upload Character”, when the popup appears, upload the .fbx file.</p><figure><img alt="Uploading Your Model to Mixamo" src="https://cdn-images-1.medium.com/max/1024/1*VTPhJTqxeB7yOCGziT7NAw.png" /><figcaption>Uploading Your Model to Mixamo</figcaption></figure><p>You will see a screen similar to this. Click next for all consecutive screens.</p><figure><img alt="Model on Mixamo" src="https://cdn-images-1.medium.com/max/1024/1*eCOcvWOVaKdyl9Qr6KZgnQ.png" /><figcaption>Model on Mixamo</figcaption></figure><p>Now go to the animations tab and select your favorite animation.</p><figure><img alt="Animation Added to the Model" src="https://cdn-images-1.medium.com/max/1024/1*dHqJKrZBg5fMsYGc4mxQ2w.gif" /><figcaption>Animation Added to the Model</figcaption></figure><p>Now click on “Download” and select the “Without Skin” option and it will download only animation.</p><figure><img alt="Downloading Animation" src="https://cdn-images-1.medium.com/max/1024/1*06rdoWDufqxENi116TQO-Q.png" /><figcaption>Downloading Animation</figcaption></figure><h4>Step 5 — Configuring the Model in the Web App:</h4><p>Now add your model and animation to the /public folder in your app. I have renamed the model avatar.glb and animation as avatar-animation.fbx. Add the required dependencies by running the following commands:</p><pre>npm install three @react-three/fiber @react-three/drei<br>npm install --save-dev @types/three</pre><p>Go to <a href="https://gltf.pmnd.rs/">https://gltf.pmnd.rs/</a> to generate a jsx file for your model and you will get something like below. Paste the code in a file named Avatar.tsx on the root of your project.</p><pre>/*<br>Auto-generated by: https://github.com/pmndrs/gltfjsx<br>*/<br><br>import React, { useRef } from &quot;react&quot;;<br>import { useGLTF } from &quot;@react-three/drei&quot;;<br><br>export function Model(props) {<br>  const { nodes, materials } = useGLTF(&quot;/65e0200654d1a2d49da6c487.glb&quot;);<br>  return (<br>    &lt;group {...props} dispose={null}&gt;<br>      &lt;primitive object={nodes.Hips} /&gt;<br>      &lt;skinnedMesh<br>        name=&quot;EyeLeft&quot;<br>        geometry={nodes.EyeLeft.geometry}<br>        material={materials.Wolf3D_Eye}<br>        skeleton={nodes.EyeLeft.skeleton}<br>        morphTargetDictionary={nodes.EyeLeft.morphTargetDictionary}<br>        morphTargetInfluences={nodes.EyeLeft.morphTargetInfluences}<br>      /&gt;<br>      &lt;skinnedMesh<br>        name=&quot;EyeRight&quot;<br>        geometry={nodes.EyeRight.geometry}<br>        material={materials.Wolf3D_Eye}<br>        skeleton={nodes.EyeRight.skeleton}<br>        morphTargetDictionary={nodes.EyeRight.morphTargetDictionary}<br>        morphTargetInfluences={nodes.EyeRight.morphTargetInfluences}<br>      /&gt;<br>      &lt;skinnedMesh<br>        name=&quot;Wolf3D_Head&quot;<br>        geometry={nodes.Wolf3D_Head.geometry}<br>        material={materials.Wolf3D_Skin}<br>        skeleton={nodes.Wolf3D_Head.skeleton}<br>        morphTargetDictionary={nodes.Wolf3D_Head.morphTargetDictionary}<br>        morphTargetInfluences={nodes.Wolf3D_Head.morphTargetInfluences}<br>      /&gt;<br>      &lt;skinnedMesh<br>        name=&quot;Wolf3D_Teeth&quot;<br>        geometry={nodes.Wolf3D_Teeth.geometry}<br>        material={materials.Wolf3D_Teeth}<br>        skeleton={nodes.Wolf3D_Teeth.skeleton}<br>        morphTargetDictionary={nodes.Wolf3D_Teeth.morphTargetDictionary}<br>        morphTargetInfluences={nodes.Wolf3D_Teeth.morphTargetInfluences}<br>      /&gt;<br>      &lt;skinnedMesh<br>        geometry={nodes.Wolf3D_Hair.geometry}<br>        material={materials.Wolf3D_Hair}<br>        skeleton={nodes.Wolf3D_Hair.skeleton}<br>      /&gt;<br>      &lt;skinnedMesh<br>        geometry={nodes.Wolf3D_Body.geometry}<br>        material={materials.Wolf3D_Body}<br>        skeleton={nodes.Wolf3D_Body.skeleton}<br>      /&gt;<br>      &lt;skinnedMesh<br>        geometry={nodes.Wolf3D_Outfit_Bottom.geometry}<br>        material={materials.Wolf3D_Outfit_Bottom}<br>        skeleton={nodes.Wolf3D_Outfit_Bottom.skeleton}<br>      /&gt;<br>      &lt;skinnedMesh<br>        geometry={nodes.Wolf3D_Outfit_Footwear.geometry}<br>        material={materials.Wolf3D_Outfit_Footwear}<br>        skeleton={nodes.Wolf3D_Outfit_Footwear.skeleton}<br>      /&gt;<br>      &lt;skinnedMesh<br>        geometry={nodes.Wolf3D_Outfit_Top.geometry}<br>        material={materials.Wolf3D_Outfit_Top}<br>        skeleton={nodes.Wolf3D_Outfit_Top.skeleton}<br>      /&gt;<br>    &lt;/group&gt;<br>  );<br>}<br><br>useGLTF.preload(&quot;/65e0200654d1a2d49da6c487.glb&quot;);</pre><p>Now we will edit this file as follows to configure our model:</p><pre>// Avatar.tsx<br><br>&quot;use client&quot;;<br><br>import React, { FC, useEffect, useRef } from &quot;react&quot;;<br>import { useAnimations, useFBX, useGLTF } from &quot;@react-three/drei&quot;;<br>import { GroupProps } from &quot;@react-three/fiber&quot;;<br><br>const Avatar: FC&lt;GroupProps&gt; = (props) =&gt; {<br>  const { nodes, materials } = useGLTF(&quot;/avatar.glb&quot;);<br><br>  // adding ref for group to add animation<br>  const groupRef = useRef();<br><br>  // loading you animation<br>  const { animations: avatarAnimation } = useFBX(&quot;/avatar-animation.fbx&quot;);<br>  // updating you animation name (optional)<br>  avatarAnimation[0].name = &quot;avatar-animation&quot;;<br><br>  // creating actions based on the animation<br>  const { actions } = useAnimations(avatarAnimation, groupRef);<br><br>  // playing the animation<br>  useEffect(() =&gt; {<br>    if (actions?.[&quot;avatar-animation&quot;])<br>      actions[&quot;avatar-animation&quot;].reset().play();<br>  }, [actions]);<br><br>  return (<br>    &lt;group {...props} ref={groupRef as any} dispose={null}&gt;<br>      &lt;group&gt;<br>        &lt;primitive object={nodes.Hips} /&gt;<br>        &lt;skinnedMesh<br>          name=&quot;EyeLeft&quot;<br>          geometry={(nodes.EyeLeft as any).geometry}<br>          material={materials.Wolf3D_Eye}<br>          skeleton={(nodes.EyeLeft as any).skeleton}<br>          morphTargetDictionary={(nodes.EyeLeft as any).morphTargetDictionary}<br>          morphTargetInfluences={(nodes.EyeLeft as any).morphTargetInfluences}<br>        /&gt;<br>        &lt;skinnedMesh<br>          name=&quot;EyeRight&quot;<br>          geometry={(nodes.EyeRight as any).geometry}<br>          material={materials.Wolf3D_Eye}<br>          skeleton={(nodes.EyeRight as any).skeleton}<br>          morphTargetDictionary={(nodes.EyeRight as any).morphTargetDictionary}<br>          morphTargetInfluences={(nodes.EyeRight as any).morphTargetInfluences}<br>        /&gt;<br>        &lt;skinnedMesh<br>          name=&quot;Wolf3D_Head&quot;<br>          geometry={(nodes.Wolf3D_Head as any).geometry}<br>          material={materials.Wolf3D_Skin}<br>          skeleton={(nodes.Wolf3D_Head as any).skeleton}<br>          morphTargetDictionary={<br>            (nodes.Wolf3D_Head as any).morphTargetDictionary<br>          }<br>          morphTargetInfluences={<br>            (nodes.Wolf3D_Head as any).morphTargetInfluences<br>          }<br>        /&gt;<br>        &lt;skinnedMesh<br>          name=&quot;Wolf3D_Teeth&quot;<br>          geometry={(nodes.Wolf3D_Teeth as any).geometry}<br>          material={materials.Wolf3D_Teeth}<br>          skeleton={(nodes.Wolf3D_Teeth as any).skeleton}<br>          morphTargetDictionary={<br>            (nodes.Wolf3D_Teeth as any).morphTargetDictionary<br>          }<br>          morphTargetInfluences={<br>            (nodes.Wolf3D_Teeth as any).morphTargetInfluences<br>          }<br>        /&gt;<br>        &lt;skinnedMesh<br>          geometry={(nodes.Wolf3D_Hair as any).geometry}<br>          material={materials.Wolf3D_Hair}<br>          skeleton={(nodes.Wolf3D_Hair as any).skeleton}<br>        /&gt;<br>        &lt;skinnedMesh<br>          geometry={(nodes.Wolf3D_Body as any).geometry}<br>          material={materials.Wolf3D_Body}<br>          skeleton={(nodes.Wolf3D_Body as any).skeleton}<br>        /&gt;<br>        &lt;skinnedMesh<br>          geometry={(nodes.Wolf3D_Outfit_Bottom as any).geometry}<br>          material={materials.Wolf3D_Outfit_Bottom}<br>          skeleton={(nodes.Wolf3D_Outfit_Bottom as any).skeleton}<br>        /&gt;<br>        &lt;skinnedMesh<br>          geometry={(nodes.Wolf3D_Outfit_Footwear as any).geometry}<br>          material={materials.Wolf3D_Outfit_Footwear}<br>          skeleton={(nodes.Wolf3D_Outfit_Footwear as any).skeleton}<br>        /&gt;<br>        &lt;skinnedMesh<br>          geometry={(nodes.Wolf3D_Outfit_Top as any).geometry}<br>          material={materials.Wolf3D_Outfit_Top}<br>          skeleton={(nodes.Wolf3D_Outfit_Top as any).skeleton}<br>        /&gt;<br>      &lt;/group&gt;<br>    &lt;/group&gt;<br>  );<br>};<br><br>useGLTF.preload(&quot;/avatar.glb&quot;);<br><br>export default Avatar;</pre><p>Add another file avatar-renderer.tsx in /components folder, we create Canvas there and render the model.</p><pre>// components/avatar-renderer.tsx<br><br>&quot;use client&quot;;<br><br>import { Suspense } from &quot;react&quot;;<br><br>import { Canvas } from &quot;@react-three/fiber&quot;;<br>import { Environment, OrbitControls } from &quot;@react-three/drei&quot;;<br><br>import Avatar from &quot;@/Avatar&quot;;<br><br>const ModelRenderer = () =&gt; {<br>  return (<br>    &lt;div className=&quot;w-full h-auto aspect-[24/25]&quot;&gt;<br>      &lt;Suspense<br>        fallback={<br>          &lt;div className=&quot;w-full flex items-center justify-center h-[calc(100vh-300px)] font-bold text-[30px] font-mono text-white&quot;&gt;<br>            loading...<br>          &lt;/div&gt;<br>        }<br>      &gt;<br>        &lt;Canvas<br>          shadows=&quot;basic&quot;<br>          // adjust camera parameters according to your needs<br>          camera={{<br>            position: [0, -5, 1.5],<br>            fov: 50,<br>            castShadow: true,<br>            zoom: 1.3,<br>          }}<br>          className=&quot;w-full h-full&quot;<br>        &gt;<br>          &lt;OrbitControls /&gt;<br>          &lt;ambientLight intensity={1.5} /&gt;<br>          &lt;Environment preset=&quot;sunset&quot; /&gt;<br>          &lt;directionalLight intensity={0.8} /&gt;<br>          &lt;Avatar /&gt;<br>        &lt;/Canvas&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ModelRenderer;</pre><p>At last, we can add this to our main layout. Go to page.tsx and add the following code:</p><pre>// app/page.tsx<br><br>import ModelRenderer from &quot;@/components/model-renderer&quot;;<br><br>export default function Home() {<br>  return (<br>    &lt;div className=&quot;flex items-center justify-center flex-col bg-gray-300&quot;&gt;<br>      &lt;div className=&quot;relative w-[90%] max-w-[1000px] h-auto mt-20&quot;&gt;<br>        &lt;ModelRenderer /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>You will see results something like:</p><figure><img alt="Your Animated Avatar" src="https://cdn-images-1.medium.com/max/1024/1*mfXp8MtTLlvphqaGGNHixA.gif" /><figcaption>Your Animated Avatar</figcaption></figure><p>And that’s it, Happy Coding! 😊</p><p><strong>Access the Code at:</strong></p><p><a href="https://github.com/faraasat/next-with-animated-avatar">GitHub - faraasat/next-with-animated-avatar</a></p><p><strong>Visit the Live version at: </strong><a href="https://next-with-animated-avatar.vercel.app/">https://next-with-animated-avatar.vercel.app/</a></p><p>If you liked my story you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>You can also explore the following related articles:</p><ul><li><a href="https://blog.stackademic.com/adding-pwa-to-next-js-with-app-directory-simple-guide-73284be7b7c1">Adding PWA to Next.js with App Directory — Simple Guide</a></li><li><a href="https://blog.stackademic.com/how-to-generate-blur-image-in-next-js-server-components-using-blur-hash-e032b74c0ebb">How to Generate Blur Image in Next.js Server Components using Blur Hash</a></li><li><a href="https://blog.devops.dev/using-next-js-13-app-directory-with-hot-reload-enabled-in-docker-simple-guide-60de42840d7e">Using Next.js 13+  App Directory with Hot-Reload Enabled in Docker — Simple Guide</a></li><li><a href="https://faraasat.medium.com/simple-guide-on-deploying-next-js-app-on-heroku-using-cli-27d7465791eb">Simple Guide on Deploying Next.js App on Heroku using CLI</a></li><li><a href="https://blog.stackademic.com/syncing-tabs-in-next-js-13-using-redux-toolkit-redux-state-sync-simple-guide-f953329c6beb">Syncing Tabs in Next.js 13+  using Redux Toolkit &amp; Redux State Sync— Simple Guide</a></li><li><a href="https://blog.stackademic.com/activating-pwa-in-next-js-13-app-directory-using-serwist-simple-guide-b84d2a29da9c">Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide</a></li><li><a href="https://blog.stackademic.com/optimizing-your-next-js-app-by-offloading-compute-intensive-tasks-from-main-thread-to-web-workers-bc2fe8e95a6d">Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers</a></li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd4405747b81" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/creating-animated-avatar-for-your-portfolio-website-using-ready-player-mixamo-next-js-fd4405747b81">Creating Animated Avatar for your Portfolio Website Using Ready Player, Mixamo, Next.js</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[Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers]]></title>
            <link>https://blog.stackademic.com/optimizing-your-next-js-app-by-offloading-compute-intensive-tasks-from-main-thread-to-web-workers-bc2fe8e95a6d?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc2fe8e95a6d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 14:22:47 GMT</pubDate>
            <atom:updated>2024-03-02T09:50:48.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers" src="https://cdn-images-1.medium.com/max/1024/1*FOtLDXMub3hcRrA0odgvCw.jpeg" /><figcaption>Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers</figcaption></figure><p>JavaScript which our browser uses, inherently runs on a single thread meaning code execution occurs in a single main thread. While this simplicity ensures predictable behavior, it also poses limitations. Long-running tasks, such as complex computations can block the main thread which could lead to a sluggish user experience.</p><p>To solve this problem, JavaScript provides a way in a browser called <strong>Web Workers</strong> which allows us to run scripts in background threads that are separate from the main thread. Web Workers are different from <strong>Worker Threads</strong> as worker threads are a way to concurrently execute different tasks in multiple parallel contexts of execution in Node.js.</p><p>In web worker, we can perform the following operations:</p><ul><li>Execute arbitrary code.</li><li>Make network calls using fetch .</li><li>Communicate with Main Thread via messages.</li><li>Caching and Push Notifications.</li><li>Access a subset of items available under window, such as WebSockets and IndexedDB.</li></ul><figure><img alt="Web Workers in JavaScript" src="https://cdn-images-1.medium.com/max/1024/1*4chb3nP8XIJOD9UqCgNklA.jpeg" /><figcaption>Web Workers in JavaScript</figcaption></figure><h3>Browser Support:</h3><p>Modern browsers like Chrome, Safari, Firefox, Edge, etc. support web workers. The following chart shows the versions of browsers that support Web Workers:</p><figure><img alt="Browser Support for Web Workers https://caniuse.com/webworkers" src="https://cdn-images-1.medium.com/max/1024/1*n2C3TDMp532JSdagfiOuPg.png" /><figcaption>Browser Support for Web Workers</figcaption></figure><h3>Communication Using postMessage() and onmessage():</h3><p>To move a task from the main thread to a worker thread and vice-versa, we require a communication channel between these two threads (or scripts). The methods postMessage() and onmessage are used to send and receive messages between the main thread and the web worker.</p><figure><img alt="Event Model for Web Worker" src="https://cdn-images-1.medium.com/max/1024/1*OY5_ILkR9N2hLFaHkJ3_Ww.jpeg" /><figcaption>Event Model for Web Worker</figcaption></figure><p>The above example can be expressed using the following code:</p><pre>// Our main thread<br><br>// creating our worker thread<br>const worker = new Worker(&quot;./worker.js&quot;);<br><br>// Step 1 - sending message to the worker thread<br>worker.postMessage({ start: 0, end: 100000 });<br><br>// Step 4 - reading the message when we will recieve the message back from main thread<br>worker.onmessage = (message) =&gt; {<br>  console.log(message.data);<br>};</pre><pre>// Web Worker<br><br>// Step 2 - Will run when recieve the message from main thread<br>self.onmessage = (message) =&gt; {<br>  // performing work<br>  const arr = [];<br>  for (let i = message.data.start; i &lt; message.data.end; i++) {<br>    arr.push(i);<br>  }<br><br>  // Step 3 - sending the result back to the main thread<br>  self.postMessage(arr);<br>};</pre><h3>Creating Hook for Next.js to Execute Custom Function on Web Worker:</h3><p>We will use the following steps to create and use hook for Web Worker in Next.js:</p><h4>Step 1 — Initialize Project:</h4><p>To create a new Next.js Project run the following command:</p><pre>npx create-next-app@latest</pre><p>Choose the prompts accordingly:</p><pre>What is your project named? next-with-web-worker<br>Would you like to use TypeScript? Yes<br>Would you like to use ESLint? Yes<br>Would you like to use Tailwind CSS? Yes<br>Would you like to use `src/` directory? Yes<br>Would you like to use App Router? (recommended) Yes<br>Would you like to customize the default import alias (@/*)? No</pre><p>If you already have a Next project go to the next step.</p><h4>Step 2 — Data Faker:</h4><p>Install faker to fake large amounts of data:</p><pre>npm install @faker-js/faker --save-dev</pre><p>Generate fake post data by using the following code. It is generating 1500 posts with general fields that every post has:</p><pre>// services/posts.ts<br><br>import { faker } from &quot;@faker-js/faker&quot;;<br><br>import { IFetchPosts } from &quot;@/types&quot;;<br><br>export const fetchPosts = ((): (() =&gt; Promise&lt;Array&lt;IFetchPosts&gt;&gt;) =&gt; {<br>  const posts: Array&lt;IFetchPosts&gt; = [];<br><br>  return () =&gt; {<br>    if (posts &amp;&amp; posts.length &gt; 0) {<br>      return Promise.resolve(posts);<br>    } else {<br>      for (let i = 0; i &lt; 1500; i++) {<br>        posts.push({<br>          id: faker.string.uuid(),<br>          title: faker.lorem.sentence(),<br>          body: faker.lorem.paragraph(),<br>          image: faker.image.urlPicsumPhotos({ width: 200, height: 200 }),<br>          email: faker.internet.email(),<br>          author: faker.person.fullName(),<br>          date: faker.date.anytime(),<br>          commentCount: faker.number.int({ min: 0, max: 1000 }),<br>          avatar: faker.image.avatar(),<br>        });<br>      }<br><br>      return Promise.resolve(posts);<br>    }<br>  };<br>})();</pre><h4>Step 3 — Creating Our Base Components Before Using Web Worker:</h4><p>This is the UI of our App without using Web Worker. When you run it you will see a lag in the performance and to show this clearly I have included a timer and you would see it stuck.</p><pre>// components/posts-with-filters.tsx<br><br>&quot;use client&quot;;<br><br>import { FC } from &quot;react&quot;;<br>import dynamic from &quot;next/dynamic&quot;;<br>import Image from &quot;next/image&quot;;<br><br>import { IPostsWithFilters, scriptListT } from &quot;@/types&quot;;<br><br>const Timer = dynamic(() =&gt; import(&quot;./timer&quot;), { ssr: false });<br><br>const scriptList: scriptListT = [<br>  {<br>    title: &quot;Sort by Date (ASC)&quot;,<br>    sortKey: &quot;DATE:ASC&quot;,<br>  },<br>  {<br>    title: &quot;Sort by Date (DESC)&quot;,<br>    sortKey: &quot;DATE:DESC&quot;,<br>  },<br>  {<br>    title: &quot;Sort by Author Name (ASC)&quot;,<br>    sortKey: &quot;AUTHOR:ASC&quot;,<br>  },<br>  {<br>    title: &quot;Sort by Author Name (DESC)&quot;,<br>    sortKey: &quot;AUTHOR:DESC&quot;,<br>  },<br>  {<br>    title: &quot;Sort by Post Title (ASC)&quot;,<br>    sortKey: &quot;TITLE:ASC&quot;,<br>  },<br>  {<br>    title: &quot;Sort by Post Title (DESC)&quot;,<br>    sortKey: &quot;TITLE:DESC&quot;,<br>  },<br>];<br><br>export const PostsWithFilters: FC&lt;IPostsWithFilters&gt; = ({<br>  index,<br>  loading,<br>  setIndex,<br>  setSortKey,<br>  posts,<br>  initialLoading,<br>  showUIStuck = true,<br>}) =&gt; {<br>  return (<br>    &lt;div className=&quot;flex flex-col gap-10&quot;&gt;<br>      &lt;div className=&quot;mt-12&quot;&gt;<br>        &lt;Timer /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;flex items-center justify-start gap-3 px-8 pt-1 pb-8&quot;&gt;<br>        {scriptList.map((sl, i) =&gt; {<br>          return (<br>            &lt;button<br>              key={i}<br>              className={`px-6 py-4 rounded-lg border cursor-pointer transition-all ${<br>                index === i<br>                  ? &quot;border-indigo-300 text-indigo-300 hover:border-indigo-500 hover:text-indigo-500&quot;<br>                  : &quot;border-[transparent] text-white bg-indigo-300 hover:bg-indigo-500&quot;<br>              }`}<br>              disabled={loading}<br>              onClick={() =&gt; {<br>                setIndex(i);<br>                setSortKey(sl.sortKey);<br>              }}<br>            &gt;<br>              {sl.title}<br>            &lt;/button&gt;<br>          );<br>        })}<br>      &lt;/div&gt;<br>      &lt;div className=&quot;flex items-center justify-center w-full h-auto&quot;&gt;<br>        &lt;div className=&quot;flex flex-col items-center justify-center max-w-[850px] w-full gap-3&quot;&gt;<br>          {showUIStuck &amp;&amp; posts.length === 0 &amp;&amp; (<br>            &lt;div className=&quot;text-[50px] text-red-800 h-[350px] font-bold&quot;&gt;<br>              UI is Stuck!!!<br>            &lt;/div&gt;<br>          )}<br>          {initialLoading || loading ? (<br>            &lt;div className=&quot;flex items-center justify-center h-[calc(100vh-400px)] min-h-[200px]&quot;&gt;<br>              &lt;p className=&quot;text-2xl font-bold&quot;&gt;Loading...&lt;/p&gt;<br>            &lt;/div&gt;<br>          ) : (<br>            &lt;&gt;<br>              {posts.map((p, i) =&gt; {<br>                return (<br>                  &lt;div<br>                    key={i}<br>                    className=&quot;flex flex-col w-full rounded-lg px-6 py-7 bg-[#fff8e6] gap-3 cursor-pointer hover:scale-[1.02] transition-all&quot;<br>                  &gt;<br>                    &lt;div className=&quot;font-bold text-gray-600&quot;&gt;#{p.id}&lt;/div&gt;<br>                    &lt;div className=&quot;flex items-start justify-start gap-4 w-full&quot;&gt;<br>                      &lt;div className=&quot;relative flex items-center justify-center w-[130px] aspect-square h-auto rounded-lg&quot;&gt;<br>                        &lt;Image<br>                          src={p.image}<br>                          alt={p.title}<br>                          fill<br>                          draggable={false}<br>                          className=&quot;rounded-lg&quot;<br>                          sizes=&quot;130px&quot;<br>                        /&gt;<br>                      &lt;/div&gt;<br>                      &lt;div className=&quot;flex flex-col w-full items-start justify-center h-full&quot;&gt;<br>                        &lt;h1 className=&quot;text-[24px] leading-[1] font-bold&quot;&gt;<br>                          {p.title}<br>                        &lt;/h1&gt;<br>                        &lt;p className=&quot;leading-[1] mt-[15px]&quot;&gt;{p.body}&lt;/p&gt;<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div className=&quot;flex mt-3 items-center justify-between&quot;&gt;<br>                      &lt;div&gt;Dated: {p.date.toString()}&lt;/div&gt;<br>                      &lt;div&gt;Comments: {p.commentCount}&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div className=&quot;flex mt-14 items-center gap-3&quot;&gt;<br>                      &lt;div className=&quot;relative flex items-center justify-center w-[60px] aspect-square h-auto rounded-full&quot;&gt;<br>                        &lt;Image<br>                          src={p.avatar}<br>                          alt={p.title}<br>                          fill<br>                          draggable={false}<br>                          className=&quot;rounded-full&quot;<br>                          sizes=&quot;60px&quot;<br>                        /&gt;<br>                      &lt;/div&gt;<br>                      &lt;div className=&quot;flex flex-col&quot;&gt;<br>                        &lt;h3 className=&quot;text-[18px] text-gray-600 font-bold leading-[1]&quot;&gt;<br>                          @{p.author}<br>                        &lt;/h3&gt;<br>                        &lt;p&gt;{p.email}&lt;/p&gt;<br>                      &lt;/div&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                );<br>              })}<br>            &lt;/&gt;<br>          )}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>// components/timer.tsx<br><br>import { useEffect, useState } from &quot;react&quot;;<br><br>const SECOND = 1000;<br>const MINUTE = SECOND * 60;<br>const HOUR = MINUTE * 60;<br><br>const Timer = () =&gt; {<br>  const [time, setTime] = useState(Date.now());<br><br>  useEffect(() =&gt; {<br>    const interval = setInterval(() =&gt; setTime(Date.now()), 1000);<br><br>    return () =&gt; clearInterval(interval);<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;flex items-center justify-center gap-4 font-bold text-red-500 text-[45px]&quot;&gt;<br>      &lt;div&gt;{`${Math.floor((time / HOUR) % 24)}`.padStart(2, &quot;0&quot;)}&lt;/div&gt;<br>      &lt;div&gt;:&lt;/div&gt;<br>      &lt;div&gt;{`${Math.floor((time / MINUTE) % 60)}`.padStart(2, &quot;0&quot;)}&lt;/div&gt;<br>      &lt;div&gt;:&lt;/div&gt;<br>      &lt;div&gt;{`${Math.floor((time / SECOND) % 60)}`.padStart(2, &quot;0&quot;)}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Timer;</pre><p>All the types used in this are as follows:</p><pre>// types/index.d.ts<br><br>import { Dispatch, SetStateAction } from &quot;react&quot;;<br><br>export type actionT = &quot;date&quot; | &quot;title&quot; | &quot;author&quot;;<br><br>export type sortKeyT =<br>  | &quot;&quot;<br>  | &quot;DATE:ASC&quot;<br>  | &quot;DATE:DESC&quot;<br>  | &quot;AUTHOR:ASC&quot;<br>  | &quot;AUTHOR:DESC&quot;<br>  | &quot;TITLE:ASC&quot;<br>  | &quot;TITLE:DESC&quot;;<br><br>export type scriptListT = Array&lt;{ title: string; sortKey: sortKeyT }&gt;;<br><br>export interface IFetchPosts {<br>  id: string;<br>  title: string;<br>  body: string;<br>  image: string;<br>  email: string;<br>  author: string;<br>  date: Date;<br>  commentCount: number;<br>  avatar: string;<br>}<br><br>export interface IPostsWithFilters {<br>  index: number | null;<br>  loading: boolean;<br>  setIndex: Dispatch&lt;SetStateAction&lt;number | null&gt;&gt;;<br>  setSortKey: Dispatch&lt;SetStateAction&lt;sortKeyT&gt;&gt;;<br>  posts: Array&lt;IFetchPosts&gt;;<br>  initialLoading: boolean;<br>  showUIStuck?: boolean;<br>}</pre><h4>Step 4 — Organizing Our Components:</h4><p>Now we will organize our components on the main page as follows:</p><pre>// app/page.tsx<br><br>&quot;use client&quot;;<br><br>import { useCallback, useEffect, useState } from &quot;react&quot;;<br><br>import { fetchPosts } from &quot;@/services/posts&quot;;<br>import { PostsWithFilters } from &quot;@/components/posts-with-filters&quot;;<br><br>import { IFetchPosts, actionT, sortKeyT } from &quot;@/types&quot;;<br><br>/**<br> * @dev performs the sorting of posts based on parameters<br> * @param {sortKeyT} sortKey to distinguish which operation to perform - ASC or DESC and on what property - title, author, date<br> * @param {IFetchPosts} posts list of posts<br> * @returns {IFetchPosts} update list of posts<br> */<br>async function sortFunction(sortKey: sortKeyT, posts: Array&lt;IFetchPosts&gt;) {<br>  // splitting our sortKey to get the action (&quot;date&quot; | &quot;title&quot; | &quot;author&quot;) and type (&quot;ASC&quot; | &quot;DESC&quot;)<br>  const [action, type] = sortKey.split(&quot;:&quot;);<br><br>  // apply filtering based on our action and type<br>  switch (type ? type : &quot;&quot;) {<br>    case &quot;ASC&quot;:<br>      return [...posts].sort((a, b) =&gt;<br>        a[action.toLowerCase() as actionT]<br>          .toString()<br>          .localeCompare(b[action.toLowerCase() as actionT].toString())<br>      );<br>    case &quot;DESC&quot;:<br>      return [...posts].sort((a, b) =&gt;<br>        b[action.toLowerCase() as actionT]<br>          .toString()<br>          .localeCompare(a[action.toLowerCase() as actionT].toString())<br>      );<br>    default:<br>      // return posts as it is if no sortKey is provided<br>      return [...posts];<br>  }<br>}<br><br>export default function Home() {<br>  const [sortKey, setSortKey] = useState&lt;sortKeyT&gt;(&quot;&quot;); // keeps track of sortKey<br>  const [index, setIndex] = useState&lt;number | null&gt;(null); // keeps track of index of tabs (just for UI purpose)<br>  const [posts, setPosts] = useState&lt;Array&lt;IFetchPosts&gt;&gt;([]); // keeps track of posts<br>  const [loading, setLoading] = useState&lt;boolean&gt;(false); // keeps track of loading state<br><br>  // loads the posts and applies sorting based on sortKey<br>  const loadData = useCallback(async () =&gt; {<br>    setLoading(true);<br>    try {<br>      const p = await fetchPosts();<br>      const res = await sortFunction(sortKey, p);<br>      setPosts(res);<br>    } catch (error) {<br>      console.log(error);<br>    } finally {<br>      setLoading(false);<br>    }<br>  }, [sortKey]);<br><br>  // calls the loadData function on initial render<br>  useEffect(() =&gt; {<br>    loadData();<br>  }, [loadData, sortKey]);<br><br>  return (<br>    &lt;PostsWithFilters<br>      index={index}<br>      loading={loading}<br>      posts={posts}<br>      setIndex={setIndex}<br>      setSortKey={setSortKey}<br>      initialLoading={loading}<br>    /&gt;<br>  );<br>}</pre><p>Our UI will look like the following, but when you use it, it will be a bit laggy:</p><figure><img alt="Next App without Web Workers" src="https://cdn-images-1.medium.com/max/1024/1*GILFWKlIHTkIQpkspaviYQ.png" /><figcaption>Next App without Web Workers</figcaption></figure><h4>Step 5— Creating Hook for Our App:</h4><p>Now we will create a hook to use our web worker:</p><pre>// hooks/useWorker.tsx<br><br>&quot;use client&quot;;<br><br>import { useCallback, useEffect, useState } from &quot;react&quot;;<br><br>import { IFetchPosts, sortKeyT } from &quot;@/types&quot;;<br><br>/**<br> * @dev This hook is used to run a custom function in a web worker.<br> * @param {Function} workerFunction - function you want to run in a web worker<br> * @param {sortKeyT} sortKey - tells how you want to sort the posts<br> * @param {Array&lt;IFetchPosts&gt;} posts - list of posts<br> * @returns {boolean, any, unknown} loading: boolean, result: any, error: unknown<br> */<br>const useWorker = (<br>  workerFunction: Function,<br>  sortKey: sortKeyT,<br>  posts: Array&lt;IFetchPosts&gt;<br>) =&gt; {<br>  const [loading, setLoading] = useState&lt;boolean&gt;(false);<br>  const [result, setResult] = useState&lt;any&gt;(null);<br>  const [error, setError] = useState&lt;unknown | null&gt;(null);<br><br>  // caching the worker function<br>  const workerFunctionCb = useCallback(workerFunction, [workerFunction]);<br><br>  useEffect(() =&gt; {<br>    (async () =&gt; {<br>      try {<br>        setLoading(true);<br>        // stringifying the function, creating a blob and creating a url for the blob<br>        const stringifiedFunction = workerFunctionCb.toString();<br>        const blob = new Blob([`(${stringifiedFunction})()`], {<br>          type: &quot;application/javascript&quot;,<br>        });<br>        const scriptUrl = URL.createObjectURL(blob);<br><br>        // initializing our worker<br>        const worker = new Worker(scriptUrl);<br><br>        // set the result when our function is done<br>        worker.onmessage = (e) =&gt; {<br>          setResult(e.data);<br>          setLoading(false);<br>          setError(null);<br>        };<br><br>        // set the error if our function throws an error<br>        worker.onerror = (e) =&gt; {<br>          setResult(null);<br>          setError(e.message);<br>          setLoading(false);<br>        };<br><br>        // sending message to the worker<br>        worker.postMessage({<br>          sortKey,<br>          posts,<br>        });<br><br>        // terminating worker on unmount<br>        return () =&gt; {<br>          worker.terminate();<br>          URL.revokeObjectURL(scriptUrl);<br>          setLoading(false);<br>        };<br>      } catch (err) {<br>        console.log(err);<br>        setLoading(false);<br>        setError(err);<br>      }<br>    })();<br>  }, [workerFunctionCb, sortKey, posts]);<br><br>  return { loading, result, error };<br>};<br><br>export default useWorker;</pre><h4>Step 6 — Updating Our Main Page Accordingly:</h4><p>Now we will update our page according to integrate our web worker.</p><p>We will update our file which is generating posts so that we can directly use it in the Web Worker:</p><pre>// services/posts.ts<br><br>import { faker } from &quot;@faker-js/faker&quot;;<br><br>import { IFetchPosts } from &quot;@/types&quot;;<br><br>const posts: Array&lt;IFetchPosts&gt; = [];<br><br>(function () {<br>  if (posts &amp;&amp; posts.length &gt; 0) {<br>    self.postMessage(posts);<br>  } else {<br>    for (let i = 0; i &lt; 500; i++) {<br>      posts.push({<br>        id: faker.string.uuid(),<br>        title: faker.lorem.sentence(),<br>        body: faker.lorem.paragraph(),<br>        image: faker.image.urlPicsumPhotos({ width: 200, height: 200 }),<br>        email: faker.internet.email(),<br>        author: faker.person.fullName(),<br>        date: faker.date.anytime(),<br>        commentCount: faker.number.int({ min: 0, max: 1000 }),<br>        avatar: faker.image.avatar(),<br>      });<br>    }<br><br>    // posting a message to main thread when posts are generated<br>    self.postMessage(posts);<br>  }<br>})();</pre><p>Now updating our page:</p><pre>// app/page.tsx<br><br>&quot;use client&quot;;<br><br>import { useEffect, useState } from &quot;react&quot;;<br><br>import useWorker from &quot;@/hooks/useWorker&quot;;<br>import { PostsWithFilters } from &quot;@/components/posts-with-filters&quot;;<br><br>import { IFetchPosts, actionT, sortKeyT } from &quot;@/types&quot;;<br><br>/**<br> * @dev this function would be called in the web worker<br> */<br>function sortFunction() {<br>  self.onmessage = async (e: any) =&gt; {<br>    // we are getting sortKey and posts from worker thread<br>    const { sortKey, posts } = e.data;<br>    const [action] = (sortKey as sortKeyT)?.split(&quot;:&quot;);<br><br>    const sortLogic = function () {<br>      switch ((sortKey as sortKeyT)?.split(&quot;:&quot;)[1] || &quot;&quot;) {<br>        case &quot;ASC&quot;:<br>          return [...posts].sort((a, b) =&gt;<br>            a[action.toLowerCase() as actionT]<br>              .toString()<br>              .localeCompare(b[action.toLowerCase() as actionT].toString())<br>          );<br>        case &quot;DESC&quot;:<br>          return [...posts].sort((a, b) =&gt;<br>            b[action.toLowerCase() as actionT]<br>              .toString()<br>              .localeCompare(a[action.toLowerCase() as actionT].toString())<br>          );<br>        default:<br>          // return posts as it is if no sortKey is provided<br>          return [...posts];<br>      }<br>    };<br><br>    // we will send back our sorted posts to main thread (hook)<br>    self.postMessage(sortLogic());<br>  };<br>}<br><br>export default function Home() {<br>  const [sortKey, setSortKey] = useState&lt;sortKeyT&gt;(&quot;&quot;); // keeps track of sortKey<br>  const [index, setIndex] = useState&lt;number | null&gt;(null); // keeps track of index of tabs (just for UI purpose)<br>  const [posts, setPosts] = useState&lt;Array&lt;IFetchPosts&gt;&gt;([]); // keeps track of posts<br>  const [initialLoading, setInitialLoading] = useState&lt;boolean&gt;(false); // keeps track of loading state<br>  <br>  const { loading, result, error } = useWorker(sortFunction, sortKey, posts); // our Web Worker Hook<br><br>  // fetch data on initial load<br>  useEffect(() =&gt; {<br>    setInitialLoading(true);<br>    // directly using our file in web worker to fetch posts<br>    const worker = new Worker(<br>      new URL(&quot;../services/posts.ts&quot;, import.meta.url)<br>    );<br><br>    // updating our state on receiving message from worker<br>    worker.onmessage = (e) =&gt; {<br>      setInitialLoading(false);<br>      setPosts(e.data);<br>    };<br>  }, []);<br><br>  return (<br>    &lt;PostsWithFilters<br>      index={index}<br>      loading={loading}<br>      posts={result || []}<br>      setIndex={setIndex}<br>      setSortKey={setSortKey}<br>      initialLoading={initialLoading}<br>      showUIStuck={false}<br>    /&gt;<br>  );<br>}</pre><p>And that’s it, Happy Coding! 😊</p><p><strong>Access the Code at:</strong></p><p><a href="https://github.com/faraasat/next-with-web-workers">GitHub - faraasat/next-with-web-workers: This example shows how to successfully use web workers in Next.js</a></p><p><strong>Visit the Web Worker version at:</strong> <a href="https://next-with-web-workers.vercel.app/">https://next-with-web-workers.vercel.app</a>/</p><p><strong>Visit the Slugish version at:</strong> <a href="https://next-with-web-workers.vercel.app/slugish">https://next-with-web-workers.vercel.app/slugish</a></p><p>If you liked my story you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>You can also explore the following related articles:</p><ul><li><a href="https://blog.stackademic.com/adding-pwa-to-next-js-with-app-directory-simple-guide-73284be7b7c1">Adding PWA to Next.js with App Directory — Simple Guide</a></li><li><a href="https://blog.stackademic.com/how-to-generate-blur-image-in-next-js-server-components-using-blur-hash-e032b74c0ebb">How to Generate Blur Image in Next.js Server Components using Blur Hash</a></li><li><a href="https://blog.devops.dev/using-next-js-13-app-directory-with-hot-reload-enabled-in-docker-simple-guide-60de42840d7e">Using Next.js 13+  App Directory with Hot-Reload Enabled in Docker — Simple Guide</a></li><li><a href="https://faraasat.medium.com/simple-guide-on-deploying-next-js-app-on-heroku-using-cli-27d7465791eb">Simple Guide on Deploying Next.js App on Heroku using CLI</a></li><li><a href="https://blog.stackademic.com/syncing-tabs-in-next-js-13-using-redux-toolkit-redux-state-sync-simple-guide-f953329c6beb">Syncing Tabs in Next.js 13+  using Redux Toolkit &amp; Redux State Sync— Simple Guide</a></li><li><a href="https://blog.stackademic.com/activating-pwa-in-next-js-13-app-directory-using-serwist-simple-guide-b84d2a29da9c">Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide</a></li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc2fe8e95a6d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/optimizing-your-next-js-app-by-offloading-compute-intensive-tasks-from-main-thread-to-web-workers-bc2fe8e95a6d">Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers</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[Principles that Distinguishes Quantum Computing from Classical Computing — Simple Guide]]></title>
            <link>https://blog.stackademic.com/principles-that-distinguishes-quantum-computing-from-classical-computing-simple-guide-fde9144d83ef?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde9144d83ef</guid>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 14:35:42 GMT</pubDate>
            <atom:updated>2024-09-09T00:52:49.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>Principles that Distinguishes Quantum Computing from Classical Computing — Simple Guide</h3><figure><img alt="Principles that Distinguishes Quantum Computing from Classical Computing — Simple Guide" src="https://cdn-images-1.medium.com/max/1024/1*L6UP-nRtH8ayp4Up6TIgqw.jpeg" /><figcaption>Principles that Distinguishes Quantum Computing from Classical Computing — Simple Guide</figcaption></figure><p>Have you ever wondered about the buzz around quantum computing and how it’s different from the classical computing we’re all familiar with? We will discuss some important principles in this article that make Quantum Computing Distinct in itself.</p><h3>Introduction:</h3><p>After the advancement of classical computing, we are moving towards an exciting new horizon of quantum computers and these Quantum Computers work on the principles of Quantum Physics.</p><p>Before going deep into this we will first discuss some things about Classical Physics.</p><h3>A little About Classical Physics:</h3><p>If we talk about classical physics it classifies entities either as particles or waves. Particles are considered to be localized in space, meaning they have a specific position at any given time and you can determine the location of a particle with a high degree of precision. Waves are spread out in space as they do not have a specific location but rather exist across various points. For example, a wave in water is not located at a single point but rather is spread out across the surface. These particles and waves cannot be exhibited by a single entity.</p><p>One of the reasons for the distinction between quantum physics and classical physics is due to the dual nature of light. Classical physics is not able to define the dual nature of light, which exhibits both wave-like and particle-like behavior. This duality is also observed in other subatomic particles such as electrons and protons. Quantum mechanics provides a more complete description of the behavior of these entities, including the wave-particle duality of light.</p><h4>- Double Slit Experiment:</h4><p>The double-slit experiment is a classic experiment that demonstrates this duality. When the electrons are fired one at a time, they behave like particles and create a pattern of discrete dots on the screen. However, when electrons are fired through two slits, they form an interference pattern on the screen, which is characteristic of waves.</p><figure><img alt="Double Slit Experiment Example" src="https://cdn-images-1.medium.com/max/1024/1*VvHKFZoa-zoqc5D_dLqzsQ.jpeg" /><figcaption>Double Slit Experiment Example</figcaption></figure><h3>Why Need Quantum Computing?</h3><p>Intel co-founder Gordon Moore predicted that we would be able to double the power of the computer every two years and this prediction is known as <strong>Moore’s Law</strong>. According to him, we would be able to do this by increasing the number of transistors on a chip.</p><p>This law worked well, but now it seems to be failing because reducing the size of a transistor was the one method to increase the power of the computer but as these transistors get smaller and smaller, the quantum effect like quantum tunneling causes problems.</p><h3>Differentiating Principles:</h3><p>Now we will discuss some general principles that distinguish Quantum Computing from Classical Computing:</p><h4>1) Qubits:</h4><p>In classical computing, we represent the information using either 0 or 1 bits. The device computes by manipulating these bits with the help of logical gates (AND, OR, NOT).</p><p>In quantum computing, a qubit or quantum bit is the basic unit of quantum information. A qubit can be in states of 0 and 1, but it can also be in a superposition of these states meaning something like a mixture of 0 and 1. This means a qubit can hold a one, a zero, or crucially a superposition of these values. The device computes by manipulating these bits with the help of quantum logic gates.</p><p>Following are three different representations of qubits:</p><figure><img alt="Different Representations of Qubits" src="https://cdn-images-1.medium.com/max/1024/1*DU7N3wdxJC-HnHpAXspg3w.jpeg" /><figcaption>Different Representations of Qubits</figcaption></figure><h4>2) Superposition:</h4><p>Currently, classical computers are accustomed to using bits. Superposition is the ability of a quantum object to be in multiple states at the same time, with probabilities of being measured in each state. Having the qubits in superposition in quantum computing makes it easier to solve permutation problems and it is extremely useful not only to crack encryptions but also to secure encryption channel generation using <strong>Quantum Key Distribution</strong>.</p><p>The concept of superposition in quantum mechanics is central to the experiment of Schrödinger’s cat.</p><figure><img alt="Schrödinger’s Cat: A Quantum Superposition Thought Experiment" src="https://cdn-images-1.medium.com/max/1024/1*9RO2dpV3l6Bo5ALYu6Fdqw.jpeg" /><figcaption>Schrödinger’s Cat: A Quantum Superposition Thought Experiment</figcaption></figure><p>You can read more about Schrödinger’s thought experiment here:</p><p><a href="https://faraasat.medium.com/schr%C3%B6dinger-cat-an-early-illustration-for-the-superposition-concept-simple-guide-e32022e541b9">Schrödinger Cat — An Early Illustration for the Superposition Concept — Simple Guide</a></p><h4>3) Interference:</h4><p>In quantum mechanics, when a particle is in a superposition of multiple states, these states can interfere with each other, leading to constructive or destructive interference. Constructive interference occurs when two in-phase waves peak at the same time, resulting in a wave that peaks twice as high. Destructive interference occurs when two out-of-phase waves peak at opposite times, resulting in a completely flat wave.</p><p>This interference is used to affect probability amplitudes. Each possible outcome of a quantum computation has some probability of occurring, and interference can amplify certain outcomes and suppress others. This is achieved by applying quantum gates that create superpositions of qubits and by controlling the relative phases of the states.</p><p>For example, Grover’s Algorithm which is a quantum search algorithm, uses interference to perform high-speed searching on unstructured data.</p><figure><img alt="Constructive Interference vs Destructive Interference" src="https://cdn-images-1.medium.com/max/1024/1*bhn2AeqhPKXN9f4XZxZiCw.jpeg" /><figcaption>Constructive Interference vs Destructive Interference</figcaption></figure><h4>4) Entanglement:</h4><p>Two quantum objects are said to be entangled when one object’s state depends on another object’s state. When these two objects are entangled, they have a defined relationship, so if you know one object’s state, you know something about the other state. This principle holds still even when these objects are separated by far distances.</p><p>Quantum Entanglement allows us to store and find information more powerfully than it is possible with classical objects. For now, entanglement is also being used to implement quantum internet.</p><h4>5) Measurement:</h4><p>Measurement is the process of forcing a superposition to pick what state the object will be in and it gives either 0 or 1. This is an irreversible process and destroys the superposition.</p><p>This collapse of the superposition can be understood using Schrödinger’s experiment in which when a cat is in the radioactive box, we do not know whether it is alive or dead (superposition), and we only know the real outcome when it box is opened.</p><figure><img alt="Effects of Measurement on Quantum Object" src="https://cdn-images-1.medium.com/max/1024/1*zETR9G6H_YglEjENkpvc7w.jpeg" /><figcaption>Effects of Measurement on Quantum Object</figcaption></figure><p>If you liked my story you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a> at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde9144d83ef" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/principles-that-distinguishes-quantum-computing-from-classical-computing-simple-guide-fde9144d83ef">Principles that Distinguishes Quantum Computing from Classical Computing — Simple Guide</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[Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide]]></title>
            <link>https://blog.stackademic.com/activating-pwa-in-next-js-13-app-directory-using-serwist-simple-guide-b84d2a29da9c?source=rss-51f7a2ca7b50------2</link>
            <guid isPermaLink="false">https://medium.com/p/b84d2a29da9c</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Farasat Ali]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 12:33:08 GMT</pubDate>
            <atom:updated>2024-03-02T10:50:16.725Z</atom:updated>
            <content:encoded><![CDATA[<h3>Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRsXC0Gq26rmVtuXajklgQ.jpeg" /><figcaption>Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide</figcaption></figure><h3>Introduction:</h3><p><strong><em>PWA</em></strong><em> </em>or <strong><em>Progressive Web App</em></strong> is a web application that uses modern web capabilities to deliver a more native app-like experience to users. PWAs aim to combine the best of web and native apps.</p><p>This guide will show how we can make our Next.js with AppDir a PWA!</p><p>I have discussed how to make your Next.js App PWA using @ducanh2912/next-pwa , but this guide will focus on @serwist , which is a more recommended way for Next.js. If you want to read about @ducanh2912/next-pwa you can check out the following article:</p><p><a href="https://blog.stackademic.com/adding-pwa-to-next-js-with-app-directory-simple-guide-73284be7b7c1">Adding PWA to Next.js with App Directory — Simple Guide</a></p><h3>Benefits of PWA:</h3><p>There are a lot of benefits to using PWA and some of them are:</p><ol><li>Offline Access.</li><li>App-Like.</li><li>Push Notifications.</li><li>Discoverable.</li><li>Installable.</li><li>Automatic Updates.</li></ol><p>and many more…</p><h3>Companies Using PWA:</h3><p>To mention some of the companies that are using PWA:</p><ol><li>AliExpress</li><li>Twitter Lite</li><li>Forbes</li></ol><p>and much more… <a href="https://brainhub.eu/library/progressive-web-apps-examples"><strong><em>Source</em></strong></a></p><h3>Adding PWA support to Next.js:</h3><h4>Step 1 — Create the Next.js App:</h4><p>To create a new Next.js Project run the following command:</p><pre>npx create-next-app@latest</pre><p>Choose the prompts accordingly:</p><pre>What is your project named? next-with-pwa<br>Would you like to use TypeScript? Yes<br>Would you like to use ESLint? Yes<br>Would you like to use Tailwind CSS? Yes<br>Would you like to use `src/` directory? Yes<br>Would you like to use App Router? (recommended) Yes<br>Would you like to customize the default import alias (@/*)? No</pre><p>If you already have a Next project go to the next step.</p><h4><strong>Step 2 — Add the Required Package:</strong></h4><p>Now install the following package:</p><pre>npm i @serwist/next @serwist/precaching @serwist/sw</pre><h4><strong>Step 3 — Configure the Package:</strong></h4><p>With the latest next.js, we get next.config.mjs , which would be configured as follows:</p><pre>// @ts-check<br>import withSerwistInit from &quot;@serwist/next&quot;;<br><br>const withSerwist = withSerwistInit({<br>  cacheOnFrontEndNav: true,<br>  swSrc: &quot;src/sw.ts&quot;, // add the path where you create sw.ts<br>  swDest: &quot;public/sw.js&quot;,<br>  reloadOnOnline: true,<br>  disable: process.env.NODE_ENV === &quot;development&quot;, // to disable pwa in development<br>  // ... other options<br>});<br><br>/** @type {import(&#39;next&#39;).NextConfig} */<br>const nextConfig = {<br>  swcMinify: true,<br>  reactStrictMode: true,<br>  // ... other next.js config options<br>};<br><br>export default withSerwist(nextConfig);</pre><p>If you have next.config.js , the configuration would be as follows:</p><pre>const withSerwist = require(&quot;@serwist/next&quot;).default({<br>  cacheOnFrontEndNav: true,<br>  swSrc: &quot;src/sw.ts&quot;,  // add the path where you create sw.ts<br>  swDest: &quot;public/sw.js&quot;,<br>  reloadOnOnline: true,<br>  disable: process.env.NODE_ENV === &quot;development&quot;, // to disable pwa in development<br>  // ... other options<br>});<br><br>/** @type {import(&#39;next&#39;).NextConfig} */<br>const nextConfig = {<br>  swcMinify: true,<br>  reactStrictMode: true,<br>// ... other next.js config options<br>};<br><br>export default withSerwist(nextConfig);</pre><p>If you are using TypeScript, update the tsconfig.json as follows:</p><pre>{<br>  // Other stuff...<br>  &quot;compilerOptions&quot;: {<br>    // Other options...<br>    &quot;types&quot;: [<br>      // Other types...<br>      // This allows Serwist to type `window.serwist`.<br>      &quot;@serwist/next/typings&quot;<br>    ],<br>    &quot;lib&quot;: [<br>      // Other libs...<br>      // Add this! Doing so adds WebWorker and ServiceWorker types to the global.<br>      &quot;webworker&quot;<br>    ],<br>  },<br>}</pre><p>For more options, visit the official documentation here:</p><p><a href="https://serwist.pages.dev/docs">Introduction - Serwist</a></p><h4><strong>Step 4 — Add a Service Worker Configuration:</strong></h4><p>Add the following configuration at src of your project in a file sw.ts:</p><pre>// sw.ts<br><br>import { defaultCache } from &quot;@serwist/next/browser&quot;;<br>import type { PrecacheEntry } from &quot;@serwist/precaching&quot;;<br>import { installSerwist } from &quot;@serwist/sw&quot;;<br><br>declare const self: ServiceWorkerGlobalScope &amp; {<br>  // Change this attribute&#39;s name to your `injectionPoint`.<br>  __SW_MANIFEST: (PrecacheEntry | string)[] | undefined;<br>};<br><br>// Anything random.<br>const revision = crypto.randomUUID();<br><br>installSerwist({<br>  precacheEntries: self.__SW_MANIFEST,<br>  skipWaiting: true,<br>  clientsClaim: true,<br>  navigationPreload: true,<br>  runtimeCaching: defaultCache,<br>  fallbacks: {<br>    entries: [<br>      {<br>        url: &quot;/~offline&quot;,<br>        revision,<br>        matcher({ request }) {<br>          return request.destination === &quot;document&quot;;<br>        },<br>      },<br>    ],<br>  },<br>});</pre><h4><strong>Step 5— Add a Fallback Page to be Shown When User is Offline:</strong></h4><p>Place the ~offline/page.tsx in /app folder and then add the following code to show as a fallback.</p><pre>import type { Metadata } from &quot;next&quot;;<br><br>export const metadata: Metadata = {<br>  title: &quot;Offline&quot;,<br>};<br><br>export default function Page() {<br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;This is offline fallback page&lt;/h1&gt;<br>      &lt;h2&gt;When offline, any page route will fallback to this page&lt;/h2&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h4>Step 6— Add manifest.json to your app:</h4><p>Go to public folder of your app and create manifest.json with the following structure:</p><pre>{<br>  &quot;id&quot;: &quot;any_id&quot;,<br>  &quot;name&quot;: &quot;Next.js PWA - Tutorial&quot;,<br>  &quot;short_name&quot;: &quot;Next PWA&quot;,<br>  &quot;description&quot;: &quot;This next.js app is a PWA.&quot;,<br>  &quot;icons&quot;: [<br>    {<br>      &quot;src&quot;: &quot;./logo72x72.png&quot;,<br>      &quot;sizes&quot;: &quot;72x72&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;./logo192x192.png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;./logo384x384.png&quot;,<br>      &quot;sizes&quot;: &quot;384x384&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;./logo512x512.png&quot;,<br>      &quot;sizes&quot;: &quot;512x512&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;<br>    }<br>  ],<br>  &quot;theme_color&quot;: &quot;#FFFFFF&quot;,<br>  &quot;background_color&quot;: &quot;#FFFFFF&quot;,<br>  &quot;start_url&quot;: &quot;/&quot;,<br>  &quot;scope&quot;: &quot;.&quot;,<br>  &quot;display&quot;: &quot;standalone&quot;,<br>  &quot;orientation&quot;: &quot;portrait&quot;<br>}</pre><h4>Step 6— Registering manifest.json in Metadata:</h4><p>Update your layout.tsx/layout.jsx to register the manifest file in the metadata:</p><pre>import { Metadata } from &quot;next&quot;;<br>// ... other imports<br><br>export const metadata: Metadata = {<br>  manifest: &quot;/manifest.json&quot;, // we are accessing our manifest file here<br>  title: &quot;...&quot;,<br>  // ... other options    <br>};<br><br>const RootLayout = ({ children }: { children: React.ReactNode }) =&gt; {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;main&gt;{children}&lt;/main&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>};<br><br>export default RootLayout;</pre><p>And that’s it, Happy Coding! 😊</p><p><strong>Access the Code at:</strong></p><p><a href="https://github.com/faraasat/next-pwa-serwist">GitHub - faraasat/next-pwa-serwist: Example code for article - Activating PWA in Next.js 13+ App Directory Using @Serwist - Simple Guide</a></p><p><strong>Visit the Live version at: </strong><a href="https://next-pwa-serwist.vercel.app/">https://next-pwa-serwist.vercel.app/</a></p><p>If you liked my story you can follow me for more interesting tips and tricks at <a href="https://faraasat.medium.com/"><strong><em>Farasat Ali — Medium</em></strong></a>.</p><p>You can Find Me on <a href="https://linkedin.com/in/faraasat"><strong><em>LinkedIn</em></strong></a> and <a href="https://github.com/faraasat"><strong><em>GitHub</em></strong></a>.</p><p>Also, Visit My <a href="https://www.farasat.me/"><strong><em>Portfolio</em></strong></a><strong><em> </em></strong>at:</p><p><a href="https://www.farasat.me/">See Outstanding Business Growth with Farasat | Get Irresistibly the Best Results &amp; Surprisingly Awesome Leads | Expert in Latest Technologies</a></p><p>You can also check out the related articles:</p><ul><li><a href="https://blog.stackademic.com/how-to-generate-blur-image-in-next-js-server-components-using-blur-hash-e032b74c0ebb">How to Generate Blur Image in Next.js Server Components using Blur Hash</a></li><li><a href="https://blog.devops.dev/using-next-js-13-app-directory-with-hot-reload-enabled-in-docker-simple-guide-60de42840d7e">Using Next.js 13+  App Directory with Hot-Reload Enabled in Docker — Simple Guide</a></li><li><a href="https://faraasat.medium.com/simple-guide-on-deploying-next-js-app-on-heroku-using-cli-27d7465791eb">Simple Guide on Deploying Next.js App on Heroku using CLI</a></li><li><a href="https://blog.stackademic.com/syncing-tabs-in-next-js-13-using-redux-toolkit-redux-state-sync-simple-guide-f953329c6beb">Syncing Tabs in Next.js 13+  using Redux Toolkit &amp; Redux State Sync— Simple Guide</a></li></ul><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b84d2a29da9c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/activating-pwa-in-next-js-13-app-directory-using-serwist-simple-guide-b84d2a29da9c">Activating PWA in Next.js 13+ App Directory Using @Serwist — Simple Guide</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>
    </channel>
</rss>