<?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 Danusha Navod on Medium]]></title>
        <description><![CDATA[Stories by Danusha Navod on Medium]]></description>
        <link>https://medium.com/@danushanavod?source=rss-35f81e9c9f0e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yl64xHpvg0NVWyJKsfcsMA.jpeg</url>
            <title>Stories by Danusha Navod on Medium</title>
            <link>https://medium.com/@danushanavod?source=rss-35f81e9c9f0e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 22:58:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danushanavod/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[Top 5 React Best Practices Every Developer Should Know]]></title>
            <link>https://medium.com/bitsrc/react-best-practices-55aca2f38606?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/55aca2f38606</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 10:09:03 GMT</pubDate>
            <atom:updated>2024-03-07T10:14:53.877Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore Composable Software, State Management, Immutability, Lifecycle Methods, Hooks and Optimization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4w_6e7NlDXbyXLuc.png" /></figure><p>Every React developer, whether an experienced professional or someone just starting their journey, should be familiar with certain best practices.</p><p>In this article, I’m going to share five essential practices that can elevate your React programming career; those are,</p><ul><li>Composable Software Architecture</li><li>State Management</li><li>Immutability</li><li>Lifecycle Methods and Hooks</li><li>Optimization</li></ul><blockquote>Are you excited to dive in? Let’s explore each of these features one by one.</blockquote><h3><strong>1. Composable Software Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RylzxwfCgxD1kv_L.png" /><figcaption><em>(https://www.netsolutions.com/insights/composable-architecture-why-its-important/)</em></figcaption></figure><p>Have you ever heard of this? Perhaps you haven’t, but you might already know its meaning.</p><blockquote><strong>Composable software architecture</strong> decomposes complex software systems into independent, reusable components.</blockquote><p>These components can be easily combined and recombined to create different functionalities, promoting <strong>modularity, scalability, and maintainability</strong>. Think of it as building with Lego bricks — each brick is self-contained, yet they can be snapped together to form intricate structures.</p><h4>Composability in React</h4><p>React, with its component-based architecture, is a natural fit for the composable software architecture.</p><p>Let’s take a look at how React embraces this approach,</p><ul><li><strong>Atomic Design:</strong> This encourages building components from basic elements (atoms) to complex layouts (molecules and organisms). Think buttons, forms, and finally, entire pages — all independent and ready to be combined!</li><li><strong>Higher-Order Components (HOCs):</strong> These components “wrap” existing ones, adding functionality without modifying their core logic. Imagine decorating a button with a loading indicator — a HOC to the rescue!</li><li><strong>Render Props:</strong> Pass down rendering logic as a prop, allowing child components to control how they’re displayed. Think of it as handing over the paintbrush and letting your components express themselves creatively.</li></ul><blockquote>But composability isn’t just about individual components. It’s about <strong>seamless integration and collaboration</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8AHIA3ombRf93EvmVDj8eA.png" /></figure><p><a href="https://bit.cloud/showoff/personal-portfolio/apps/portfolio/~graph">Take a look at the image above</a>. If you look at it closely, you can see it’s comprised of different React components pieced together to form a single React app.</p><p>You have components like — picture, items and hooks all aggregated together through compositions that can be swapped at any given time to create a composable React app. By doing so, you make sure that you aren&#39;t tied to a single monolith, but rather have the capacity to scale your app without worrying about any monolith limits.</p><h3><strong>2. State Management</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4sCZ-ZlWWkSbYveS.png" /></figure><p>While composability focuses on the structure, <strong>state management</strong> is the heart of data flow in your React application. This ensures that every component receives the right information at the right time.</p><blockquote>State management is the process of controlling and manipulating data that drives the dynamic behavior and UI updates within your React application.</blockquote><p>React provides several state management options out of the box, such as React <a href="https://react.dev/reference/react/useState"><strong>useState</strong></a>, <a href="https://react.dev/reference/react/useReducer"><strong>useReducer</strong></a>, and <a href="https://react.dev/reference/react/useContext"><strong>context</strong></a>. However, these tools aren’t always enough to handle the complex data flows of modern applications. Therefore, numerous external state management libraries are out there, such as <a href="https://redux.js.org/"><strong>Redux</strong></a>, <a href="https://mobx.js.org/README.html"><strong>MobX</strong></a>, <a href="https://hookstate.js.org/"><strong>Hookstate</strong></a>, and <a href="https://docs.pmnd.rs/zustand/getting-started/introduction"><strong>Zustand</strong></a>, offering additional capabilities.</p><p>Let’s quickly take a look at the React inbuilt state management methods that we discussed above. Whether you are a React beginner or an expert, these methods are very crucial in your React journey.</p><h4>1. <a href="https://react.dev/reference/react/useState">useState</a></h4><p>Perfect for managing <strong>simple, local states within a single component</strong>. Think of toggling buttons, handling form data, or tracking basic UI elements. It’s lightweight and efficient for quick interactions.</p><pre>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  const handleClick = () =&gt; {<br>    setCount(count + 1);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={handleClick}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>2. <a href="https://react.dev/reference/react/useReducer">useReducer</a></h4><p>Ideal for handling <strong>complex states with multiple values or derived values</strong>. Consider managing complex forms, shopping carts, or global states with intricate dependencies. It offers more control over updates using actions and reducer functions.</p><pre>const reducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return { ...state, count: state.count + 1 };<br>    default:<br>      return state;<br>  }<br>};<br><br>const Counter = () =&gt; {<br>  const [state, dispatch] = useReducer(reducer, { count: 0 });<br><br>  const handleClick = () =&gt; {<br>    dispatch({ type: &#39;increment&#39; });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {state.count}&lt;/p&gt;<br>      &lt;button onClick={handleClick}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>3. <a href="https://react.dev/reference/react/useContext#usecontext">Context API</a></h4><p>Enables <strong>sharing data across multiple, related components</strong> without prop drilling. Useful for global states like user authentication or theme preferences, keeping component structure clean and maintainable.</p><pre>// Creates the new context<br>const ThemeContext = React.createContext(&#39;light&#39;);<br><br>const App = () =&gt; {<br>  const [theme, setTheme] = useState(&#39;light&#39;);<br><br>  const toggleTheme = () =&gt; {<br>    setTheme(theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;);<br>  };<br><br>  return (<br>    &lt;ThemeContext.Provider value={theme}&gt;<br>      &lt;Toolbar toggleTheme={toggleTheme} /&gt;<br>      &lt;Content /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>};<br><br>const Toolbar = ({ toggleTheme }) =&gt; {<br>  // Access the context<br>  const theme = useContext(ThemeContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Current theme: {theme}&lt;/p&gt;<br>      &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>const Content = () =&gt; {<br>  // Access the context<br>  const theme = useContext(ThemeContext);<br><br>  return (<br>    &lt;div style={{ backgroundColor: theme }}&gt;<br>      {/* Content based on theme */}<br>    &lt;/div&gt;<br>  );<br>};</pre><blockquote>There is a lot to cover in React state management; it’s not easy to explain in just a few words. For a deeper understanding, consider reading <a href="https://react.dev/learn/managing-state#">React’s official documentation</a>.</blockquote><p>Additionally, exploring other external state management libraries can unveil many more useful features compared to these built-in methods.</p><h3>3. <strong>Immutability</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZyUtZlr5_9ZLlS8g.png" /></figure><p>While managing the state is crucial, ensuring its predictability and stability is equally important. This is where the concept of <strong>immutability</strong> comes in.</p><blockquote>By treating data as immutable, meaning it cannot be directly modified.</blockquote><p>With immutability in React, you unlock several benefits:</p><ul><li><strong>Predictable Rendering:</strong> When data remains unchanged, React can efficiently determine which components need to re-render, leading to smoother performance and fewer unexpected side effects.</li><li><strong>Easier Debugging:</strong> Immutability creates a clear history of changes, allowing you to easily track down the source of issues and debug more effectively.</li><li><strong>State Management Libraries:</strong> Many popular state management libraries like <strong>Redux,</strong> <strong>MobX,</strong> and <strong>HookState</strong> are built around the principle of immutability, providing predictable data flow and simplified reasoning.</li></ul><p>However, implementing immutability in JavaScript can seem cumbersome due to the mutability of objects. Here are some common approaches:</p><ul><li><strong>Type safety:</strong> Declare variables as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a> or use <a href="https://www.typescriptlang.org/"><strong>Typescript</strong></a> read-only types (<a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype">readonly&lt;{}&gt;</a>) to prevent accidental modifications. TypeScript&#39;s static type checking acts as a robust line of defense, catching potential immutability violations at compile time.</li><li><strong>Spread operator:</strong> When updating data, utilize <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread syntax</a> ({...object, ...changes}) to create entirely new objects with the desired modifications. This ensures the original data remains untouched, preserving immutability.</li><li><strong>Concat and Slice:</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat">concat</a> generates a new array by combining existing ones, upholding immutability as long as you deal strictly with arrays and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">slice</a> extracts a portion of an array into a new array, ensuring immutability by its inherent nature.</li></ul><p>Want to see how to practically use these methods in your project? Then, let’s quickly delve into some examples to get an idea of how to <strong>handle</strong> <strong>type safety, and</strong> <strong>utilize the spread operator, concat, and slice</strong>.</p><ol><li><strong>Type Safety</strong></li></ol><pre>// Without TypeScript:<br>let user = { name: &quot;John&quot;, age: 30 };<br>user.age = 31; // Can modify the object accidentally<br><br>// With TypeScript:<br>const user: Readonly&lt;{ name: string; age: number }&gt; = { name: &quot;John&quot;, age: 30 };<br>// user.age = 31; // TypeScript will throw an error</pre><p><strong>2. Spread Operator</strong></p><pre>const originalArray = [1, 2, 3];<br>const newArray = originalArray.concat([4]); // Modifies original array<br>const updatedArray = [...originalArray, 4]; // Creates a new array with spread<br><br>const originalObject = { name: &quot;Jane&quot; };<br>const updatedObject = { ...originalObject, age: 30 }; // Creates a new object with spread</pre><p><strong>3. Concat and Slice</strong></p><pre>const originalArray = [1, 2, 3];<br>const newArray = originalArray.concat([4]); // Returns a new array<br>const subArray = originalArray.slice(1, 3); // Returns a new sub-array</pre><p>Apart from these, there are dedicated libraries for handling immutability, such as <a href="https://www.npmjs.com/package/immer"><strong>Immer</strong></a>, <a href="https://immutable-js.com/"><strong>Immutable.js</strong></a>, and <a href="https://github.com/kolodny/immutability-helper"><strong>immutability-helper</strong></a>.</p><blockquote>You don’t need to use all of these in your next project, but the <strong>concept of immutability is essential</strong> for every React developer. Also, take a look at this <a href="https://react.dev/learn/tutorial-tic-tac-toe#why-immutability-is-important">React document about immutability</a>.</blockquote><h3>4. <strong>Lifecycle Methods and Hooks</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WvJUWuwnXFA3v8q-.png" /></figure><p>React components undergo a series of well-defined phases throughout their existence, known as their <strong>lifecycle</strong>.</p><p>Understanding these phases and how to leverage them effectively is crucial for building robust and responsive applications.</p><p><strong>Traditionally, class-based components</strong> relied on lifecycle methods:</p><ol><li><a href="https://react.dev/reference/react/Component#componentdidmount"><strong>componentDidMount</strong></a></li><li><a href="https://react.dev/reference/react/Component#componentdidupdate"><strong>componentDidUpdate</strong></a></li><li><a href="https://react.dev/reference/react/Component#componentwillunmount"><strong>componentWillUnmount</strong></a></li></ol><p>You can hook into these stages and perform specific actions. However, with the introduction of <strong>Functional Components</strong> and <a href="https://react.dev/reference/react/hooks"><strong>Hooks</strong></a>, a new paradigm emerged.</p><blockquote>With Functional Components, there’s no need to worry about lifecycle methods like <strong>componentDidMount</strong>. React Hooks like useEffect and useState can <a href="https://react.dev/learn/lifecycle-of-reactive-effects#">handle these for you</a>.</blockquote><h4><a href="https://react.dev/reference/react/useEffect">useEffect</a></h4><p>Think of useEffect as your gateway to performing actions that interact with the outside world, like <strong>fetching data</strong>, <strong>setting up subscriptions</strong>, or <strong>manipulating the DOM</strong>. It executes after a component renders or updates, giving you precise control over when these actions occur.</p><p><strong>Here’s how it works:</strong></p><ul><li><strong>Callback function:</strong> This function houses the actual side effect logic.</li><li><strong>Dependency array (optional):</strong> This array specifies which changes trigger the effect to re-run. An empty array ensures it runs only once on mount.</li></ul><p><strong>Example:</strong> Fetching data from an API and updating the component’s state:</p><pre>useEffect(() =&gt; {<br>  fetch(&#39;https://api.example.com/data&#39;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; setData(data));<br>}, []); // Empty array for one-time execution on mount</pre><h4>useState</h4><blockquote>Remember our discussion about useState in the state management section?</blockquote><p>Under the hood, this is a React Hook. Now, let’s revisit them, exploring their functionalities and how they work together within functional components.</p><p><strong>Integrating</strong> useState<strong>:</strong></p><p>Imagine you have a counter component that needs to fetch data once it mounts and update the counter value based on the fetched data. You can use useState to manage the counter state and useEffect to trigger the data fetch:</p><pre>const [data, setData] = useState(null);<br><br>useEffect(() =&gt; {<br>  if (!data) {<br>    fetch(&#39;https://api.example.com/data&#39;)<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; setData(data));<br>  }<br>}, [data]);</pre><p>In this example, useEffect only runs when the data state is null, ensuring the data is fetched only once on mount.</p><blockquote>By mastering these hooks and understanding their interplay, you can build React applications with efficient state management and well-defined lifecycle behaviors.</blockquote><h3><strong>5. Optimization</strong></h3><p>Every React developer should have a good knowledge of building optimized applications for enhanced user experiences and better overall efficiency.</p><h4>1. Code Splitting</h4><p>This allows you to break down your code into smaller, independent bundles. Users only load the bundles needed for the current view, significantly reducing initial load time.</p><p>Popular libraries like React.lazy and dynamic import() make this process seamless.</p><p><strong>Example:</strong></p><pre>// App.js<br>import React, { Suspense } from &#39;react&#39;;<br><br>const Home = React.lazy(() =&gt; import(&#39;./components/Home&#39;));<br>const About = React.lazy(() =&gt; import(&#39;./components/About&#39;));<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;Home /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;About /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><blockquote><strong>Tip:</strong> While code splitting offers immense benefits, excessive splitting can lead to many small network requests, impacting performance. So, consider the trade-off between bundle size and loading time for optimal results.</blockquote><h4><strong>2. Memoization</strong></h4><p>This comes into play if you want to cache a complex calculation that performs with every render. This prevents redundant computations and unnecessary re-renders, boosting performance. Libraries like <a href="https://react.dev/reference/react/memo">React.memo</a> and <a href="https://react.dev/reference/react/useMemo#">useMemo</a> simplify implementing this technique.</p><p><strong>Example:</strong></p><pre>// ExpensiveComponent.js<br>import React, { useMemo } from &#39;react&#39;;<br><br>function ExpensiveComponent({ data }) {<br>  const processedData = useMemo(() =&gt; {<br>    // Perform expensive calculations on data<br>    return processedResult;<br>  }, [data]);<br><br>  return (<br>    &lt;div&gt;{processedData}&lt;/div&gt;<br>  );<br>}</pre><blockquote><strong>Tip:</strong> Don’t over-memoize! Use memoization strategically for pure functions and components that re-render frequently due to changing inputs.</blockquote><h4>Wrapping Up</h4><p>And that’s pretty much it. Master these 5 practices, and you’ll see a huge improvement in the overall scalability and performance of your React apps.</p><p>Here’s a quick recap of what we discussed:</p><ul><li><strong>Composable Architecture:</strong> Build modular, scalable, and maintainable applications.</li><li><strong>Effective State Management:</strong> Ensure predictable data flow and simplify complex scenarios.</li><li><strong>Immutability:</strong> Enhance performance, improve debugging, and embrace safer code.</li><li><strong>Lifecycle Hooks:</strong> Leverage useEffect and useState for efficient side effects and state management in functional components.</li><li><strong>Optimization Techniques:</strong> Speed up your app with code splitting, memoization, virtualization, and more.</li></ul><p>If you have any thoughts or anything you’d like to add, feel free to leave a comment in the discussions!</p><p>I hope you found this article helpful.</p><p>Thank you for reading.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/composable-applications-a-practical-guide-335f47a92b41">Composable Applications: A Practical Guide</a></li><li><a href="https://blog.bitsrc.io/10-microservice-anti-patterns-278bcb7f385d">Top 10 Microservice Anti-Patterns</a></li><li><a href="https://blog.bitsrc.io/modern-angular-development-b469341a3620">A Modern Approach for Angular Development</a></li><li><a href="https://blog.bitsrc.io/modern-approach-to-react-development-090358b04e7d">A Modern Approach to React Development</a></li><li><a href="https://blog.bitsrc.io/creating-a-vue-js-app-in-2024-274069973542">Getting Started with a Vue.js App in 2024</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55aca2f38606" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/react-best-practices-55aca2f38606">Top 5 React Best Practices Every Developer Should Know</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 5 Node.js Features Every Developer Should Know]]></title>
            <link>https://medium.com/bitsrc/top-5-features-of-nodejs-e49d1c68f4a7?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e49d1c68f4a7</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 12:57:45 GMT</pubDate>
            <atom:updated>2024-02-13T12:57:45.746Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore Node.js Worker Threads, Cluster, http2, Streams API and REPL</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNh8HR61oYIQU0gAMMGLLw.png" /></figure><p>Whether you’re an experienced Node.js developer or just starting your journey, there’s always something waiting to be unleashed within Node.js.</p><p>In this article, I’ll explore five Node.js features that can enhance your overall experience, and those are:</p><ul><li>Worker Threads</li><li>Cluster Process Module</li><li>Built-in HTTP/2 Support</li><li>Streams API</li><li>REPL</li></ul><blockquote>Are you excited to dive in? Let’s explore each of these features one by one.</blockquote><p>But before we do, let’s quickly take a look at the <strong>Single-Threaded behavior</strong> of Node.js. Understanding this foundational aspect will provide valuable context for the features we’re about to delve into.</p><h3>Single-Threaded Node.js: A Quick Overview</h3><p>Node.js is known for its single-threaded architecture. But more accurate to call it a “single-threaded event loop”.</p><h4><strong>But why a Single-Threaded Event Loop?</strong></h4><p>Initially, Node.js was designed for I/O-bound tasks like web servers. For these, creating multiple threads adds overhead and complexity in managing thread synchronization and context switching. Instead, Node.js adopted an event-driven approach.</p><p>This behavior brings several advantages and also limitations to Node.js.</p><h4><strong>The advantages are okay. But what about limitations?</strong></h4><p>The main limitations that the Node.js Single-Threaded Event Loop brings are as follows,</p><ul><li><strong>CPU-bound tasks can block the loop:</strong> Extensive calculations can “freeze” the loop, affecting responsiveness for other requests.</li><li><strong>No true parallelism:</strong> Tasks are still executed one after another, not simultaneously.</li></ul><blockquote>To address these limitations, Node.js introduced <strong>Worker Threads</strong> and the <strong>Cluster Module</strong> in various Node.js versions.</blockquote><p>These two features can truly impact your software development journey. So, let’s delve into <strong>Worker Threads</strong> and the <strong>Cluster Module</strong> in the upcoming sections to understand their incredible usefulness.</p><blockquote>Afterwards, we’ll explore <strong>three more Node.js features</strong> that can come to your rescue in various situations. Stay tuned!</blockquote><h3>1. Worker Threads</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uHcdivbqfc5PwBei.png" /></figure><p><em>(https://nodesource.com/blog/worker-threads-nodejs/)</em></p><p>While the single-threaded event loop excels at handling I/O-bound tasks, Node.js’s <a href="https://nodejs.org/api/worker_threads.html">worker_threads</a> module empowers you to break free from its limitations when dealing with <a href="https://en.wikipedia.org/wiki/CPU-bound"><strong>CPU-bound</strong></a> operations.</p><p>Imagine having multiple chefs working independently in the kitchen, simultaneously preparing different dishes (tasks) — that’s the essence of worker threads!</p><h4>What’s happening under the hood?</h4><p>Node.js, by default, has a single-threaded event loop that excels at handling I/O-bound tasks. But for CPU-bound tasks, it can become a bottleneck.</p><blockquote>Think of worker threads as separate JavaScript execution contexts within the same Node.js process.</blockquote><p>Instead of the main thread handling everything, it can delegate CPU-intensive tasks to these worker threads. This allows the main thread to remain responsive and handle other requests while the worker threads crunch away on the complex calculations.</p><p><strong>Essentially, worker threads allow you to:</strong></p><ul><li><strong>Offload CPU-bound tasks:</strong> Free up the main thread for other work.</li><li><strong>Achieve parallelism:</strong> Execute tasks concurrently for faster performance.</li><li><strong>Share data efficiently:</strong> Avoid the overhead of copying data between processes.</li></ul><h4><strong>Getting started with worker threads</strong></h4><p>The <a href="https://nodejs.org/api/worker_threads.html">worker_threads</a> module provides a simple API for creating and communicating with worker threads:</p><pre>const { Worker } = require(&#39;worker_threads&#39;);<br><br>const worker = new Worker(&#39;./worker.js&#39;, { data: { someData: &#39;to process&#39; } });<br><br>worker.on(&#39;message&#39;, (message) =&gt; {<br>  console.log(Received message from worker: ${message} );<br>});<br><br>worker.postMessage({ anotherData: &#39;to send&#39; });</pre><p>Remember, worker threads share memory. So data structures like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer">SharedArrayBuffer</a> are recommended for large data exchanges to avoid unnecessary copying.</p><p><strong>Also remember:</strong></p><ul><li>Creating and managing worker threads has some overhead, so consider its benefit vs. cost for your specific use case.</li><li>Thread safety is crucial! Use synchronization mechanisms to ensure data integrity.</li><li>Worker threads add complexity, so use them judiciously for tasks that truly benefit from parallelism.</li></ul><h3>2. Cluster Process Module</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4F2f1LHzjAJE8pDf.png" /></figure><p><em>(https://cheatcode.co/tutorials/how-to-add-cluster-support-to-node-js)</em></p><p>While worker threads work great for parallelism, the cluster module empowers you to go even further in your multi-core system.</p><p>Imagine having multiple kitchens (Node.js processes) running independently, each handling requests simultaneously — that’s the power of clustering!</p><h4>What’s happening under the hood?</h4><p>The <a href="https://nodejs.org/api/cluster.html"><strong>Cluster Module</strong></a> creates multiple separate Node.js processes, each with its own event loop and memory space.</p><blockquote>These processes run independently on <strong>different cores</strong>, utilizing multiple cores for improved performance (<strong>Horizontal Scaling</strong>).</blockquote><p>This operates by creating a master process and several worker processes. The master process manages the distribution of incoming connections among the worker processes. If a worker process fails, the master process can respawn a new one, ensuring robustness in the face of failures.</p><p><strong>But why embrace the Cluster?</strong></p><ul><li><strong>Boost Performance:</strong> Handle higher traffic volumes and improve response times, especially for I/O-bound tasks.</li><li><strong>Maximize Resource Utilization:</strong> Take advantage of all available cores in your server, significantly increasing processing power.</li><li><strong>Enhanced Fault Tolerance:</strong> If one worker crashes, others keep the application running, ensuring reliability and uptime.</li></ul><h4><strong>Getting Started with the Cluster</strong></h4><p>The <a href="https://nodejs.org/api/cluster.html">cluster</a> module provides a straightforward API for setting up and managing worker processes:</p><pre>const cluster = require(&#39;cluster&#39;);<br><br>if (cluster.isMaster) {<br>  // Master process<br>  const numWorkers = require(&#39;os&#39;).cpus().length;<br><br>  for (let i = 0; i &lt; numWorkers; i++) {<br>    cluster.fork();<br>  }<br><br>  cluster.on(&#39;exit&#39;, (worker, code, signal) =&gt; {<br>    console.log(worker ${worker.process.pid} died );<br>  });<br>} else {<br>  // Worker process<br>  // Your application logic here<br>  app.listen(3000);<br>}</pre><p><strong>Remember:</strong></p><ul><li>Worker processes share memory and resources, so consider data synchronization carefully.</li><li>The cluster module adds complexity to your application architecture, so evaluate its benefit vs. complexity for your specific needs.</li></ul><p><strong>When to Consider the Cluster:</strong></p><ul><li><strong>High-Traffic Websites:</strong> When your single-threaded event loop reaches its limits, scaling horizontally with cluster helps manage large user bases efficiently.</li><li><strong>Long-Running Tasks:</strong> If some requests involve lengthy operations (like image processing or data encryption), distributing them across worker processes improves responsiveness for other requests.</li><li><strong>Fault Tolerance is Critical:</strong> For mission-critical applications, the cluster module’s resilience to individual process failures offers valuable protection.</li></ul><h3>3. Built-in HTTP/2 Support</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4LhdUVLCf5JMGLr_.png" /></figure><p><em>(https://github.com/nodejs/http2)</em></p><p>While worker threads and the cluster module address different concerns, Node.js’s <a href="https://nodejs.org/api/http2.html#http2">http2</a> module tackles performance directly by offering built-in support for the efficient <a href="https://en.wikipedia.org/wiki/HTTP/2"><strong>HTTP/2 protocol</strong></a>.</p><h4><strong>What is this HTTP/2?</strong></h4><p>HTTP/2, the successor to HTTP/1.1, brings several performance enhancements:</p><ul><li><strong>Multiplexing:</strong> Enables simultaneous sending and receiving of multiple requests and responses on a single connection, eliminating the head-of-line blocking issue plaguing HTTP/1.1.</li><li><strong>Header compression:</strong> Shrinks header size by compressing them, dramatically reducing data transmission overhead.</li><li><strong>Server push:</strong> Allows servers to proactively send resources to clients before they request them, potentially accelerating page load times.</li></ul><h4>How does Node.js provide support for HTTP/2?</h4><p>Node.js provides a robust <a href="https://nodejs.org/api/http2.html#http2">http2</a> module for working with HTTP/2. Here are some of the features it offers:</p><ul><li><a href="https://nodejs.org/api/http2.html#core-api"><strong>Creating HTTP/2 servers</strong></a><strong>:</strong> Use familiar Node.js server patterns with additional options for managing streams and server push functionality.</li><li><a href="https://nodejs.org/api/http2.html#client-side-example"><strong>Handling HTTP/2 clients</strong></a><strong>:</strong> Access client-side capabilities to connect to and interact with HTTP/2 servers.</li><li><a href="https://nodejs.org/api/http2.html#core-api"><strong>Extensive API</strong></a><strong>:</strong> Explore various methods and events to manage connections, streams, push mechanisms, and error handling.</li></ul><h4><strong>Getting started with http2</strong></h4><p><a href="https://nodejs.org/api/http2.html">Node.js documentation</a> offers detailed guides and examples for using the http2 module. However, simply providing a link isn’t enough. Let’s jump into some practical examples to demonstrate its usage.</p><p><strong>1. Creating a basic HTTP/2 Server:</strong></p><pre>const http2 = require(&#39;http2&#39;);<br><br>const server = http2.createServer();<br><br>server.on(&#39;stream&#39;, (stream, headers) =&gt; {<br>  stream.respond({<br>    &#39;status&#39;: 200,<br>    &#39;content-type&#39;: &#39;text/plain&#39;,<br>  });<br>  stream.end(&#39;Hello from your HTTP/2 server!&#39;);<br>});<br><br>server.listen(3000, () =&gt; {<br>  console.log(&#39;Server listening on port 3000&#39;);<br>});</pre><p>This code creates a simple server that sends a “Hello” message to any client connecting through HTTP/2.</p><p><strong>2. Handling Client Requests:</strong></p><pre>const http2 = require(&#39;http2&#39;);<br><br>const server = http2.createServer();<br><br>server.on(&#39;stream&#39;, (stream, headers) =&gt; {<br>  const path = headers[&#39;:path&#39;];<br><br>  if (path === &#39;/&#39;) {<br>    stream.respond({<br>      &#39;status&#39;: 200,<br>      &#39;content-type&#39;: &#39;text/plain&#39;,<br>    });<br>    stream.end(&#39;Hello from HTTP/2 server!&#39;);<br>  } else {<br>    stream.respond({<br>      &#39;status&#39;: 404,<br>      &#39;content-type&#39;: &#39;text/plain&#39;,<br>    });<br>    stream.end(&#39;Not found&#39;);<br>  }<br>});<br><br>server.listen(3000, () =&gt; {<br>  console.log(&#39;Server listening on port 3000&#39;);<br>});</pre><p>This code extends the previous example to handle different request paths (/) and send appropriate responses.</p><h3>4. Streams API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EmBQH-2R-H_F0yJo.png" /></figure><p><em>(https://www.scaler.com/topics/nodejs/streams-in-nodejs/)</em></p><p>Node.js’s Streams API provides a powerful foundation for efficient data handling in your applications. Understanding streams helps you build scalable and performant systems.</p><h4><strong>What are Streams?</strong></h4><blockquote>Imagine data flowing like a stream of water — that’s essentially the concept.</blockquote><p>Streams represent continuous sequences of data chunks delivered over time. Node.js provides <a href="https://nodejs.org/api/stream.html#types-of-streams">various stream types</a>, each catering to different use cases:</p><ul><li><strong>Readable Streams:</strong> Emit data chunks for consumption, ideal for reading files, network connections, or user input.</li><li><strong>Writable Streams:</strong> Allow writing data chunks, perfect for writing to files, network connections, or databases.</li><li><strong>Duplex Streams:</strong> Combine reading and writing capabilities, useful for bidirectional communication like sockets or pipes.</li><li><strong>Transform Streams:</strong> Modify data as it flows through, enabling encryption, compression, or data manipulation.</li></ul><h4>Why should you use Streams?</h4><p>Streams shine in scenarios where large datasets or continuous data flows are involved. They offer several advantages:</p><ul><li><strong>Memory efficiency:</strong> They handle data in chunks, avoiding loading the entire dataset into memory at once.</li><li><strong>Non-blocking nature:</strong> They don’t block the main thread, allowing your application to remain responsive while processing data.</li><li><strong>Flexibility:</strong> Different stream types cater to various data handling needs.</li></ul><h4><strong>Getting Started with Streams</strong></h4><p>Exploring the built-in <a href="https://nodejs.org/api/fs.html">fs</a> module provides a practical introduction to streams. Here&#39;s an example reading a file chunk by chunk:</p><pre>const fs = require(&#39;fs&#39;);<br><br>const readableStream = fs.createReadStream(&#39;large_file.txt&#39;);<br><br>readableStream.on(&#39;data&#39;, (chunk) =&gt; {<br>  console.log(&#39;Received data chunk:&#39;, chunk.toString());<br>});<br><br>readableStream.on(&#39;end&#39;, () =&gt; {<br>  console.log(&#39;Finished reading file&#39;);<br>});</pre><p>This code reads the large_file.txt file in chunks and logs them to the console. Explore the <a href="https://nodejs.org/api/stream.html">Node.js documentation</a> for more types and their usage.</p><h3>5. REPL (Read-Eval-Print Loop)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/0*Ti2y12Xw0U00RMg9.png" /></figure><p><em>(https://www.scaler.com/topics/nodejs/node-js-repl/)</em></p><p>While worker threads and the cluster module contribute to improved performance and scalability, the dynamic duo of HTTP/2 and streams extends their abilities, offering versatile benefits across multiple domains. On a different front, the <a href="https://nodejs.org/en/learn/command-line/how-to-use-the-nodejs-repl"><strong>REPL (Read-Eval-Print Loop)</strong></a> introduces a distinct kind of power — <strong>interactivity and exploration</strong>.</p><blockquote>Imagine a sandbox environment where you can experiment with code snippets, test ideas, and get immediate feedback — that’s the essence of REPL.</blockquote><p>Think of it as a <strong>conversational coding experience</strong>. You type in code expressions, and the REPL evaluates them and displays the results, allowing you to iterate and learn quickly. This makes REPL invaluable for:</p><ul><li><strong>Learning and Experimentation:</strong> Try out new JavaScript features, explore libraries, and test hypotheses in a safe, isolated environment.</li><li><strong>Debugging and Troubleshooting:</strong> Isolate and fix issues in your code line by line, inspecting variables and values at each step.</li><li><strong>Interactive Development:</strong> Prototype ideas quickly, get immediate feedback, and refine your code iteratively.</li></ul><p><strong>Accessing the REPL:</strong></p><p>Open your terminal and simply type node. Voilà! You’re now in the REPL, ready to play. Type any JavaScript variable assignment, a function call, or even a complex calculation.</p><pre>Welcome to Node.js v20.11.0.<br>Type &quot;.help&quot; for more information.<br>&gt; Math.random()<br>0.6148448277159013</pre><p>When compared to all the robust features outlined earlier, the REPL may seem deceptively simple. However, its true value becomes evident only through hands-on experience. As a Node.js developer, embracing and integrating the REPL into your workflow is not just beneficial but essential.</p><h3>Concluding Thoughts</h3><p>Among the powerful arsenal of tools that Node.js provides, <strong>worker threads</strong> tackle CPU-bound tasks, the <strong>cluster module</strong> enables horizontal scaling, and <strong>http2</strong> gives the power of HTTP/2 network protocol. <strong>Streams</strong> provide efficient data handling, and the <strong>REPL</strong> empowers interactive exploration and learning.</p><p>By mastering these features, you’ll unlock the full potential of Node.js and build performant, scalable, and enjoyable development experiences.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/5-tools-and-patterns-for-typesafe-apis-72dd6db17a76">5 Tools and Patterns for Typesafe APIs</a></li><li><a href="https://blog.bitsrc.io/how-bit-versions-independent-components-719aa9f0af68">How Bit Versions Independent Components</a></li><li><a href="https://blog.bitsrc.io/creating-a-frontend-platform-in-2024-d4e45e19c0f5">Creating a Frontend Platform in 2024</a></li><li><a href="https://blog.bitsrc.io/adapter-pattern-in-web-applications-995c517ff420">Exploring The Adapter Pattern In Modern Web Applications</a></li><li><a href="https://blog.bitsrc.io/mach-architecture-a-practical-guide-7952b7329862">MACH Architecture: A Practical Guide</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://blog.bitsrc.io/modern-angular-development-b469341a3620">A Modern Approach for Angular Development</a></li><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/modern-approach-to-react-development-090358b04e7d">A Modern Approach to React Development</a></li><li><a href="https://blog.bitsrc.io/monorepo-poly-repo-or-no-repo-at-all-830328c7a546">Monorepo, Poly-repo, or No Repo at all?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e49d1c68f4a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/top-5-features-of-nodejs-e49d1c68f4a7">Top 5 Node.js Features Every Developer Should Know</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 Node.js Design Patterns Every Developer Should Know]]></title>
            <link>https://medium.com/bitsrc/nodejs-design-patterns-must-know-8ef0a73b3339?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ef0a73b3339</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 11:55:38 GMT</pubDate>
            <atom:updated>2025-03-04T17:59:47.430Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore the Facade, Adapter, Singleton, Prototype, Builder, Proxy and Factory for modern software design.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8PuClELl1cRbarRH.png" /></figure><p>Design patterns are needed to solve every-day software design problems. This could be problems like:</p><ol><li>Maintaining database connections</li><li>Creating and managing objects</li><li>Notifying a set of users subscribed to a particular entity.</li></ol><p>If you try to come up with a solution all by yourself, you’d likely need to put in a lot of effort into these problems and design optimal solutions to such problems.</p><blockquote>But you don’t have to do that at all!</blockquote><p>Design patterns were introduced as a means of providing solutions to such recurring problems. All you have to do is implement the pattern according to your framework/language and you’re good to go!</p><p>So, let’s take a look at the most frequent design patterns that you might need to implement when you’re working with Node.js.</p><figure><a href="https://bit.cloud/"><img alt="Build in AI speed — Compose enterprise-grade applications, features, and components" src="https://cdn-images-1.medium.com/max/1024/1*yX0vq3scSudyT61IuWFuEg.png" /></a><figcaption>Build in AI speed — Compose enterprise-grade applications, features, and components</figcaption></figure><blockquote><strong>Pst, if you want to skip the article and jump directly to the code, check out my</strong> <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo"><strong>Bit Scope</strong></a><strong>.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I8LDXkzAXUMRYCF3.png" /><figcaption><a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo/~graph">A List of Components That Showcase Design Patterns</a></figcaption></figure><h3><strong>1. Facade</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*GFAHN18MqctGr1Sy.png" /></figure><p><em>(Source: </em><a href="https://refactoring.guru/design-patterns/facade)"><em>https://refactoring.guru/design-patterns/facade)</em></a></p><p>Firstly, it’s important that you understand the Facade pattern. This is very important in Node.js apps.</p><blockquote>Simply put, the Facade design pattern simplifies complex subsystems by providing a unified interface.</blockquote><p>It acts as a single entry point, hiding all the internal implementation details and promoting easier interaction with the underlying functionalities. It acts as a gateway, shielding clients from intricate details.</p><p>For example, the process of logging into a website using a Google account can be considered as a real-world example of a Facade. You only need to click on the “Login with Google” button and it acts as a unified login option.</p><blockquote>You don’t need to worry about entering your email, password, or other personal details.</blockquote><h4>Benefits:</h4><ul><li><strong>Simplified Interface</strong>: This reduces cognitive load for developers making the interactions with complex systems easy.</li><li><strong>Reduced Coupling</strong>: Decoupling client code from internal implementation details can improve code maintainability and flexibility.</li><li><strong>Improved Readability</strong>: Encapsulates complex logic within the Facade, making code more organized and understandable.</li><li><strong>Controlled Access:</strong> Enable specific rules or validations before accessing the underlying features.</li></ul><p>Consider this snippet:</p><pre>// Complex Module<br>class ComplexModule {<br>  initialize() {<br>    // Complex initialization logic<br>  }<br><br>  operation1() {<br>    // Complex operation 1<br>  }<br><br>  operation2() {<br>    // Complex operation 2<br>  }<br>}<br><br>// Client Code<br>const complexModule = new ComplexModule();<br>complexModule.initialize();<br>complexModule.operation1();<br>complexModule.operation2();</pre><p>The snippet showcases how your app might interact if you added the subsystem communication outside of your module. You’d have to manually execute all of the operations, and you’d likely face issues in maintaining your code.</p><p>However, check out this snippet:</p><pre>// Facade for Complex Module<br>class ModuleFacade {<br>  constructor() {<br>    this.complexModule = new ComplexModule();<br>  }<br><br>  performOperations() {<br>    this.complexModule.initialize();<br>    this.complexModule.operation1();<br>    this.complexModule.operation2();<br>  }<br>}<br><br>// Client Code<br>const moduleFacade = new ModuleFacade();<br>moduleFacade.performOperations();</pre><p>Now, as you can see, we no longer have the sub-module initializations outside of the module, but rather encapsulated in a function performOperations that handles all internal complex sub-system communication.</p><blockquote>So you get one clean approach to handle complex communication trees.</blockquote><p>To view it’s full implementation, <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo/facade/~code"><strong>visit here</strong></a><strong>.</strong></p><h3><strong>2. Singleton</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*pJA5RFC4J-Rd6Xr4.png" /></figure><p><em>(Source: </em><a href="https://refactoring.guru/design-patterns/singleton)"><em>https://refactoring.guru/design-patterns/singleton)</em></a></p><p>Next up, this is one of the patterns that you’ll likely be using every single day of your life until you retire. Sometimes, you’ll need to make sure that you only have one instance of something.</p><blockquote>For example, consider a database connection. Do you need more than one database connection to your app at a given time? Can you reuse an existing connection?</blockquote><p>That’s where Singleton comes into the picture. It ensures that your class has one global instance that can be accessed using a static method.</p><h4>Benefits:</h4><ul><li><strong>Global Access:</strong> A convenient way to access shared data or functionality from anywhere in your application.</li><li><strong>Resource Management:</strong> Ensures efficient use of resources like database connections, loggers, or file handles by having only one instance.</li><li><strong>Consistency:</strong> Enforces consistent behavior as modifications affect only a single instance.</li><li><strong>Controlled State:</strong> Simplifies state management by having a central point for data manipulation.</li></ul><p>Here’s how a singleton implementation will look like in Node.js:</p><pre>class ConfigManager {<br>  constructor() {<br>    this.databaseConfig = { /* database configuration */ };<br>    this.apiKey = &quot;your_api_key&quot;;<br>    // Other application-wide configurations<br>  }<br><br>  static getInstance() {<br>    if (!this.instance) {<br>      this.instance = new ConfigManager();<br>    }<br>    return this.instance;<br>  }<br><br>  getDatabaseConfig() {<br>    return this.databaseConfig;<br>  }<br><br>  getApiKey() {<br>    return this.apiKey;<br>  }<br><br>  // Additional methods to retrieve other configurations<br>}<br><br>// Usage<br>const configManager = ConfigManager.getInstance();<br><br>// Accessing configurations<br>const databaseConfig = configManager.getDatabaseConfig();<br>const apiKey = configManager.getApiKey();</pre><p>You might have a Node.js application that interacts with multiple external services, each requiring specific configuration parameters. Using the Singleton pattern, you can create a ConfigManager class responsible for handling these configurations in a centralized manner.</p><p>To view it’s full implementation, <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo/singleton/~code"><strong>visit here</strong></a>.</p><h3>3. <strong>Adapter</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*CfYROj3PqQ-Cjt6A.png" /></figure><p><em>(Source: </em><a href="https://refactoring.guru/design-patterns/adapter)"><em>https://refactoring.guru/design-patterns/adapter)</em></a></p><p>Next, you’ll have to imagine a scenario where an API that you’re consuming and a client that you’re working on has an incompatible API.</p><p>For example, you might have a React component that accepts two props:</p><ol><li>First Name</li><li>Last Name</li></ol><p>But your API returns a variable:</p><ol><li>Full Name</li></ol><p>So, if you’re in a position where you don’t have access to update the API Body, you’ll have to work with what you have, and make your app work.</p><blockquote>That’s where the adapter pattern comes into the picture.</blockquote><p>The Adapter pattern bridges the gap between incompatible interfaces, allowing them to work together seamlessly.</p><h4>Benefits:</h4><ul><li><strong>Interoperability:</strong> Enables communication between components with different interfaces, promoting system integration and reuse.</li><li><strong>Loose Coupling:</strong> Decouples client code from the concrete implementation of the adapted component, improving flexibility and maintainability.</li><li><strong>Flexibility:</strong> Allows adapting new components without modifying existing code by creating new adapters.</li><li><strong>Reusability:</strong> The adapter implementation can be reused for similar compatibility needs, reducing code duplication.</li></ul><h4>Example:</h4><p>Below, you can find a simple coding example of an Adapter design pattern. To view a full implementation, <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo/adapter/~code"><strong>visit here</strong></a>.</p><p><strong>Old system</strong></p><pre>class OldSystem {<br>  request() {<br>    return &quot;Old System Request&quot;;<br>  }<br>}</pre><p><strong>New system &amp; Adapter</strong></p><pre>class NewSystem {<br>  newRequest() {<br>    return &quot;New System Request&quot;;<br>  }<br>}<br><br>class Adapter {<br>  constructor(newSystem) {<br>    this.newSystem = newSystem;<br>  }<br><br>  request() {<br>    return this.newSystem.newRequest();<br>  }<br>}</pre><p><strong>Client usage</strong></p><pre>// Using the OldSystem<br>const oldSystem = new OldSystem();<br>console.log(oldSystem.request()); // Outputs: Old System Request<br><br>// Using the Adapter with the NewSystem<br>const newSystem = new NewSystem();<br>const adapter = new Adapter(newSystem);<br>console.log(adapter.request()); // Outputs: New System Request</pre><h3>4. <strong>Builder</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*XeU_oQnQDN4EItx6.png" /></figure><p><em>(Source: </em><a href="https://refactoring.guru/design-patterns/builder)"><em>https://refactoring.guru/design-patterns/builder)</em></a></p><blockquote>Next, we’re going to be looking a pattern that you can use to construct objects and make object management much easier.</blockquote><p>The Builder pattern separates the construction of a complex object from its representation.</p><p>It’s like assembling a custom PC — choosing components individually and constructing the final product. In Node.js, the Builder pattern aids in constructing objects with intricate configurations, ensuring a step-by-step, customizable process.</p><p>In this design pattern, instead of having a constructor with numerous arguments, you create separate methods (“builders”) for each optional property of the object. These methods often return the current instance of the class (this) to allow chaining them together for building objects incrementally.</p><h4><strong>Benefits:</strong></h4><ul><li><strong>Improved Readability:</strong> Clearer code by explicitly setting each property with meaningful method names.</li><li><strong>Flexibility:</strong> Construct objects with only the necessary properties, avoiding unexpected values in unused fields.</li><li><strong>Immutability:</strong> The build() method often creates a new instance instead of modifying the builder, promoting immutability and easier reasoning.</li><li><strong>Error Handling</strong>: It is easier to validate property values and throw errors within builder methods than in a complex constructor.</li></ul><h4>Example:</h4><p>Below, you can find a simple coding example of a Builder design pattern. To explore it’s full implementation, <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo/builder/~code"><strong>visit here</strong></a>.</p><pre>class UserBuilder {<br>  constructor(name) {<br>    this.name = name;<br>    this.email = null;<br>    this.address = null;<br>  }<br><br>  withEmail(email) {<br>    this.email = email;<br>    return this; // Method chaining<br>  }<br><br>  withAddress(address) {<br>    this.address = address;<br>    return this;<br>  }<br><br>  build() {<br>    // Validate and build the User object<br>    const user = new User({<br>      name: this.name,<br>      email: this.email,<br>      address: this.address,<br>    });<br>    return user;<br>  }<br>}<br><br>// Client code<br>const user1 = new UserBuilder(&#39;John&#39;)<br>  .withEmail(&#39;john@example.com&#39;)<br>  .withAddress(&#39;123 Main St.&#39;)<br>  .build();<br><br>console.log(user1); // Prints the complete User object with values</pre><h3>5. <strong>Factory</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*KLY0Xf0BMH5DBnu_.png" /></figure><p><em>(Source: </em><a href="https://refactoring.guru/design-patterns/factory-method)"><em>https://refactoring.guru/design-patterns/factory-method)</em></a></p><p>The Factory pattern provides an interface for creating objects but lets subclasses alter the type of objects created.</p><p>Picture it as a manufacturing plant with different assembly lines for producing distinct products. In Node.js, the Factory pattern excels in creating objects without specifying their concrete classes, fostering flexibility and extensibility.</p><h4><strong>Benefits:</strong></h4><ul><li><strong>Decoupling:</strong> Client code is decoupled from specific object creation logic, promoting flexibility and maintainability.</li><li><strong>Centralized Control:</strong> You can easily add new object types or modify existing ones without affecting client code, as long as the Factory handles the changes.</li><li><strong>Flexibility:</strong> The Factory can choose the appropriate object based on runtime conditions or configuration, making your code more adaptable.</li><li><strong>Encapsulation:</strong> Object creation details are hidden within the Factory, improving code readability and maintainability.</li></ul><h4>Example:</h4><p>Below, you can find a simple coding example of a Factory design pattern. <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo/factory/~code"><strong>Visit here</strong></a> for more coding examples.</p><p><strong>Shape Interface</strong></p><pre>// Shape interface<br>class Shape {<br>  draw() {}<br>}</pre><p><strong>Concrete shapes</strong></p><pre>// Concrete implementations of the Shape interface<br>class Circle extends Shape {<br>  draw() {<br>    console.log(&quot;Drawing Circle&quot;);<br>  }<br>}<br><br>class Square extends Shape {<br>  draw() {<br>    console.log(&quot;Drawing Square&quot;);<br>  }<br>}<br><br>class Triangle extends Shape {<br>  draw() {<br>    console.log(&quot;Drawing Triangle&quot;);<br>  }<br>}</pre><p><strong>Shape factory</strong></p><pre>// ShapeFactory class responsible for creating instances of shapes<br>class ShapeFactory {<br>  createShape(type) {<br>    switch (type) {<br>      case &#39;circle&#39;:<br>        return new Circle();<br>      case &#39;square&#39;:<br>        return new Square();<br>      case &#39;triangle&#39;:<br>        return new Triangle();<br>      default:<br>        throw new Error(&#39;Invalid shape type&#39;);<br>    }<br>  }<br>}</pre><p><strong>Client code</strong></p><pre>// Client code using the ShapeFactory to create shapes<br>const shapeFactory = new ShapeFactory();<br><br>const circle = shapeFactory.createShape(&#39;circle&#39;);<br>circle.draw(); // Outputs: Drawing Circle<br><br>const square = shapeFactory.createShape(&#39;square&#39;);<br>square.draw(); // Outputs: Drawing Square<br><br>const triangle = shapeFactory.createShape(&#39;triangle&#39;);<br>triangle.draw(); // Outputs: Drawing Triangle</pre><h3>6. <strong>Prototype</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*UjUekpoMC7LsK09f.png" /></figure><p><em>(Source: </em><a href="https://refactoring.guru/design-patterns/prototype)"><em>https://refactoring.guru/design-patterns/prototype)</em></a></p><blockquote>The Prototype pattern involves creating new objects by copying an existing object, known as the prototype.</blockquote><p>It creates duplicates of a master key. It’s useful when creating an object is more expensive than copying an existing one.</p><h4><strong>Concept:</strong></h4><ol><li><strong>Prototype:</strong> Define a base object with desired properties and methods. This serves as the blueprint for subsequent objects.</li><li><strong>Cloning:</strong> You create new objects by copying the prototype, often using built-in methods like Object.create or custom cloning logic.</li><li><strong>Customization:</strong> The newly created objects can have their individual properties modified without affecting the original prototype.</li></ol><h4><strong>Benefits:</strong></h4><ul><li><strong>Performance:</strong> Cloning existing objects is generally faster than constructing new ones from scratch, especially for complex objects.</li><li><strong>Memory Efficiency:</strong> By sharing properties and methods through the prototype, you avoid redundant storage, reducing memory usage.</li><li><strong>Dynamic Modifications:</strong> You can easily extend the prototype later to add new functionalities to all existing and future instances.</li></ul><h4>Example:</h4><p>Below, you can find a simple coding example of a Prototype design pattern. <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo/prototype/~code"><strong>Visit here</strong></a> for more coding examples.</p><p><strong>Prototype object</strong></p><pre>// Prototype object<br>const animalPrototype = {<br>  type: &#39;unknown&#39;,<br>  makeSound: function () {<br>    console.log(&#39;Some generic sound&#39;);<br>  },<br>  clone: function () {<br>    return Object.create(this); // Using Object.create() for cloning<br>  },<br>};</pre><p><strong>Customize instance</strong></p><pre>// Custom instances based on the prototype<br>const dog = animalPrototype.clone();<br>dog.type = &#39;Dog&#39;;<br>dog.makeSound = function () {<br>  console.log(&#39;Woof!&#39;);<br>};<br><br>const cat = animalPrototype.clone();<br>cat.type = &#39;Cat&#39;;<br>cat.makeSound = function () {<br>  console.log(&#39;Meow!&#39;);<br>};</pre><p>Client code</p><pre>// Client code using the customized instances<br>dog.makeSound(); // Outputs: Woof!<br>cat.makeSound(); // Outputs: Meow!</pre><h3>7. <strong>Proxy</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*8f45wVvxaDAfV-Hj.png" /></figure><p><em>(Source: </em><a href="https://refactoring.guru/design-patterns/proxy)"><em>https://refactoring.guru/design-patterns/proxy)</em></a></p><blockquote>The Proxy pattern serves as a surrogate or placeholder for another object, controlling access to it.</blockquote><p>This creates an intermediary object (“proxy”) that stands between a client and a real object. This proxy controls access to the real object, potentially intercepting and modifying operations before or after they reach the target.</p><p>This allows you to add additional functionalities without directly altering the real object’s implementation. The Proxy pattern is instrumental for lazy loading, access control, or adding logging/debugging features.</p><p>To gain a better understanding of the Proxy Design Pattern and its use cases in the React environment, check this out:</p><p><a href="https://blog.bitsrc.io/proxy-design-pattern-with-react-c0b465980fbf">Using Proxy Design Pattern with React in Practice</a></p><h4><strong>Benefits:</strong></h4><ul><li><strong>Controlled Access:</strong> Enforce permissions or validation before interacting with the real object.</li><li><strong>Additional Functionality:</strong> Add features like logging, caching, or security without changing the object itself.</li><li><strong>Abstraction:</strong> Simplify client code by hiding the real object’s implementation details.</li><li><strong>Flexibility:</strong> Dynamically change the target object or handler behavior at runtime.</li></ul><h4><strong>Example:</strong></h4><p>Below, you can find a simple coding example of the Proxy design pattern, and for more coding examples <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo/proxy/~code"><strong>visit here</strong></a>.</p><p>In all of these examples, I used the JavaScript Proxy object to create proxies for other objects. To get a more in-depth understanding of the JavaScript inbuilt Proxy, you can <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy"><strong>visit here</strong></a>.</p><pre>const target = {<br>  name: &#39;Alice&#39;,<br>  sayHello() {<br>    console.log(Hello, my name is ${this.name} );<br>  },<br>};<br><br>const handler = {<br>  get(target, prop, receiver) {<br>    console.log(Property ${prop} accessed );<br>    return Reflect.get(target, prop, receiver);<br>  },<br>  set(target, prop, value, receiver) {<br>    console.log(Property ${prop} set to ${value} );<br>    return Reflect.set(target, prop, value, receiver);<br>  },<br>};<br><br>const proxy = new Proxy(target, handler);<br><br>proxy.name; // Output: Property name accessed<br>proxy.sayHello(); // Output: Property sayHello accessed<br>                  //        Hello, my name is Alice<br>proxy.name = &#39;Bob&#39;; // Output: Property name set to Bob</pre><h3>Concluding Thoughts</h3><p>Design patterns are important for every developer to learn. Whether you’re a beginner or an expert, it’s important that you understand design patterns and its use in modern software development as it lets you build better software, quicker.</p><p>If you wish to check out the code we covered, checkout <a href="https://bit.cloud/wulfridng/nodejs-design-patterns-demo">this Bit Scope</a> I’ve implemented.</p><p>Thank you for reading.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/modern-angular-development-b469341a3620">A Modern Approach for Angular Development</a></li><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://blog.bitsrc.io/modern-approach-to-react-development-090358b04e7d">A Modern Approach to React Development</a></li><li><a href="https://blog.bitsrc.io/monorepo-poly-repo-or-no-repo-at-all-830328c7a546">Monorepo, Poly-repo, or No Repo at all?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef0a73b3339" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/nodejs-design-patterns-must-know-8ef0a73b3339">7 Node.js Design Patterns Every Developer Should Know</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Concept of Workspaces: Bit, NPM and NX]]></title>
            <link>https://medium.com/bitsrc/the-concept-of-workspaces-bit-vs-npm-vs-nx-356f59ceeef9?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/356f59ceeef9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 15:58:40 GMT</pubDate>
            <atom:updated>2024-01-05T17:18:30.510Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the concept of workspaces and how it&#39;s used in Bit, NPM, and NX.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwYLpoYbQeUvj2Mb3wlc4A.png" /></figure><p>Everyone is talking about Monorepos nowadays, and it’s no surprise, given the complexities of today’s applications.</p><p>With the rise of Monorepos, the demand for robust tooling to handle collaborative coding, streamlined dependency management, and efficient code reuse has grown. It demanded more from your typical development environment.</p><h3>What are Workspaces?</h3><p>Workspaces are simply an extension of your development environment with robust tooling integration. For example, if we take a Monorepo, you may need a workspace that understands different components in the repository. In addition to that, it may provide tooling for dependency management, code sharing, and improved collaboration.</p><p>Workspaces can take different shapes depending on the technology it needs to support. Therefore, let’s look at 3 different tools that offer workspaces with unique capabilities for developers.</p><h3>1. Bit — Next Generation Build System for Composable Software</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*dLQi5kplCMdSh8sI.png" /></figure><p>Bit is a build system for <a href="https://bit.dev/docs/intro/"><strong>composable software</strong>.</a> Bit is similar to Monorepos but opposes the idea of centralizing all code in a single repository. Instead, Bit is bringing simplicity to the distribution of source code into independently versioned components, depending on each other.</p><p>Therefore, you may need unique tooling in your development environment to work with multiple components and handle their development lifecycle.</p><h4>What is Bit Workspace?</h4><p>At the center of these tools, Bit Workspace provides the local work environment to develop Bit components. Bit requires you to create a workspace to work with Bit components. You typically start by creating an empty workspace or using a predefined one with a default set of components.</p><h4>Features of a Bit Workspace</h4><ul><li>You can run the components development server within the workspace and preview your components.</li><li>Run the application development server to test the application.</li><li>Execute tests and builds and export them to a remote scope in <a href="https://bit.cloud/">bit.cloud</a>.</li><li>All the workspace configurations are defined in a file named <a href="https://bit.dev/reference/workspace/workspace-json">workspace.jsonc.</a></li></ul><p>Let’s look at how to set up a workspace in Bit.</p><h4>Setting up your first Bit Workspace</h4><p><strong>1) Installation</strong></p><p>To get started, first of all, we need to install Bit on your machine,</p><pre>npx @teambit/bvm install</pre><p>For a more advanced installation guide, <a href="https://bit.dev/docs/getting-started/installing-bit/installing-bit/">refer to this</a>.</p><p><strong>2) Setup the Workspace</strong></p><p>Run the following command to build a workspace with a sample ReactJS project.</p><pre>bit new hello-world my-hello-world --env teambit.community/starters/hello-world</pre><p>Alternatively, you can choose another workplace starter template <a href="https://bit.dev/docs/getting-started/installing-bit/start-bit-workspace/">from here</a> to continue.</p><p><strong>3) Run the application</strong></p><p>First, change the directory to newly created workspace,</p><pre>cd my-hello-world</pre><p>Then run the following command to run the application,</p><pre>bit run hello-world-app</pre><p>Now, you have a working Bit Workplace where you can explore creating composable software.</p><h3>2. NPM Workspaces — Managing Multiple Packages within a Root Package</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*MzFDaFHoeGpk0wpI.png" /></figure><h4>What is an NPM Workspace?</h4><p>NPM Workspace enables ways to manage multiple packages from your local file system within a single root package.</p><h4><strong>Features of an NPM Workspace</strong></h4><ul><li>NPM Workspaces opens paths for Monorepo designs.</li><li>NPM Workspaces can automatically handle dependencies within your Monorepo system, ensuring there are no more duplicate dependencies or version conflicts.</li><li>With NPM Workspaces, you can deploy, update, and version individual packages independently without impacting the entire codebase. This can empower faster development cycles.</li><li>Workspace configuration is defined in the package.json file at the root.</li></ul><p>You can readily use the NPM Workspace feature as it comes with the NPM CLI.</p><h4>Setting up your first NPM Workspace</h4><p>You can define a Workspace in package.json file using the <a href="https://www.writergate.com/editor/mslq6mzpwayg/%7B%20%20%20%22name%22:%20%22my-workspaces-powered-project%22,%20%20%20%22workspaces%22:%20[%22workspace-a%22]%20%7D">workspaces</a> property,</p><pre>{<br>  &quot;name&quot;: &quot;my-workspaces-powered-project&quot;,<br>  &quot;workspaces&quot;: [&quot;workspace-a&quot;]<br>}</pre><p>The above configuration tells NPM to consider the folder workspace-a when running npm install and symlink the workspace-a folder to the node_modules of the current working directory.</p><p>Let’s take a look at the folder structure of the project before and after the npm install.</p><p><strong>Before</strong></p><pre>.<br>+-- package.json<br>`-- workspace-a<br>   `-- package.json</pre><p><strong>After</strong></p><pre>.<br>+-- node_modules<br>|  `-- workspace-a -&gt; ../workspace-a<br>+-- package-lock.json<br>+-- package.json<br>`-- workspace-a<br>   `-- package.json</pre><p>Just like creating workspace-a, you have the flexibility to create multiple projects using NPM Workspaces. You can store shared packages in the root directory and specific packages in separate projects as needed.</p><p>To better understand how NPM Workspaces work, refer to the <a href="https://docs.npmjs.com/cli/v7/using-npm/workspaces">official documentation.</a></p><h3>3. NX Workspaces — Helps you Maintain and Scale Monorepos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LKoh9WMZZb7-EpXF.png" /></figure><p><a href="https://nx.dev/">NX</a> lets you create and manage NX Workspaces that let you manage independent codebases, applications, libraries, and even UI components in a single space.</p><p>Inside NX Workspaces, the core Workspace functionality is offered via @nx/<a href="https://nx.dev/nx-api/workspace">workspace</a> plugin.</p><h4>Features of NX Workspace</h4><ul><li>It organizes projects within a monorepo in a structured manner. It provides dedicated directories for applications, libraries, and shared code, thus promoting code reuse, modularity, and maintainability.</li><li>With a monorepo-style NX workspace, you can easily add new projects, refactor existing ones, and manage the entire codebase as a cohesive unit.</li></ul><h4>Setting up your first NX Workspace</h4><p>To initialize the NX Workspace and set up a React Monorepo, navigate to the desired project directory and execute the following,</p><pre>npx create-nx-workspace@latest react-monorepo --preset=react-monorepo</pre><p>Follow the prompts to choose a workspace name, preferred preset (e.g., Angular, React, Node, or empty), and further configuration options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*-eY1ncfJO4NkeA-M.png" /></figure><p>To server the app, run,</p><pre>nx serve react-monorepo</pre><p>For a more in-depth explanation, refer to <a href="https://nx.dev/getting-started/tutorials/react-monorepo-tutorial/">this official NX React monorepo guide</a>.</p><h3>Choosing the Right Tool: The Concluding Thoughts</h3><p>Workspaces emerge as a pivotal concept, offering tooling to work with multiple projects or components in a codebase. Different build systems and package management tools use it to provide a better developer experience.</p><blockquote>Ultimately, the ideal tool depends on your project’s unique needs and the team’s capabilities.</blockquote><p>Experiment, explore, and choose the one that empowers your team to build efficiently, maintain code effectively, and collaborate seamlessly.</p><p>And there we have it. I hope you have found this useful. Thank you for reading!!</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/dependency-handling-in-react-e596c4567c89">Dependency Handling Best Practices in a React Components</a></li><li><a href="https://blog.bitsrc.io/how-to-create-a-nextjs-project-in-2024-27621475075a">How To Create a New Next.js Project in 2024?</a></li><li><a href="https://blog.bitsrc.io/building-a-composable-graphql-app-with-bit-dd7e01bbc310">Building a Composable GraphQL App with Bit</a></li><li><a href="https://blog.bitsrc.io/sharing-static-types-between-your-graphql-client-and-api-42570a01c6e1">Sharing Static Types between your GraphQL Client and API</a></li><li><a href="https://blog.bitsrc.io/modern-angular-development-b469341a3620">A Modern Approach for Angular Development</a></li><li><a href="https://blog.bitsrc.io/modern-approach-to-react-development-090358b04e7d">A Modern Approach to React Development</a></li><li><a href="https://blog.bitsrc.io/monorepo-poly-repo-or-no-repo-at-all-830328c7a546">Monorepo, Poly-repo, or No Repo at all?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=356f59ceeef9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/the-concept-of-workspaces-bit-vs-npm-vs-nx-356f59ceeef9">The Concept of Workspaces: Bit, NPM and NX</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Proxy Design Pattern with React in Practice]]></title>
            <link>https://medium.com/bitsrc/proxy-design-pattern-with-react-c0b465980fbf?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0b465980fbf</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 14:42:57 GMT</pubDate>
            <atom:updated>2025-03-05T11:29:24.602Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using The Proxy Design Pattern with React</h3><h4>Explore the usage of the Proxy Design Pattern in a React environment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ps8bQ2R2XTKxe0gKGeJvfA.png" /></figure><p>As developers, you’ve undoubtedly encountered the term <strong>‘Design Patterns.’</strong> This isn’t just a word to glance over; it’s a key to unlocking a realm of coding mastery. These varied and diverse patterns serve as valuable tools in software development, enhancing code organization, maintainability, and scalability.</p><p>Among the other design patterns out there, the <strong>Proxy Design Pattern</strong>, introduced in 1995 as a <strong>Structural Design Pattern</strong>, has since found widespread application in various scenarios.</p><p>In this article, we dive deeper into Proxy Design Patterns, exploring their usages, and let’s uncover how to apply these patterns to your future React applications, enhancing their structure and functionality.</p><h3>Understanding the Proxy Design Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*RS0uzpy7JeLdLyib.png" /><figcaption>Source: https://refactoring.guru/design-patterns/proxy</figcaption></figure><p>The Proxy Design Pattern, lets you provide a substitute or placeholder for another object.</p><p>By doing so, the proxy gains control over access to the original object, enabling the execution of actions before or after the request reaches the original object.</p><figure><a href="https://bit.cloud/"><img alt="Build in AI speed — Compose enterprise-grade applications, features, and components" src="https://cdn-images-1.medium.com/max/1024/1*yX0vq3scSudyT61IuWFuEg.png" /></a><figcaption>Build in AI speed — Compose enterprise-grade applications, features, and components</figcaption></figure><h4>Why do you want to control the access to an object?</h4><p>For example, you might have encountered situations where certain functions operate continuously, creating massive objects consuming heavy system and network resources. You may need to run this periodically or under some conditions but continuous running can harm the overall performance of the code.</p><p>In such cases, the Proxy Design Pattern becomes valuable. This involves building another proxy class mirroring the original service object’s interface.</p><h4>What is the benefit of having this?</h4><p>By implementing a proxy object, you can execute some other logic before or after executing the main logic of the class.</p><p>For instance, in the example scenario mentioned earlier, you can set up a proxy object to cache data handled by the main object. This proactive caching minimizes the repetition of expensive computations, improving performance and resource efficiency.</p><p>Not only for data caching but proxy design patterns can also be beneficial in many ways, including,</p><ul><li><strong>Improving security:</strong> These can enforce security measures, such as authentication and authorization checks, ensuring that sensitive data or operations are accessible only to authorized users.</li><li><strong>Reduced Resource Consumption:</strong> Lazy loading, caching, and controlled access through proxies can reduce the resource consumption of the application.</li><li><strong>Network Optimization:</strong> In distributed systems, proxy design patterns can optimize network communication by acting as placeholders for remote objects. This aids in minimizing the impact of network latency.</li><li><strong>Concurrency Control:</strong> Proxies can implement mechanisms for controlling concurrent access to shared resources, preventing race conditions, and ensuring data consistency.</li></ul><h3>What is the Proxy Object in JavaScript</h3><p>JavaScript’s Proxy Object has been constructed based on the core concept of proxies in other programming languages, but it comes with its own set of features tailored to the dynamic nature of JavaScript.</p><p>Unlike traditional proxy objects in other languages, JavaScript’s Proxy object provides a highly flexible and dynamic way to interact with and manipulate objects.</p><p>In JavaScript a Proxy object can be defined as follows:</p><pre>const proxy = new Proxy(target, handler);</pre><p>The target refers to the object that the proxy wraps around, while the handler is an object containing one or more &quot;traps&quot; — functions designed to intercept and modify operations carried out on the target object.</p><p><strong>Example usage:</strong></p><pre>const targetObject = {<br>  message: &quot;Hello, Proxy!&quot;,<br>};<br><br>const handler = {<br>  get: function (target, prop) {<br>    console.log(`Accessing property: ${prop}`);<br>    return target[prop];<br>  },<br>};<br><br>const proxy = new Proxy(targetObject, handler);<br>console.log(proxy.message);<br><br>// Accessing property: message <br>// Hello, Proxy!</pre><p>In this example, I used the get trap to demonstrate a basic usage of the JS Proxy Object. You can find more <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">from here</a>.</p><p>Having a basic knowledge of JS proxy objects will be helpful when understanding the next section.</p><h3>How to Use The Proxy Design Pattern in React?</h3><blockquote>If you wish to directly explore the code, feel free to check out this <a href="https://bit.cloud/wulfridng/react-proxy-examples">Bit Scope</a>.</blockquote><p>Now, you should have a clear idea about the proxy design pattern and the proxy object in JavaScript. It’s time to get your hands dirty and gain hands-on experience with React using Proxy.</p><p>React comes with its built-in features set to optimize the performance and overall responsiveness of the app. However, when combining the proxy design pattern with these features, you can further enhance the performance of the app with well-controlled object interactions and data access.</p><h4><strong>Enhanced Security</strong></h4><p>Proxy design patterns can be helpful in a React application to enhance security by providing layers of control over object interactions and access to sensitive data. Below, you can find a simple demonstration of this concept.</p><pre>import { useEffect, useState } from &#39;react&#39;;<br><br>const fetchUserData = () =&gt; {<br> // Place the network request here<br> console.log(&#39;Data fetching...&#39;);<br><br> return {<br>  username: &#39;john_doe&#39;,<br>  password: &#39;user_password&#39;,<br> };<br>};<br><br>const useSecureUserData = () =&gt; {<br> const [userData, setUserData] = useState(null);<br><br> const isUserAdmin = () =&gt; {<br>  // Implement your authorization logic here<br>  // For simplicity, assume logged user is admin<br>  return true;<br> };<br><br> useEffect(() =&gt; {<br>  const userProxy = new Proxy(fetchUserData(), {<br>   get(target, prop) {<br>    // Check if the user is authorized to access the user password<br>    if (prop === &#39;password&#39; &amp;&amp; !isUserAdmin()) {<br>     console.warn(&#39;Unauthorized access to password!&#39;);<br>     return null; // Return null or handle unauthorized access<br>    }<br><br>    return target[prop];<br>   },<br>  });<br><br>  setUserData(userProxy);<br> }, []);<br><br> return userData;<br>};<br><br>export const UserProfile = () =&gt; {<br> const userData = useSecureUserData();<br><br> if (!userData) {<br>  return &lt;div&gt;Loading...&lt;/div&gt;;<br> }<br><br> return (<br>  &lt;div&gt;<br>   &lt;p&gt;Username: {userData.username}&lt;/p&gt;<br>   &lt;p&gt;Password: {userData.password}&lt;/p&gt;<br>  &lt;/div&gt;<br> );<br>};</pre><p>In this simple example, the useSecureUserData custom hook fetches the user data and creates a proxy object to validate user data before returning it. Here the fetchUserData returns the real object and userProxy is the Proxy object. Finally UserProfile component works as the client calling the proxy object.</p><p>While this example illustrates using a Proxy object for access management, it’s important to note that using Higher-Order Components (HOC), the Context API, or router guards are common and sometimes more conventional approaches in React. The choice depends on the specific requirements of your application and the desired level of access control.</p><h4><strong>Efficient Data Management</strong></h4><p>If your application involves heavy network requests that consume resources and slow down performance, caching fetched data can be a viable solution. There are lots of solutions out there for caching data in React, and using a proxy object is one of them.</p><p>In this next example, we will <strong>construct a proxy object to cache the network response</strong> and reuse the data without making additional network requests.</p><pre>import React from &#39;react&#39;;<br><br>const fetchUserData = () =&gt; {<br> // Place the network request here<br> console.log(&#39;Data fetching...&#39;);<br><br> return [<br>  {<br>   id: &#39;0001&#39;,<br>   name: &#39;John Doe&#39;,<br>   email: &#39;john@mail.com&#39;,<br>  },<br> ];<br>};<br><br>const cachedUserData = new Proxy([], {<br> get: function (target: any) {<br>  if (!target.data) {<br>   // Fetch data if it&#39;s not cached<br>   target.data = fetchUserData();<br>  } else {<br>   console.log(&#39;Returning cached data...&#39;);<br>  }<br><br>  return target.data;<br> },<br>});<br><br>export function UserList() {<br> const [state, setState] = React.useState(<br>  [] as { id: string; name: string; email: string }[]<br> );<br><br> return (<br>  &lt;div&gt;<br>   {state.map((user) =&gt; (<br>    &lt;div key={user.id}&gt;<br>     &lt;p&gt;Name: {user.name}&lt;/p&gt;<br>     &lt;p&gt;Email: {user.email}&lt;/p&gt;<br>    &lt;/div&gt;<br>   ))}<br>   &lt;button onClick={() =&gt; setState(cachedUserData.data)}&gt;Click me&lt;/button&gt;<br>  &lt;/div&gt;<br> );<br>}</pre><p>Here, the API call won’t be sent if the data is already in the object. Otherwise, it fetches the data and caches it using the proxy object. Try clicking on the “Click me” button <a href="https://bit.cloud/wulfridng/react-proxy-examples/components/data-management/user-list">here</a> and check the console to get a better idea of how the caching works here.</p><p>For a simple scenario like this, managing data states effectively and avoiding network requests in every render can mitigate performance issues in the application. Not only for a scenario like this, but Proxy data objects can also be helpful in many ways to cache data in your application.</p><p><strong>Take a look at the following code:</strong></p><pre>const createExpensiveFunction = () =&gt; {<br> // Replace this with your actual expensive function<br> const expensiveFunction = (arg) =&gt; {<br>  console.log(`Calculating expensive value for ${arg}`);<br><br>  return arg * 2;<br> };<br><br> const cache = new Map();<br><br> const handler = {<br>  apply(target, thisArg, argumentsList) {<br>   const arg = argumentsList[0];<br><br>   if (!cache.has(arg)) {<br>    cache.set(arg, expensiveFunction(arg));<br>   } else {<br>    console.log(&#39;Returning cached data...&#39;);<br>   }<br><br>   return cache.get(arg);<br>  },<br> };<br><br> return new Proxy(expensiveFunction, handler);<br>};<br><br>const memorizedFunction = createExpensiveFunction();<br><br>export const MemorizeExpensiveFunction = () =&gt; {<br> const items = [1, 2, 1, 1, 5];<br><br> return (<br>  &lt;div&gt;<br>   {items.map((item, index) =&gt; (<br>    &lt;div key={`${item}-${index}`}&gt;<br>     &lt;p&gt;Item: {item}&lt;/p&gt;<br>     &lt;p&gt;Expensive Value: {memorizedFunction(item)}&lt;/p&gt;<br>    &lt;/div&gt;<br>   ))}<br>  &lt;/div&gt;<br> );<br>};</pre><p>This example illustrates a straightforward method for caching expensive function results. The createExpensiveFunction returns the Proxy object. It checks the input arguments, and if the function is called with the same inputs again, it retrieves the cached result. Otherwise, it executes the expensiveFunction and stores the result in the cache.</p><h4>Other common use cases</h4><p>Not only these mentioned ones but there are a lot of use cases out there in using proxy design patterns that can be beneficial to your development including,</p><ul><li><strong>Abstraction and code reusability:</strong> Proxies can simplify, reduce code duplication, and enhance the reusability of the code by abstracting complex data access patterns or API interactions.</li><li><strong>Data validation and sanitization:</strong> Proxies can be used to validate user inputs before reaching the component’s logic. This can also help sanitize data, guarding against XSS attacks and enhancing overall application security.</li><li><strong>Performance monitoring and optimization:</strong> Proxies can be used to monitor performance metrics like API call durations or data access patterns, enabling developers to pinpoint and address performance bottlenecks.</li></ul><p>Take a look at this <a href="https://bit.cloud/wulfridng/react-proxy-examples"><strong>Bit Scope</strong></a> for more coding examples related to the mentioned use cases. Feel free to try, customize, and experiment with it to gain a deeper understanding of the concept.</p><h3>Concluding Thoughts</h3><p>The Proxy design pattern, coupled with JavaScript’s Proxy object, offers a powerful toolkit for enhancing React applications. From optimizing performance and securing sensitive data to efficient data management and beyond, proxies provide a versatile solution.</p><p>While we explored practical use cases, remember that the ideal solution varies based on specific application requirements. React empowers developers with flexibility, allowing them to choose the best approach.</p><p>As you explore Proxy design patterns, remember their power: streamlined code, improved security, and optimized performance for a resilient React development experience.</p><p>If you wish to explore the code we’ve implemented, <a href="https://bit.cloud/wulfridng/react-proxy-examples">explore this Bit Scope</a>.</p><p>Thank you for reading.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/react-design-patterns-for-2024-5f2696868222">Top 5 React Design Patterns That You Should Know in 2024</a></li><li><a href="https://blog.bitsrc.io/component-driven-development-and-composable-applications-a-guide-7a0934e60936">Composable Applications and Component-Driven Development: a Guide</a></li><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://blog.bitsrc.io/creating-a-developer-website-with-bit-components-3f4083a7f050">Creating a Developer Website with Bit components</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0b465980fbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/proxy-design-pattern-with-react-c0b465980fbf">Using Proxy Design Pattern with React in Practice</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Mistakes That You Should Definitely Avoid With A Monorepo]]></title>
            <link>https://medium.com/bitsrc/5-mistakes-that-you-should-avoid-with-a-monorepo-956e8fe3633e?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/956e8fe3633e</guid>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 11:02:07 GMT</pubDate>
            <atom:updated>2023-11-13T11:02:07.795Z</atom:updated>
            <content:encoded><![CDATA[<h4>Avoid These 5 Common Monorepo Mistakes: A Developer’s Guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5Ou1xsnmYyd-KwTzQ-J1Q.png" /></figure><p>Whether you’re an experienced software developer or just diving into the world of code, you’ve likely heard about the word monorepos. Monorepos have gained popularity in the software development community for good reason.</p><p>They offer a streamlined approach to managing your codebase, improving collaboration, and ensuring your projects stay on the right track. Along with their incredible advantages, they have their fair share of pitfalls.</p><p>In this developer’s guide, we will unravel the mysteries of monorepos and show you how to sidestep five common mistakes you must avoid.</p><h3>What is monorepo?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*6Toheli5vVQqhGr1.png" /></figure><p><em>(https://dev.to/stanley/monorepo-o-que-e-devo-usar-133c)</em></p><p>At its core, a monorepo is a single, unified repository that houses the entire codebase of a project or an organization. Instead of spreading code across multiple repositories, a monorepo keeps all code in one place, offering several benefits:</p><ul><li><strong>Simplified Version Control:</strong> Having a single repository can be helpful for developers to easily track changes, branches, and updates, enhancing collaboration and reducing the risk of code conflicts.</li><li><strong>Efficient Code Sharing:</strong> Monorepo enables easy code sharing across different project parts. This promotes code reusability, which can significantly speed up development and reduce duplication of effort.</li><li><strong>Streamlined Builds and Testing:</strong> Building and testing code in a monorepo is more efficient because it’s all in one place. This reduces build times and minimizes integration issues.</li></ul><p>Large-scale companies like Facebook, Google, and Airbnb have embraced monorepos in their development workflows. They rely on large monorepo systems to manage their extensive codebases and streamline development processes.</p><p>The scale and complexity of monorepos, which make them ideal for tech giants, can challenge smaller teams or less complex projects. Without proper management and workflows, a monorepo can introduce complexities, hinder collaboration, and lead to performance issues.</p><h3>What are the common monorepo mistakes that you should avoid?</h3><h4>Mistake 01: Tight coupling</h4><p>Tight coupling in a monorepo occurs when individual components or modules overly depend on one another. This creates a situation where modifications to one component have a cascading effect, requiring changes in interconnected parts.</p><p>In a monorepo system, developers may lean towards tight coupling due to the convenience of having all code in one place. While this centralization can enhance visibility and ease of access, it also increases this tight coupling, making the codebase rigid, and difficult to maintain.</p><p><strong>How to avoid tight coupling:</strong></p><p>Developers can mitigate this by following best practices and various strategies. You can find some of them down below.</p><ul><li><strong>Define Clear Interfaces:</strong> Define interfaces between components to establish a contract for their interaction. This allows components to communicate without relying on each other’s internal details.</li><li><strong>Dependency Injection:</strong> Implement dependency injection to provide components with the dependencies they need rather than allowing them to create or manage them directly. This decouples components, making them more modular and easier to update independently.</li><li><strong>Modular Architecture:</strong> Design components to be modular and self-contained. Break down complex functionalities into smaller, independent modules that can be updated or replaced without affecting other system parts.</li><li><strong>Communication Protocols:</strong> Establish well-defined communication protocols between components. Especially when working with microservices, such as using APIs or message queues. This allows components to interact in a standardized way without relying on the internal implementation details of each other.</li></ul><h4>Mistake 02: Broken Master</h4><p>The broken master is the state where the master branch is not working. This can disrupt the collaborative development flow, leading to integration conflicts and impeding progress for the entire team.</p><p>The broken master in a monorepo system is way more dangerous because this breaks all the projects in the repository. And also, it is difficult to diagnose because there is more code to analyze in the repo.</p><p>Therefore, following some best practices when working with monorepos is important to prevent this.</p><p><strong>Tips for avoiding a broken master in monorepo:</strong></p><ul><li><strong>Use a branching strategy:</strong> Employ a branching strategy with a dedicated integration branch for merging changes into the main branch. This mitigates merge conflicts and minimizes build errors.</li><li><strong>Use a continuous integration (CI) pipeline:</strong> Integrate a CI pipeline to pre-test changes before merging into the main branch. This proactive approach identifies and resolves build errors and test failures, safeguarding the stability of the main branch.</li><li><strong>Use a code review process:</strong> Enforce a thorough code review process to ensure high-quality changes before integration into the main branch. This practice identifies and rectifies potential issues before they impact the main branch.</li><li><strong>Use a monorepo tool:</strong> Implement a dedicated monorepo tool to manage dependencies and prevent conflicts. This fortifies the main branch, preventing disruptive breaks and maintaining the stability of your development environment.</li></ul><h4>Mistake 03: Not using monorepo tools</h4><p>Neglecting specialized monorepo tools limits the potential benefits of a unified repository. Large companies like <strong>Google</strong> thrive within the monorepo system due to their dedicated tools. Otherwise, managing a larger codebase at that scale could be a nightmare.</p><p>There are plenty of monorepo tools available, so why not leverage them to boost productivity? Utilizing monorepo tools comes with numerous benefits, including:</p><ul><li><strong>Enhanced dependency management:</strong> Monorepo tools streamline dependency management with automatic resolution, preventing conflicts and ensuring consistent versions across all projects.</li><li><strong>Increased build performance:</strong> Boosting build speed, monorepo tools use strategies like artifact caching and parallel builds, facilitating quicker development workflows.</li><li><strong>Automated release management:</strong> Monorepo tools automate release tasks, including version updates and deployment, reducing errors and simplifying the release process.</li><li><strong>Improved developer experience:</strong> Improving the overall developer experience, monorepo tools offer features like code completion, navigation, and dependency analysis for efficient and accurate coding.</li></ul><p><strong>Monorepo Tools</strong></p><ul><li><a href="https://lerna.js.org/"><strong>Lerna</strong></a><strong>:</strong> Manages multi-package repositories, simplifying versioning and releases.</li><li><a href="https://yarnpkg.com/"><strong>Yarn Workspaces</strong></a><strong>:</strong> Facilitates dependency management across JS/TS packages, optimizing linking and installation.</li><li><a href="https://nx.dev/"><strong>Nx</strong></a><strong>:</strong> Supports JS/TS, providing tools for building, testing, and sharing libraries.</li><li><a href="https://bazel.build/"><strong>Bazel</strong></a><strong>:</strong> General-purpose tool supporting multiple languages, designed for large-scale codebases, optimizing build and test performance.</li><li><a href="https://rushjs.io/"><strong>Rush</strong></a><strong>:</strong> Manages JS/TS multi-package repositories, aiding versioning, release management, and changelog generation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*zHsXbBK1KZbce4JO.png" /></figure><p><em>(https://bit.dev/docs/thinking-bit/#bit-in-a-monorepo)</em></p><p>These are some famous and commonly used monorepo tools out there. Having the right tools in your monorepo project can provide you with numerous advantages. Do not limit yourself to these tools; for example, you can use tools like <a href="https://bit.dev/"><strong>Bit</strong></a> to enhance your workflow in the repository.</p><p><strong>Bit</strong> is a build system for composable software. With <a href="https://bit.dev/docs/thinking-bit/#bit-in-a-monorepo">Bit integrated into your monorepo environment</a>, developers can seamlessly access a unified repository of components. This fosters collaboration and ensures consistency across projects through Bit’s <strong>composable component architecture</strong>.</p><h4><strong>Mistake 04: Unclear Project Structure</strong></h4><p>An unclear project structure hinders collaboration and makes it challenging for developers to locate and work on specific components. This can end up having many negative consequences including,</p><ul><li>Increased difficulty for developers to understand and find the code.</li><li>Difficult to code reuse, and this tends to cause code duplications.</li><li>Increased difficulty in maintaining and refactoring the code.</li><li>Reduce developer productivity.</li></ul><p>This is a common issue in monorepo if you fail to structure the code from the beginning. Complexity and difficulty in managing monorepos can end up with bad project structures.</p><p><strong>Here are some tips to build a clearer project structure:</strong></p><ul><li><strong>Use a consistent naming convention:</strong> Apply a uniform naming convention for projects, packages, and modules to improve code clarity, making it easier for developers to find code within a large codebase.</li><li><strong>Organize the code by feature:</strong> Structure your monorepo based on features rather than projects. This approach simplifies code navigation, enabling developers to locate code seamlessly.</li><li><strong>Use modules and interfaces:</strong> Decouple your code using modules and interfaces. This promotes code reusability and streamlines development by reducing dependencies.</li><li><strong>Use monorepo tools:</strong> Integrate a dedicated monorepo tool to manage the structure effectively. This tool ensures a consistent layout, minimizing the risk of common structural errors and enhancing overall project organization.</li></ul><h4><strong>Mistake 05: Overlapping Responsibilities Between Packages</strong></h4><p>In monorepo development, a common pitfall is assigning overlapping responsibilities to different packages. This occurs when multiple packages share similar functionality or features, leading to confusion, redundancy, and inefficiency.</p><p>Unlike polyrepo systems, where repositories are more isolated, the interconnected nature of packages within a monorepo can exacerbate this issue.</p><p><strong>Prevention Strategies:</strong></p><ul><li><strong>Clear definition of responsibilities:</strong> Clearly define and allocate specific responsibilities to each package, ensuring a distinct purpose for each.</li><li><strong>Regular code audits:</strong> Conduct regular code audits to identify and rectify instances of overlapping responsibilities.</li><li><strong>Documentation:</strong> Maintain comprehensive documentation outlining the purpose and scope of each package to guide developers.</li><li><strong>Communication:</strong> Foster open communication among developers to address and rectify potential overlaps in responsibilities.</li><li><strong>Automated checks:</strong> Implement automated checks or tools that analyze code dependencies to identify and flag potential overlaps.</li></ul><h3>Concluding Thoughts</h3><p>While monorepos offer powerful advantages in code management and collaboration, avoiding common pitfalls is crucial. Strategic use of monorepo tools, clear project structuring, and proactive measures against issues like tight coupling ensure a harmonious development environment.</p><p>By adopting best practices and staying vigilant, developers can harness the full potential of monorepos for streamlined workflows and efficient code sharing.</p><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/component-driven-development-and-composable-applications-a-guide-7a0934e60936">Composable Applications and Component-Driven Development: a Guide</a></li><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://blog.bitsrc.io/creating-a-developer-website-with-bit-components-3f4083a7f050">Creating a Developer Website with Bit components</a></li><li><a href="https://blog.bitsrc.io/5-tools-for-building-react-component-libraries-in-2023-d8fb8e4c13b4">5 Tools for Building React Component Libraries in 2023</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=956e8fe3633e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/5-mistakes-that-you-should-avoid-with-a-monorepo-956e8fe3633e">5 Mistakes That You Should Definitely Avoid With A Monorepo</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Ways to build composable applications]]></title>
            <link>https://medium.com/bitsrc/5-ways-to-build-composable-applications-d24b897a4424?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d24b897a4424</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[composables]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[composable-application]]></category>
            <category><![CDATA[bit]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 03:55:09 GMT</pubDate>
            <atom:updated>2023-09-12T03:55:25.940Z</atom:updated>
            <content:encoded><![CDATA[<h3>5 ways to build composable applications</h3><h4>Understand and step into composable application development</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*oGhe0xI--eOWjEib.png" /></figure><p>Imagine if creating software was like putting together a puzzle: where one piece perfectly complements the others to form a fantastic whole. That’s what composable applications are all about — making things innovative by cleverly arranging smaller parts.</p><p>At the heart of it, a composable application represents the idea of making software in a modular way. This means taking a complex application and breaking it into smaller parts that can work independently. Imagine these parts like building blocks, each doing a specific thing. But what’s really impressive is how these parts fit together smoothly.</p><h3>How Composable Applications Work?</h3><p>Composable applications serve as practical and valuable building blocks for various business processes. Their distinct components simplify traditional development, enabling efficient creation of new applications or enhancing existing ones.</p><p>These applications’ plug-and-play design empowers organizations to consolidate resources, fostering innovation and adaptability. Businesses can dismantle and modify more significant components to align with evolving needs.</p><p>Composable apps’ loosely coupled nature facilitates easy reuse and integration across multiple systems. The architecture’s well-defined APIs connect independent components, ensuring seamless accessibility through the cloud.</p><h4><strong>Benefits of Composable Applications:</strong></h4><ul><li><strong>Efficient Development:</strong> Composable applications break down complexity into reusable components, enhancing code quality and enabling parallel development for faster results.</li><li><strong>Agile Adaptation:</strong> The modular nature of composable apps allows swift assembly and reassembly to meet changing business needs, ensuring adaptability in a dynamic market.</li><li><strong>Scalable Performance:</strong> Individual component scaling optimizes resource allocation, boosting performance precisely where needed while minimizing waste.</li><li><strong>Interoperability:</strong> Standardized interfaces facilitate seamless interaction between components developed by different teams or technologies, creating a cohesive ecosystem.</li><li><strong>Rapid Innovation:</strong> Reusable components reduce development time, freeing resources for innovation and unique features that set applications apart.</li></ul><h3>Building Composable Applications</h3><p>Building composable applications involves a structured approach that maximizes the benefits of modular design and component-driven development. This approach simplifies development by focusing on individual functionalities encapsulated within components. Like building blocks, these components enable seamless integration, scalability, and adaptability.</p><h4>Composable Apps With Component-Driven Development</h4><p>Component-driven development is the philosophy behind composable applications, emphasizing the creation of modular, self-contained units of functionality known as components. These components encapsulate specific features or services, promoting reusability, maintainability, and agility in software development.</p><p>When integrated into composable applications, these components serve as building blocks that simplify the development process and facilitate collaborative work. By following these principles, composable applications achieve modularity, flexibility, and the ability to respond quickly to changes, resulting in a dynamic ecosystem of interoperable components.</p><h4><strong>Go Composable With Component-Driven Development(CDD) Platforms</strong></h4><p>Leveraging Component-Driven Development (CDD) platforms is crucial to embark on the journey of composable applications. These platforms offer a structured environment that empowers developers to effectively create, manage, and collaborate on components.</p><p>Here are some well-regarded platforms that facilitate building CDD applications:</p><ul><li><a href="https://bit.dev/">Bit</a></li><li><a href="https://www.builder.io/">Builder.io</a></li><li><a href="https://uniform.dev/">Uniform</a></li><li><a href="https://storybook.js.org/">Storybook</a></li><li><a href="https://reactcosmos.org/">React Cosmos</a></li></ul><p>In upcoming sections of this article, we will dive more into the mentioned platforms.</p><p>The capabilities of these platforms should encompass:</p><ul><li><strong>Isolated Development:</strong> Allowing developers to work on components in isolation, ensuring each component’s functionality is thoroughly tested before integration.</li><li><strong>Efficient Collaboration:</strong> Enabling teams to collaborate seamlessly, share components, and synchronize changes across projects.</li><li><strong>Versioning and Dependency Management:</strong> Supporting proper versioning and managing dependencies between components.</li><li><strong>Testing and Validation:</strong> Offering tools for testing components, ensuring their correctness and compatibility.</li><li><strong>Integration with Development Workflow:</strong> Integrating smoothly with existing development tools and workflows.</li><li><strong>Customization and Theming:</strong> Allowing customization and theming of components for consistent branding and user experience.</li><li><strong>Visual Previews:</strong> Providing visual representations of components for more precise understanding and design consistency.</li><li><strong>Documentation:</strong> Facilitating the creation of comprehensive component documentation that aids understanding and usage.</li></ul><p>Now it’s time to take a look at the capabilities of the mentioned platforms individually.</p><h3>Bit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*d2mo8nvgtR06eA4OBTtI4g.png" /></figure><p><strong>Bit</strong> and <strong>Bit Cloud</strong> provide a comprehensive solution tailored for innovative teams crafting composable software solutions. As a prominent platform championing component-driven development, it creates scalable composable applications for numerous teams, including Fortune 500 companies.</p><h4><strong>Exploring Bit</strong></h4><p><a href="https://bit.dev/"><strong>Bit.dev</strong></a> is a dynamic development platform that empowers teams to build, manage, and share composable software components. Its feature-rich environment offers an ideal foundation for crafting composable applications, focusing on efficiency and collaboration.</p><p>Bit stands out as a pivotal player in component-driven development, offering a range of tools and features that accelerate building modular and adaptable software.</p><p>It is a centralized hub where developers can create, organize, and collaborate on components, effectively transforming the development landscape. Bit’s emphasis on modularity and reusability aligns perfectly with the principles of composable applications.</p><p><strong>Key Features:</strong></p><ul><li><strong>Component Isolation and Testing:</strong> Bit enables developers to work on components in isolation, facilitating thorough testing and validation before integration. This enhances reliability and minimizes potential conflicts.</li><li><strong>Reusable Component Ecosystem:</strong> Bit encourages the creation of a reusable component ecosystem. Developers can easily share components across projects, teams, and even organizations, fostering collaboration and reducing redundant development efforts.</li><li><strong>Version Control and Dependency Management:</strong> Proper version control and dependency management are central to Bit’s capabilities. It ensures that components can be tracked, updated, and integrated without causing compatibility issues.</li><li><strong>Effortless Integration:</strong> Bit’s integration capabilities streamline the process of incorporating components into different applications. This promotes flexibility and adaptability, crucial aspects of composable applications.</li><li><strong>Enhanced Collaboration:</strong> Bit Cloud, the cloud-based extension of Bit, takes collaboration to the next level by offering a centralized component repository. This facilitates cross-team collaboration and accelerates development cycles.</li><li><strong>Scalability for Enterprises:</strong> Bit’s widespread adoption among Fortune 500 companies showcases its scalability. The platform’s ability to handle large-scale composable app development speaks to its robustness and effectiveness.</li></ul><p>Bit.dev empowers teams to build, manage, and share composable software components. This positions it as an optimal platform for crafting composable applications.</p><p><strong>Examples of Bit.dev in Action:</strong></p><ul><li><strong>Efficient Website Development:</strong> Development teams can leverage Bit.dev to curate a library of reusable components for their company’s website. This enables swift creation of new pages and features without recurring from scratch.</li><li><strong>Component Marketplace:</strong> Organizations can establish a component marketplace via Bit.dev, promoting component sharing and simplifying application building for various companies.</li><li><strong>Interactive Learning Platforms:</strong> Educational institutions can employ Bit.dev to create interactive learning platforms, educating students on diverse software components and their application in crafting innovative solutions.</li></ul><p>These instances showcase the versatility of Bit.dev in fostering the creation of composable applications. The canvas of possibilities it unfurls is boundless. (<a href="https://blog.bitsrc.io/component-driven-development-and-composable-applications-a-guide-7a0934e60936">A good read</a>).</p><h3>Builder.io</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a9xo38DHIXfTXjxu.png" /></figure><p>(https://cdn.builder.io/api/v1/image/assets%2FYJIGb4i01jvw0SRdL5Bt%2Fd9e611e767984d9ca9dc2caaab72a510?format=webp&amp;width=2000)</p><p><a href="https://www.builder.io/"><strong>Builder.io</strong></a> is the only headless CMS with a complete no-code visual editor that allows editors to drag and drop to create pages and content with your data and code components. This plays a pivotal role in driving composable applications.</p><h4><strong>Exploring Builder.io</strong></h4><p>At its core, Builder.io expedites software development with streamlined tools that facilitate efficient component management, reinforcing the core tenets of modularity and reusability.</p><p><strong>Key Attributes:</strong></p><ul><li><strong>Unleashing Component Potential:</strong> Empowering developers to autonomously craft components ensures rigorous testing and heightened reliability.</li><li><strong>Promoting Component Reusability:</strong> Builder.io promotes cooperation and reduces effort duplication by facilitating seamless component sharing across projects.</li><li><strong>Seamless Version Control:</strong> Maintain stability by flexibly managing component versions to avoid incompatibilities.</li><li><strong>Facilitating Effortless Integration:</strong> Builder.io’s ability to seamlessly integrate components makes integration simple and promotes flexibility.</li><li><strong>Collaboration Amplification:</strong> Builder Cloud acts as a nexus for cross-team collaboration, accelerating development cycles.</li><li><strong>Scalability at Core:</strong> Builder.io caters to diverse teams and even Fortune 500 companies, affirming its scalability credentials.</li></ul><p>In essence, Builder.io fuels component-driven development, ushering in applications characterized by modularity and collaborative creation.</p><h3>Uniform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*UTAwUWG3E_W6rx_I.png" /></figure><p>(https://images.ctfassets.net/9ku1oyd4k3wo/z0nLWV9FoyysfgMihErYU/5abe3c807867ef4beca83dc934e7433e/blog.jpg?w=800)</p><p><a href="https://uniform.dev/"><strong>Uniform.dev</strong></a> is a Digital Experience Composition Platform (DXCP) that empowers businesses to craft, manage, and amplify digital experiences with remarkable ease. Positioned as a composable DXCP, it liberates businesses from the constraints of a singular vendor or platform, allowing them to create experiences by leveraging various tools and services.</p><h4><strong>Exploring Uniform</strong></h4><p>To begin crafting a composable application with Uniform.dev, the initial step involves creating a Canvas workspace. Within this space, you can effortlessly connect to content sources like a Content Management System (CMS) or Digital Asset Management (DAM), setting the foundation for building your experience.</p><p>The user-friendly drag-and-drop tools empower you to seamlessly integrate various components, including text, images, videos, and forms. Concurrently, the Context tools streamline personalization and A/B testing. After crafting your experience, it can be effortlessly published across a range of channels, such as websites, mobile apps, or even digital signage systems.</p><p><strong>Key Attributes:</strong></p><ul><li><strong>Accelerated Development:</strong> Uniform.dev expedites creating and deploying digital experiences, outpacing traditional methods.</li><li><strong>Enhanced Flexibility:</strong> As a composable DXCP, Uniform.dev grants the liberty to construct experiences through a diverse toolkit, ensuring optimal tool selection for each distinct task.</li><li><strong>Seamless Scalability:</strong> Engineered to cater to businesses of varying scales, Uniform.dev effortlessly scales to meet the demands of projects both big and small.</li><li><strong>Reliable Foundation:</strong> With a seasoned team underpinning the platform, Uniform.dev emerges as a steadfast and trustworthy solution for composable applications.</li></ul><p>This transformation streamlines the content while retaining the core information about Uniform.dev’s capabilities and benefits.</p><h3>StoryBook</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KPXgTHxQMobBygjP.png" /></figure><p><a href="https://storybook.js.org/"><strong>Storybook</strong></a> is an open-source tool that aids developers in constructing, testing, and documenting UI components within isolated environments. It’s a favoured choice across teams of all scales, facilitating the creation of coherent, reusable, and sustainable user interfaces.</p><h4>Exploring StoryBook</h4><p>To craft a composable component using Storybook, begin by creating a standard component. Following this, establish a ‘story’ for the component that outlines its intended usage. This narrative should detail the accepted props of the component and the resulting output it generates.</p><p>Once your component’s story is set, it becomes a valuable resource for testing and documentation purposes. Additionally, it provides a seamless means of sharing the component with fellow developers.</p><p><strong>Key Attributes:</strong></p><ul><li><strong>Enhanced Modularity:</strong> Embracing a modular approach, Storybook encourages the construction of individual components, fostering maintainability and reusability.</li><li><strong>Streamlined Development:</strong> Storybook accelerates the creation and refinement of UI components, optimizing the development process.</li><li><strong>Seamless Integration:</strong> Storybook’s compatibility with various frameworks and libraries enables seamless integration into existing development workflows.</li><li><strong>Robust Testing and Documentation:</strong> Storybook offers a dedicated space for thorough component testing and documentation, ensuring components function as intended within isolated contexts.</li><li><strong>Collaborative Component Sharing:</strong> With Storybook, sharing components with fellow developers becomes effortless, enhancing teamwork and facilitating code reusability.</li></ul><p>For those seeking enhanced UI development, Storybook is a good choice. This potent tool not only aids in crafting composable components but also streamlines component testing and documentation, thereby elevating the quality of your user interfaces.</p><h3>React Cosmos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_bi8GbNM5HtQr02l.png" /></figure><p>React Cosmos is a React library that offers a dedicated environment for constructing, recycling, and examining UI components within their isolated environment. This facilitates an in-depth concentration on individual components, fostering accelerated iteration and the production of high-quality elements.</p><h4>Exploring React Cosmos</h4><p><a href="https://reactcosmos.org/"><strong>React Cosmos</strong></a> offers a way to separate and independently test components, acting as an environment for the development of composable systems.</p><p>These steps are involved in adopting React Cosmos for composable applications:</p><ul><li>Create a component library using React Cosmos that contains all the components required for your application.</li><li>Import these components from your library into your application.</li><li>Seamlessly compose the imported components to create the desired functionality.</li></ul><p><strong>Key Attributes:</strong></p><ul><li><strong>Scalability Empowerment:</strong> React Cosmos provides tools for building scalable applications, supporting the seamless addition of new components and modifications to existing ones.</li><li><strong>Enhanced Modularity:</strong> This excels in promoting enhanced modularity. It advocates for a modular approach, allowing developers to create smaller, reusable components that enhance maintainability and reusability.</li><li><strong>Efficient Testing:</strong> React Cosmos streamlines the testing process by isolating components for thorough individual testing. This enhances the overall efficiency of testing procedures.</li><li><strong>Structured Composition:</strong> React Cosmos encourages a structured approach to application design. It allows developers to compose smaller, reusable components into larger ones, fostering a modular application architecture.</li></ul><h3>What Should You Choose?</h3><p>Ultimately, your ideal platform choice hinges on your unique needs and criteria.</p><p>For those seeking a robust avenue for constructing, overseeing, and distributing composable software components, <strong>Bit.dev</strong> emerges as a strong contender. If your aim is a user-friendly visual builder that facilitates the creation of composable applications, <strong>Builder.io</strong> is a good selection. For those in search of a composable DXCP that fosters experience creation through an array of tools and services, <strong>Uniform.dev</strong> is a fitting solution.</p><p>Moreover, suppose your focus lies on component-driven development within an isolated environment. In that case, <strong>Storybook</strong> provides an effective platform, while <strong>React Cosmos</strong>, with its React library, facilitates the creation, testing, and development of UI components in isolation.</p><h3>Final Thoughts</h3><p>In software development, composable applications bring a new level of innovation by ingeniously arranging smaller parts to create remarkable wholes, akin to assembling a puzzle. These applications are the perfect example of modularity since they deconstruct complicated systems into easily controlled parts that work together flawlessly to provide excellent results while functioning independently.</p><p>The core principles of composable applications — efficiency, adaptability, scalability, interoperability, and rapid innovation — reshape the development landscape. The convergence of component-driven development with platforms like Bit, Builder.io, Uniform.dev, Storybook, and React Cosmos amplify this transformation, offering structured environments to craft, manage, and share components.</p><p>The selection among these platforms depends on specific requirements, yet collectively, they unveil a future where software development is a puzzle solved through ingenious arrangement and collaborative innovation.</p><h3>Build Apps with reusable components, just like Lego</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mRaDWGrQrDO3oY6Z.png" /></figure><p><a href="https://bit.cloud/"><strong>Bit</strong></a><strong>’s open-source tool </strong>help 250,000+ devs to build apps with components.</p><p>Turn any UI, feature, or page into a <strong>reusable component</strong> — and share it across your applications. It’s easier to collaborate and build faster.</p><p><strong>→ </strong><a href="https://bit.dev/"><strong>Learn more</strong></a></p><p>Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:</p><h4>→ <a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">Micro-Frontends</a></h4><h4>→ <a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">Design System</a></h4><h4>→ <a href="https://bit.cloud/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4">Code-Sharing and reuse</a></h4><h4>→ <a href="https://www.youtube.com/watch?v=5wxyDLXRho4&amp;t=2041s">Monorepo</a></h4><h3>Read more</h3><ul><li><a href="https://blog.bitsrc.io/component-driven-development-and-composable-applications-a-guide-7a0934e60936">Composable Applications and Component-Driven Development: a Guide</a></li><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://blog.bitsrc.io/creating-a-developer-website-with-bit-components-3f4083a7f050">Creating a Developer Website with Bit components</a></li><li><a href="https://blog.bitsrc.io/5-tools-for-building-react-component-libraries-in-2023-d8fb8e4c13b4">5 Tools for Building React Component Libraries in 2023</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d24b897a4424" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/5-ways-to-build-composable-applications-d24b897a4424">5 Ways to build composable applications</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline Development with Code Sharing Between Frontend and Backend]]></title>
            <link>https://javascript.plainenglish.io/streamline-development-with-code-sharing-between-frontend-and-backend-e4b0b5322b78?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4b0b5322b78</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 06:02:21 GMT</pubDate>
            <atom:updated>2024-02-06T09:44:52.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>Code Sharing Between Frontend and Backend</h3><h4>How to share code between frontend and backend</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P0KsEph8TRoJCWN4.jpg" /></figure><p>As a developer, have you ever faced challenges with code duplication, maintainability, long development times, and team collaboration? If the answer is yes, don’t worry since you’re not alone. Everyone one of us has faced these issues, and without a doubt, they are frustrating and time-consuming.</p><p>Code sharing between frontend and backend is one of the most effective ways to overcome the above issues. So, in this article, I will discuss the benefits of code sharing, the limitations, and the modern web technologies that encourage this practice to give you a better understanding.</p><h3>Can we share code across frontend and backend?</h3><p>YES! We can certainly <a href="https://blog.bitsrc.io/sharing-components-at-the-enterprise-12f9e5f1bb67">share code</a> across frontend and backend. But it’s important to consider a few things before doing so.</p><p>For example, it is essential to choose a compatible programming language between the two environments since frontend and backend have different execution contexts and capabilities. Using languages like JavaScript will make it pretty easy to write shareable code since it is used extensively on both frontend (<a href="https://blog.bitsrc.io/top-8-tools-for-angular-development-in-2023-a99d9f3a2e4e">Angular</a>, <a href="https://blog.bitsrc.io/6-best-ways-to-create-a-new-react-application-57b17e5d331a">React</a>, <a href="https://blog.bitsrc.io/getting-started-with-a-new-vue-js-project-in-2023-7ea97498ab6a">Vue.js</a>) and backend (Node.js).</p><p>Similarly, you can also try the below language/framework combinations to write sharable codes between the frontend and backend.</p><ul><li>Python — <a href="https://www.djangoproject.com/">Django</a> and <a href="https://flask.palletsprojects.com/en/2.3.x/">Flask</a> for backend, <a href="https://brython.info/">Brython</a> for frontend.</li><li>Ruby — <a href="https://rubyonrails.org/">Ruby on Rails</a> for backend, <a href="https://github.com/openhealthcare/opal">Opal</a> for frontend.</li><li>C#- <a href="https://dotnet.microsoft.com/en-us/">.NET</a> for backend, <a href="https://dotnet.microsoft.com/en-us/apps/aspnet/web-apps/blazor">Blazor</a> with WebAssembly for frontend.</li></ul><p>Apart from the programming language, you must consider factors like dependencies, security considerations, maintainability, etc.</p><blockquote><em>💡</em> If you were using the BFF pattern, that would enable you to <a href="https://bit.dev/blog/sharing-types-between-your-frontend-and-backend-applications-l5qih48g/"><strong>share types between the frontend and the backend</strong></a>, making it possible to have true typesafety between the client and the server.</blockquote><h3>What to share?</h3><p>Now that you know we can share code between backend and frontend, let’s see what we can share.</p><ul><li><strong>Models</strong>: Shared data models can help maintain consistency between the frontend and backend, reducing the risk of bugs caused by differences in data handling.</li><li><strong>Interfaces</strong>: Shared interfaces can help define the shape of data objects used by both the frontend and backend. This can help maintain consistency and reduce the risk of bugs caused by differences in data handling.</li><li><strong>Classes</strong>: Shared classes can be used to abstract away common functionality between the frontend and backend, reducing duplicated code.</li><li><strong>Constants</strong>: Constants like configuration variables or error codes can be shared between the frontend and backend, helping to keep them in sync and reducing the risk of bugs caused by differences in behaviour.</li><li><strong>Utility functions</strong>: Shared utility functions can be used to handle common tasks like data validation or formatting.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdOyFYACIugc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdOyFYACIugc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdOyFYACIugc%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/c0cb5e0ffe184d8ac8f941739ebeb2f1/href">https://medium.com/media/c0cb5e0ffe184d8ac8f941739ebeb2f1/href</a></iframe><h3>How to share code between frontend and backend</h3><p>Let’s consider a small code example to better understand how code sharing works.</p><p>The interface below defines the properties that are required for making an API call, like endpoint URL, HTTP method, and optional request body. This interface can be shared between the frontend and backend, allowing both sides to use the same data type for API calls, reducing duplication and inconsistencies.</p><pre>// Shared interface for an API call data type <br>interface ApiCall { <br>  endpoint: string; <br>  method: &#39;GET&#39; | &#39;POST&#39; | &#39;PUT&#39; | &#39;DELETE&#39;; <br>  body?: Record&lt;string, unknown&gt;; <br>}</pre><p>The React component down here shows the interface usage we’ve created above.</p><pre>import React, { useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>import { ApiCall } from &#39;./types&#39;;<br><br>const MyComponent = () =&gt; {<br>  const [result, setResult] = useState(&#39;&#39;);<br><br>  const makeApiCall = async (apiCall: ApiCall) =&gt; {<br>    const response = await axios({<br>      method: apiCall.method,<br>      url: apiCall.endpoint,<br>      data: apiCall.body,<br>    });<br><br>    setResult(response.data);<br>  };<br><br>  const handleButtonClick = () =&gt; {<br>    const apiCall: ApiCall = {<br>      endpoint: &#39;/api/my-endpoint&#39;,<br>      method: &#39;GET&#39;,<br>    };<br><br>    makeApiCall(apiCall);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleButtonClick}&gt;Make API Call&lt;/button&gt;<br>      &lt;div&gt;{result}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Simple use of the shared ApiCall interface from the backend side can be found below. In this example, we use the Request object from Express to specify that the incoming request body should match the ApiCall interface, which is the same interface that we used in our React component above.</p><pre>import express, { Request, Response } from &#39;express&#39;;<br>import { ApiCall } from &#39;./types&#39;;<br><br>const app = express();<br><br>app.get(&#39;/api/my-endpoint&#39;, (req: Request&lt;ApiCall&gt;, res: Response) =&gt; {<br>  const { method, endpoint, body } = req.body;<br><br>  // Perform some business logic using the API call data<br>  // ...<br><br>  res.send(&#39;API call successful&#39;);<br>});<br><br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Server is running on port 3000&#39;);<br>});</pre><h3>Which tools enable code sharing?</h3><p>Many modern tools and technologies encourage code sharing. Here are some of the most popular technologies and tools you can use for code sharing between frontend and backend.</p><h4>1. Bit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eV9QtMklo5uSZZrf.png" /></figure><p><a href="https://bit.dev/">Bit</a> helps developers build component-driven applications and collaborate on components independent of a Git repo or any other development setup. It allows you to design, develop and test components independently in an <a href="https://bit.dev/blog/introducing-angular-component-development-environment-lfhd699k/">integrated dev environment</a>, so you can easily share the components without needing access to the entire codebase.</p><p>You can get a better understanding of how to share codes between backend and frontend using <a href="https://youtu.be/tUGB5UKIOrY">Bit entity components</a> from the below article:</p><p><a href="https://bit.dev/blog/sharing-types-between-your-frontend-and-backend-applications-l5qih48g/">Sharing Types Between Your Frontend and Backend Applications</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5wxyDLXRho4&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5wxyDLXRho4&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2F5wxyDLXRho4%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/ab5c289d5f058965062a78d3d0cba361/href">https://medium.com/media/ab5c289d5f058965062a78d3d0cba361/href</a></iframe><h4>2. NPM packages</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k8G-Zl3rp07nie_j.png" /></figure><p><a href="https://www.npmjs.com/">NPM (Node Package Manager)</a> is the default package manager for JavaScript. It provides a vast repository of open-source libraries and packages that can be easily installed and shared across projects.</p><h4>3. Yarn Workspaces</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wTcAAsx6_S3bWsFu.png" /></figure><p><a href="https://classic.yarnpkg.com/en/">Yarn</a> is another popular package manager for JavaScript that allows you to manage multiple packages and dependencies in a single repository. 4.</p><h4>4. Lerna</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AOYE174rzepYmn4i.png" /></figure><p><a href="https://lerna.js.org/">Lerna</a> is a tool for managing JavaScript projects with multiple packages. It provides a monorepo like workspace and allows you to independently version and publish your packages.</p><h4>5. Webpack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xVp8yWkiMClNnQO5.png" /></figure><p><a href="https://webpack.js.org/">Webpack</a> is a module bundler for JavaScript that allows you to bundle your code and its dependencies into a single file. It also supports code splitting, allowing you to load only the necessary code for each page.</p><h4>6. Rust with WebAssembly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EIIFt7Ef912x9Kzq.png" /></figure><p><a href="https://www.rust-lang.org/">Rust</a> is a systems programming language that can be compiled to <a href="https://webassembly.org/">WebAssembly</a>, allowing you to write high-performance code that can run both on the frontend and backend. Tools like <a href="https://rustwasm.github.io/wasm-pack/">wasm-pack</a> can be used to manage Rust dependencies and create WebAssembly modules.</p><h3>Conclusion</h3><p>Efficiently sharing code between frontend and backend is vital for successful project development. Utilizing appropriate tools and methodologies such as TypeScript, Bit, Lerna, Yarn Workspaces, and Webpack can significantly enhance code maintainability and productivity.</p><p>Developers should also consider what to share between the frontend and backend, such as models, classes, constants, and utility functions. By sharing these elements, developers can reduce code duplication and improve consistency throughout the project.</p><p>Overall, code sharing between the frontend and backend is an essential aspect of modern web development, and with the right tools and approaches, developers can greatly improve the efficiency and quality of their projects.</p><h4>Build Apps with reusable components, just like Lego</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*noNaZEhkkro45rO7.png" /></figure><p><a href="https://bit.cloud/"><strong>Bit</strong></a><strong>’s open-source tool </strong>help 250,000+ devs to build apps with components.</p><p>Turn any UI, feature, or page into a <strong>reusable component</strong> — and share it across your applications. It’s easier to collaborate and build faster.</p><p><strong>→ </strong><a href="https://bit.dev/"><strong>Learn more</strong></a></p><p>Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:</p><h4>→ <a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">Micro-Frontends</a></h4><h4>→ <a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">Design System</a></h4><h4>→ <a href="https://bit.cloud/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4">Code-Sharing and reuse</a></h4><h4>→ <a href="https://www.youtube.com/watch?v=5wxyDLXRho4&amp;t=2041s">Monorepo</a></h4><h4>Learn more:</h4><ul><li><a href="https://blog.bitsrc.io/creating-a-developer-website-with-bit-components-3f4083a7f050">Creating a Developer Website with Bit components</a></li><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://bit.dev/blog/-extracting-and-reusing-pre-existing-components-using-bit-add-l28qlxpz/">Extracting and Reusing Pre-existing Components using bit add</a></li><li><a href="https://bit.dev/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4/">How to reuse React components across your projects</a></li><li><a href="https://bit.dev/blog/how-to-create-a-composable-react-app-with-bit-l7ejpfhc/">How to Create a Composable React App with Bit</a></li><li><a href="https://itnext.io/how-to-reuse-and-share-react-components-in-2023-a-step-by-step-guide-85642e543afa">How to Reuse and Share React Components in 2023: A Step-by-Step Guide</a></li><li><a href="https://blog.bitsrc.io/the-reusable-revolution-best-practices-for-component-development-da714c9cdaa5">The Reusable Revolution: Best Practices for Component Development</a></li><li><a href="https://blog.bitsrc.io/maximizing-code-reusability-with-bit-and-node-js-aece9eb94496">Maximizing Code Reusability with Bit and Node.js</a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> 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><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</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><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li><li><a href="https://plainenglish.io/differ"><strong>Submit content to In Plain English</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b0b5322b78" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/streamline-development-with-code-sharing-between-frontend-and-backend-e4b0b5322b78">Streamline Development with Code Sharing Between Frontend and Backend</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Node.js in Your Browser with WebContainers]]></title>
            <link>https://medium.com/bitsrc/running-node-js-in-your-browser-with-webcontainers-48ada077518e?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ada077518e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-container]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stackblitz]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 07:36:36 GMT</pubDate>
            <atom:updated>2025-03-05T11:31:28.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Run Node.js in Your Browser with WebContainers</h3><h4>How to Run Node.js in Your Browser</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9gTeWx11K86xOXjp.jpg" /></figure><p>WebContainers is a revolutionary product introduced by <a href="https://stackblitz.com/">StackBlitz</a> last year. It allows developers to create, edit, and run a secure Node.js environment in their browser tab in milliseconds. As a result, developers can now build <a href="https://bit.dev/blog/component-driven-microservices-with-nodejs-and-bit-l64shurc/">Node.js</a>, Angular, <a href="https://bit.dev/blog/how-to-create-a-composable-react-app-with-bit-l7ejpfhc/">React</a>, and Vue.js projects in their browsers entirely locally.</p><p>So, in this article, I will discuss the features of WebContainers, how they differ from other IDEs and how to get started with WebContainers.</p><figure><a href="https://bit.cloud/"><img alt="Build in AI speed — Compose enterprise-grade applications, features, and components" src="https://cdn-images-1.medium.com/max/1024/1*yX0vq3scSudyT61IuWFuEg.png" /></a><figcaption>Build in AI speed — Compose enterprise-grade applications, features, and components</figcaption></figure><h3><strong>What is a WebContainer</strong></h3><p>A WebContainer is a WebAssembly-based operating system that allows developers to spin up Node.js environments instantly. Thus, the main purpose of WebContainers is to accelerate the global shift to WebAssembly-based computing.</p><p>A WebContainer consists of several key components:</p><ul><li>Virtual File System integrated with lazy-loading</li><li>Virtual networking</li><li>Multi-thread/ multi-process application support</li><li>Inter-Process communication/process signaling</li><li>POSIX-esque shell with the ability to shell out between processes</li></ul><p>StackBlitz’s WebContainer-based IDE lets you build full-stack Node.js environments that boot in milliseconds, go online instantly, and can share the application through links with just one click. Furthermore, VS Code’s robust editing interface, a complete terminal, npm, and other development tools are preloaded into the environment. Also, it is entirely browser-based and does not depend on external remote services.</p><h3><strong>Features of WebContainers</strong></h3><h4><strong>Security</strong></h4><p>With StackBlitz’s novel compute model, code executions occur in the browser security sandbox. This provides far greater protection while producing a development environment that is quicker and less constrained than localhost.</p><p>Many development environments are operated under excessive privileges, allowing third-party dependencies to have total control over the operating system. However, WebContainers provide an extra degree of security and process separation by confining runtime environments within a browser context.</p><h4><strong>Works offline</strong></h4><p>With the help of WebContainers, you can quickly build live Node.js servers on-demand that function even while you’re offline. This is possible due to a virtualized TCP network stack mapped to your browser’s ServiceWorker API.</p><h4><strong>Better than localhost</strong></h4><p>The server responds faster than localhost and shields your web servers from localhost scraping attempts since it runs behind the browser’s security sandbox.</p><h4><strong>A clean environment on every page load</strong></h4><p>The built-in npm client for WebContainer is so quick that it does a fresh install on every page load, guaranteeing you always have a clean environment. Furthermore, you can restore your environment to its original condition by refreshing the page if something goes wrong.</p><h4><strong>Access to the local file system</strong></h4><p>PWAs can request persistent read and write access to certain local file system areas using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API">File System Access API</a>. Combined with StackBlitz WebContainers, there can be a future where you do not need to install node, npm, git, Visual Studio Code, or any other software on your computer. Instead, all you need is a web browser.</p><h4><strong>Seamless Node.js debugging with Chrome DevTools</strong></h4><p>Debugging JavaScript is relatively easy using browsers. The connection with Chrome DevTools operates right out of the box by running Node.js within the browser. No downloads or plugins are required, only native back-end debugging within the browser.</p><h3><strong>How does WebContainer-based StackBlitz IDE differ from other online IDEs?</strong></h3><p>With traditional IDEs, your complete development environment runs on a distant server, which feeds the results to your browser via the internet. The issue with this approach is that it offers a few security advantages and mostly delivers a worse user experience than using your local computer.</p><p>WebContainers are entirely browser-based and do not depend on external remote services. Hence, the browser’s security sandbox provides far greater protection than traditional IDEs.</p><p>Also, typical online IDEs take a long time to spin up containers. As a result, they are not offline-capable and frequently cause network timeouts. Also, it is very difficult to troubleshoot frozen or broken containers. Clicking the refresh button only reconnects you to the broken container once again.</p><h3><strong>Setup Your First WebContainer-based StackBlitz Project</strong></h3><p>WebContainers and EngineBlock are the two types of environments used by StackBlitz to execute applications. One or the other is connected to each project in StackBlitz.</p><p>WebContainers can execute module bundlers like Webpack or Vite since they are focused on providing a native Node.js environment. Therefore, any front-end framework can be used with one of these tools, like working in a local environment. In addition, WebContainers, also support several back-end frameworks.</p><p>You can quickly start a new WebContainer-based StackBlitz project by picking their starter project or importing a project from GitHub or your local computer.</p><h4><strong>1. Picking a Starter Project</strong></h4><p>Starter projects are virtual playgrounds often created by the project’s core staff and run on StackBlitz. You can find a list of starter projects on the StackBlitz homepage. They have introduced around 60 starter projects with different technologies, such as Angular, React, Next.js, Vue 3, Express, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d7UtTX9S8nRw2Wlh.png" /></figure><p>You can also start an open-source starter project by simply visiting the dedicated URL with the “.new” domain for that selected project. <a href="https://developer.stackblitz.com/guides/user-guide/starter-projects#new-domains"><em>Check the URL list</em></a>.</p><h4><strong>2. Importing a project from the local computer</strong></h4><p>Open the StackBlitz project you want, then drag &amp; drop any files or folders you wish to import. It’s as simple as that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5rE1dg3MJc3T3str.gif" /></figure><h4><strong>3. Importing a public project from GitHub</strong></h4><p>By adding the username and repository name to the URL, as shown below, you can use StackBlitz to execute any public GitHub repository.</p><pre>stackblitz.com/github/{GH_USERNAME}/{REPO_NAME}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O-xSnv5c4UoazoR6.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zY2GiBhLBG1SMB13.png" /></figure><p>You can specify the branch, tag, or commit when importing the GitHub repository.</p><pre>.../github/{GH_USERNAME}/{REPO_NAME}/tree/{TAG|BRANCH|COMMIT}</pre><p>The related StackBlitz project automatically updates with the most recent changes whenever you post commits to GitHub, ensuring that the code in your GitHub repository continues to be the official source.</p><p>In addition, you can set up a launch command for your project while you import the project to StackBlitz. It will allow your project to execute the code once the editor launches automatically.</p><pre>stackblitz.com/fork/github/{gh_username}/{repo_name}?terminal={npm_script_name}</pre><h3><strong>WebContainers limitations</strong></h3><h4><strong>HTTP Networking</strong></h4><p>The ability of WebContainers to connect to databases like MongoDB, Redis, and PostgreSQL is currently restricted by the browser’s capacity to perform network requests. However, this might soon change since Native Sockets will quickly be shipped by Chromium.</p><p>It can support additional HTTP-based protocols like WebSockets but is currently only able to handle HTTP connections. Also, it is necessary to allow CORS or a CORS proxy when making HTTP queries to external services.</p><h4><strong>NPM postinstall Scripts and Native Binaries</strong></h4><p>While many postinstall scripts are safe to use; the majority are used to configure or compile native binaries and are frequently executed in privileged root contexts, providing arbitrary code access to the whole system. The WebContainers will not support this behavior because they are secure by default.</p><h4><strong>Browser Support</strong></h4><p>WebContainers is in its Alpha stage and only supports Firefox and Chromium-based browsers. In most cases, supported browsers work well with WebContainers. But specific browsers have built-in content limitations, such as preventing third-party cookies and Service Workers, which can stop StackBlitz WebContainers from functioning as expected.</p><h3><strong>Conclusion</strong></h3><p>Compared with other online IDEs, StackBlitz’s WebContainers-based IDE has far more advanced capabilities. However, with speed, security, usability, and other features like clean environment loading, and offline functioning, WebContainers win the battle.</p><p>The fact that WebContainers is free to use for open-source projects but requires a membership if you want to use it for private repositories is a drawback. Nevertheless, WebContainers is still a SaaS product, even though it runs great locally. That’s the only significant disadvantage we can notice in WebContainers.</p><p>Overall, if you are a full-stack developer, StackBlitz’s WebContainer is an excellent fit for your project tests and developments.</p><h3>Build apps with reusable components like Lego</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*6J5W3PNx9VMh0nYv.png" /></figure><p><a href="https://bit.cloud/"><strong>Bit</strong></a><strong>’s open-source tool </strong>help 250,000+ devs to build apps with components.</p><p>Turn any UI, feature, or page into a <strong>reusable component</strong> — and share it across your applications. It’s easier to collaborate and build faster.</p><p><strong>→ </strong><a href="https://bit.dev/"><strong>Learn more</strong></a></p><p>Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:</p><h4>→ <a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">Micro-Frontends</a></h4><h4>→ <a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">Design System</a></h4><h4>→ <a href="https://bit.cloud/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4">Code-Sharing and reuse</a></h4><h4>→ <a href="https://www.youtube.com/watch?v=5wxyDLXRho4&amp;t=2041s">Monorepo</a></h4><ul><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://bit.cloud/blog/how-to-reuse-react-components-across-your-projects-l3bhezsg">How to reuse React components across your projects</a></li><li><a href="https://blog.bitsrc.io/5-ways-to-build-a-react-monorepo-a294b6c5b0ac">5 Ways to Build a React Monorepo</a></li><li><a href="https://bit.cloud/blog/how-to-create-a-composable-react-app-with-bit-l7ejpfhc">How to Create a Composable React App with Bit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ada077518e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/running-node-js-in-your-browser-with-webcontainers-48ada077518e">Running Node.js in Your Browser with WebContainers</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Smart Contracts on Blockchain?]]></title>
            <link>https://medium.com/@danushanavod/what-are-smart-contracts-on-blockchain-ff255e135085?source=rss-35f81e9c9f0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff255e135085</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Danusha Navod]]></dc:creator>
            <pubDate>Thu, 02 Sep 2021 19:03:12 GMT</pubDate>
            <atom:updated>2021-09-02T19:03:12.770Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction into Blockchain Smart Contracts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSDdfqc5jaleNz418Fx2LA.png" /></figure><p>Have you ever heard of Smart Contracts or ever had an interest in them? Great, you are in the right place. Today I’m going to cover <strong>how these smart contracts work, the use cases, the benefits, risks, and are they really smart</strong>.</p><h4>First of all to all who don’t have an idea about, “what is this Blockchain?”,</h4><blockquote>Blockchain is an immutable, shared ledger that usually use in business to record transactions and track assets. Most of the <strong>cryptocurrencies </strong>are also based on a blockchain and these smart contracts are stored on these <a href="https://en.wikipedia.org/wiki/Blockchain">blockchains</a>.</blockquote><h3>How Smart Contracts works?</h3><p>Smart Contract is a simple program that stores on a blockchain and runs when the predetermined conditions are met and verified. These are typically used to execute an agreement between two or more parties. Smart contracts can receive, store, and send funds and trigger the next action when conditions are met. Nowadays, Smart Contracts are used in<strong> supply chains</strong>, <strong>government voting systems</strong>, <strong>healthcare</strong>, <strong>financial services, </strong>and <strong>much more</strong>.</p><p>All smart contracts are immutable. That means, when smart contracts are deployed, they cannot be modified again. These Smart Contracts are worked by a simple program following “if, when, then” statements written on the blockchain. When the transaction is complete, it automatically updates on the blockchain. That means the transaction cannot be reversed because blockchains are cannot reverse to the previous state. Only parties involved in the transaction have been granted permission to see the transaction results.</p><p>The biggest blockchain which supports smart contracts is <strong>Ethereum</strong>. In Ethereum, Smarts Contracts are written using a Turing complete programming language called <strong>Solidity</strong>. Also, <strong>Polkadot</strong>, <strong>Hyperledger</strong>, <strong>Tezos</strong>, <strong>Stellar</strong>, <strong>Solana</strong> blockchains are support smart contracts, but they all have different characteristics.</p><h4>Let’s look at a simple example:</h4><p>Imagine that Alice wants to give a book to Bob. And in return, Bob needs to give another book to Alice. Also, they want to exchange those books before noon. But they both can’t trust each other. Therefore both of them invite Philipe as a middleman.</p><ul><li><strong>So traditionally</strong>, Bob and Alice give their books to Philipe before noon, and then he exchanges those books among them. But what would happen if Philipe keeps those books without exchanging? Or if he lost those books in the period of transition? or if he delays the exchange?</li><li><strong>And how would it be if Philipe acts as a Smart Contract? </strong>Then, the complete process would be a computer program. Until the conditions are met, the books exchange won’t happen. If Alice isn’t able to give the book to Philip before noon or if Bob can’t give the book to Philipe before noon, the operation would cancel. And everything will turn back to the same as they were.</li></ul><blockquote>Smart Contracts were firstly proposed by an American computer scientist, Nick Szabo in 1994. His idea was to create self-executing contracts with the help of cryptography, digital signatures, and secure computation.</blockquote><h3>Use cases of Smart Contracts</h3><h4><strong>1) Supply Chains</strong></h4><p>If we consider a large-scale computer manufacturing company, they have built on a complex web of relationships worldwide. This worldwide provides materials, manufactures the components, assembles the computers, delivers to the market, and this complex process is called the supply chain. Because of the complexity of the process, large manufacturing companies occur difficulties when tracking the supply chain.</p><p>Smart Contracts could manage this supply chain simpler and more transparently. The idea behind smart contracts in the supply chain is to create a source of all information in a single global ledger. Each component would have its own entry on the blockchain, and it can get tracked all of the time. Authorized companies could update the components in real-time. In the end, the company can track all the components at any time, and the decrease of the laborious process would automatically decrease the risks of fraud and loss.</p><h4>2) Healthcare</h4><p>Smart Contracts can be used in many cases in the healthcare sector, such as health insurance, manage patient’s health records, telemedicine, verifying medical staff credentials, and much more. Let’s look into a few of them.</p><p><strong>Health Insurance </strong>companies can use Smart Contracts to reduce many inefficiencies in the current system. For example, if anyone uses smart contracts to buy their insurance, all policy details will automatically be stored on the blockchain. And it could reduce the use of lengthy file insurance claim forms. Because if the insuree goes through a medical procedure covered by the insurance policy, the smart contract would be automatically triggered. And that means the money will automatically transfer from the insurance company’s account to the hospital&#39;s account without delays.</p><p>Smart Contracts can also be used to store the <strong>Health Records</strong> of patients on a digital ledger. So if a patient moves from a hospital to another, they would easily read patients&#39; records. Hospitals and healthcare companies use several databases filled with patient information. Then using Smart Contract and blockchain, everything can be stored in the same place with higher security.</p><h4>3) Financial Services</h4><p>Smart Contracts can use widely in Financial Services. For example, this can be used in banking services to <strong>ensure the money flow</strong> between parties seamlessly. And also, in the traditional way, the transaction settlement and clearance process of securities markets is really inefficient. But <strong>improving the security</strong>, smart contracts can reduce the settlement timeline to a few minutes.</p><p>And all Banking services require <strong>KYC, customer identity verification process</strong>. It is an essential step in all financial activities. However, traditionally, obtaining customer credit histories is tedious and costly. But it is a mandatory step to avoid financial fraud. Therefore, blockchain-based smart contracts can be used here to verify credit records of individuals and very their identities stored in a blockchain.</p><p>Not only these, in financial services, smart contracts can also use to <strong>reduce transaction costs</strong>, <strong>do audits</strong>, <strong>increase speed</strong>, and <strong>much more</strong>.</p><h3>Benefits of Smart Contracts</h3><ul><li><strong>Accuracy —</strong> One of the most important benefits of the smart contract is accuracy. Because the smart contract is a computer program, there won’t be any human errors, but we can’t forget “bugs” in the program. Let’s talk about that later.</li><li><strong>Transparency — </strong>The terms and conditions of these smart contracts are fully visible and accessible to relevant parties. And also, anyone cannot modify the contract after it executes on the blockchain. Therefore, this facilitates the transparency of all the transactions.</li><li><strong>Speed —</strong>Smart Contracts work without involving any documents, and also, it is a computer program that runs live on the internet. Therefore, transactions can be executed very quickly when using these.</li><li><strong>Security —</strong>Automated smart contracts use the highest level of data encryptions as modern crypto-currencies use, rather than traditional data stored in papers and hard drives. This level of protection makes them one of the most secure things on the world wide web.</li><li><strong>Efficiency —</strong>The nature of smart contracts makes them much efficient because of their higher accuracy and speed. Higher efficiency results in the execution of more transactions per unit of time.</li><li><strong>Low cost —</strong> Another of the main benefits is that it reduces the cost by eliminating the need for a vast chain of middlemen such as lawyers, witnesses, and banks.</li></ul><h3>Risks of Smart Contracts</h3><ul><li><strong>Bugs — DAO Hack</strong> is an example of a smart contract bug. As a result, it lost millions of dollars worth ether. Etherium community come up with very strict security measures after the incident, and now pretty much all popular smart contracts have gone through a security audit. You can find out more details about DAO Hack from <a href="https://www.gemini.com/cryptopedia/the-dao-hack-makerdao">here</a>.</li><li><strong>Protocol Changes —</strong> We still cannot guarantee that changes in the platform level will not cost any problems.</li></ul><p>Not only these but there are also other risks involved in things like <strong>real-world issues</strong>, <strong>regulations</strong>, and <strong>taxes</strong>. But they believe that most of these will eventually solve.</p><h3>Conclusion</h3><p>We are still in a very early stage of smart contracts. The possible use cases of smart contracts are getting discovered day by day. And most of the problems regarding smart contracts would solve eventually. Smart contracts won’t replace lawyers soon, but it has very bright future.</p><p><strong>Thank you for reading!!</strong></p><h3>Learn More</h3><ul><li><a href="https://enlear.academy/infrastructure-as-code-with-aws-cognito-federated-identity-and-serverless-edf33b347657">Infrastructure as Code with AWS Cognito, Federated Identity, and Serverless</a></li><li><a href="https://enlear.academy/how-to-build-a-voice-assistant-with-react-and-alan-ai-e4df0bc93c44">How to Build a Voice Assistant with React and Alan AI</a></li><li><a href="https://enlear.academy/open-source-licenses-explained-5641e5a0767a">Different Types of Open Source Licenses</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff255e135085" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>