<?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 Mohamed Mamdouh  on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Mamdouh  on Medium]]></description>
        <link>https://medium.com/@mamdouhibr67?source=rss-61ecdba46abb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O1Vk2MWUNei86TwdigJHwA@2x.jpeg</url>
            <title>Stories by Mohamed Mamdouh  on Medium</title>
            <link>https://medium.com/@mamdouhibr67?source=rss-61ecdba46abb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 07:20:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mamdouhibr67/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[Stop Fighting Your State: The Angular NgRx + SignalStore Hybrid Architecture]]></title>
            <link>https://medium.com/@mamdouhibr67/stop-fighting-your-state-the-angular-ngrx-signalstore-hybrid-architecture-2c0c949c0b6b?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c0c949c0b6b</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[ngrx-signalstore]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 21:15:39 GMT</pubDate>
            <atom:updated>2026-07-22T21:15:39.796Z</atom:updated>
            <content:encoded><![CDATA[<p>Every Angular developer has stared at a sprawling NgRx codebase and thought, “Do I really need an Action, Reducer, Effect, and Selector just to toggle a dropdown or manage a multi-step form?”</p><p>For years, we accepted the boilerplate because the predictable, event-driven architecture of NgRx kept our enterprise applications from collapsing into chaos. But when the Angular team introduced Signals, the community started asking a dangerous question: Should we abandon traditional NgRx entirely?</p><p>The answer is a resounding no.</p><p>The new gold standard in modern Angular architecture isn’t about choosing between global event-driven state and local reactive state. It’s about seamlessly combining them. Here is how to build a scalable, developer-friendly architecture using traditional NgRx for global orchestration and the new NgRx SignalStore for highly reactive, local feature state.</p><p>The Core Philosophy: Two Brains are Better Than One</p><p>To understand this architecture, you have to stop looking at state as a single monolith. Your application actually has two different “nervous systems,” and they need different tools.</p><ol><li>The Global Nervous System (Traditional NgRx)</li></ol><p>This is your app’s central hub. It is event-driven, declarative, and shared. Components here don’t mutate state; they shout into the void that something happened (e.g., ⁠[Auth] User Logged In⁠), and the global store decides how to react.</p><p>What lives here?</p><p>User authentication and permissions.</p><p>Application-wide settings (dark mode, language preferences).</p><p>Shared entity caches used across completely unrelated features.</p><p>Cross-cutting events (handling 401 Unauthorized API responses via Effects).</p><p>2. The Local Brain (NgRx SignalStore)</p><p>This is the state tied directly to a specific feature or route. It is method-based, imperative, and highly reactive. It lives and dies with the component or route it serves.</p><p>What lives here?</p><p>The data currently loaded in a specific data grid or dashboard.</p><p>Pagination, sorting, and filtering parameters for a single page.</p><p>Complex, multi-step form state.</p><p>Direct API orchestrations for a localized feature.</p><p>The Blueprint: Folder Structure</p><p>When you mix paradigms, your boundaries must be visually obvious the second a developer opens the repository. We lean heavily into Domain-Driven Design (DDD) to keep the global state pure and the feature states isolated.</p><pre>src/app/<br>│<br>├── core/                        # 🌍 THE GLOBAL ZONE (Loaded on startup)<br>│   ├── services/                <br>│   └── state/                   # Traditional NgRx<br>│       ├── app.state.ts         <br>│       ├── auth/                <br>│       │   ├── auth.actions.ts<br>│       │   ├── auth.effects.ts<br>│       │   └── auth.reducer.ts<br>│<br>├── shared/                      # 🧱 REUSABLE UI (Dumb components only)<br>│   └── components/              <br>│       └── ui-button/           # No state injected here!<br>│<br>└── features/                    # 🧩 THE FEATURE ZONE (Lazy-loaded)<br>    │<br>    └── profile/                 <br>        ├── components/          <br>        ├── services/            <br>        ├── profile.routes.ts    <br>        └── store/               # Local SignalStore<br>            └── profile.store.ts <br></pre><p>The Golden Rule: Features are completely selfish. The ⁠profile⁠ feature is never allowed to import a SignalStore from the ⁠orders⁠ feature. If they need to communicate, the feature must dispatch a global action.</p><p>Building the Bridge: How They Talk</p><p>The true power of this architecture is how easily these two systems interact. Because both are built for the modern Angular ecosystem, your local SignalStore can inject the global ⁠Store⁠ to read global context and dispatch global events.</p><p>Let’s look at a practical example. Imagine a ⁠ProfileStore⁠ (our local SignalStore) that needs to update a user’s avatar. It needs the ⁠userId⁠ from the Global Store to make the API call, and once successful, it needs to dispatch a global action so the app’s top navigation bar updates the user’s picture.</p><pre>import { inject } from &#39;@angular/core&#39;;<br>import { Store } from &#39;@ngrx/store&#39;;<br>import { signalStore, withState, withMethods, patchState, withComputed } from &#39;@ngrx/signals&#39;;<br>import { rxMethod } from &#39;@ngrx/signals/rxjs-interop&#39;;<br>import { pipe, switchMap, tap } from &#39;rxjs&#39;;<br><br>// 1. Import Global State selectors and actions<br>import { selectUserId } from &#39;../../core/state/auth/auth.selectors&#39;;<br>import { AuthActions } from &#39;../../core/state/auth/auth.actions&#39;;<br>import { ProfileApiService } from &#39;../services/profile-api.service&#39;;<br><br>interface ProfileState {<br>  isUploading: boolean;<br>  uploadError: string | null;<br>}<br><br>const initialState: ProfileState = {<br>  isUploading: false,<br>  uploadError: null,<br>};<br><br>export const ProfileStore = signalStore(<br>  withState(initialState),<br>  <br>  // 2. Read from the Global Store using computed signals<br>  withComputed((_, globalStore = inject(Store)) =&gt; ({<br>    currentUserId: globalStore.selectSignal(selectUserId)<br>  })),<br><br>  withMethods((<br>    store, <br>    api = inject(ProfileApiService), <br>    globalStore = inject(Store) // Inject the global NgRx Store<br>  ) =&gt; ({<br>    <br>    // 3. Imperative method called directly by the UI component<br>    updateAvatar: rxMethod&lt;File&gt;(<br>      pipe(<br>        tap(() =&gt; patchState(store, { isUploading: true, uploadError: null })),<br>        switchMap((file) =&gt; {<br>          // Use the computed signal derived from global state<br>          const userId = store.currentUserId(); <br>          <br>          return api.uploadAvatar(userId, file).pipe(<br>            tap({<br>              next: (response) =&gt; {<br>                patchState(store, { isUploading: false });<br>                <br>                // 4. Dispatch to the Global Store so the rest of the app reacts!<br>                globalStore.dispatch(AuthActions.avatarUpdated({ newUrl: response.url }));<br>              },<br>              error: (err) =&gt; {<br>                patchState(store, { isUploading: false, uploadError: err.message });<br>              }<br>            })<br>          );<br>        })<br>      )<br>    )<br>  }))<br>);<br></pre><p>Why this is a game-changer:</p><ol><li>Zero Global Clutter: The global store doesn’t need to know about ⁠isUploading⁠ or ⁠uploadError⁠. That transient UI state is handled perfectly by the local SignalStore.</li><li>2. Strict Traceability: The moment the avatar actually changes, a formal action (⁠[Auth] Avatar Updated⁠) is dispatched globally, allowing the Redux DevTools to track the data flow across the app.</li><li>3. Incredible DX: The component developer just calls ⁠profileStore.updateAvatar(file)⁠. They don’t have to wire up complex effects or track loading selectors.</li><li>The Takeaway</li><li>By marrying traditional NgRx with the new SignalStore, you get the best of both worlds. You retain the strict, event-driven traceability required to keep an enterprise app stable, while recovering the rapid, imperative developer experience that makes building individual features actually fun again.</li><li>Stop fighting the boilerplate, and start putting your state where it actually belongs.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c0c949c0b6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Component Doesn’t Know What Color It Is. That’s the Whole Trick.]]></title>
            <link>https://medium.com/@mamdouhibr67/your-component-doesnt-know-what-color-it-is-that-s-the-whole-trick-6d43ff099c7a?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d43ff099c7a</guid>
            <category><![CDATA[angular-material]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[style-guides]]></category>
            <category><![CDATA[primeng]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 23:35:49 GMT</pubDate>
            <atom:updated>2026-06-30T23:35:49.800Z</atom:updated>
            <content:encoded><![CDATA[<h3>A component should know what it is. It should never know what it looks like.</h3><p>Here’s an uncomfortable question. Open your last Angular component. The one with the button, or the card, or the modal. Now look at the .ts file.</p><p>Does it know it’s blue?</p><p>Does it know it has 8px of padding? Does it know its border radius is 6px and not 4px?</p><p>If the answer is yes — if your component’s logic file has any opinion at all about how it looks — I want you to sit with that for a second. Because Angular Material doesn’t do that. PrimeNG doesn’t do that. And there’s a reason every component library that survives more than one design refresh follows the same rule.</p><h3>A component should know what it is. It should never know what it looks like.</h3><p>That’s it. That’s the whole article, really. Everything below is just me proving it to you with code.</p><h3>The Sin We All Commit</h3><p>Let’s not pretend this is a strawman. Here’s what 90% of “reusable” components look like in the wild:</p><pre>@Component({<br>  template: `<br>    &lt;button [ngStyle]=&quot;{<br>      &#39;background&#39;: disabled ? &#39;#ccc&#39; : &#39;#3b82f6&#39;,<br>      &#39;padding&#39;: size === &#39;sm&#39; ? &#39;4px 8px&#39; : &#39;8px 16px&#39;,<br>      &#39;border-radius&#39;: &#39;6px&#39;<br>    }&quot;&gt;<br>      &lt;ng-content&gt;&lt;/ng-content&gt;<br>    &lt;/button&gt;<br>  `<br>})<br>export class ButtonComponent {<br>  @Input() disabled = false;<br>  @Input() size: &#39;sm&#39; | &#39;md&#39; = &#39;md&#39;;<br>}<br></pre><p>It works. Ship it, right?</p><p>Six months later, design comes back and says the brand is changing from blue to a deep teal. Now you’re grepping your entire codebase for #3b82f6. You find it in fourteen components. Three of them spelled it slightly differently. One of them is actually #3b82f7 because someone fat-fingered a hex code in 2023 and nobody noticed.</p><p>This isn’t a styling bug. It’s an architecture bug. You let presentation leak into logic, and now the two are welded together so tightly that changing one means surgery on the other.</p><p>Angular Material took one look at this problem in 2017 and said: never again.</p><h3>The Rule That Changes Everything</h3><p>Here it is, the one sentence worth bookmarking:</p><blockquote>Components emit state. Stylesheets interpret state. Never let the wires cross.</blockquote><p>A button doesn’t say “I am blue.” A button says “I am primary.” Somewhere else — far away, in a file the component has never met — something decides what primary means today.</p><p>This is the difference between a component and a vocabulary. Material and PrimeNG aren’t shipping you components. They’re shipping you a vocabulary of semantic states, plus a translator that turns that vocabulary into pixels. Swap the translator, keep the vocabulary, and the entire visual identity of your app changes without a single component file being touched.</p><p>Let’s build it.</p><h3>Step 1: Logic Speaks Only in Semantics</h3><pre>@Component({<br>  selector: &#39;ui-button&#39;,<br>  standalone: true,<br>  templateUrl: &#39;./button.component.html&#39;,<br>  styleUrl: &#39;./button.component.scss&#39;,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  host: {<br>    &#39;class&#39;: &#39;ui-button&#39;,<br>    &#39;[class.ui-button--disabled]&#39;: &#39;disabled()&#39;,<br>    &#39;[attr.data-variant]&#39;: &#39;variant()&#39;,<br>    &#39;[attr.data-size]&#39;: &#39;size()&#39;,<br>    &#39;[attr.aria-disabled]&#39;: &#39;disabled() || null&#39;,<br>  }<br>})<br>export class ButtonComponent {<br>  variant = input&lt;&#39;primary&#39; | &#39;secondary&#39; | &#39;danger&#39;&gt;(&#39;primary&#39;);<br>  size = input&lt;&#39;sm&#39; | &#39;md&#39; | &#39;lg&#39;&gt;(&#39;md&#39;);<br>  disabled = input(false);<br>}<br></pre><p>Read that host block again. There is not one color, one pixel value, one hex code anywhere in this file. Every line answers the question “what is this button,” never “how does it look.” That’s not an accident — that’s the discipline.</p><p>If you ever find yourself reaching for [ngStyle] or [style.background] inside component logic, stop. You’re about to weld the wires together. Don’t.</p><h3>Step 2: Tokens — The Vocabulary Itself</h3><p>This is the part most people skip, and it’s the part that actually matters. Don’t go straight from “primitive color” to “component.” Put a translator in between. Three layers, every time:</p><pre>// Layer 1 — Primitives. Raw values. Nobody outside this file should see these.<br>:root {<br>  --blue-500: #3b82f6;<br>  --space-2: 0.5rem;<br>  --space-4: 1rem;<br>  --radius-md: 6px;<br>}<br><br>// Layer 2 — Semantic. What the value *means* in your design system.<br>:root {<br>  --color-primary: var(--blue-500);<br>  --color-on-primary: white;<br>  --radius-default: var(--radius-md);<br>}<br><br>// Layer 3 — Component. What the value means to *this specific component*.<br>.ui-button {<br>  --button-bg: var(--color-primary);<br>  --button-color: var(--color-on-primary);<br>  --button-radius: var(--radius-default);<br>}<br></pre><p>Three layers feels like overkill until the day your design team rebrands. Then it feels like the only decision you got right all year. Change Layer 1, and Layers 2 and 3 update for free — every button, every card, every component in your library, all at once, with zero component code touched.</p><p>This is precisely what Angular Material did when it moved to Material Design 3. The components didn’t change. The token layer underneath them did.</p><h3>Step 3: Style Reads State, Never the Reverse</h3><pre>.ui-button {<br>  background: var(--button-bg);<br>  color: var(--button-color);<br>  border-radius: var(--button-radius);<br>  transition: background 0.15s ease;<br><br>  &amp;--disabled {<br>    background: var(--gray-300);<br>    cursor: not-allowed;<br>  }<br><br>  &amp;[data-variant=&#39;danger&#39;] {<br>    --button-bg: var(--color-danger);<br>  }<br><br>  &amp;[data-size=&#39;sm&#39;] {<br>    --button-bg: var(--button-bg);<br>    padding: var(--space-2);<br>  }<br>}<br></pre><p>Notice what’s happening in [data-variant=’danger’]. It doesn’t write new CSS properties. It reassigns the token. The component still only ever reads — button-bg. It has no idea that “danger” exists as a concept. It just knows its background is whatever the token says, and the token’s value depends on an attribute the component itself exposed — without ever interpreting what that attribute means.</p><p>That separation is the entire ballgame. Logic exposes facts. Style assigns meaning to facts. Neither one does the other’s job.</p><h3>Why This Is the Difference Between a Component and a Liability</h3><p>Skip this pattern, and here’s your future, guaranteed:</p><p>•	Rebrand request → grep-and-replace across 40 files, pray nothing breaks.</p><p>•	Dark mode request → duplicate every component with a -dark variant, double your maintenance surface.</p><p>•	White-label request → fork the entire library.</p><p>Follow this pattern, and here’s the same future:</p><p>•	Rebrand → edit one token file.</p><p>•	Dark mode → swap the semantic layer based on a media query or a class on &lt;html&gt;. Done.</p><p>•	White-label → ship a different token file per client. Same components, zero forks.</p><p>This is not a styling preference. It’s the difference between a system that scales and a system that accumulates technical debt every single sprint until someone proposes a rewrite.</p><h3>The Three Commandments</h3><p>If you remember nothing else, remember these:</p><p>1.	A component’s TypeScript and template never contain a color, a size, or a spacing literal. Not one. If you typed a hex code into a .ts file, you already lost.</p><p>2.	A component’s stylesheet never reads @Input() values directly. It reads the classes and attributes the component already exposed, and resolves those against tokens.</p><p>3.	Tokens are layered — primitive, semantic, component — so a rebrand only ever touches the top two layers. The component layer is sacred. Don’t touch it for a color change. Ever.</p><p>Angular Material didn’t get lucky. PrimeNG didn’t get lucky. They followed these three rules with religious discipline, and it’s why both libraries have survived multiple design-language rewrites without their consumers having to rewrite a single line of application code.</p><p>Your component library can do the same thing. It just has to stop knowing what color it is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d43ff099c7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fix you angular LCP problem for dynamic hero image]]></title>
            <link>https://medium.com/@mamdouhibr67/fix-you-angular-lcp-problem-for-dynamic-hero-image-fd927cd5cb44?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd927cd5cb44</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[lcp]]></category>
            <category><![CDATA[optimize-web-performance]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 02:05:01 GMT</pubDate>
            <atom:updated>2026-03-12T02:05:01.448Z</atom:updated>
            <content:encoded><![CDATA[<p>How SSR Fixes Your Angular LCP Problem</p><p>A practical guide to dynamic images, TransferState, and caching</p><p>If your Angular app fetches an image URL from a CMS before it can display the hero image, you almost certainly have a poor LCP (Largest Contentful Paint) score. This article explains exactly why that happens, how SSR (Server-Side Rendering) fixes it, and what you need to know about TransferState and caching to make it production-ready.</p><p>Understanding the Problem</p><p>LCP measures how long it takes for the largest visible element on the page – usually a hero image – to appear. When that image URL is dynamic and must be fetched from a CMS API, your browser has to go through a painful waterfall before the image even starts loading:</p><ul><li>Browser downloads your HTML shell and JavaScript bundle</li><li>• Angular bootstraps and runs your component</li><li>• Your component makes an HTTP call to the CMS to get the image URL</li><li>• The browser finally starts fetching the actual image</li></ul><p>Every step in that chain adds latency before the image appears. On a slow device or slow network – exactly the conditions Google measures for Core Web Vitals – this can easily push LCP beyond the 2.5 second threshold.</p><p>Why SSR Helps</p><p>With Server-Side Rendering, Angular runs on a Node.js server before the response is sent to the browser. This fundamentally changes the sequence:</p><p>• The Node.js server runs your component, including the HTTP call to the CMS</p><p>• The server gets the image URL and renders the full HTML, including the &lt;img&gt; tag with the real src already embedded</p><p>• The browser receives that pre-rendered HTML and immediately starts fetching the image – before any JavaScript has even been parsed</p><p>The key insight is that the image fetch always happens in the browser – SSR does not move image delivery to the server. What SSR does is give the browser the image URL earlier, so the fetch can start sooner.</p><p>What the Browser Receives</p><p>Without SSR (CSR):</p><p>&lt;app-hero&gt;&lt;/app-hero&gt;. &lt;! – empty shell, Angular fills this in later – &gt;</p><p>With SSR:</p><p>&lt;app-hero&gt;</p><p>&lt;img src=” https://cdn.cms.com/hero-banner.jp”</p><p>. alt=”Hero Banner”</p><p>. fetchpriority=”high” /&gt;</p><p>&lt;/app-hero&gt;</p><p>That src being present in the initial HTML is everything. The browser can start the image fetch in parallel with downloading the JavaScript bundle, instead of waiting for Angular to run first.</p><p>Server-to-Server Calls Are Faster</p><p>When your SSR server calls the CMS, it is a server-to-server call, not a browser-to-server call. This is typically much faster for several reasons:</p><p>• Network proximity: Your SSR server and CMS are likely in the same cloud region. Latency between them can be single-digit milliseconds. A user in a different country hitting the CMS directly could be 150 – 300ms.</p><p>• Connection reuse: The SSR server maintains a persistent HTTP/2 connection pool to the CMS. Each browser user starts fresh with a new TCP and TLS handshake.</p><p>• No user network variability: Server infrastructure is on a stable, high-bandwidth connection. Users could be on mobile with poor signal.</p><p>So SSR does not just move the CMS call off the browser’s critical path – it also resolves that call faster, meaning the rendered HTML arrives sooner.</p><p>The Code: Before and After</p><p>Before SSR (CSR)</p><p>@Component({</p><p>selector: “app-hero”,</p><p>template: `</p><p>. &lt;img *ngIf=”imageUrl” [src]=”imageUrl” alt=”Hero Banner” /&gt;</p><p>`</p><p>})</p><p>export class HeroComponent implements OnInit {</p><p>imageUrl: string | null = null;</p><p>constructor(private http: HttpClient) {}</p><p>ngOnInit() {</p><p>. this.http.get&lt;{ imageUrl: string }&gt;(“/api/cms/hero-image”)</p><p>. .subscribe(res =&gt; {</p><p>. this.imageUrl = res.imageUrl;</p><p>. });</p><p>}</p><p>}</p><p>The component makes the HTTP call in ngOnInit, which only runs after Angular has fully bootstrapped in the browser. The image URL is unknown until then.</p><p>After SSR (with TransferState)</p><p>@Component({</p><p>selector: “app-hero”,</p><p>template: `</p><p>. &lt;img *ngIf=”imageUrl” [src]=”imageUrl”</p><p>. alt=”Hero Banner” fetchpriority=”high” /&gt;</p><p>`</p><p>})</p><p>export class HeroComponent implements OnInit {</p><p>imageUrl: string | null = null;</p><p>private IMAGE_KEY = makeStateKey&lt;string&gt;(“hero-image-url”);</p><p>constructor(</p><p>. private http: HttpClient,</p><p>. private transferState: TransferState</p><p>) {}</p><p>ngOnInit() {</p><p>. // On the client: reuse what the server already fetched</p><p>. if (this.transferState.hasKey(this.IMAGE_KEY)) {</p><p>. this.imageUrl = this.transferState.get(this.IMAGE_KEY, null);</p><p>. this.transferState.remove(this.IMAGE_KEY);</p><p>. return;</p><p>. }</p><p>. // On the server: fetch and store in TransferState</p><p>. this.http.get&lt;{ imageUrl: string }&gt;(“/api/cms/hero-image”)</p><p>. .subscribe(res =&gt; {</p><p>. this.imageUrl = res.imageUrl;</p><p>. this.transferState.set(this.IMAGE_KEY, res.imageUrl);</p><p>. });</p><p>}</p><p>}</p><p>What is TransferState?</p><p>With SSR, ngOnInit runs twice – once on the server during render, and once on the client during hydration. Without TransferState, this means two HTTP calls to your CMS, which defeats part of the benefit.</p><p>TransferState is Angular’s solution. It is a key-value store that lets the server pass data to the client, embedded directly inside the HTML as a script tag:</p><p>&lt;script id=”serverApp-state” type=”application/json”&gt;</p><p>{“hero-image-url”:”ghttps://cdn.cms.com/hero-banner.jp”}</p><p>&lt;/script&gt;</p><p>When Angular hydrates on the client, it reads that script tag. The data is available instantly – no extra HTTP call needed. The flow looks like this:</p><p>SERVER</p><p>│</p><p>├── ngOnInit runs</p><p>├── HTTP call to CMS → gets image URL</p><p>├── transferState.set(“hero-image-url”, url)</p><p>├── Renders &lt;img src=”…”&gt; into HTML</p><p>└── Sends HTML to browser (with state script tag embedded)</p><p>BROWSER</p><p>│</p><p>├── Parses HTML → sees &lt;img src=”…”&gt; → starts image fetch immediately</p><p>├── Downloads JS bundle</p><p>├── Angular hydrates</p><p>├── ngOnInit runs again</p><p>├── transferState.hasKey(“hero-image-url”) → true</p><p>└── Uses the value directly – skips the HTTP call ✓</p><p>The SSR Tradeoff: TTFB vs LCP</p><p>SSR is not a free win. The user is blocked from receiving any HTML until the server finishes the CMS call and completes the render. This increases Time to First Byte (TTFB).</p><p>. CSR. SSR</p><p>─────────────────────. ─────────────────────</p><p>TTFB. Fast. Slower (waits for CMS)</p><p>Image. Late. Early (in initial HTML)</p><p>LCP. Poor. Much better</p><p>Whether SSR wins overall depends on how fast your CMS call is and how slow the user’s device is at bootstrapping Angular. On slow devices or slow networks, SSR almost always wins because Angular bootstrap is expensive. On fast devices with a slow CMS, CSR might show the image sooner.</p><p>The solution is caching – which removes the TTFB penalty almost entirely.</p><p>Caching the CMS Response</p><p>If you cache the CMS response on your SSR server, subsequent users pay no extra wait time at all. The flow becomes:</p><p>First request:</p><p>Server → CMS call (500ms) → cache result → respond</p><p>All subsequent requests (within TTL):</p><p>Server → cache hit (1ms) → respond immediately</p><p>In-Memory Cache (Simple)</p><p>// cache.ts</p><p>interface CacheEntry&lt;T&gt; {</p><p>value: T;</p><p>expiresAt: number;</p><p>}</p><p>export class SimpleCache {</p><p>private store = new Map&lt;string, CacheEntry&lt;any&gt;&gt;();</p><p>get&lt;T&gt;(key: string): T | null {</p><p>. const entry = this.store.get(key);</p><p>. if (!entry) return null;</p><p>. if (Date.now() &gt; entry.expiresAt) {</p><p>. this.store.delete(key);</p><p>. return null;</p><p>. }</p><p>. return entry.value;</p><p>}</p><p>set&lt;T&gt;(key: string, value: T, ttlMs: number): void {</p><p>. this.store.set(key, {</p><p>. value,</p><p>. expiresAt: Date.now() + ttlMs</p><p>. });</p><p>}</p><p>}</p><p>export const cache = new SimpleCache();</p><p>Redis Cache (Production)</p><p>// redis-cache.ts</p><p>import { createClient } from “redis”;</p><p>const client = createClient({ url: process.env.REDIS_URL });</p><p>client.connect();</p><p>export async function getFromCache&lt;T&gt;(key: string): Promise&lt;T | null&gt; {</p><p>const value = await client.get(key);</p><p>return value ? JSON.parse(value) : null;</p><p>}</p><p>export async function setInCache&lt;T&gt;(</p><p>key: string,</p><p>value: T,</p><p>ttlSeconds: number</p><p>): Promise&lt;void&gt; {</p><p>await client.set(key, JSON.stringify(value), { EX: ttlSeconds });</p><p>}</p><p>Use in-memory cache for single-instance or development environments. Use Redis in production – especially if you run multiple SSR instances – because Redis is shared across all instances while in-memory cache is not.</p><p>Where to Deploy the SSR Server</p><p>CSR Angular apps are just static files – you can host them on S3, Netlify, or any CDN. SSR changes this fundamentally. You now have a running Node.js/Express process that needs to stay alive.</p><p>• If your team already manages backend infrastructure (Spring, Node API), deploy the SSR Express app alongside it</p><p>• For containerized deployments: Docker on AWS ECS, Google Cloud Run, or Azure Container Apps</p><p>• For zero-ops: Vercel and Netlify both support Angular SSR automatically – point them at your repo and they handle the rest</p><p>• For serverless: Angular SSR can be adapted to run on AWS Lambda</p><p>Key Takeaways</p><p>• LCP suffers when the browser has to wait for Angular to bootstrap before it knows the image URL</p><p>• SSR pre-renders the HTML on the server, embedding the image URL so the browser can start fetching immediately</p><p>• The CMS HTTP call happens server-to-server during SSR render – faster due to network proximity and connection reuse</p><p>• The image itself always downloads to the browser – SSR only changes when the browser gets the URL</p><p>• ngOnInit runs twice with SSR (server + client); use TransferState to avoid making the CMS call twice</p><p>• SSR increases TTFB – always pair it with a cache layer to eliminate the penalty for most users</p><p>g</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd927cd5cb44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript’s Biggest Regret? Replace enum for as const]]></title>
            <link>https://medium.com/@mamdouhibr67/typescripts-biggest-regret-replace-enum-for-as-const-70814c7fa20e?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/70814c7fa20e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 19:21:34 GMT</pubDate>
            <atom:updated>2025-11-30T19:21:34.935Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re focusing on how to handle constant values in TypeScript. You know, things that never change, like status names (‘LOADING’, ‘ERROR’) or specific route paths.</p><p>For many years, the standard way to handle these values while keeping strong type safety was the TypeScript enum.</p><pre>// The classic Enum approach<br>enum Status {<br>  LOADING = &#39;LOADING&#39;,<br>  SUCCESS = &#39;SUCCESS&#39;,<br>  ERROR = &#39;ERROR&#39;,<br>}<br><br>// Usage: Status.LOADING<br></pre><p>The Unnecessary Weight of the enum</p><p>When TypeScript compiles your code into simple JavaScript, the enum is not treated lightly.</p><p>It creates a substantial block of JavaScript code (often an object wrapper) just to handle things you might not even need, like reverse mapping (the ability to look up the key from the value).</p><p>This means every enum you define adds extra, often unused code to your final application bundle.</p><h3>The Lean Solution: const with as const</h3><p>The modern, lighter approach uses a standard JavaScript object combined with the powerful as const assertion.</p><p>This method gives us the runtime simplicity of JavaScript with the same powerful compile-time safety of TypeScript.</p><pre>// The modern, lightweight approach<br>export const Status = {<br>  LOADING: &#39;LOADING&#39;,<br>  SUCCESS: &#39;SUCCESS&#39;,<br>  ERROR: &#39;ERROR&#39;,<br>} as const; <br>// The &#39;as const&#39; tells TypeScript these values are fixed!<br><br>// Usage: Status.LOADING<br></pre><h3>Getting Perfect Type Safety</h3><pre>export type StatusType = typeof Status[keyof typeof Status]; <br>// StatusType is now: &quot;LOADING&quot; | &quot;SUCCESS&quot; | &quot;ERROR&quot;<br></pre><p>This is a win-win: Maximum type safety with minimum runtime cost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70814c7fa20e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unrepresentable Invalid State with complete NGRX example]]></title>
            <link>https://medium.com/@mamdouhibr67/unrepresentable-invalid-state-with-complete-ngrx-example-01d283e82c32?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/01d283e82c32</guid>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 15:43:24 GMT</pubDate>
            <atom:updated>2025-11-23T15:43:24.121Z</atom:updated>
            <content:encoded><![CDATA[<h2>Unrepresentable Invalid State and complete NGRX example</h2><p>One of the cleanest ways to reduce complexity in applications is to design your state in a way that invalid situations simply cannot exist. This idea is often described as:</p><p>Make invalid states impossible to represent.</p><p>It sounds fancy, but the idea is simple:</p><p>When your model allows impossible combinations of data, your code becomes full of defensive checks.</p><p>But when your model only allows valid states, TypeScript itself can guide and protect you through type narrowing.</p><p>This is not just about correctness.</p><p>It’s about developer experience, clearer UI logic, and removing dozens of unnecessary if conditions.</p><p>⸻</p><p>❌ The Classic Problem: Boolean Flags + Nullable Fields</p><p>Let’s start with something like a user-loading flow:</p><pre>interface UserState {<br>  user: User | null;<br>  loading: boolean;<br>  error: string | null;<br>}</pre><p>This looks normal, but TypeScript doesn’t know how these values relate.</p><p>We can accidentally represent situations that should never happen:</p><p>•	loading = true and error = “timeout”</p><p>•	user !== null and error !== null</p><p>•	loading = false, error = null, user = null → what state is that?</p><p>These impossible combinations leak everywhere — into selectors, into components, into effects.</p><p>Your UI now has to defensively write checks like:</p><pre>if (state.user &amp;&amp; !state.loading &amp;&amp; !state.error) {<br>  // ...<br>}</pre><p>This is where complexity snowballs.</p><p>✅ The Transform: Model Real Domain States</p><p>Instead, model your state as a union of valid states:</p><pre>type UserState =<br>  | { status: &#39;idle&#39; }<br>  | { status: &#39;loading&#39; }<br>  | { status: &#39;success&#39;; user: User }<br>  | { status: &#39;error&#39;; message: string };</pre><p>Now TypeScript understands your assumptions.</p><p>There is no way to create a state where both user and message exist.</p><p>There is no way to have status: ‘loading’ with an error.</p><p>There is no way to “forget” a required field.</p><p>Everything is encoded in the type itself.</p><p>🎯 The Magic: Type Narrowing Becomes Natural</p><p>When you switch on this state:</p><pre>switch (state.status) {<br>  case &#39;success&#39;:<br>    console.log(state.user); // &lt;-- Fully typed, cannot be null<br>    break;<br>  case &#39;error&#39;:<br>    console.log(state.message); // &lt;-- Always available<br>    break;<br>}</pre><p>No optional chaining.</p><p>No “what if this is null?”</p><p>No type guards.</p><p>No guessing.</p><p>TypeScript knows what exists based on the status value.</p><p>This is exhaustive type narrowing, and it eliminates a whole category of UI bugs.</p><p>In contrast, with the old shape:</p><pre>state.user // might be null<br>state.error // might be null<br>state.loading // might conflict with other fields</pre><p>TypeScript cannot help you, because you allowed contradictory states.</p><p>🧠 Example #1: Payment Form</p><p>Bad model:</p><pre>interface PaymentState {<br>  submitted: boolean;<br>  valid: boolean;<br>  cardNumber: string | null;<br>  expiry: string | null;<br>  cvc: string | null;<br>}</pre><p>Too many invalid combos:</p><p>•	form is submitted but invalid</p><p>•	valid = true but cardNumber = null</p><p>•	submitted = false but valid = false → what does that mean?</p><p>Better model:</p><pre>type PaymentState =<br>  | { status: &#39;incomplete&#39; }<br>  | { status: &#39;invalid&#39;; errors: string[] }<br>  | { status: &#39;valid&#39;; cardNumber: string; expiry: string; cvc: string };</pre><p>Now:</p><p>•	If status is valid, all fields exist — no checking.</p><p>•	If status is invalid, errors must exist.</p><p>•	If status is incomplete, nothing else is accessible.</p><p>And TypeScript automatically narrows based on status.</p><pre>// ============================================<br>// 1. ENTITY TYPE DEFINITIONS<br>// ============================================<br>export interface User {<br>id: number;<br>name: string;<br>email: string;<br>}<br><br>export interface Product {<br>id: number;<br>name: string;<br>price: number;<br>category: string;<br>}<br><br>// ============================================<br>// 2. INDIVIDUAL ENTITY STATES (Discriminated Unions)<br>// ============================================<br><br>// Users State<br>export type UsersState =<br>| { status: ‘idle’ }<br>| { status: ‘loading’ }<br>| { status: ‘success’; data: User[] }<br>| { status: ‘error’; error: string };<br><br>// Products State  <br>export type ProductsState =<br>| { status: ‘idle’ }<br>| { status: ‘loading’ }<br>| { status: ‘success’; data: Product[] }<br>| { status: ‘error’; error: string };<br><br>// ============================================<br>// 3. SHARED/FEATURE STATE (Combines Everything)<br>// ============================================<br>export interface SharedState {<br>users: UsersState;<br>products: ProductsState;<br>}<br><br>// Initial state for the entire feature<br>export const initialSharedState: SharedState = {<br>users: { status: ‘idle’ },<br>products: { status: ‘idle’ }<br>};<br><br>// ============================================<br>// 4. ACTIONS - Users<br>// ============================================<br>import { createAction, props } from ‘@ngrx/store’;<br><br>export const loadUsers = createAction(’[Shared] Load Users’);<br>export const loadUsersSuccess = createAction(<br>‘[Shared API] Load Users Success’,<br>props&lt;{ data: User[] }&gt;()<br>);<br>export const loadUsersFailure = createAction(<br>‘[Shared API] Load Users Failure’,<br>props&lt;{ error: string }&gt;()<br>);<br>export const resetUsers = createAction(’[Shared] Reset Users’);<br><br>// ============================================<br>// 5. ACTIONS - Products<br>// ============================================<br>export const loadProducts = createAction(’[Shared] Load Products’);<br>export const loadProductsSuccess = createAction(<br>‘[Shared API] Load Products Success’,<br>props&lt;{ data: Product[] }&gt;()<br>);<br>export const loadProductsFailure = createAction(<br>‘[Shared API] Load Products Failure’,<br>props&lt;{ error: string }&gt;()<br>);<br>export const resetProducts = createAction(’[Shared] Reset Products’);<br><br>// ============================================<br>// 6. REDUCER - Combined<br>// ============================================<br>import { createReducer, on } from ‘@ngrx/store’;<br><br>export const sharedReducer = createReducer(<br>initialSharedState,<br><br>// Users Actions<br>on(loadUsers, (state) =&gt; ({<br>…state,<br>users: { status: ‘loading’ }<br>})),<br><br>on(loadUsersSuccess, (state, { data }) =&gt; ({<br>…state,<br>users: { status: ‘success’, data }<br>})),<br><br>on(loadUsersFailure, (state, { error }) =&gt; ({<br>…state,<br>users: { status: ‘error’, error }<br>})),<br><br>on(resetUsers, (state) =&gt; ({<br>…state,<br>users: { status: ‘idle’ }<br>})),<br><br>// Products Actions<br>on(loadProducts, (state) =&gt; ({<br>…state,<br>products: { status: ‘loading’ }<br>})),<br><br>on(loadProductsSuccess, (state, { data }) =&gt; ({<br>…state,<br>products: { status: ‘success’, data }<br>})),<br><br>on(loadProductsFailure, (state, { error }) =&gt; ({<br>…state,<br>products: { status: ‘error’, error }<br>})),<br><br>on(resetProducts, (state) =&gt; ({<br>…state,<br>products: { status: ‘idle’ }<br>}))<br>);<br><br>// ============================================<br>// 7. SELECTORS<br>// ============================================<br>import { createFeatureSelector, createSelector } from ‘@ngrx/store’;<br><br>// Select the entire shared state<br>export const selectSharedState = createFeatureSelector&lt;SharedState&gt;(‘shared’);<br><br>// Select just the users state<br>export const selectUsersState = createSelector(<br>selectSharedState,<br>(state) =&gt; state.users<br>);<br><br>// Select just the products state<br>export const selectProductsState = createSelector(<br>selectSharedState,<br>(state) =&gt; state.products<br>);<br><br>// ============================================<br>// 8. EFFECTS - Users<br>// ============================================<br>import { Injectable } from ‘@angular/core’;<br>import { Actions, createEffect, ofType } from ‘@ngrx/effects’;<br>import { of } from ‘rxjs’;<br>import { map, catchError, switchMap } from ‘rxjs/operators’;<br><br>@Injectable()<br>export class SharedEffects {<br><br>loadUsers$ = createEffect(() =&gt;<br>this.actions$.pipe(<br>ofType(loadUsers),<br>switchMap(() =&gt;<br>this.dataService.getUsers().pipe(<br>map(users =&gt; loadUsersSuccess({ data: users })),<br>catchError(error =&gt; of(loadUsersFailure({ error: error.message })))<br>)<br>)<br>)<br>);<br><br>loadProducts$ = createEffect(() =&gt;<br>this.actions$.pipe(<br>ofType(loadProducts),<br>switchMap(() =&gt;<br>this.dataService.getProducts().pipe(<br>map(products =&gt; loadProductsSuccess({ data: products })),<br>catchError(error =&gt; of(loadProductsFailure({ error: error.message })))<br>)<br>)<br>)<br>);<br><br>constructor(<br>private actions$: Actions,<br>private dataService: DataService<br>) {}<br>}<br><br>// ============================================<br>// 9. SERVICE (Mock)<br>// ============================================<br>import { Injectable } from ‘@angular/core’;<br>import { Observable, of } from ‘rxjs’;<br>import { delay } from ‘rxjs/operators’;<br><br>@Injectable({ providedIn: ‘root’ })<br>export class DataService {<br>getUsers(): Observable&lt;User[]&gt; {<br>const mockUsers: User[] = [<br>{ id: 1, name: ‘John Doe’, email: ‘john@example.com’ },<br>{ id: 2, name: ‘Jane Smith’, email: ‘jane@example.com’ }<br>];<br>return of(mockUsers).pipe(delay(1000));<br>}<br><br>getProducts(): Observable&lt;Product[]&gt; {<br>const mockProducts: Product[] = [<br>{ id: 1, name: ‘Laptop’, price: 999, category: ‘Electronics’ },<br>{ id: 2, name: ‘Mouse’, price: 29, category: ‘Accessories’ },<br>{ id: 3, name: ‘Keyboard’, price: 79, category: ‘Accessories’ }<br>];<br>return of(mockProducts).pipe(delay(1500));<br>}<br>}<br><br>// ============================================<br>// 10. COMPONENT - Using Both States<br>// ============================================<br>import { Component } from ‘@angular/core’;<br>import { Store } from ‘@ngrx/store’;<br>import { Observable } from ‘rxjs’;<br><br>@Component({<br>selector: ‘app-dashboard’,<br>template: `<br>&lt;div class=&quot;dashboard&quot;&gt;<br>&lt;h1&gt;Dashboard&lt;/h1&gt;<br><br>```<br> &lt;!-- Users Section --&gt;<br> &lt;section class=&quot;section&quot;&gt;<br>   &lt;h2&gt;Users&lt;/h2&gt;<br>   &lt;button (click)=&quot;onLoadUsers()&quot;&gt;Load Users&lt;/button&gt;<br>   &lt;button (click)=&quot;onResetUsers()&quot;&gt;Reset Users&lt;/button&gt;<br>   <br>   &lt;ng-container *ngIf=&quot;usersState$ | async as usersState&quot;&gt;<br>     &lt;div [ngSwitch]=&quot;usersState.status&quot;&gt;<br>       <br>       &lt;div *ngSwitchCase=&quot;&#39;idle&#39;&quot;&gt;<br>         No users loaded. Click &quot;Load Users&quot; to fetch.<br>       &lt;/div&gt;<br>       <br>       &lt;div *ngSwitchCase=&quot;&#39;loading&#39;&quot;&gt;<br>         Loading users...<br>       &lt;/div&gt;<br>       <br>       &lt;div *ngSwitchCase=&quot;&#39;error&#39;&quot; class=&quot;error&quot;&gt;<br>         Users Error: {{ usersState.error }}<br>       &lt;/div&gt;<br>       <br>       &lt;ul *ngSwitchCase=&quot;&#39;success&#39;&quot;&gt;<br>         &lt;li *ngFor=&quot;let user of usersState.data&quot;&gt;<br>           {{ user.name }} - {{ user.email }}<br>         &lt;/li&gt;<br>       &lt;/ul&gt;<br>       <br>     &lt;/div&gt;<br>   &lt;/ng-container&gt;<br> &lt;/section&gt;<br> <br> &lt;!-- Products Section --&gt;<br> &lt;section class=&quot;section&quot;&gt;<br>   &lt;h2&gt;Products&lt;/h2&gt;<br>   &lt;button (click)=&quot;onLoadProducts()&quot;&gt;Load Products&lt;/button&gt;<br>   &lt;button (click)=&quot;onResetProducts()&quot;&gt;Reset Products&lt;/button&gt;<br>   <br>   &lt;ng-container *ngIf=&quot;productsState$ | async as productsState&quot;&gt;<br>     &lt;div [ngSwitch]=&quot;productsState.status&quot;&gt;<br>       <br>       &lt;div *ngSwitchCase=&quot;&#39;idle&#39;&quot;&gt;<br>         No products loaded. Click &quot;Load Products&quot; to fetch.<br>       &lt;/div&gt;<br>       <br>       &lt;div *ngSwitchCase=&quot;&#39;loading&#39;&quot;&gt;<br>         Loading products...<br>       &lt;/div&gt;<br>       <br>       &lt;div *ngSwitchCase=&quot;&#39;error&#39;&quot; class=&quot;error&quot;&gt;<br>         Products Error: {{ productsState.error }}<br>       &lt;/div&gt;<br>       <br>       &lt;div *ngSwitchCase=&quot;&#39;success&#39;&quot;&gt;<br>         &lt;table&gt;<br>           &lt;thead&gt;<br>             &lt;tr&gt;<br>               &lt;th&gt;Name&lt;/th&gt;<br>               &lt;th&gt;Category&lt;/th&gt;<br>               &lt;th&gt;Price&lt;/th&gt;<br>             &lt;/tr&gt;<br>           &lt;/thead&gt;<br>           &lt;tbody&gt;<br>             &lt;tr *ngFor=&quot;let product of productsState.data&quot;&gt;<br>               &lt;td&gt;{{ product.name }}&lt;/td&gt;<br>               &lt;td&gt;{{ product.category }}&lt;/td&gt;<br>               &lt;td&gt;\${{ product.price }}&lt;/td&gt;<br>             &lt;/tr&gt;<br>           &lt;/tbody&gt;<br>         &lt;/table&gt;<br>       &lt;/div&gt;<br>       <br>     &lt;/div&gt;<br>   &lt;/ng-container&gt;<br> &lt;/section&gt;<br> <br> &lt;!-- Combined View Example --&gt;<br> &lt;section class=&quot;section&quot; *ngIf=&quot;sharedState$ | async as shared&quot;&gt;<br>   &lt;h2&gt;Summary&lt;/h2&gt;<br>   &lt;p&gt;Users: {{ shared.users.status }}&lt;/p&gt;<br>   &lt;p&gt;Products: {{ shared.products.status }}&lt;/p&gt;<br> &lt;/section&gt;<br> <br>&lt;/div&gt;<br>```<br><br>`, styles: [`<br>.dashboard {<br>padding: 20px;<br>font-family: Arial, sans-serif;<br>}<br><br>```<br>.section {<br> margin: 20px 0;<br> padding: 15px;<br> border: 1px solid #ddd;<br> border-radius: 8px;<br>}<br><br>button {<br> margin: 5px;<br> padding: 8px 16px;<br> cursor: pointer;<br>}<br><br>.error {<br> color: red;<br> padding: 10px;<br> background: #fee;<br> border: 1px solid red;<br> border-radius: 4px;<br> margin: 10px 0;<br>}<br><br>table {<br> width: 100%;<br> border-collapse: collapse;<br> margin: 10px 0;<br>}<br><br>th, td {<br> padding: 8px;<br> text-align: left;<br> border-bottom: 1px solid #ddd;<br>}<br><br>th {<br> background-color: #f5f5f5;<br> font-weight: bold;<br>}<br>```<br><br>`]<br>})<br>export class DashboardComponent {<br>// Select individual entity states<br>usersState$: Observable&lt;UsersState&gt;;<br>productsState$: Observable&lt;ProductsState&gt;;<br><br>// Or select the entire shared state if needed<br>sharedState$: Observable&lt;SharedState&gt;;<br><br>constructor(private store: Store) {<br>this.usersState$ = this.store.select(selectUsersState);<br>this.productsState$ = this.store.select(selectProductsState);<br>this.sharedState$ = this.store.select(selectSharedState);<br>}<br><br>onLoadUsers() {<br>this.store.dispatch(loadUsers());<br>}<br><br>onResetUsers() {<br>this.store.dispatch(resetUsers());<br>}<br><br>onLoadProducts() {<br>this.store.dispatch(loadProducts());<br>}<br><br>onResetProducts() {<br>this.store.dispatch(resetProducts());<br>}<br>}<br><br>// ============================================<br>// 11. MODULE SETUP<br>// ============================================<br>import { NgModule } from ‘@angular/core’;<br>import { StoreModule } from ‘@ngrx/store’;<br>import { EffectsModule } from ‘@ngrx/effects’;<br><br>@NgModule({<br>imports: [<br>StoreModule.forRoot({ shared: sharedReducer }),<br>EffectsModule.forRoot([SharedEffects])<br>]<br>})<br>export class AppModule {}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01d283e82c32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SEO in Angular — Simple Guide with code snippet every angular dev should include]]></title>
            <link>https://medium.com/@mamdouhibr67/seo-in-angular-simple-guide-with-code-snippet-every-angular-dev-should-include-16f1bfe199bc?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/16f1bfe199bc</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 09:47:35 GMT</pubDate>
            <atom:updated>2025-09-29T09:47:35.396Z</atom:updated>
            <content:encoded><![CDATA[<h3>SEO in Angular — Simple Guide with code snippet every angular dev should include</h3><p>When we build apps in Angular, we often forget about SEO. Search engines need to know what each page is about: the title, the description, sometimes even social media tags. If we don’t set them, Google will just guess. And trust me, Google is not good at guessing.</p><p>So, let’s fix this the Angular way.</p><h3>Step 1: Add Data to Your Routes</h3><p>In Angular routing, every route can have a data object. We can store the SEO info there.</p><p>Example:</p><pre>// app-routing.module.ts<br>const routes: Routes = [<br>  {<br>    path: &#39;home&#39;,<br>    component: HomeComponent,<br>    data: {<br>      title: &#39;Home - My Angular App&#39;,<br>      description: &#39;Welcome to our awesome Angular app homepage.&#39;<br>    }<br>  },<br>  {<br>    path: &#39;about&#39;,<br>    component: AboutComponent,<br>    data: {<br>      title: &#39;About Us - My Angular App&#39;,<br>      description: &#39;Learn more about our team and mission.&#39;<br>    }<br>  }<br>];</pre><h3>Step 2: Listen for Route Changes in AppComponent</h3><p>Now we need a place where the app reads this data and sets the title + meta tags. The best place is AppComponent, because it lives as long as the app does.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Router, NavigationEnd, ActivatedRoute } from &#39;@angular/router&#39;;<br>import { Title, Meta } from &#39;@angular/platform-browser&#39;;<br>import { filter, map } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;<br>})<br>export class AppComponent {<br>  constructor(<br>    private router: Router,<br>    private activatedRoute: ActivatedRoute,<br>    private title: Title,<br>    private meta: Meta<br>  ) {<br>    this.router.events.pipe(<br>      filter(event =&gt; event instanceof NavigationEnd),  // wait until navigation ends<br>      map(() =&gt; {<br>        // Start at the first child route<br>        let route = this.activatedRoute.firstChild;<br>        // Keep going down until the deepest child<br>        while (route?.firstChild) {<br>          route = route.firstChild;<br>        }<br>        // Return the route data<br>        return route?.snapshot.data;<br>      })<br>    ).subscribe(data =&gt; {<br>      if (data?.[&#39;title&#39;]) {<br>        this.title.setTitle(data[&#39;title&#39;]);<br>      }<br>      if (data?.[&#39;description&#39;]) {<br>        this.meta.updateTag({<br>          name: &#39;description&#39;,<br>          content: data[&#39;description&#39;]<br>        });<br>      }<br>    });<br>  }<br>}</pre><h3>Step 3: Understand the Code</h3><pre>let route = this.activatedRoute.firstChild;<br>while (route?.firstChild) {<br>  route = route.firstChild;<br>}<br>return route?.snapshot.data;</pre><ul><li>this.activatedRoute → the top-level route.</li><li>.firstChild → the next active child route.(note first child doesn’t mean the first child in tree becuase the name is a little bit misleading. it mean the active route in next level in the tree)</li><li>The while loop → keeps moving until we reach the <strong>deepest active route</strong> (for nested routes like /products/123/details).</li><li>.snapshot.data → the data object we defined in the route (title, description).</li></ul><h3>Step 4: Result</h3><p>Now, when you navigate to:</p><ul><li>/home → title = “Home - My Angular App”, description updated.</li><li>/about → title = “About Us - My Angular App”, description updated.</li></ul><p>Google and social media will see the correct title + description in the page &lt;head&gt;.</p><h3>Final Note</h3><p>This works perfectly for dynamic client-side SEO.<br>But if you want search engines to index your pages properly, the safer choice is <strong>Angular Universal</strong> (Server-Side Rendering). That makes sure the meta tags are ready before the crawler arrives.</p><p>And that’s it! With just a few lines, you can make your Angular app SEO-friendly using route data and AppComponent logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16f1bfe199bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extend bootstrap]]></title>
            <link>https://medium.com/@mamdouhibr67/extend-bootstrap-3751a0bbc847?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3751a0bbc847</guid>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[sass]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 08:39:56 GMT</pubDate>
            <atom:updated>2025-09-24T08:39:56.105Z</atom:updated>
            <content:encoded><![CDATA[<p>Extend bootstrap</p><p>So, kiddo, you open up that SCSS file and you see this weird thing:</p><pre>$utilities: () !default;</pre><p>And you go: “Wait a sec… why the heck am I making an empty map if I’m just gonna fill it later?!”</p><p>Well, sit tight, I will tell you the tale.</p><p>The Sass Drama</p><p>Here’s how it works:</p><p>•	Normally, when you say $color: red; – boom, $color is red forever unless you overwrite it later.</p><p>•	But when you say $color: red !default; – Sass whispers:</p><p>“Hey… if you’ve already set $color before, I won’t mess with it. If not, I’ll give you red as a backup plan.”</p><p>That’s all !default means: “use me only if nobody else did the job.”</p><p>Why Bootstrap Cares</p><p>Bootstrap is like a big burger restaurant. They give you a ready-made burger ($utilities full of classes like bg-primary, fs-1, rounded).</p><p>But they also know you might want to add your own extra cheese. So they write:</p><pre>$utilities: () !default;<br></pre><p>That way:</p><p>•	If you didn’t bring your own $utilities, you get the Bootstrap burger as-is.</p><p>•	If you did define $utilities earlier, Bootstrap won’t overwrite your recipe.</p><p>map-get + map-merge Trick</p><p>Now, when you see this fancy dance in your code:</p><pre>&quot;background-color&quot;: map-merge(<br>  map-get($utilities, &quot;background-color&quot;),<br>  (<br>    values: map-merge(<br>      map-get(map-get($utilities, &quot;background-color&quot;), &quot;values&quot;),<br>      $myTheme<br>    )<br>  )<br>),</pre><p>Don’t panic.</p><p>All it’s doing is:</p><p>1.	Look at Bootstrap’s burger toppings (map-get).</p><p>2.	Add your own toppings (map-merge).</p><p>3.	Serve it back without throwing away the old flavors.</p><p>So you keep Bootstrap’s defaults plus your custom theme colors.</p><p>So next time you see !default, don’t think “empty.” Think:</p><p>“This is a safety net – Bootstrap left me room to play without breaking the kitchen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3751a0bbc847" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Fighting Angular Material Styles: Meet CSS Layers]]></title>
            <link>https://medium.com/@mamdouhibr67/stop-fighting-angular-material-styles-meet-css-layers-0d7372a4b501?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d7372a4b501</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[angular-material]]></category>
            <category><![CDATA[css-layer]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 22:01:27 GMT</pubDate>
            <atom:updated>2025-09-23T22:01:27.525Z</atom:updated>
            <content:encoded><![CDATA[<p>You know that feeling when you add Angular Material to your project and it looks awesome… until your designer walks in and says:</p><p>“Hey, can we make all the buttons rounder? And by the way, the cards need lighter shadows.”</p><p>Suddenly, you’re in CSS hell.</p><p>You try overriding .mat-mdc-button in styles.scss. It doesn’t work.</p><p>You try .mat-mdc-button.mat-mdc-raised-button. Still nope.</p><p>You throw in !important. Ugly, but it works.</p><p>And before you know it, your stylesheet looks like a battlefield of !important bombs</p><p>Why Is This So Hard?</p><p>Because Angular Material ships with lots of styles.</p><p>And in CSS, when two rules fight, the winner depends on:</p><p>1.	!important</p><p>2.	Selector specificity</p><p>3.	The order in which rules load</p><p>So Material often beats you, unless you cheat with !important.</p><p>Enter CSS Layers 🪄</p><p>Think of layers like stacking boxes.</p><p>Instead of relying on messy “last one wins” rules, you declare the order upfront.</p><p>Example:</p><pre>@layer reset, base, material, overrides;</pre><p>This means:</p><p>•	Reset styles go first</p><p>•	Then base styles</p><p>•	Then Angular Material</p><p>•	And finally, your overrides 💪</p><p>No more guessing, no more !important.</p><p>How It Looks in Angular</p><p>Here’s a clean setup in styles.scss:</p><pre>@layer reset, base, material, overrides;<br><br>// Reset<br>@layer reset {<br>  * { margin: 0; padding: 0; box-sizing: border-box; }<br>}<br><br>// Base<br>@layer base {<br>  body { font-family: Roboto, sans-serif; }<br>}<br><br>// Angular Material in its own layer<br>@layer material {<br>  @use &#39;@angular/material&#39; as mat;<br><br>  $my-theme: mat.define-light-theme((<br>    color: (<br>      primary: mat.define-palette(mat.$indigo-palette),<br>      accent: mat.define-palette(mat.$pink-palette),<br>    ),<br>  ));<br><br>  @include mat.all-component-themes($my-theme);<br>}<br><br>// Your overrides<br>@layer overrides {<br>  .mat-mdc-raised-button {<br>    border-radius: 12px;<br>    background: orange;<br>  }<br><br>  .mat-mdc-card {<br>    box-shadow: none;<br>    border: 1px solid #ddd;<br>  }<br>}</pre><p>Notice something?</p><p>No !important. No weird selector gymnastics.</p><p>Just clean, predictable order.</p><p>The Big Win</p><p>•	✅ Angular Material stays in its own sandbox</p><p>•	✅ Your overrides always win in the overrides layer</p><p>•	✅ Styles are easier to read and maintain</p><p>And most importantly: you can tell your designer “Yes, we can change that” without sweating bullets.</p><p>With CSS layers, you set the rules of the game, and Material politely steps aside when your overrides come in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d7372a4b501" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Peer Dependencies: The Secret Handshake Between Libraries]]></title>
            <link>https://medium.com/@mamdouhibr67/peer-dependencies-the-secret-handshake-between-libraries-1e2fd395a244?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e2fd395a244</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[peer-dependencies]]></category>
            <category><![CDATA[compatibility]]></category>
            <category><![CDATA[packagejson]]></category>
            <category><![CDATA[dependency-management]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 14:48:03 GMT</pubDate>
            <atom:updated>2025-08-07T14:48:03.190Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Avoid Dependency Hell Without Selling Your Soul</h3><p>If you’ve ever added a library to your project only to watch it burst into flames like a vampire in sunlight, you’ve likely met peer dependencies. They’re the polite (but firm) way one library says:</p><blockquote>“Hey, I need this other library to work, but I’m not going to install it for you. That’s your job. Also, it has to be exactly the right version, or I’ll throw a tantrum.”</blockquote><p>Today, we’ll demystify peer dependencies, why they exist, and — most importantly — how to avoid the dreaded “UNMET PEER DEPENDENCY” error that haunts developers like a bad regex.</p><h3>What the Heck Are Peer Dependencies?</h3><p>Imagine you’re at a party (your node_modules folder).</p><ul><li>Dependencies are friends you brought with you. They’re <em>your</em> responsibility.</li><li>DevDependencies are friends who only show up when you’re working (testing, building, etc.).</li><li>Peer Dependencies are friends who say: <em>“I’ll come, but only if my bestie (another library) is already here.”</em></li></ul><p>In npm terms:</p><ul><li>dependencies → <em>&quot;I need this, and I’ll install it myself.&quot;</em></li><li>devDependencies → <em>&quot;I need this, but only when I’m developing.&quot;</em></li><li>peerDependencies → <em>&quot;I need this, but YOU must provide it.&quot;</em></li></ul><h3>Why Not Just Use Regular Dependencies?</h3><p>Because duplicate installations cause chaos.</p><p>Suppose:</p><ul><li>Library A needs lodash@^4.0.0.</li><li>Library B also needs lodash@^4.0.0.</li></ul><p>If both install their own copies, you now have two different lodash instances in memory. This leads to:</p><ul><li>Bloated bundles.</li><li>Weird bugs where lodash functions don’t behave the same.</li></ul><p>Peer dependencies say: <em>“Hey, just use ONE </em><em>lodash, and make sure it’s the right version.&quot;</em></p><h3>Real-World Example: Angular Material</h3><p>Angular Material (@angular/material) is a great example because it depends on Angular core. Let’s say you run:</p><pre>npm install @angular/material@latest</pre><p>Then, you check its peer dependencies:</p><pre>npm info @angular/material peerDependencies</pre><p>You might see something like:</p><pre>{<br>  &quot;@angular/core&quot;: &quot;^16.0.0&quot;,<br>  &quot;@angular/common&quot;: &quot;^16.0.0&quot;,<br>  &quot;@angular/forms&quot;: &quot;^16.0.0&quot;,<br>  // ...etc.<br>}</pre><p>This means:</p><ul><li>Angular Material v16 expects Angular v16.</li><li>If your project uses Angular v15, things will break.</li></ul><h3>How to Check Compatibility</h3><p>Find your current Angular version:</p><pre>ng version<br># or<br>npm list @angular/core</pre><p>Check the library’s peer deps:</p><pre>npm info @angular/material@latest peerDependencies</pre><p>Do they match?</p><ul><li>✅ Yes → Happy coding!</li><li>❌ No → Either:</li></ul><p>1- Upgrade/downgrade your Angular.</p><p>2- Find a version of Angular Material that matches</p><h3>The Golden Rule of Peer Dependencies</h3><blockquote>“Thou shalt not ignore UNMET PEER DEPENDENCY warnings.&quot;</blockquote><ul><li>npm 7+ installs peer deps automatically (but may still complain).</li><li>Yarn and pnpm are stricter (they’ll yell at you).</li></ul><p>If you see:</p><pre>npm WARN @angular/material@16.2.0 requires a peer of @angular/core@^16.0.0 but none is installed.</pre><p>Fix it. Don’t just --force or --legacy-peer-depslike a reckless cowboy.</p><h3>Final Advice</h3><ol><li>Peer dependencies are contracts. Respect them.</li><li>Check compatibility early. Like checking if your parachute works <em>before</em> jumping.</li><li>Use tools like npm-check-updates to automate upgrades wisely.</li></ol><p>Now go forth, and may your node_modules never implode.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e2fd395a244" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Angular Renaissance: What Changed in Angular 17]]></title>
            <link>https://medium.com/@mamdouhibr67/the-angular-renaissance-what-changed-in-angular-17-f5677d66afa2?source=rss-61ecdba46abb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5677d66afa2</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[esbuild]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[build]]></category>
            <dc:creator><![CDATA[Mohamed Mamdouh ]]></dc:creator>
            <pubDate>Mon, 19 May 2025 15:23:19 GMT</pubDate>
            <atom:updated>2025-05-19T15:23:19.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JRPy_zJa1l6TNnBbdAV5w.jpeg" /></figure><p>If you’re an Angular developer who’s been happily running ng serve for years, the recent tooling chatter probably sounds like someone threw a dictionary at you: <em>&quot;ESModules... esbuild... Vite... Webpack... cheese pancakes?&quot;</em> 🥞 (Okay, maybe not that last one). Let&#39;s cut through the noise.</p><p>Alright, alright, settle down, kiddo! Let’s rap about this “bundling” thing like we’re sharing secrets in a back alley.</p><p>See these files, right? We got File A and File B. Now, File A over here, it’s kinda needy. It’s got this itch, this craving for something File B’s got — a special function, see?</p><p>Now, imagine sending little messengers all the time, back and forth, “Hey B, can I borrow that thing?” “Okay, A, here you go!” That’s a lot of running around, yeah? Makes the whole thing kinda slow and clunky.</p><p>So, what do we do? We get smart! We take all these little files — A, B, maybe even C and D — and we smoosh ’em all together into ONE BIG DUDE. One massive file.</p><p>Why the heck would we do that? Simple, see? Instead of sending a whole gang of messengers, we just send ONE. One big request over the internet wire. BAM! One trip, one delivery. Makes everything lightning fast.</p><p>So, yeah, bundling? It’s like taking all your buddies who live down the street and packing ’em into one car instead of everyone taking their own. Fewer trips, faster arrival. Got it, slick?</p><pre>// b.js<br>function addNumbers(x, y) {<br>  return x + y;<br>}<br><br>module.exports = {<br>  addNumbers: addNumbers<br>};</pre><pre>// a.js<br>const b = require(&#39;./b&#39;);<br><br>const num1 = 5;<br>const num2 = 10;<br>const sum = b.addNumbers(num1, num2);<br><br>console.log(`The sum of ${num1} and ${num2} is: ${sum}`);</pre><p>Aha, you’re digging deeper into the nitty-gritty now, that’s what I like to see! So, this whole needing-something-from-another-file thing, you’re right, that was a big part of this old-school way of doing things called CommonJS.</p><p>Think of CommonJS like this: it’s like asking your neighbor for a tool <em>while</em> you’re in the middle of fixing something. You just shout over the fence, “Hey, got a wrench?” It works, right? But nobody knows beforehand what tools you’re gonna need until you actually need ’em. That’s the “dynamic” part you’re talking about. Things get figured out as they go.</p><p>Now, the smart folks came along and said, “Hold on a minute! This makes it tough for the tool guys — the ones who help us build and speed up our projects — to see what’s going on.” They can’t really plan ahead or make things super efficient if they don’t know what pieces are connected until the last second.</p><p>That’s where ES Modules, the new kid on the block, swaggered in. They said, “Nah, we’re gonna do things differently.” They brought in these special keywords: import and export.</p><p>Think of ES Modules like making a detailed shopping list <em>before</em> you go to the store. You write down exactly what you need from each aisle. The store knows exactly what you’re looking for right from the start. That’s the “static” part. The connections between files are declared upfront.</p><p>Because of this upfront declaration, the “tool guys” can now see exactly who needs what, way before the code even runs. This lets them do all sorts of cool optimizations, like shaking things up and making the final bundled file even smaller and faster.</p><p>So, CommonJS got the job done, like borrowing tools on the fly. But ES Modules? They brought in a whole new level of organization and planning, making things much smoother and faster in the long run. You tracking with me?</p><pre>// b.js<br>export function addNumbers(x, y) {<br>  return x + y;<br>}</pre><pre>// a.js<br>import { addNumbers } from &#39;./b.js&#39;;<br><br>const num1 = 5;<br>const num2 = 10;<br>const sum = addNumbers(num1, num2);<br><br>console.log(`The sum of ${num1} and ${num2} is: ${sum}`);</pre><p>Exactly! You’re putting all the pieces together now.</p><p>So, yeah, modern browsers got smart and can now understand ES Modules natively. That’s a big deal! It means, in theory, we could just ship all our individual JavaScript files to the browser, and it would figure out all the import and export connections on its own. No more need for that big bundling step, right?</p><p>Well, not entirely. Even though the browser <em>can</em> handle ES Modules, sending a whole bunch of tiny files still means the browser has to make a separate HTTP request for <em>each</em> one. Imagine your webpage needing, say, 50 different JavaScript files. That’s 50 individual trips the browser has to make to the server! That can still take a while and slow things down, even with fast internet.</p><p>That’s why we <em>still</em> bundle. It’s all about reducing those HTTP requests. Even though the browser understands the individual pieces, delivering one big package is still way more efficient than sending a whole fleet of smaller ones. Less overhead, faster loading times for the user — and a happier user means a happier you!</p><p>Now, you’re asking about <strong>esbuild</strong>. Think of esbuild as the super-speedy delivery guy in this whole scenario. You’ve still got your bunch of files (maybe using ES Modules with all those import and export statements). You <em>still</em> want to bundle them into a smaller number of files (ideally just one) to minimize those HTTP requests.</p><p>But the traditional bundling tools, like Webpack and Rollup, while powerful, can sometimes take their sweet time to do all that processing. They have a lot of features and can do some really complex things, but for the basic job of bundling, they can feel a bit… sluggish.</p><p>Enter esbuild, the speed demon! It’s a brand new tool written in Go (a super-fast programming language). Its main goal is to do the bundling job — taking all your JavaScript (and sometimes CSS and other assets) and squishing them together — incredibly quickly.</p><p>Think of it like this:</p><ul><li><strong>Webpack and Rollup</strong> are like experienced moving companies. They can handle really big and complicated moves, pack everything carefully, and even offer extra services. But sometimes, for a smaller move, they might take a bit longer.</li><li><strong>esbuild</strong> is like a super-efficient delivery service that specializes in quickly packing and shipping boxes. They might not offer all the extra fancy services, but when it comes to getting your stuff bundled and ready to go, they’re lightning fast.</li></ul><p>So, esbuild is a modern bundler that focuses on pure speed, making that crucial step of reducing HTTP requests much, much faster, especially for simpler projects or as a development-time tool. It plays really nicely with the modern ES Module system but still understands the need to bundle for optimal performance in the browser. Make sense?</p><p>Ah, Vite! Now we’re talking about the cool kid on the block, the one that learned some serious lessons from the OGs. You’ve nailed the core idea: Vite takes a different approach, especially during development.</p><p>Think back to our conversation. We talked about how modern browsers understand ES Modules. Vite said, “Hey, if the browser understands it, why are we spending all this time bundling everything <em>during development</em>?”</p><p><strong>Vite’s Smart Split:</strong></p><p>Vite cleverly splits the process into two phases:</p><ul><li><strong>Development:</strong> This is where Vite shines with its speed. Instead of bundling your own source code, it leverages the browser’s native ES Module support. When your browser requests a module, Vite serves it up almost instantly. It’s like having a super-fast waiter who brings you exactly what you ask for, right when you ask for it, without having to prepare a giant buffet beforehand.</li><li>However, it’s still smart about those node_modules – the external libraries you pull in. These often come in different formats that the browser might not understand directly. So, Vite uses <strong>esbuild</strong> under the hood to quickly <em>pre-bundle</em> these dependencies into more browser-friendly formats. This is a one-time, super-fast step. It also uses esbuild for quick tasks like converting TypeScript and JSX into JavaScript. This makes the development server start almost instantly, no matter how big your project gets – a huge improvement over waiting for Webpack to bundle everything!</li><li><strong>Production:</strong> When it’s time to build the final version of your website for the world to see, Vite switches gears and uses <strong>Rollup</strong>. Rollup is another excellent bundler, known for producing highly optimized and smaller bundles for production. Within this production build process, Vite still uses <strong>esbuild</strong> for speedy transpilation and minification (making the code smaller).</li></ul><p><strong>So, to recap Vite’s strategy:</strong></p><ul><li><strong>Fast Development:</strong> Lean on the browser’s ES Modules, use esbuild for quick dependency pre-bundling and transformations.</li><li><strong>Optimized Production:</strong> Use Rollup for the final, efficient bundle, with esbuild helping out with speedier tasks.</li></ul><p><strong>Now, about what we were using before migrating to Vite… you correctly identified it: Webpack.</strong></p><p><strong>Webpack: The Old Faithful</strong></p><p>Webpack has been the king of the frontend build tools for a long time, and for good reason. As you mentioned, it treats <em>everything</em> as a module — JavaScript, CSS, images, fonts, you name it. It builds a dependency graph, figuring out how all these pieces connect, and then bundles them together.</p><p><strong>Key strengths of Webpack:</strong></p><ul><li><strong>Versatility:</strong> It can handle incredibly complex build setups and a wide range of assets.</li><li><strong>Massive Ecosystem:</strong> It boasts a huge collection of plugins and loaders that can handle almost any task you can imagine.</li><li><strong>Mature and Stable:</strong> It’s been around for a while, so it’s very stable and well-documented.</li><li><strong>Advanced Features:</strong> Things like code splitting (breaking your code into smaller chunks for faster initial loading) and Hot Module Replacement (HMR) were pioneered and perfected in Webpack.</li></ul><p><strong>The Trade-off:</strong></p><p>The power and flexibility of Webpack often came with a cost: <strong>build times</strong>, especially for larger projects. Because it had to analyze and bundle everything from the start, the development server could take a significant amount of time to spin up.</p><p><strong>Why the Shift to Vite (for many)?</strong></p><p>Vite addressed this main pain point of Webpack — slow development builds. By leveraging native ES Modules in development, it offers a significantly faster and more enjoyable development experience.</p><p><strong>Angular’s Move:</strong></p><p>You also mentioned Angular moving away from Webpack as the default in version 17+. This highlights the industry trend towards faster build tools. While Angular’s new build system (esbuild-based) has its own specifics, the underlying motivation is the same: to provide a quicker and more efficient development workflow.</p><p>So, in our migration discussion, we were likely looking to take advantage of Vite’s speed and modern approach compared to the more traditional (but still very capable) Webpack setup we were probably using before. Does that paint a clearer picture of the difference between Webpack and Vite?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5677d66afa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>