<?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 Majed Bannouri on Medium]]></title>
        <description><![CDATA[Stories by Majed Bannouri on Medium]]></description>
        <link>https://medium.com/@majed.bannouri12?source=rss-83e66847f193------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fjcslO_FmIM7gtLjG8yGTg.png</url>
            <title>Stories by Majed Bannouri on Medium</title>
            <link>https://medium.com/@majed.bannouri12?source=rss-83e66847f193------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 09:49:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@majed.bannouri12/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[Web Performance Mastery: Using Device Insights and Speculation Rules to Delight Users]]></title>
            <link>https://medium.com/@majed.bannouri12/web-performance-mastery-using-device-insights-and-speculation-rules-to-delight-users-3e871d2f8016?source=rss-83e66847f193------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e871d2f8016</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Majed Bannouri]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 17:46:43 GMT</pubDate>
            <atom:updated>2025-12-17T17:46:43.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction: Why Web Performance Always Matters</h3><p>Imagine walking into a coffee shop and waiting 10 minutes for a simple cup of coffee. Frustrating, right? The same goes for websites and apps — users expect fast, smooth experiences, or they’ll simply walk away.</p><p>Web performance is all about making your site load quickly, look stable, and respond instantly. It affects everything from user satisfaction and engagement to SEO rankings and business revenue. As the web grows more complex and users access it on a huge variety of devices and network conditions, performance optimization becomes both a challenge and a necessity.</p><p>In this article, we’ll explore essential web performance metrics, how to measure them, how your user’s environment impacts experience, and smart ways to adapt your site dynamically to deliver the best possible experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*jUpFbl8T3IpE0TYzQZ6kUA.png" /></figure><h3>2. Key Performance Metrics: Understanding What Really Matters</h3><p>To improve performance, first you have to measure it. Google’s Web Vitals initiative highlights three core metrics that capture the essence of user experience:</p><h4>2.1. Largest Contentful Paint (LCP)</h4><p><strong>What is LCP?</strong><br> Think of LCP as the moment when the main part of the page — the headline, hero image, or a big block of text — finishes loading and becomes visible. If your page is a restaurant, LCP is like the waiter bringing your main course to the table.</p><p><strong>Why is it important?</strong><br> Users want to see meaningful content fast. If this takes more than 2.5 seconds, many get impatient.</p><p><strong>How to test LCP?</strong><br> Open Chrome DevTools → Performance tab → Record a page load → Look for “Largest Contentful Paint” markers. Alternatively, use the Web Vitals extension or Lighthouse reports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*0fhvIOAkMSFNKQ7-_3NKZQ.png" /></figure><h4>2.2. Cumulative Layout Shift (CLS)</h4><p><strong>What is CLS?</strong><br> Imagine reading a book and suddenly the page you’re reading shifts, making you lose your place. CLS measures how much unexpected visual shifting happens during page load.</p><p><strong>Why is it important?</strong><br> Unexpected movement is annoying and can cause accidental clicks. Keeping CLS below 0.1 means your page feels stable.</p><p><strong>How to test CLS?</strong><br> Use Chrome DevTools → Performance tab or Lighthouse. CLS events are shown as layout shifts with scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*FJe2vFet1tQe73jCwq8_SA.png" /></figure><h4>2.3. Interaction to Next Paint (INP)</h4><p><strong>What is INP?</strong><br> INP measures how quickly your page responds to user interactions, like clicks or key presses. It’s like how fast the barista responds after you place your order.</p><p><strong>Why is it important?</strong><br> Responsiveness directly impacts usability. Delays make sites feel sluggish.</p><p><strong>How to test INP?</strong><br> Currently experimental, INP can be measured with Web Vitals tools or via custom scripts using the PerformanceObserver API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*WY4YSUS3wZKjs1aGGyjL3w.png" /></figure><h3>3. Environment Settings: Testing Device memory, Connection and CPU</h3><p>Just like a chef adapts cooking based on available kitchen tools and ingredients, websites can adapt based on the user’s device memory, CPU cores, and network speed. Let’s see how to detect those.</p><h4>3.1. Detecting Device Memory</h4><pre>const deviceMemory = navigator.deviceMemory || &#39;unknown&#39;;<br>console.log(`Device Memory: ${deviceMemory} GB`);</pre><p><strong>Why it matters:</strong><br> On devices with less memory, heavy animations or large images can cause slowdowns or crashes. Knowing this helps you serve lighter versions.</p><h4>3.2. Detecting CPU Cores</h4><pre>const cores = navigator.hardwareConcurrency || 1;<br>console.log(`CPU Cores: ${cores}`);</pre><p><strong>Why it matters:</strong><br> More cores mean the device can handle more simultaneous tasks. On low-core devices, it’s better to limit complex background processes or animations.</p><h4>3.3. Detecting Network Connection</h4><pre>const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;<br>if (connection) {<br>  console.log(`Effective connection type: ${connection.effectiveType}`);<br>  console.log(`Downlink speed: ${connection.downlink} Mbps`);<br>  console.log(`RTT: ${connection.rtt} ms`);<br>}</pre><p><strong>Why it matters:</strong><br> A fast 4G connection can handle high-res images; a slow 2G connection can’t. By detecting connection quality, you can throttle data usage and improve perceived performance.</p><h4>3.4. Example: Using React-Adaptive-Hooks to Adapt Your App</h4><p>The react-adaptive-hooks library provides React hooks that simplify detecting device and network info so you can adapt your UI accordingly.</p><h4>Adapting to Network Conditions</h4><pre>import { useConnection } from &#39;react-adaptive-hooks/network&#39;;<br>function AdaptiveImage() {<br>  const connection = useConnection();<br>  if (connection.effectiveType === &#39;4g&#39;) {<br>    return &lt;img src=&quot;high-res.jpg&quot; alt=&quot;High quality&quot; /&gt;;<br>  } else {<br>    return &lt;img src=&quot;low-res.jpg&quot; alt=&quot;Low quality&quot; /&gt;;<br>  }<br>}</pre><h4>Adapting to Device Memory</h4><pre>import { useDeviceMemory } from &#39;react-adaptive-hooks/device-memory&#39;;<br>function MemoryAwareComponent() {<br>  const memory = useDeviceMemory();<br>return (<br>    &lt;div&gt;<br>      {memory &gt;= 8 ? &lt;HeavyFeature /&gt; : &lt;LightFeature /&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Adapting to CPU Cores</h4><pre>import { useHardwareConcurrency } from &#39;react-adaptive-hooks/hardware-concurrency&#39;;<br>function CPUAwareAnimation() {<br>  const cores = useHardwareConcurrency();<br>  return cores &gt; 4 ? &lt;ComplexAnimation /&gt; : &lt;SimpleAnimation /&gt;;<br>}</pre><h3>4. Speculation Rules: How and When They Help</h3><p>Speculation rules allow browsers to <strong>proactively fetch or prerender resources</strong> based on predicted user behavior, improving perceived performance by getting assets ready before they’re actually requested.</p><p>Think of it like a smart waiter who anticipates you’ll order your favorite dish and starts preparing it early, so it arrives faster.</p><h3>How to Check Speculation Rules in Chrome DevTools</h3><p>You can inspect how speculation rules affect your page by using Chrome DevTools:</p><ol><li>Open Chrome DevTools</li><li>Go to the <strong>Application</strong> tab.</li><li>On the left sidebar, under <strong>Cache Storage</strong> or <strong>Speculation Rules</strong> (if available), you can see details about active speculation rules.</li><li>You can also monitor <strong>prerendered pages</strong> or preloaded resources here.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*XFfEuojimY2rYzZXGgua2w.png" /></figure><blockquote>Note that native speculation rules support is experimental and available only in some Chrome versions, so this info might not always appear.</blockquote><h4>4.1. Native Speculation Rules with &lt;script type=&quot;speculationrules&quot;&gt;</h4><p>Modern browsers are starting to support native speculation rules via a special script tag:</p><pre>if (HTMLScriptElement.supports?.(&#39;speculationrules&#39;)) {<br>  const specScript = document.createElement(&#39;script&#39;);<br>  specScript.type = &#39;speculationrules&#39;;<br>const SpecRules = {<br>    prerender: [<br>      {<br>        source: &#39;document&#39;,<br>        where: {<br>          and: [{ href_matches: &#39;/vacatures/*&#39; }],<br>        },<br>        eagerness: &#39;moderate&#39;,<br>      },<br>    ],<br>  };<br>specScript.textContent = JSON.stringify(SpecRules);<br>  document.body.append(specScript);<br>}</pre><h4>4.2. Explanation</h4><ul><li><strong>Feature detection:</strong> We first check if the browser supports speculation rules using HTMLScriptElement.supports(&#39;speculationrules&#39;).</li><li><strong>Create the script:</strong> A new &lt;script&gt; element with type speculationrules is created.</li><li><strong>Define rules:</strong></li><li>prerender tells the browser to prerender matching pages ahead of time.</li><li>The rule here says: when the current document’s URL matches /vacatures/* (a hypothetical job vacancies section), prerender those pages with <strong>moderate eagerness</strong> — meaning the browser will load them carefully, balancing speed and resource use.</li><li><strong>Attach to document:</strong> The script with these rules is appended to the body, activating the speculation behavior.</li></ul><h4>4.3. Why This Helps</h4><p>By prerendering pages you expect the user to visit next (based on URL patterns or user actions), you drastically reduce wait times when they actually navigate there. This leads to a smoother experience and better Core Web Vitals like LCP.</p><p><strong>Note:</strong> Speculation rules are an evolving web platform feature and may not be supported in all browsers yet. Always include feature detection as shown.</p><h3>5. Conclusion: Build Smarter, Faster Web Experiences</h3><p>Web performance isn’t just about raw speed — it’s about adapting intelligently to the unique environment of each user. Measuring key metrics like LCP, CLS, and INP helps you understand the quality of the experience, while detecting device memory, CPU cores, and network status lets you tailor your app’s behavior.</p><p>Tools like react-adaptive-hooks make it easier than ever to build responsive, adaptive React apps that delight users everywhere—from high-end desktops to constrained mobile networks.</p><p>Start measuring, detecting, and speculating today. Your users — and your business — will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e871d2f8016" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Why SOLID Principles Still Matter]]></title>
            <link>https://medium.com/@majed.bannouri12/why-solid-principles-still-matter-3509803c3fd1?source=rss-83e66847f193------2</link>
            <guid isPermaLink="false">https://medium.com/p/3509803c3fd1</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Majed Bannouri]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 07:46:16 GMT</pubDate>
            <atom:updated>2025-10-11T07:46:49.738Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧩 The World Before SOLID</h3><p>Imagine walking into a kitchen where the chef also repairs the oven, takes customer orders, handles the cash register, and occasionally paints the walls.<br> You might still get your meal — but chaos is guaranteed.</p><p>Early software systems were like that.<br> Classes managed everything: business logic, database access, even UI.<br> It worked… until it didn’t.</p><blockquote><em>💭 </em>“We needed a way to make code grow gracefully — not collapse under its own weight.”</blockquote><p>That’s when a few brilliant minds stepped in — and <strong>SOLID</strong> was born.</p><h3>👨‍🏫 The Origins of SOLID</h3><p>The <strong>SOLID principles</strong> were introduced by <strong>Robert C. Martin</strong> (<em>Uncle Bob</em>) in the early 2000s.<br> He built upon earlier ideas from pioneers like Barbara Liskov and Bertrand Meyer, packaging them into a simple acronym that changed how we design software forever.</p><blockquote><em>🧠 SOLID became a design compass — helping developers write </em><strong><em>clean, maintainable, and scalable</em></strong><em> code.</em></blockquote><p>And yes, even today — in the era of <strong>microservices, REST APIs, and Spring Boot</strong> — these principles still hold their ground.</p><h3>🔠 What Does SOLID Stand For?</h3><blockquote><strong><em>S</em></strong><em> — Single Responsibility Principle<br> </em><strong><em>O</em></strong><em> — Open/Closed Principle<br> </em><strong><em>L</em></strong><em> — Liskov Substitution Principle<br> </em><strong><em>I</em></strong><em> — Interface Segregation Principle<br> </em><strong><em>D</em></strong><em> — Dependency Inversion Principle</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*tDFzcv6KwVbmXlaI2hBXVg.png" /></figure><p>Each principle solves one of the timeless problems of software:<br> <strong>rigidity, fragility, and untestable complexity.</strong></p><p>Let’s unpack them — with real-life analogies and examples.</p><h3>⚙️ 1. Single Responsibility Principle (SRP)</h3><blockquote>“A class should have only one reason to change.”</blockquote><p>🧍‍♀️ <strong>Analogy:</strong><br> Think of your smartphone. The camera takes photos, the calculator does math, and the calendar manages events.<br> If your camera started calculating your grocery budget, you’d be confused — and the app would be a mess.</p><p>💻 <strong>Code Example (Bad)</strong></p><pre>public class InvoiceService {<br>    public void calculateTotal() { /* ... */ }<br>    public void printInvoice() { /* ... */ }<br>    public void saveToDatabase() { /* ... */ }<br>}</pre><p>💡 <strong>Refactored (Good)</strong></p><pre>public class InvoiceCalculator { /* ... */ }<br>public class InvoicePrinter { /* ... */ }<br>public class InvoiceRepository { /* ... */ }</pre><p>Each class now has a <em>single responsibility</em> — clear, focused, and testable.</p><h3>🧩 2. Open/Closed Principle (OCP)</h3><blockquote>“Software entities should be open for extension, but closed for modification.”</blockquote><p>📱 <strong>Analogy:</strong><br> Your smartphone OS doesn’t change every time you install a new app — it’s closed for modification, yet open for extension.</p><p>💻 <strong>Example (Strategy Pattern)</strong></p><pre>public interface Discount {<br>    double apply(double price);<br>}<br><br>public class BlackFridayDiscount implements Discount {<br>    public double apply(double price) { return price * 0.5; }<br>}</pre><p>Now you can add new discount types without editing existing code.<br> That’s OCP — evolve without breaking.</p><h3>🧬 3. Liskov Substitution Principle (LSP)</h3><blockquote>“Subtypes must be substitutable for their base types.”</blockquote><p>🚗 <strong>Analogy:</strong><br> If you rent a car, you expect to drive it — not push it.<br> Whether it’s a Tesla or a Toyota, you shouldn’t need to change how you drive.</p><p>💻 <strong>Violation Example</strong></p><pre>class Bird {<br>    void fly() {}<br>}<br><br>class Penguin extends Bird {<br>    void fly() { throw new UnsupportedOperationException(&quot;Can&#39;t fly!&quot;); }<br>}</pre><p>🐧 <strong>Fix:</strong></p><pre>interface Bird {}<br>interface FlyingBird extends Bird { void fly(); }</pre><p>Now Penguin and Eagle both behave correctly — no surprises.</p><h3>🧠 4. Interface Segregation Principle (ISP)</h3><blockquote>“Clients should not be forced to depend on interfaces they do not use.”</blockquote><p>👨‍🍳 <strong>Analogy:</strong><br> A chef cooks, a waiter serves, a cleaner cleans — and you don’t ask all of them to fly a plane.</p><p>💻 <strong>Violation</strong></p><pre>public interface Worker {<br>    void cook();<br>    void clean();<br>    void serve();<br>}<br>public class Chef implements Worker {<br>    public void cook() {}<br>    public void clean() {} // not my job<br>    public void serve() {} // not my job<br>}</pre><p>✅ <strong>Fix</strong></p><pre>public interface Chef { void cook(); }<br>public interface Waiter { void serve(); }</pre><p>Each role (or class) focuses on what it actually does.</p><h3>🔌 5. Dependency Inversion Principle (DIP)</h3><blockquote>“High-level modules should not depend on low-level modules. Both should depend on abstractions.”</blockquote><p>🔌 <strong>Analogy:</strong><br> You don’t design your house to use only one brand of sockets — you depend on <strong>a standard plug interface</strong>.</p><p>💻 <strong>Example</strong></p><pre>public interface NotificationService {<br>    void send(String message);<br>}<br><br>public class EmailService implements NotificationService {<br>    public void send(String message) { /* send email */ }<br>}<br>public class AlertManager {<br>    private final NotificationService service;<br>    public AlertManager(NotificationService service) {<br>        this.service = service;<br>    }<br>}</pre><p>AlertManager doesn’t care if the service is Email, SMS, or Push — it just depends on the <strong>abstraction</strong>.</p><h3>🚀 Applying SOLID in a Spring Boot Project</h3><p>Now let’s make this modern.</p><p>Suppose you’re building a <strong>notification system</strong> in a Spring Boot app.</p><p>Here’s how SOLID naturally fits in 👇</p><p>💻 <strong>Example: SOLID in Spring Boot</strong></p><pre>// D — Dependency Inversion<br>public interface NotificationService {<br>    void send(String message);<br>}<br>// O — Open for Extension<br>@Service<br>public class EmailNotificationService implements NotificationService {<br>    @Override<br>    public void send(String message) {<br>        System.out.println(&quot;Sending email: &quot; + message);<br>    }<br>}<br><br>@Service<br>public class SmsNotificationService implements NotificationService {<br>    @Override<br>    public void send(String message) {<br>        System.out.println(&quot;Sending SMS: &quot; + message);<br>    }<br>}<br><br>// S — Single Responsibility<br>@Service<br>public class NotificationManager {<br>    private final NotificationService notificationService;<br>@Autowired<br>    public NotificationManager(NotificationService notificationService) {<br>        this.notificationService = notificationService;<br>    }<br>    public void notifyUser(String message) {<br>        notificationService.send(message);<br>    }<br>}</pre><p>With Spring’s dependency injection, you can easily swap implementations — <strong>no code modification</strong>, just configuration.</p><p>If tomorrow you add a PushNotificationService, your core logic stays untouched.<br> That’s <strong>SOLID in the real world</strong>.</p><h3>🔍 How to Know If You’re Writing SOLID Code</h3><p>Ask yourself:</p><ul><li>🔹 Can I add new features without touching existing code?</li><li>🔹 Can I test each component independently?</li><li>🔹 Are my classes small and cohesive?</li><li>🔹 Does a change in one module break others?</li></ul><p>If the answers are <em>yes, yes, yes, and no</em> — congratulations 🎉 you’re writing SOLID code.</p><blockquote><em>🧭 </em>Tools like SonarQube can even help detect violations of SRP, excessive coupling, or poor cohesion automatically.</blockquote><h3>💪 The Benefits of SOLID</h3><p>Applying SOLID isn’t about rules — it’s about <strong>freedom</strong>:</p><p>✅ Maintainable code that grows gracefully<br> ✅ Easier testing and debugging<br> ✅ Clear separation of concerns<br> ✅ Fewer merge conflicts in teams<br> ✅ Easier onboarding for new developers</p><blockquote><em>🏙️ </em>A SOLID codebase is like a well-structured city — you can build new districts without demolishing the old ones.</blockquote><h3>🧭 Conclusion</h3><p>Writing SOLID code isn’t about memorizing an acronym — it’s about <strong>writing with empathy</strong>.<br> Empathy for future developers.<br> Empathy for your future self.</p><p>When you design with SOLID in mind, your code becomes <strong>predictable, elegant, and timeless</strong>.</p><p>So next time you start a new feature, pause and ask yourself:</p><blockquote><em>💭 “Am I just making it work — or am I making it SOLID?”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3509803c3fd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to RxJS: Mastering Operators and Subjects for Reactive Programming]]></title>
            <link>https://medium.com/@majed.bannouri12/the-complete-guide-to-rxjs-mastering-operators-and-subjects-for-reactive-programming-8fcc06a73fd0?source=rss-83e66847f193------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fcc06a73fd0</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Majed Bannouri]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 10:15:39 GMT</pubDate>
            <atom:updated>2025-09-24T10:34:30.835Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine building a complex water distribution system for a city. You need pipes (Observables) to carry water (data), valves and filters (Operators) to control the flow, and central distribution points (Subjects) to manage where the water goes. This is exactly how RxJS works — it gives you everything you need to build sophisticated data flow systems for modern applications.</p><h3>Why RxJS Matters in Modern Development</h3><p>In today’s complex web applications, you’re constantly dealing with multiple asynchronous data sources: user interactions, API calls, WebSocket messages, timers, and more. RxJS provides a unified way to handle all these events using a reactive programming approach that’s more declarative, composable, and maintainable than traditional callback-based code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5xOQCEW1VwKM2jcgy80tA.jpeg" /></figure><h3>Part 1: Understanding the Foundation — Observables and Observers</h3><p>Before diving into operators and subjects, let’s understand the basic building blocks:</p><pre>import { Observable } from &#39;rxjs&#39;;<br>// Creating a simple Observable<br>const numberObservable = new Observable(subscriber =&gt; {<br>  subscriber.next(1);<br>  subscriber.next(2);<br>  subscriber.next(3);<br>  setTimeout(() =&gt; {<br>    subscriber.next(4);<br>    subscriber.complete();<br>  }, 1000);<br>});<br><br>// Subscribing to the Observable<br>const subscription = numberObservable.subscribe({<br>  next: value =&gt; console.log(&#39;Received:&#39;, value),<br>  error: err =&gt; console.error(&#39;Error:&#39;, err),<br>  complete: () =&gt; console.log(&#39;Completed&#39;)<br>});<br>// Output:<br>// Received: 1<br>// Received: 2<br>// Received: 3<br>// (after 1 second) Received: 4<br>// Completed</pre><h3>Part 2: Mastering RxJS Operators — Your Data Transformation Toolkit</h3><p>Operators are pure functions that transform, filter, and combine Observable streams. They’re the tools that make RxJS so powerful for handling complex data flows.</p><h3>Creation Operators: Starting Your Streams</h3><p>Real Scenario: Initializing data streams from various sources</p><pre>import { of, from, interval, fromEvent, timer } from &#39;rxjs&#39;;<br>// Create from static values<br>const staticData$ = of(&#39;Hello&#39;, &#39;World&#39;, 42);<br>// Create from array/Promise<br>const arrayData$ = from([1, 2, 3, 4, 5]);<br>const promiseData$ = from(fetch(&#39;/api/data&#39;));<br>// Create from DOM events<br>const click$ = fromEvent(document, &#39;click&#39;);<br>const input$ = fromEvent(searchInput, &#39;input&#39;);<br>// Create timed sequences<br>const seconds$ = interval(1000); // Emit every second<br>const delayed$ = timer(3000); // Emit after 3 seconds<br>// Real-world use: Initialize application with multiple data sources<br>const appInit$ = from([<br>  this.userService.loadUser(),<br>  this.configService.loadConfig(),<br>  this.translationService.loadTranslations()<br>]);</pre><h3>Transformation Operators: Shaping Your Data</h3><p>Real Scenario: Processing API responses and user input</p><p>map - Transform each value:</p><pre>const apiResponse$ = this.http.get(&#39;/api/users&#39;);<br>const userEmails$ = apiResponse$.pipe(<br>  map(response =&gt; response.users),<br>  map(users =&gt; users.map(user =&gt; user.email))<br>);<br>// Real scenario: Extracting and transforming API data<br>const weatherData$ = this.weatherService.getForecast().pipe(<br>  map(forecast =&gt; ({<br>    temperature: forecast.current.temp,<br>    condition: forecast.current.weather[0].description,<br>    icon: this.getWeatherIcon(forecast.current.weather[0].icon)<br>  }))<br>);</pre><p>switchMap - Most common scenario: Search with API calls</p><pre>const searchTerm$ = fromEvent(searchInput, &#39;input&#39;).pipe(<br>  map(event =&gt; event.target.value),<br>  debounceTime(300),<br>  distinctUntilChanged()<br>);<br>const searchResults$ = searchTerm$.pipe(<br>  filter(term =&gt; term.length &gt;= 3),<br>  switchMap(term =&gt; this.productService.search(term))<br>);<br>// Real scenario: Typeahead search that cancels previous requests</pre><p>mergeMap vs concatMap - Concurrent vs sequential operations:</p><pre>// mergeMap: Parallel file uploads<br>const fileUploads$ = fromEvent(fileInput, &#39;change&#39;).pipe(<br>  mergeMap(event =&gt; this.uploadService.uploadFiles(event.target.files))<br>);<br>// concatMap: Sequential operations that must maintain order<br>const userActions$ = fromEvent(saveButton, &#39;click&#39;).pipe(<br>  concatMap(() =&gt; this.saveUserData()) // Saves happen in order<br>);</pre><h3>Filtering Operators: Controlling What Gets Through</h3><p>Real Scenario: User input validation and event rate limiting</p><p>filter - Basic validation:</p><pre>const formInput$ = fromEvent(formInput, &#39;input&#39;).pipe(<br>  map(event =&gt; event.target.value),<br>  filter(value =&gt; value.length &gt;= 3) // Only allow valid input<br>);</pre><p>debounceTime and throttleTime - Performance optimization:</p><pre>// debounceTime: Wait for user to stop typing<br>const search$ = fromEvent(searchBox, &#39;input&#39;).pipe(<br>  debounceTime(400) // Wait 400ms after last keystroke<br>);<br>// throttleTime: Limit click rate to prevent spam<br>const buttonClicks$ = fromEvent(button, &#39;click&#39;).pipe(<br>  throttleTime(1000) // Only allow one click per second<br>);</pre><p>takeUntil - Automatic unsubscription pattern:</p><pre>export class UserComponent implements OnDestroy {<br>  private destroy$ = new Subject&lt;void&gt;();<br>  <br>  ngOnInit() {<br>    this.userService.getUserData().pipe(<br>      takeUntil(this.destroy$)<br>    ).subscribe(user =&gt; {<br>      // Handle user data<br>    });<br>  }<br>  <br>  ngOnDestroy() {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><h3>Combination Operators: Working with Multiple Streams</h3><p>Real Scenario: Dashboard with multiple data sources</p><p>combineLatest - Combine multiple data sources:</p><pre>const filter1$ = this.filterService.dateFilter$;<br>const filter2$ = this.filterService.categoryFilter$;<br>const filter3$ = this.filterService.statusFilter$;<br>const dashboardData$ = combineLatest([<br>  filter1$,<br>  filter2$, <br>  filter3$,<br>  this.dataService.getData()<br>]).pipe(<br>  map(([dateFilter, categoryFilter, statusFilter, data]) =&gt; {<br>    return data.filter(item =&gt; <br>      item.date &gt;= dateFilter.start &amp;&amp;<br>      item.category === categoryFilter &amp;&amp;<br>      item.status === statusFilter<br>    );<br>  })<br>);</pre><p>forkJoin - Wait for multiple API calls:</p><pre>const userInterface$ = forkJoin({<br>  user: this.userService.getCurrentUser(),<br>  permissions: this.authService.getPermissions(),<br>  preferences: this.settingsService.getUserPreferences()<br>});<br><br>userInterface$.subscribe(({user, permissions, preferences}) =&gt; {<br>  // All data loaded, now render UI<br>  this.initializeDashboard(user, permissions, preferences);<br>});</pre><h3>Part 3: Advanced RxJS — Mastering Subjects for State Management</h3><p>While operators handle data transformation, Subjects give you control over when and how data is emitted to multiple subscribers.</p><h3>Understanding Subjects: The Multicast Powerhouse</h3><pre>import { Subject } from &#39;rxjs&#39;;<br>// Regular Observable: Unicast (each subscriber gets independent execution)<br>const observable = new Observable(subscriber =&gt; {<br>  console.log(&#39;Observable executed&#39;);<br>  subscriber.next(Math.random());<br>});<br><br>observable.subscribe(v =&gt; console.log(&#39;Subscriber A:&#39;, v));<br>observable.subscribe(v =&gt; console.log(&#39;Subscriber B:&#39;, v));<br>// Output: <br>// Observable executed<br>// Subscriber A: 0.123<br>// Observable executed  <br>// Subscriber B: 0.456<br>// Subject: Multicast (shared execution)<br>const subject = new Subject&lt;number&gt;();<br>subject.subscribe(v =&gt; console.log(&#39;Subject A:&#39;, v));<br>subject.subscribe(v =&gt; console.log(&#39;Subject B:&#39;, v));<br>subject.next(Math.random());<br>// Output:<br>// Subject A: 0.789<br>// Subject B: 0.789</pre><h3>BehaviorSubject: Managing Application State</h3><p>Real Scenario: User authentication and global state management</p><pre>// auth.service.ts - Managing user authentication state<br>export class AuthService {<br>  // Private BehaviorSubject holds current state<br>  private currentUserSubject = new BehaviorSubject&lt;User | null&gt;(null);<br>  <br>  // Public observable for components to subscribe to<br>  public currentUser$ = this.currentUserSubject.asObservable();<br>  <br>  // Get current value synchronously<br>  public get currentUserValue(): User | null {<br>    return this.currentUserSubject.getValue();<br>  }<br>  <br>  login(credentials: LoginData): Observable&lt;User&gt; {<br>    return this.http.post(&#39;/api/login&#39;, credentials).pipe(<br>      tap(user =&gt; {<br>        // Update state - all subscribers get notified<br>        this.currentUserSubject.next(user);<br>        localStorage.setItem(&#39;currentUser&#39;, JSON.stringify(user));<br>      })<br>    );<br>  }<br>  <br>  logout() {<br>    this.currentUserSubject.next(null);<br>    localStorage.removeItem(&#39;currentUser&#39;);<br>  }<br>  <br>  autoLogin() {<br>    const storedUser = localStorage.getItem(&#39;currentUser&#39;);<br>    if (storedUser) {<br>      this.currentUserSubject.next(JSON.parse(storedUser));<br>    }<br>  }<br>}<br><br>// header.component.ts - Reacting to auth state changes<br>export class HeaderComponent implements OnInit {<br>  isLoggedIn = false;<br>  currentUser: User | null = null;<br>  <br>  constructor(private authService: AuthService) {}<br>  <br>  ngOnInit() {<br>    // Immediately get current state and react to changes<br>    this.authService.currentUser$.subscribe(user =&gt; {<br>      this.isLoggedIn = !!user;<br>      this.currentUser = user;<br>    });<br>  }<br>}</pre><h3>ReplaySubject: Maintaining History and Context</h3><p>Real Scenario: Chat application with message history</p><pre>// chat.service.ts - Managing chat messages with history<br>export class ChatService {<br>  // Store last 100 messages for new subscribers<br>  private messageHistory = new ReplaySubject&lt;ChatMessage&gt;(100);<br>  public messages$ = this.messageHistory.asObservable();<br>  <br>  private messageBuffer: ChatMessage[] = [];<br>  private isConnected = false;<br>  <br>  connectToChat(roomId: string) {<br>    this.chatSocket = new WebSocket(`ws://api/chat/${roomId}`);<br>    <br>    this.chatSocket.onmessage = (event) =&gt; {<br>      const message = JSON.parse(event.data);<br>      this.addMessage(message);<br>    };<br>    <br>    this.chatSocket.onopen = () =&gt; {<br>      this.isConnected = true;<br>      this.loadInitialMessages(roomId);<br>    };<br>  }<br>  <br>  private addMessage(message: ChatMessage) {<br>    this.messageBuffer.push(message);<br>    <br>    // Keep buffer size manageable<br>    if (this.messageBuffer.length &gt; 100) {<br>      this.messageBuffer.shift();<br>    }<br>    <br>    this.messageHistory.next(message);<br>  }<br>  <br>  private loadInitialMessages(roomId: string) {<br>    this.http.get&lt;ChatMessage[]&gt;(`/api/chat/${roomId}/history`).subscribe(<br>      messages =&gt; {<br>        this.messageBuffer = messages.slice(-100); // Keep last 100<br>        messages.forEach(msg =&gt; this.messageHistory.next(msg));<br>      }<br>    );<br>  }<br>  <br>  sendMessage(text: string) {<br>    if (this.isConnected) {<br>      this.chatSocket.send(JSON.stringify({ text, timestamp: Date.now() }));<br>    }<br>  }<br>}<br>// chat.component.ts - Displaying messages with history<br>export class ChatComponent implements OnInit {<br>  messages: ChatMessage[] = [];<br>  <br>  constructor(private chatService: ChatService) {}<br>  <br>  ngOnInit() {<br>    // When component loads, gets recent message history immediately<br>    this.chatService.messages$.subscribe(message =&gt; {<br>      this.messages = [...this.messages, message];<br>    });<br>  }<br>}</pre><h3>AsyncSubject: Handling Final Results</h3><p>Real Scenario: Long-running processes where only the final result matters</p><pre>// data-processing.service.ts<br>export class DataProcessingService {<br>  processLargeDataset(data: any[]): Observable&lt;ProcessResult&gt; {<br>    const resultSubject = new AsyncSubject&lt;ProcessResult&gt;();<br>    <br>    let processedItems = 0;<br>    const totalItems = data.length;<br>    <br>    // Simulate processing with progress updates<br>    const processNext = (index: number) =&gt; {<br>      if (index &gt;= totalItems) {<br>        const finalResult = this.compileResults(data);<br>        resultSubject.next(finalResult);<br>        resultSubject.complete();<br>        return;<br>      }<br>      <br>      // Process item (simulate async work)<br>      setTimeout(() =&gt; {<br>        this.processItem(data[index]);<br>        processedItems++;<br>        <br>        // Could emit progress to a different subject<br>        this.progressSubject.next({<br>          processed: processedItems,<br>          total: totalItems,<br>          percentage: (processedItems / totalItems) * 100<br>        });<br>        <br>        processNext(index + 1);<br>      }, 10);<br>    };<br>    <br>    processNext(0);<br>    return resultSubject.asObservable();<br>  }<br>}<br><br>// usage in component<br>this.processingService.processLargeDataset(largeData).subscribe(<br>  finalResult =&gt; {<br>    // Only receives the final compiled result<br>    this.displayResults(finalResult);<br>  }<br>);</pre><h3>Part 4: Real-World Complete Example — E-commerce Application</h3><p>Let’s build a complete e-commerce scenario combining operators and subjects:</p><pre>// ecommerce.service.ts<br>export class EcommerceService {<br>  // BehaviorSubject for current shopping cart state<br>  private cartSubject = new BehaviorSubject&lt;CartItem[]&gt;([]);<br>  public cart$ = this.cartSubject.asObservable();<br>  <br>  // ReplaySubject for order history<br>  private orderHistorySubject = new ReplaySubject&lt;Order[]&gt;(20);<br>  public orderHistory$ = this.orderHistorySubject.asObservable();<br>  <br>  // Subjects for user interactions<br>  private searchSubject = new Subject&lt;string&gt;();<br>  private filterSubject = new BehaviorSubject&lt;ProductFilter&gt;({});<br>  <br>  constructor(private http: HttpClient) {<br>    this.loadInitialData();<br>  }<br>  <br>  // Product search with debounce and API integration<br>  setupProductSearch() {<br>    this.searchSubject.pipe(<br>      debounceTime(300),<br>      distinctUntilChanged(),<br>      filter(term =&gt; term.length &gt;= 2 || term.length === 0),<br>      switchMap(term =&gt; <br>        term ? this.searchProducts(term) : this.getFeaturedProducts()<br>      ),<br>      catchError(error =&gt; {<br>        console.error(&#39;Search error:&#39;, error);<br>        return of([]);<br>      })<br>    ).subscribe(products =&gt; {<br>      this.displayProducts(products);<br>    });<br>  }<br>  <br>  // Shopping cart management<br>  addToCart(product: Product, quantity: number = 1) {<br>    const currentCart = this.cartSubject.getValue();<br>    const existingItem = currentCart.find(item =&gt; item.productId === product.id);<br>    <br>    let newCart: CartItem[];<br>    if (existingItem) {<br>      newCart = currentCart.map(item =&gt;<br>        item.productId === product.id<br>          ? { ...item, quantity: item.quantity + quantity }<br>          : item<br>      );<br>    } else {<br>      newCart = [...currentCart, {<br>        productId: product.id,<br>        name: product.name,<br>        price: product.price,<br>        quantity: quantity<br>      }];<br>    }<br>    <br>    this.cartSubject.next(newCart);<br>    this.saveCartToStorage(newCart);<br>  }<br>  <br>  // Checkout process with multiple async steps<br>  checkout(): Observable&lt;Order&gt; {<br>    const cartItems = this.cartSubject.getValue();<br>    <br>    return this.http.post&lt;Order&gt;(&#39;/api/orders&#39;, { items: cartItems }).pipe(<br>      switchMap(order =&gt; {<br>        // Clear cart on successful order<br>        this.cartSubject.next([]);<br>        this.clearCartStorage();<br>        <br>        // Add to order history<br>        return this.getOrderDetails(order.id).pipe(<br>          tap(orderDetails =&gt; {<br>            this.orderHistorySubject.next(orderDetails);<br>          })<br>        );<br>      }),<br>      retry(2), // Retry failed orders<br>      catchError(error =&gt; {<br>        this.notifyError(&#39;Checkout failed. Please try again.&#39;);<br>        throw error;<br>      })<br>    );<br>  }<br>  <br>  // Combined product filtering<br>  getFilteredProducts(): Observable&lt;Product[]&gt; {<br>    return combineLatest([<br>      this.filterSubject,<br>      this.searchSubject.pipe(startWith(&#39;&#39;))<br>    ]).pipe(<br>      debounceTime(100), // Avoid excessive filtering<br>      switchMap(([filters, searchTerm]) =&gt; <br>        this.http.get&lt;Product[]&gt;(&#39;/api/products&#39;, { <br>          params: { ...filters, search: searchTerm }<br>        })<br>      ),<br>      shareReplay(1) // Cache results for multiple subscribers<br>    );<br>  }<br>}<br><br>// product-list.component.ts<br>export class ProductListComponent implements OnInit {<br>  products: Product[] = [];<br>  filteredProducts: Product[] = [];<br>  <br>  constructor(private ecommerceService: EcommerceService) {}<br>  <br>  ngOnInit() {<br>    // Combine search and filter streams<br>    const searchAndFilter$ = combineLatest([<br>      this.ecommerceService.getFilteredProducts(),<br>      this.ecommerceService.cart$ // To show cart status<br>    ]);<br>    <br>    searchAndFilter$.pipe(<br>      takeUntil(this.destroy$)<br>    ).subscribe(([products, cartItems]) =&gt; {<br>      this.products = products;<br>      this.filteredProducts = this.applyLocalFilters(products);<br>      this.updateCartStatus(cartItems);<br>    });<br>    <br>    // Handle infinite scroll<br>    fromEvent(window, &#39;scroll&#39;).pipe(<br>      throttleTime(200),<br>      filter(() =&gt; this.isNearBottom()),<br>      distinctUntilChanged(),<br>      switchMap(() =&gt; this.loadMoreProducts())<br>    ).subscribe(moreProducts =&gt; {<br>      this.products = [...this.products, ...moreProducts];<br>    });<br>  }<br>  <br>  onSearch(term: string) {<br>    this.ecommerceService.searchSubject.next(term);<br>  }<br>  <br>  onAddToCart(product: Product) {<br>    this.ecommerceService.addToCart(product);<br>  }<br>}</pre><h3>Part 5: Advanced Patterns and Best Practices</h3><h3>Custom Operator Creation</h3><pre>// Custom operator for API response handling<br>function handleApiResponse&lt;T&gt;() {<br>  return (source: Observable&lt;any&gt;) =&gt; source.pipe(<br>    map(response =&gt; response.data),<br>    catchError(error =&gt; {<br>      console.error(&#39;API Error:&#39;, error);<br>      throw new Error(&#39;Failed to fetch data&#39;);<br>    }),<br>    retry(2)<br>  );<br>}<br>// Usage<br>this.http.get(&#39;/api/data&#39;).pipe(<br>  handleApiResponse()<br>).subscribe(data =&gt; console.log(data));<br>// Custom operator with configuration<br>function logStream&lt;T&gt;(name: string) {<br>  return (source: Observable&lt;T&gt;) =&gt; source.pipe(<br>    tap({<br>      next: value =&gt; console.log(`[${name}] Next:`, value),<br>      error: err =&gt; console.error(`[${name}] Error:`, err),<br>      complete: () =&gt; console.log(`[${name}] Complete`)<br>    })<br>  );<br>}</pre><h3>Error Handling Strategy</h3><pre>// Comprehensive error handling<br>class ErrorHandlingService {<br>  private errorSubject = new Subject&lt;AppError&gt;();<br>  public errors$ = this.errorSubject.asObservable();<br>  <br>  handleApiCall&lt;T&gt;(apiCall: Observable&lt;T&gt;): Observable&lt;T&gt; {<br>    return apiCall.pipe(<br>      timeout(5000),<br>      retryWhen(errors =&gt; errors.pipe(<br>        delay(1000),<br>        take(3),<br>        tap(error =&gt; {<br>          if (!this.isNetworkError(error)) {<br>            throw error; // Don&#39;t retry non-network errors<br>          }<br>        })<br>      )),<br>      catchError(error =&gt; {<br>        this.errorSubject.next(this.normalizeError(error));<br>        return throwError(() =&gt; error);<br>      })<br>    );<br>  }<br>}</pre><h3>Performance Optimization</h3><pre>// Avoiding unnecessary subscriptions<br>class OptimizedComponent {<br>  private data$ = this.dataService.getData().pipe(<br>    shareReplay({ bufferSize: 1, refCount: true })<br>  );<br>  <br>  // Multiple templates can subscribe to the same shared observable<br>  get userData$() {<br>    return this.data$.pipe(map(data =&gt; data.user));<br>  }<br>  <br>  get stats$() {<br>    return this.data$.pipe(map(data =&gt; data.stats));<br>  }<br>}ty</pre><h3>Conclusion: Building Reactive Applications with Confidence</h3><p>RxJS provides a comprehensive toolkit for managing asynchronous data flows in modern applications. By mastering both operators and subjects, you can:</p><ul><li>Transform and combine data streams with powerful operators</li><li>Manage application state efficiently with Subjects</li><li>Handle complex scenarios like real-time updates, search, and state synchronization</li><li>Write more maintainable and declarative code</li></ul><h3>Quick Reference Guide</h3><p>For data transformation: Use operators like map, filter, switchMap<br>For current state: Use BehaviorSubject<br>For event history: Use ReplaySubject<br>For final results: Use AsyncSubject<br>For simple events: Use regular Subject</p><p><strong>Remember:</strong> The key to RxJS mastery is understanding the patterns and choosing the right tool for each scenario. Start simple, practice with real projects, and gradually incorporate more advanced patterns as you become comfortable with reactive programming concepts.</p><p>What RxJS patterns have you found most useful in your projects? Share your experiences and questions in the comments below!</p><p><a href="https://www.linkedin.com/in/majed-bannouri-8791341b4/">https://www.linkedin.com/in/majed-bannouri-8791341b4/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fcc06a73fd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hey GSAP — Let’s Make Your Website Move!]]></title>
            <link>https://medium.com/@majed.bannouri12/hey-gsap-lets-make-your-website-move-7aee49a527e3?source=rss-83e66847f193------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aee49a527e3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[Majed Bannouri]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 22:50:25 GMT</pubDate>
            <atom:updated>2025-07-11T22:50:25.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hey GSAP — Let’s Make Your Website Move!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*sVUn_MeKvFZJyodMtdNnJw.png" /></figure><p>“Hey wasuup!” 👋<br>“Hi GSAP!” ✨<br>“Wait… GSAP? Like the animation thing?”<br>“Yeah! The secret sauce behind those fancy websites where stuff glides in as you scroll.”</p><p>“But like… how did we even get here? Weren’t websites just text and blue links before?”</p><p>“Oh absolutely! Let me show you the glow-up:”</p><p>Like architecture, web design evolved from primitive structures into elegant, purposeful systems. In the early web, design wasn’t a priority — it was survival. The first sites were just raw text and hyperlinks (remember &lt;marquee&gt; tags? 😅). But as the internet matured, we went :</p><h3>1. From Pixels to Purpose: A Brief History of Web Design 🕰️</h3><p>Here’s a timeline that traces the transformation of web design from clunky code to immersive art:</p><h4>🔸 1991 — The First Website</h4><ul><li>Tim Berners-Lee launches the <strong>first webpage</strong>.</li><li>Pure HTML, no images, no layout — just hyperlinks and text.</li></ul><h4>🦮 1995 — The Birth of the Browser Wars</h4><ul><li>Netscape and Internet Explorer introduce support for <strong>inline images</strong>.</li><li>Designers begin experimenting with background colors, fonts (via &lt;font&gt; tags), and table layouts.</li></ul><h4>🧰 1996 — Cascading Style Sheets (CSS1)</h4><ul><li>CSS1 is introduced by the W3C, separating style from content for the first time.</li><li>Designers gain control over margins, paddings, colors, and fonts — without cluttering HTML.</li></ul><h4>🧠 1998–2000 — The Rise of UX Thinking</h4><ul><li><strong>Jakob Nielsen</strong> popularizes usability with principles like “Don’t Make Me Think.”</li><li>Web design becomes more user-centered, not just developer-driven.</li></ul><h4>🎨 2003 — CSS Zen Garden</h4><ul><li>A landmark in showing the power of CSS for design without touching HTML.</li><li>Sparks the modern <strong>web standards movement</strong> and inspires creative layout evolution.</li></ul><h4>📱 2007 — The iPhone and Responsive Design</h4><ul><li>Mobile-first thinking becomes essential.</li><li>Ethan Marcotte coins the term <strong>Responsive Web Design</strong> in 2010, encouraging fluid grids and media queries.</li></ul><h4>⚙️ 2014 — HTML5, CSS3, and JavaScript Animation</h4><ul><li>Major leap for semantic HTML, video embedding, SVG, animation, and native form validation.</li><li><strong>Flat design</strong> becomes a trend, inspired by Google’s Material Design.</li></ul><h4>🎭 2018–2024 — The Age of Storytelling, Animation, and Emotion</h4><ul><li>Tools like <strong>GSAP</strong>, <strong>Framer Motion</strong>, and <strong>Three.js</strong> empower designers to build motion-rich, immersive experiences.</li><li>Websites evolve from static documents into <strong>living, interactive stories</strong>.</li></ul><blockquote><strong><em>Fact:</em></strong><em> By 2023, over </em><strong><em>94% of first impressions</em></strong><em> are design-related. (Stanford Web Credibility Research)</em></blockquote><h3>2. The Psychology of Effective Web Animation 🧠</h3><p>Animations work because they tap into how our brains process information:</p><ul><li>Directional cues: Motion guides users’ eyes to important elements</li><li>Feedback loops: Animations confirm actions (like button clicks)</li><li>Emotional connection: Smooth transitions create delight</li><li>Perceived performance: Well-designed motion makes interfaces feel faster</li></ul><p>Case Study: When Apple introduced the “genie effect” minimizing windows to the dock, it wasn’t just pretty — it helped users track where windows went.</p><h3>3. Crafting High-Performance With React And GSAP ⚡</h3><h4>3.1 What is GSAP and Why Use It?</h4><p>GSAP (GreenSock Animation Platform) is a <strong>professional-grade animation library</strong> for JavaScript, tailored for high-performance interfaces:</p><ul><li>🎯 <strong>Precision timing</strong> (millisecond control)</li><li>⚡ <strong>Smooth performance</strong> (even with heavy DOM/SVG)</li><li>🌐 <strong>Cross-browser consistency</strong></li><li>🔌 <strong>Powerful plugin ecosystem</strong> (e.g., ScrollTrigger, SplitText, MorphSVG)</li></ul><p><strong>Why it outperforms CSS animations:</strong></p><ul><li>Full control over complex timelines ⏱️</li><li>Better handling of interrupting/resuming animations 🚀</li><li>Cleaner integration with React 🛠️</li><li>Visual storytelling with synchronized transitions ⚡</li></ul><blockquote>“GSAP powers animations on over 11 million sites because it solves real-world animation challenges.”<em> — GSAP Team</em></blockquote><h4>3.2 Installation ⚙️</h4><pre>npm install gsap @gsap/react</pre><h4>3.3 GSAP Animation Basics 🏗️</h4><p>3.3.1 gsap.from() and gsap.to() 🔄</p><p>What They Mean:</p><ul><li>gsap.to(): Animates an element from its current state <em>to</em> new values.</li><li>gsap.from(): Animates an element from specified values <em>to</em> its current state.</li></ul><p>How They Work:</p><pre>gsap.from(&quot;.box&quot;, {<br>  y: 50,        // Starts 50px lower<br>  opacity: 0,   // Starts invisible<br>  duration: 1<br>});<br>gsap.to(&quot;.box&quot;, {<br>  x: 100,       // Moves 100px to the right<br>  rotation: 360,<br>  duration: 1<br>});</pre><p>Why Use Them?:</p><p>to() is ideal for:</p><ul><li>Moving elements to new positions.</li><li>Creating “entrance” effects (e.g., fading in).</li></ul><p>from() is perfect for:</p><ul><li>“Reset” animations (e.g., elements fly in from offscreen).</li><li>Sequencing animations with different starting points.</li></ul><p>3.3.2 gsap.timeline() ⏳</p><p>What It Means:</p><p>A container for sequencing multiple animations with precise timing control.</p><p>How It Works:</p><pre>const tl = gsap.timeline({ defaults: { ease: &quot;power2.out&quot; } });<br>tl.from(&quot;.title&quot;, { y: 50 })               // Starts first<br>  .from(&quot;.subtitle&quot;, { x: -30 })           // Starts after .title ends<br>  .from(&quot;.button&quot;, { scale: 0.8 }, &quot;-=0.3&quot;); // Overlaps previous by 0.3s</pre><p>Why Use It?:</p><ul><li>Avoids “callback hell” (no nested onComplete callbacks).</li><li>Control timing with offsets (+=1, -=0.5, &lt;, &gt;).</li><li>Reuse timelines across components.</li></ul><p><strong>Timeline Positioning:</strong></p><p><strong>+=1</strong> — Delay start by 1s<br> <strong>-=0.5</strong> — Start 0.5s before previous ends<br> <strong>&lt;</strong> — Start at the same time</p><p>3.3.3 ScrollTrigger 🖱️</p><p>What It Means:</p><p>Triggers animations based on scroll position (e.g., parallax, pinning).</p><p>How It Works:</p><pre>gsap.to(&quot;.image&quot;, {<br>  y: -100,<br>  scrollTrigger: {<br>    trigger: &quot;.section&quot;,<br>    start: &quot;top center&quot;,<br>    end: &quot;bottom top&quot;,<br>    scrub: true,<br>    markers: true, // dev only (it will highlight scroll limits in sections)<br>  }<br>});</pre><p>Why Use It?:</p><ul><li>Storytelling: Animate sections as users scroll.</li><li>Performance: Optimized for buttery-smooth scrolling.</li><li>No scroll-jacking: Respects native scroll behavior.</li></ul><p><strong>Key Props:</strong></p><p><strong>trigger</strong> — Element that triggers animation → .section<br> <strong>start</strong> — Start point in viewport → &quot;top center&quot;<br> <strong>end</strong> — End point → &quot;bottom top&quot;<br> <strong>scrub</strong> — Sync with scroll → true / 0.5</p><p>3.3.4 stagger 🌊</p><p>What It Means:</p><p>Animates elements in a sequence with delays between each.</p><p>How It Works:</p><pre>gsap.from(&quot;.card&quot;, {<br>  y: 50,<br>  opacity: 0,<br>  stagger: 0.1,<br>  ease: &quot;back.out&quot;<br>});</pre><p>Why Use It?:</p><ul><li>Visual polish: Creates organic, non-robotic motion.</li><li>Highlight lists/grids: Cards, menus, or galleries.</li><li>Avoids overwhelming users: Animates elements sequentially.</li></ul><p>3.3.5 ease 🎢</p><p>What It Means:</p><p>Controls acceleration/deceleration of animations (how motion “feels”).</p><p>How It Works:</p><pre>// Common eases<br>&quot;power1.out&quot;      // Smooth<br>&quot;bounce.out&quot;      // Bouncy entrance<br>&quot;elastic&quot;         // Stretch + snap<br>&quot;back.out(1.7)&quot;   // Pull back then shoot</pre><p>Why Use It?:</p><ul><li>Realism: Mimics physics (e.g., gravity, elasticity).</li><li>Emotion: Different eases convey different moods.</li><li>Guidance: Directs user attention effectively.</li></ul><h4>3.4 Advanced Typography with SplitText ✒️</h4><p>3.4.1 Basic</p><pre>import { SplitText } from &quot;gsap/SplitText&quot;;<br>useGSAP(() =&gt; {<br>  const split = new SplitText(&quot;.headline&quot;, { type: &quot;chars&quot; });<br>  gsap.from(split.chars, {<br>    y: 50,<br>    stagger: 0.05<br>  });<br>}, { scope: container });</pre><p>3.4.2 Advanced</p><p><strong>Morphing Text</strong></p><pre>const split = new SplitText(&quot;.text&quot;, { type: &quot;chars&quot; });<br>gsap.to(split.chars, {<br>  y: -20,<br>  duration: 0.5,<br>  stagger: 0.1<br>});</pre><p><strong>Line-by-Line Reveal</strong></p><pre>const split = new SplitText(&quot;.paragraph&quot;, { type: &quot;lines&quot; });<br>gsap.from(split.lines, {<br>  y: 100,<br>  stagger: 0.2<br>});</pre><h4>3.5 Performance Optimization 🚀</h4><p><strong>3.5.1. Use </strong><strong>will-change:</strong></p><pre>.animated {<br>  will-change: transform, opacity;<br>}</pre><p><strong>3.5.2. Cleanup on unmount (with </strong><strong>useGSAP from </strong><strong>@gsap/react):</strong></p><pre>useGSAP(() =&gt; {<br>  // GSAP cleans up automatically in this scope<br>}, { scope: container });</pre><p><strong>3.5.3. Respect reduced motion preferences:</strong></p><pre>const prefersReduced = window.matchMedia(<br>  &#39;(prefers-reduced-motion: reduce)&#39;<br>).matches;</pre><h3>5. Conclusion: Design Is Not Decoration — It’s Strategy ♟️</h3><p>The best websites don’t just look good — they <strong>solve problems</strong>, <strong>influence behavior</strong>, and <strong>drive results</strong>. Great design blends history, psychology, and technology into a seamless user experience.</p><p>Let’s recap the journey:</p><h4>✅ From Pixels to Purpose</h4><p>Web design has evolved from &lt;table&gt; layouts to interactive storytelling. Each era brought new tools—but purpose-driven design remained constant.</p><h4>✅ Psychology Shapes Perception</h4><p>Every scroll, hover, and delay affects how users feel. <strong>Motion isn’t fluff</strong> — it’s a communication tool that makes your product feel faster, more polished, and more human.</p><h4>✅ React + GSAP = Performance Meets Emotion</h4><p>GSAP gives you total control over animation timing and sequencing — making it the ideal partner for React-based interfaces. Whether you’re building SaaS dashboards, portfolios, or landing pages, <strong>GSAP elevates interaction to impact</strong>.</p><h4>🔑 Key Takeaways</h4><ul><li><strong>Motion = Emotion</strong> — Animations guide users, reduce friction, and boost retention.</li><li><strong>Study the Greats</strong> — Explore Awwwards-winning sites like <a href="https://bruno-simon.com/">Bruno Simon</a> for inspiration.</li><li><strong>GSAP + React = Future-Proof UI</strong> — It’s the most flexible, performant animation toolkit for modern frontends.</li></ul><blockquote><em>“Design is intelligence made visible.” — Alina Wheeler</em></blockquote><h4>🚀 Ready to Build?</h4><p>You now understand how visual storytelling, behavioral science, and powerful tooling come together. Start small. Animate a headline. Add scroll-driven interactions. Refine your timeline. Your next interface could be <strong>award-worthy</strong> — and <strong>unforgettable</strong>.</p><p>Your users will feel the difference.<br> Your brand will stand out.<br> Your product will sell better.</p><p>Let GSAP be your brush.<br> Let React be your canvas.<br> Now — <strong>design something that moves.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aee49a527e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Apache Kafka: Guide to Real-Time Data Streaming]]></title>
            <link>https://medium.com/@majed.bannouri12/understanding-apache-kafka-guide-to-real-time-data-streaming-315c637a61e9?source=rss-83e66847f193------2</link>
            <guid isPermaLink="false">https://medium.com/p/315c637a61e9</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Majed Bannouri]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 09:25:27 GMT</pubDate>
            <atom:updated>2025-03-22T09:31:14.890Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Apache Kafka: A Guide to Real-Time Data Streaming</h3><h3>1. The Problem: A Startup in Crisis</h3><p>Picture this: you’re running a startup, a cutting-edge e-commerce platform. Initially, everything runs smoothly. Orders come in, the system processes them, and your customers are satisfied. Your microservices architecture is simple: services like payments, orders, and inventory communicate directly. For instance, when a customer places an order, the order service notifies the others: “Hey, we’ve got a new order. Update your systems!” And for a while, this setup works perfectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*s_VwIgGMJul_SZ7tFyVdBA.png" /></figure><p>But then, something incredible happens. Your store becomes wildly popular. Maybe it’s because of a viral product or a Black Friday sale. Suddenly, your app is flooded with hundreds of thousands of orders. While this is great news, your architecture can’t keep up. The system starts crashing, everything slows to a crawl, and customers are left staring at loading screens. Sales are slipping away every minute. What seemed like a clean and efficient architecture on paper has turned into a disaster.</p><p>Here’s what’s going wrong behind the scenes:</p><h4>a. Tightly Coupled Services</h4><p>Your microservices are deeply interconnected. If one service fails — like the payment service crashing under heavy load — the entire order process grinds to a halt. It’s like a chain reaction: one weak link, and the whole system collapses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*9T2C_I3z0CX_-vwgxIQ7Uw.png" /></figure><h4>b. Synchronous Communication</h4><p>Every order sets off a series of updates. For example:</p><ul><li>The inventory service updates the database to reflect the sold items.</li><li>The notification service sends a confirmation email to the customer.</li><li>The payment service generates an invoice and emails it to the customer.</li><li>The analytics service updates the sales dashboard with the latest figures.</li></ul><p>But because these services communicate directly and wait for responses, a single slow service (like the payment system) causes delays across the board. During peak times, customers are left waiting, and you’re losing sales by the minute.</p><h4>c. Single Points of Failure</h4><p>Your system has several critical vulnerabilities. For instance:</p><ul><li>A 10-minute outage in the inventory service results in hours of order backlogs and countless lost sales.</li><li>If the analytics service goes down for an hour, you lose crucial data, like Black Friday sales metrics.</li></ul><h4>d. Lost Data</h4><p>When the analytics service crashes, you lose valuable insights. For example, during a Black Friday sale, an hour of downtime means missing out on key customer behavior and sales trends.</p><p>After a week of chaos, you realize something has to change. You think, “What if we redesign the system so that orders flow through like items on a <strong>conveyor belt</strong> instead of this chaotic game of hot potato?” That’s when you discover <strong>Apache Kafka</strong>.</p><h3>2. The Importance of Kafka in a Nutshell</h3><p>Apache Kafka is a <strong>distributed streaming platform</strong> designed to handle high volumes of data in real time. It acts as a <strong>central nervous system</strong> for your application, ensuring that data flows smoothly between services without bottlenecks or failures. Kafka decouples your services, making your architecture more resilient, scalable, and fault-tolerant. It’s like adding a <strong>postal service</strong> to your system — instead of services delivering data directly to each other, they hand it over to Kafka, which ensures it reaches the right destination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qiGP9jU_h--cSBpkntFeg.png" /></figure><h3>3. The Solution: With Kafka</h3><p>With Kafka, we completely redesigned our system to remove tight coupling and introduce a <strong>broker</strong> that sits between services. Here’s how it works:</p><h4>a. Removing Tight Coupling</h4><p>Instead of services calling each other directly and waiting for replies, we introduced Kafka as a middleman. Think of it like a <strong>post office</strong>:</p><ul><li>When you order something online, the seller doesn’t deliver the package themselves. They hand it over to the post office, which handles the delivery.</li><li>Similarly, when the order service receives an order, it doesn’t call the inventory, payment, or notification services directly. Instead, it sends a <strong>package</strong> (called an event) to Kafka.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfL5MJgL7d3VG-GmJkXMMA.png" /></figure><p>For example, the order service sends an event to Kafka that says:</p><p><strong>📩 Hey!</strong><br>An <strong>🛒 order</strong> was made for this <strong>👤 customer</strong>.<br>Here are the <strong>📄 details</strong>:</p><ul><li><strong>📦 Products</strong>: [List of products]</li><li><strong>💰 Total</strong>: [Amount]</li><li><strong>📅 Date</strong>: [Order date]</li></ul><p><strong>📢 Please make this information available for anyone who needs it to update and do stuff in the background.</strong></p><p><strong>👋 Bye!</strong></p><p>The event has a simple structure with key-value pairs and metadata. Once the order service sends the event, it doesn’t need to wait around to make sure the other services received the information. It trusts Kafka to deliver the event to the right services in the background.</p><h4>b. How Kafka Acts as a Broker</h4><p>Kafka acts as a <strong>broker</strong> between services, ensuring that data flows efficiently and reliably. Here’s how it works:</p><ol><li><strong>Producers</strong>: Services like the order service produce events and send them to Kafka.</li><li><strong>Topics</strong>: Kafka organizes events into topics (e.g., “orders,” “payments”).</li><li><strong>Consumers</strong>: Services like inventory, payment, and notification subscribe to these topics and process the events.</li></ol><p>For example:</p><ul><li>The inventory service subscribes to the “orders” topic. When a new order event arrives, it updates the stock in the database.</li><li>The notification service subscribes to the same topic and sends a confirmation email to the customer.</li><li>The payment service generates an invoice and sends it to the customer.</li></ul><p>By using Kafka as a broker, we removed the tight coupling between services. Each service works independently, and Kafka ensures that events are delivered reliably and in real time.</p><h4>c. Benefits of Using Kafka</h4><ul><li><strong>Decoupling</strong>: Services no longer depend on each other directly. They communicate through Kafka, making the system more resilient.</li><li><strong>Asynchronous Communication</strong>: Services don’t need to wait for replies. They send events to Kafka and continue their work.</li><li><strong>Scalability</strong>: Kafka can handle massive amounts of data by distributing it across multiple partitions and brokers.</li><li><strong>Fault Tolerance</strong>: If a service goes down, Kafka ensures that events are not lost. They are stored and can be processed when the service comes back online.</li></ul><h3>4. Fault Tolerance: Ensuring No Data is Lost</h3><p>One of Kafka’s most powerful features is its <strong>fault tolerance</strong>. In a distributed system, failures are inevitable — servers can crash, networks can go down, or services can become unresponsive. Kafka is designed to handle these failures gracefully, ensuring that no data is lost and that your system remains operational even during outages.</p><p>Here’s how Kafka achieves fault tolerance:</p><h4>a. Data Replication</h4><p>Kafka stores data in <strong>partitions</strong>, which are distributed across multiple servers (called <strong>brokers</strong>). Each partition is replicated across several brokers to ensure redundancy. For example:</p><ul><li>If you have a topic with three partitions, Kafka might create three replicas of each partition and distribute them across three different brokers.</li><li>This means that even if one broker goes down, the data is still available on the other brokers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dI2WzAmRzdLgimA6b77SVQ.png" /></figure><p>Think of it like having multiple copies of an important document stored in different locations. If one copy is lost or damaged, you can still access the document from another location.</p><h4>b. Leader and Followers</h4><p>Within a Kafka cluster, each partition has a <strong>leader</strong> and one or more <strong>followers</strong>:</p><ul><li>The <strong>leader</strong> handles all read and write requests for the partition.</li><li>The <strong>followers</strong> replicate the data from the leader and stay in sync.</li></ul><p>If the leader broker fails, Kafka automatically promotes one of the followers to be the new leader. This ensures that the partition remains available for reads and writes, even during a failure.</p><p>For example:</p><ul><li>Imagine a team of workers in a factory. If the team leader gets sick, another worker steps up to take their place, ensuring that the production line keeps running.</li></ul><h4>c. Durability Through Disk Storage</h4><p>Kafka stores all events on disk, not just in memory. This means that even if a broker crashes and restarts, the data is not lost. Events are persisted and can be replayed once the broker is back online.</p><p>Think of it like writing a letter and saving it in a filing cabinet. Even if your desk gets messy or your computer crashes, the letter is still safe in the cabinet.</p><h4>d. Consumer Offsets</h4><p>Kafka tracks the position of each consumer in a partition using <strong>offsets</strong>. An offset is like a bookmark that tells Kafka, “This is where the consumer last left off.” If a consumer goes down, it can pick up where it left off once it comes back online.</p><p>For example:</p><ul><li>Imagine you’re reading a book and you lose your place. If you’ve bookmarked the last page you read, you can easily pick up where you left off. Kafka does the same thing with consumer offsets.</li></ul><h4>e. Real-World Example</h4><p>Let’s say the <strong>inventory service</strong> goes down for 10 minutes due to a server crash. During this time:</p><ul><li>The order service continues to send order events to Kafka.</li><li>Kafka stores these events in the “orders” topic, ensuring they are not lost.</li><li>When the inventory service comes back online, it reads the events from Kafka and processes them in the correct order.</li></ul><p>This ensures that no orders are lost, even during an outage. The inventory service can catch up on the missed events and update the stock levels accordingly.</p><h3>5. Real-Time Processing: A Game-Changer</h3><p>Kafka’s ability to process data in <strong>real time</strong> is revolutionary. Here’s how it works:</p><ul><li>The order service sends an event to Kafka: “Hey, an order was placed by this customer. Here are the details.”</li><li>Kafka stores this event in a <strong>topic</strong> (e.g., “orders”).</li><li>Consumers (e.g., inventory, payment services) read the event and process it immediately.</li></ul><p>This ensures that orders are processed as soon as they come in, without delays. Kafka acts like a <strong>conveyor belt</strong>, moving data through your system efficiently. The order service doesn’t need to wait around to confirm that other services received the information. It trusts Kafka to deliver the data to the right services in the background.</p><h3>6. Topics and Partitions: Organizing Data</h3><p>Kafka organizes data into <strong>topics</strong>, which are like categories or channels. For example:</p><ul><li><strong>Orders Topic</strong>: Stores all order-related events.</li><li><strong>Payments Topic</strong>: Stores all payment-related events.</li></ul><p>Each topic is divided into <strong>partitions</strong>, which are like lanes on a highway. Partitions allow Kafka to:</p><ul><li>Distribute data across multiple servers for parallel processing.</li><li>Scale horizontally to handle massive amounts of data.</li></ul><p>For example, you could partition the “orders” topic by zone (e.g., North zone orders, Western zone orders, South zone orders …) to improve performance. This is like a postal service adding sections for letters, large packages, and small packages. Each section has its own queue, making the process more efficient.</p><h3>7. Producers and Consumers: The Key Players</h3><ul><li><strong>Producers</strong>: Applications that send events to Kafka. For example, the order service produces an event when a customer places an order.</li><li><strong>Consumers</strong>: Applications that read and process events from Kafka. For example, the inventory service consumes order events to update stock levels.</li></ul><p>Kafka ensures that producers and consumers are decoupled, allowing them to work independently. In code, this is how it would look using the Kafka Producer API. For example, in JavaScript or Java, you would use the API to create an event and send it to Kafka.</p><h3>8. Consumer Groups: Scaling Consumption</h3><p>As your application grows, a single consumer might not be enough to handle the load. Kafka solves this with <strong>consumer groups</strong>:</p><ul><li>Multiple instances of a service (e.g., inventory service) form a consumer group.</li><li>Kafka distributes partitions among the consumers in the group, enabling parallel processing.</li></ul><p>For example, if you have three instances of the inventory service, Kafka assigns each instance a subset of partitions to process. This ensures that orders are processed quickly, even during peak traffic. It’s like adding more workers to a postal service section to handle a sudden surge in packages.</p><h3>9. Kafka Brokers: The Backbone of the System</h3><p>Kafka brokers are the servers that store and manage data. They form a <strong>Kafka cluster</strong>, which ensures fault tolerance and scalability:</p><ul><li>Each broker stores a subset of partitions.</li><li>Data is replicated across multiple brokers for fault tolerance.</li><li>If one broker fails, another takes over seamlessly.</li></ul><p>Think of brokers as <strong>postal service branches</strong> that handle the storage and delivery of messages. They store the actual messages on disk, handle requests from producers and consumers, and replicate data for fault tolerance.</p><h3>10. Kafka vs. Traditional Message Brokers</h3><p>Kafka is different from traditional message brokers like RabbitMQ in several ways:</p><ul><li><strong>Durability</strong>: Kafka stores data on disk, ensuring it’s not lost even if a server crashes.</li><li><strong>Real-Time Processing</strong>: Kafka processes data in real time, making it ideal for time-sensitive applications.</li><li><strong>Scalability</strong>: Kafka can handle massive amounts of data with low latency.</li><li><strong>Persistence</strong>: Kafka retains data for as long as you need, allowing consumers to read it multiple times.</li></ul><p>Kafka is like <strong>Netflix</strong>, where consumers can watch (process) data on demand, while traditional brokers are like <strong>TV</strong>, where data is consumed once and then discarded.</p><h3>11. Kafka’s Ecosystem</h3><p>Kafka’s ecosystem includes powerful tools for data integration and stream processing:</p><ul><li><strong>Kafka Connect</strong>: For integrating Kafka with external systems.</li><li><strong>Kafka Streams</strong>: For building real-time stream processing applications.</li><li><strong>KSQL</strong>: A SQL-like language for querying Kafka data.</li></ul><p>These tools make Kafka a complete platform for real-time data processing.</p><h3>12. The Solution: Kafka to the Rescue</h3><p>By integrating Kafka into app architecture, we can:</p><ul><li>Handle thousands of orders per second without crashing.</li><li>Process orders in real time, ensuring customers get instant confirmations.</li><li>Scale effortlessly as our user base grows.</li><li>Ensure no data is lost, even during peak traffic.</li></ul><p>With Kafka, our app is no longer in crisis — it’s thriving.</p><h3>Conclusion</h3><p>Apache Kafka is more than just a tool — it’s a lifeline for startups and businesses dealing with high volumes of data. By enabling real-time processing, scalability, and fault tolerance, Kafka ensures that your app can handle anything thrown its way. Whether you’re running an e-commerce platform, a real-time analytics system, or a messaging app, Kafka is the key to staying ahead in today’s fast-paced world.</p><p>Ready to build a fault-tolerant system with Kafka? Start exploring its features today and see how it can transform your application. Check out the <a href="https://kafka.apache.org/documentation/">official Kafka documentation</a> to get started!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=315c637a61e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caution: You’re Entering the Temporal Dead Zone (TDZ) in JavaScript!]]></title>
            <link>https://medium.com/@majed.bannouri12/caution-youre-entering-the-temporal-dead-zone-tdz-in-javascript-28c305988364?source=rss-83e66847f193------2</link>
            <guid isPermaLink="false">https://medium.com/p/28c305988364</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[temporal-dead-zone]]></category>
            <dc:creator><![CDATA[Majed Bannouri]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 08:46:37 GMT</pubDate>
            <atom:updated>2025-03-12T08:46:37.343Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript is a powerful and flexible language, but it has its quirks. One such quirk is the <strong>Temporal Dead Zone (TDZ)</strong>, a concept that often confuses developers, especially those new to JavaScript. If you’ve ever encountered a ReferenceError when using let or const, you’ve likely run into the TDZ. In this blog post, we’ll break down what the TDZ is, why it exists, and how to avoid common pitfalls. Buckle up—you’re about to enter the Temporal Dead Zone!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*efVHTtX1FBIfrYtDbN7L1A.png" /></figure><h3>1. What is the Temporal Dead Zone (TDZ)?</h3><p>The Temporal Dead Zone is the period between when a variable is declared (using let or const) and when it is initialized. During this time, accessing the variable results in a ReferenceError.</p><h3>Example:</h3><pre>console.log(z); // ReferenceError: Cannot access &#39;z&#39; before initialization<br>let z = 30;</pre><p>Here:</p><ul><li>The variable z is in the TDZ from the start of the block until the line let z = 30; is executed.</li><li>Accessing z before initialization throws an error.</li></ul><h3>2. When Did TDZ Appear?</h3><p>The Temporal Dead Zone was introduced in <strong>ES6 (ECMAScript 2015)</strong> as part of the new variable declarations let and const. Before ES6, JavaScript only had var, which didn’t have a TDZ. The introduction of TDZ was a deliberate design choice to make JavaScript more robust and less error-prone.</p><h3>3. Why Does TDZ Exist?</h3><p>The TDZ might seem like an unnecessary complication, but it serves an important purpose:</p><h3>1. Prevent Bugs</h3><ul><li>With var, variables are hoisted and initialized with undefined, which can lead to subtle bugs.</li><li>TDZ ensures that variables cannot be accessed before they are properly initialized.</li></ul><h3>2. Encourage Best Practices</h3><ul><li>TDZ encourages developers to declare variables at the top of their scope, making code more predictable and easier to debug.</li></ul><h3>3. Distinguish let/const from var</h3><ul><li>Unlike var, which can lead to unexpected behavior, let and const provide a safer and more predictable way to declare variables.</li></ul><h3>4. What is Hoisting?</h3><p>To fully understand the TDZ, it’s important to understand <strong>hoisting</strong>. Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. However, <strong>only the declarations are hoisted, not the initializations</strong>.</p><h3>Example with var:</h3><pre>console.log(x); // undefined<br>var x = 10;</pre><p>Here’s what happens:</p><ol><li>The declaration var x is hoisted to the top.</li><li>The variable x is initialized with undefined by default.</li><li>The assignment x = 10 happens later.</li></ol><h3>Example with let and const:</h3><pre>console.log(y); // ReferenceError: Cannot access &#39;y&#39; before initialization<br>let y = 20;</pre><p>Here’s what happens:</p><ol><li>The declaration let y is hoisted to the top.</li><li>However, y is not initialized (unlike var).</li><li>Accessing y before initialization results in a ReferenceError.</li></ol><h3>5. Differences Between let, const, and var</h3><p>Understanding the differences between these variable declarations is key to avoiding the TDZ.</p><h3>var:</h3><ul><li><strong>Scope</strong>: Function-scoped or globally-scoped.</li><li><strong>Hoisting</strong>: Hoisted and initialized with undefined.</li><li><strong>Reassignment</strong>: Can be reassigned.</li><li><strong>Redeclaration</strong>: Can be redeclared in the same scope.</li></ul><h3>let:</h3><ul><li><strong>Scope</strong>: Block-scoped (e.g., inside {}, if, for).</li><li><strong>Hoisting</strong>: Hoisted but not initialized (TDZ applies).</li><li><strong>Reassignment</strong>: Can be reassigned.</li><li><strong>Redeclaration</strong>: Cannot be redeclared in the same scope.</li></ul><h3>const:</h3><ul><li><strong>Scope</strong>: Block-scoped.</li><li><strong>Hoisting</strong>: Hoisted but not initialized (TDZ applies).</li><li><strong>Reassignment</strong>: Cannot be reassigned (must be initialized at declaration).</li><li><strong>Redeclaration</strong>: Cannot be redeclared in the same scope.</li></ul><h3>6. How to Avoid TDZ Issues</h3><p>Here are some practical tips to avoid TDZ-related errors:</p><h3>1. Declare Variables at the Top of the Scope</h3><pre>let x = 10;<br>console.log(x); // Works fine</pre><h3>2. Use const for Constants</h3><ul><li>If a variable’s value won’t change, use const to make your intent clear.</li></ul><pre>const PI = 3.14;</pre><h3>3. Be Mindful of Block Scopes</h3><ul><li>Pay attention to block scopes when using let and const.</li></ul><h3>7. Conclusion</h3><p>The Temporal Dead Zone is a key concept in JavaScript that ensures variables declared with let and const are used correctly. While it might seem confusing at first, understanding TDZ can help you write cleaner, more predictable code. By following best practices like declaring variables at the top of their scope and using const for constants, you can avoid TDZ-related errors and become a more confident JavaScript developer.</p><p>If you found this post helpful, feel free to share it with your fellow developers! Have you encountered the Temporal Dead Zone in your projects? Let me know in the comments below. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28c305988364" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Healthy Angular Project Recipes: Building a Maintainable and Scalable Application]]></title>
            <link>https://medium.com/@majed.bannouri12/healthy-angular-project-recipes-building-a-maintainable-and-scalable-application-c249f9661f41?source=rss-83e66847f193------2</link>
            <guid isPermaLink="false">https://medium.com/p/c249f9661f41</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Majed Bannouri]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 21:52:08 GMT</pubDate>
            <atom:updated>2025-02-22T21:52:08.560Z</atom:updated>
            <content:encoded><![CDATA[<p>Just like a balanced diet is essential for a healthy lifestyle, a well-structured Angular project is crucial for building maintainable, scalable, and efficient applications. Just as you carefully select ingredients, follow recipes, and avoid unhealthy habits to create nutritious meals, you need to choose the right tools, follow best practices, and avoid common pitfalls to craft a robust Angular project.</p><p>In this article, we’ll explore the <strong>“recipes”</strong> for building a healthy Angular project. From organizing your project structure to optimizing performance and ensuring accessibility, we’ll cover everything you need to create a project that’s not only functional but also easy to maintain and scale. Let’s dive into the kitchen of Angular development and cook up something amazing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*KWCxDmZ_McfaATmSfkKraQ.png" /></figure><h3>1. Project Structure: The Foundation of a Healthy Angular Project</h3><p>Just as a strong foundation is key to a sturdy house, a well-organized project structure is the backbone of a healthy Angular application. Here’s how to structure your project for maximum maintainability:</p><h3>1.1. Root-Level Structure</h3><ul><li><strong>src/</strong>: The main pantry where all your ingredients (source code) are stored.</li><li><strong>app/</strong>: The kitchen where the magic happens—your modules, components, and services.</li><li><strong>assets/</strong>: The spice rack—static assets like images, fonts, and JSON files.</li><li><strong>environments/</strong>: The recipe book—environment-specific configurations.</li><li>environment.ts (development)</li><li>environment.prod.ts (production)</li><li><strong>styles/</strong>: The seasoning—global styles and themes.</li><li><strong>main.ts</strong>: The chef’s table—the entry point of your application.</li></ul><h3>1.2. Feature-Based Module Structure</h3><p>Organize your application into feature modules, just like you’d organize a meal into courses. Here’s a clear folder structure for a typical Angular project:</p><pre>src/<br>├── app/<br>│   ├── core/                  # Core functionality (singleton services, interceptors, guards)<br>│   │   ├── guards/            # Route guards (e.g., auth.guard.ts)<br>│   │   ├── interceptors/      # HTTP interceptors (e.g., auth.interceptor.ts)<br>│   │   ├── services/          # Core services (e.g., auth.service.ts)<br>│   │   └── core.module.ts     # Core module<br>│   │<br>│   ├── shared/                # Shared components, directives, and pipes<br>│   │   ├── components/        # Shared components (e.g., header.component.ts)<br>│   │   ├── directives/        # Shared directives (e.g., highlight.directive.ts)<br>│   │   ├── pipes/             # Shared pipes (e.g., custom-date.pipe.ts)<br>│   │   └── shared.module.ts   # Shared module<br>│   │<br>│   ├── features/              # Feature modules (e.g., user, dashboard, products)<br>│   │   ├── user/              # User feature module<br>│   │   │   ├── components/    # User-related components (e.g., user-list.component.ts)<br>│   │   │   ├── services/      # User-related services (e.g., user.service.ts)<br>│   │   │   ├── models/        # User-related models (e.g., user.model.ts)<br>│   │   │   ├── user-routing.module.ts # User routing<br>│   │   │   └── user.module.ts # User module<br>│   │   │<br>│   │   ├── dashboard/         # Dashboard feature module<br>│   │   │   ├── components/    # Dashboard-related components<br>│   │   │   ├── services/      # Dashboard-related services<br>│   │   │   ├── dashboard-routing.module.ts # Dashboard routing<br>│   │   │   └── dashboard.module.ts # Dashboard module<br>│   │   │<br>│   │   └── products/          # Products feature module<br>│   │       ├── components/    # Product-related components<br>│   │       ├── services/      # Product-related services<br>│   │       ├── products-routing.module.ts # Products routing<br>│   │       └── products.module.ts # Products module<br>│   │<br>│   ├── app-routing.module.ts  # Main routing configuration<br>│   └── app.module.ts          # Root module<br>│<br>├── assets/                    # Static assets (images, fonts, JSON files)<br>├── environments/              # Environment configurations<br>│   ├── environment.ts         # Development environment<br>│   └── environment.prod.ts    # Production environment<br>├── styles/                    # Global styles and themes<br>└── main.ts                    # Entry point of the application</pre><h3>1.3. Naming Conventions</h3><ul><li>Use <strong>kebab-case</strong> for file names (e.g., user-profile.component.ts).</li><li>Use <strong>PascalCase</strong> for class names (e.g., UserProfileComponent).</li><li>Use <strong>camelCase</strong> for variable and method names.</li></ul><h3>2. Best Practices: The Recipe for Success</h3><p>Just as following a recipe ensures a delicious meal, adhering to Angular best practices ensures a healthy project. Here are some key practices:</p><h3>2.1. Use Angular CLI</h3><p>Angular CLI is your kitchen assistant — it ensures consistency and saves time.</p><pre>ng generate component user-profile<br>ng generate service auth</pre><h3>2.2. Lazy Loading</h3><p>Lazy loading is like cooking only what you need — it improves performance by loading only the necessary code.</p><pre>// app/app-routing.module.ts<br>const routes: Routes = [<br>  { path: &#39;dashboard&#39;, loadChildren: () =&gt; import(&#39;./features/dashboard/dashboard.module&#39;).then(m =&gt; m.DashboardModule) }<br>];</pre><h3>2.3. Use Standalone Components (Angular 14+)</h3><p>Standalone components are like pre-portioned ingredients — they reduce the need for NgModule and make your code more modular.</p><pre>// app/user-profile.component.ts<br>@Component({<br>  standalone: true,<br>  selector: &#39;app-user-profile&#39;,<br>  template: `&lt;p&gt;User Profile&lt;/p&gt;`<br>})<br>export class UserProfileComponent {}</pre><h3>2.4. Use Pipes for Data Transformation</h3><p>Pipes are like kitchen gadgets — they transform data without modifying the original ingredients.</p><pre>// app/shared/pipes/custom-date.pipe.ts<br>@Pipe({ name: &#39;customDate&#39; })<br>export class CustomDatePipe implements PipeTransform {<br>  transform(value: string): string {<br>    return new Date(value).toLocaleDateString();<br>  }<br>}</pre><pre>&lt;!-- app/user-profile.component.html --&gt;<br>&lt;p&gt;{{ user.createdAt | customDate }}&lt;/p&gt;</pre><h3>2.5. Avoid Logic in Templates</h3><p>Keep your templates clean, just like you’d keep your kitchen counter tidy. Move logic to component methods or services.</p><h3>2.6. Use Change Detection Strategies</h3><p>Optimize performance by using OnPush change detection—it’s like cooking only when the ingredients change.</p><pre>// app/user-list.component.ts<br>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  template: `...`<br>})<br>export class UserListComponent {}</pre><h3>3. Performance Optimization: Cooking Up a Fast Application</h3><p>Just as a well-organized kitchen speeds up cooking, performance optimization ensures your application runs smoothly.</p><h3>3.1. Lazy Loading Modules</h3><p>Lazy loading ensures you only cook what’s needed, reducing the initial load time.</p><pre>// app/app-routing.module.ts<br>const routes: Routes = [<br>  { path: &#39;dashboard&#39;, loadChildren: () =&gt; import(&#39;./features/dashboard/dashboard.module&#39;).then(m =&gt; m.DashboardModule) }<br>];</pre><h3>3.2. OnPush Change Detection</h3><p>Using OnPush is like cooking only when the ingredients change—it prevents unnecessary work.</p><pre>// app/user-list.component.ts<br>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  template: `...`<br>})<br>export class UserListComponent {}</pre><h3>3.3. TrackBy in ngFor</h3><p>When rendering lists, use trackBy to avoid re-rendering the entire list—it’s like reusing prepped ingredients.</p><pre>&lt;!-- app/user-list.component.html --&gt;<br>&lt;div *ngFor=&quot;let user of users; trackBy: trackByUserId&quot;&gt;<br>  {{ user.name }}<br>&lt;/div&gt;</pre><pre>// app/user-list.component.ts<br>trackByUserId(index: number, user: User) {<br>  return user.id;<br>}</pre><h3>3.4. Use hidden Instead of *ngIf</h3><p>Use the hidden attribute for simple visibility toggling instead of *ngIf when the element is frequently shown/hidden. This avoids destroying and recreating the DOM element, which can be costly.</p><pre>&lt;!-- app/user-list.component.html --&gt;<br>&lt;div [hidden]=&quot;!isVisible&quot;&gt;<br>  This content is hidden or shown without destroying the DOM.<br>&lt;/div&gt;</pre><h3>3.5. AOT (Ahead-of-Time) Compilation</h3><p>AOT compilation is like prepping ingredients before cooking — it reduces the size of your application and improves runtime performance.</p><pre>ng build --prod</pre><h3>3.6. Pure Pipes</h3><p>Pure pipes are like pre-measured ingredients — they only recalculate when their input changes.</p><pre>// app/shared/pipes/custom-date.pipe.ts<br>@Pipe({ name: &#39;customDate&#39;, pure: true })<br>export class CustomDatePipe implements PipeTransform {<br>  transform(value: string): string {<br>    return new Date(value).toLocaleDateString();<br>  }<br>}</pre><h3>3.7. Avoid Heavy Computations in Templates</h3><p>Move heavy computations to component methods or services — it’s like using a food processor instead of chopping by hand.</p><h3>4. Accessibility (a11y): Serving Everyone</h3><p>Just as a good meal is accessible to everyone, your application should be usable by all, including people with disabilities.</p><h3>4.1. Use Semantic HTML</h3><p>Semantic HTML is like using the right utensils — it improves accessibility and structure.</p><pre>&lt;header&gt;<br>  &lt;h1&gt;My App&lt;/h1&gt;<br>  &lt;nav&gt;<br>    &lt;a routerLink=&quot;/home&quot;&gt;Home&lt;/a&gt;<br>    &lt;a routerLink=&quot;/about&quot;&gt;About&lt;/a&gt;<br>  &lt;/nav&gt;<br>&lt;/header&gt;</pre><h3>4.2. ARIA Attributes</h3><p>ARIA attributes are like labels on your ingredients — they make dynamic content accessible.</p><pre>&lt;button aria-label=&quot;Close&quot; (click)=&quot;close()&quot;&gt;X&lt;/button&gt;</pre><h3>4.3. Keyboard Navigation</h3><p>Ensure all interactive elements are keyboard-navigable — it’s like making sure everyone can reach the table.</p><pre>&lt;button tabindex=&quot;0&quot; (click)=&quot;submit()&quot;&gt;Submit&lt;/button&gt;</pre><h3>4.4. Angular Accessibility Tools</h3><p>Angular provides built-in support for accessibility:</p><ul><li>Use ngAria to automatically add ARIA attributes.</li><li>Use @angular/cdk/a11y for focus management and screen reader support.</li></ul><h3>5. Pre-Commit Hooks: Keeping Your Kitchen Clean</h3><p>Just as you clean your kitchen after cooking, pre-commit hooks ensure your code is clean and consistent.</p><h3>5.1. Install Husky and lint-staged</h3><pre>npm install husky lint-staged --save-dev</pre><h3>5.2. Configure Husky</h3><p>Add a pre-commit hook to run linting and formatting.</p><pre>// package.json<br>&quot;husky&quot;: {<br>  &quot;hooks&quot;: {<br>    &quot;pre-commit&quot;: &quot;lint-staged&quot;<br>  }<br>},<br>&quot;lint-staged&quot;: {<br>  &quot;*.ts&quot;: [&quot;eslint --fix&quot;, &quot;prettier --write&quot;]<br>}</pre><h3>5.3. Conventional Commit Messages</h3><p>Use a consistent commit message format like:</p><pre>feat(user): add user profile component<br>fix(auth): resolve login issue<br>chore: update dependencies</pre><h3>6. Common Pitfalls: Avoiding Kitchen Disasters</h3><p>Even experienced chefs make mistakes. Here’s how to avoid common Angular pitfalls:</p><h3>6.1. Memory Leaks from Unsubscribed Observables</h3><p>Always unsubscribe from observables to prevent memory leaks.</p><pre>// app/user-list.component.ts<br>private destroy$ = new Subject&lt;void&gt;();<br><br>ngOnInit() {<br>  this.userService.getUsers().pipe(<br>    takeUntil(this.destroy$)<br>  ).subscribe(users =&gt; this.users = users);<br>}<br><br>ngOnDestroy() {<br>  this.destroy$.next();<br>  this.destroy$.complete();<br>}</pre><h3>6.2. Overloading Components</h3><p>Avoid putting too much logic in components — it’s like overloading a dish with too many ingredients.</p><h3>6.3. Overusing ngOnChanges</h3><p>Instead of relying on ngOnChanges, use observables and reactive programming patterns.</p><pre>// Bad: Overusing ngOnChanges<br>ngOnChanges(changes: SimpleChanges) {<br>  if (changes[&#39;input&#39;]) {<br>    this.processInput(changes[&#39;input&#39;].currentValue);<br>  }<br>}</pre><pre>// Better: Use observables<br>this.input$.pipe(<br>  distinctUntilChanged(),<br>  switchMap(input =&gt; this.processInput(input))<br>).subscribe();</pre><h3>6.4. Ignoring Error Handling</h3><p>Always handle errors in HTTP requests and other asynchronous operations — it’s like tasting your food before serving.</p><pre>// app/user.service.ts<br>this.userService.getUsers().pipe(<br>  catchError(error =&gt; {<br>    console.error(&#39;Error fetching users:&#39;, error);<br>    return of([]); // Provide a fallback value<br>  })<br>).subscribe(users =&gt; this.users = users);</pre><h3>7. Conclusion</h3><p>Building a healthy Angular project is like preparing a nutritious meal — it requires the right ingredients, careful preparation, and attention to detail. By following the recipes in this article, you can create a project that’s not only functional but also maintainable, scalable, and efficient. Bon appétit! 🍽️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c249f9661f41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Of CORS you’re blocked!]]></title>
            <link>https://medium.com/@majed.bannouri12/of-cors-youre-blocked-bb803f1b6b68?source=rss-83e66847f193------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb803f1b6b68</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Majed Bannouri]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 08:19:13 GMT</pubDate>
            <atom:updated>2025-02-03T08:22:12.250Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, let me tell you a story. Imagine you’re visiting a secure mansion. You walk up to the door, knock, and wait. A security guard opens the door, checks who you are, and decides whether to let you in. Sounds simple, right? Well, this is exactly how CORS (Cross-Origin Resource Sharing) works in the world of web development. Let’s break it down together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQrwFaoELFGDTflaTq2t5Q.jpeg" /></figure><p><strong>1. The Knock: Preflight Requests</strong></p><p>So, you knock on the mansion’s door. The security guard opens it and asks:<br>“Hey, who are you? What do you need? Are you bringing anything with you?” This is like a preflight request in CORS.</p><p><strong>What’s a Preflight Request?</strong></p><ul><li>It’s an OPTIONS request sent by the browser to the server. The browser is basically saying: <em>&quot;Hey, can I come in with this </em><em>POST request and these headers?&quot;</em></li><li>The server responds with a set of rules, like: <em>“Sure, but only if you’re from </em><em>https://yourwebsite.com and you&#39;re not bringing anything suspicious.&quot;</em></li><li><strong>When Does This Happen?</strong><br>Preflight requests are triggered for <strong>non-simple requests</strong>, such as:</li><li>Using HTTP methods like PUT or DELETE.</li><li>Sending custom headers like Authorization or Content-Type: application/json.</li></ul><p><strong>2. The Secret Handshake: CORS Headers</strong></p><p>Now, the security guard has some rules for visitors. These rules are like the <strong>secret handshake</strong> that ensures only the right people can enter, under the right conditions. In CORS, these rules are communicated through <strong>headers</strong>.</p><ul><li><strong>Access-Control-Allow-Origin</strong>:<br>Specifies which origins are allowed (e.g., https://yourwebsite.com).<br>Example: <em>&quot;You can come in, but only if you&#39;re from </em><em>https://yourwebsite.com.&quot;</em></li><li><strong>Access-Control-Allow-Methods</strong>:<br>Lists the HTTP methods allowed (e.g., GET, POST, PUT).<br>Example: <em>&quot;You can bring a </em><em>POST request, but not a </em><em>DELETE.&quot;</em></li><li><strong>Access-Control-Allow-Headers</strong>:<br>Lists the headers allowed in the request (e.g., Content-Type, Authorization).<br>Example: <em>&quot;You can bring </em><em>Authorization and </em><em>Content-Type, but nothing else.&quot;</em></li><li><strong>Access-Control-Max-Age</strong>:<br>Specifies how long the preflight response can be cached (e.g., 24 hours).<br>Example: <em>&quot;This handshake is valid for 24 hours. After that, you&#39;ll need to knock again.&quot;</em></li></ul><p><strong>3. When the Door Stays Closed: CORS Errors</strong></p><p>Sometimes, the security guard might say no. Maybe you’re not on the guest list, or you’re trying to bring something they don’t allow. When that happens, you’re left standing outside, wondering what went wrong. In CORS, this is when you see a <strong>CORS error</strong>.</p><ul><li><strong>Unauthorized Origin</strong>:<br>The server doesn’t recognize the browser’s origin.<br>Example: <em>“Sorry, I don’t know you. You can’t come in.”</em></li><li><strong>Unsupported Method</strong>:<br>The browser tries to use a method the server doesn’t allow (e.g., DELETE).<br>Example: <em>&quot;You can&#39;t bring a </em><em>DELETE request. Only </em><em>GET and </em><em>POST are allowed.&quot;</em></li><li><strong>Missing Headers</strong>:<br>The browser sends headers the server doesn’t allow (e.g., Authorization).<br>Example: <em>&quot;You can&#39;t bring </em><em>Authorization. That&#39;s not allowed here.&quot;</em></li></ul><p><strong>4. Unlocking the Door: Fixing CORS Issues</strong></p><p>To fix the issue, you need to follow the rules. Make sure you’re on the guest list, bring only what’s allowed, and respect the time limits. Once you do that, the door opens, and you’re welcome inside. In CORS, this means configuring the server correctly.</p><p><strong>Server-Side Configuration:</strong><br>Set the right headers (e.g., Access-Control-Allow-Origin, Access-Control-Allow-Methods).<br>Example in Node.js (Express):</p><pre>app.use((req, res, next) =&gt; {<br>  res.header(&#39;Access-Control-Allow-Origin&#39;, &#39;https://yourwebsite.com&#39;);<br>  res.header(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, PUT&#39;);<br>  res.header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);<br>  if (req.method === &#39;OPTIONS&#39;) {<br>    return res.sendStatus(200); // Respond to preflight requests<br>  }<br>  next();<br>});</pre><p><strong>Client-Side Checks:</strong><br>Ensure your frontend code is sending the correct headers and credentials.</p><p><strong>5. Conclusion: Mastering the Art of CORS</strong></p><p><strong>Visualizing the Analogy</strong></p><p>To make this even clearer, imagine this scene:</p><ol><li>The browser knocks on the server’s door.</li><li>The server checks the browser’s credentials and responds with the rules.</li><li>If everything checks out, the door opens, and the browser enters.</li></ol><p>CORS might seem complicated at first, but it’s just a <strong>security system</strong> to protect servers from unauthorized access. By understanding the <strong>door analogy</strong> — the knock, the secret handshake, and the rules — you can unlock the door and make your cross-origin requests work seamlessly.<br>So the next time you see a CORS error, remember: it’s just the server saying, <em>“Hey, let’s make sure we’re on the same page before you come in.”</em> With the right configuration, you’ll be able to open that door and let your requests flow freely.</p><p>If you’re encountering CORS issues, take the time to review your server-side and client-side setup. Make sure your headers align, the methods are correct, and your origins are authorized. Once you’ve done that, the security guard will let you right in!</p><p>Feel free to experiment with these concepts on your own projects, and don’t hesitate to reach out if you’re stuck. Mastering CORS will save you time and headache in the long run. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb803f1b6b68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>