<?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 Adred on Medium]]></title>
        <description><![CDATA[Stories by Adred on Medium]]></description>
        <link>https://medium.com/@adredars?source=rss-53569232c933------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*emY_iIMsRdpBhT6ee2BV7A.png</url>
            <title>Stories by Adred on Medium</title>
            <link>https://medium.com/@adredars?source=rss-53569232c933------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:23:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adredars/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[Building a VSCode Extension That Detects Hardcoded Secrets — End to End]]></title>
            <link>https://medium.com/@adredars/building-a-vscode-extension-that-detects-hardcoded-secrets-end-to-end-ed56477cbd55?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed56477cbd55</guid>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 18:18:28 GMT</pubDate>
            <atom:updated>2026-04-11T18:19:02.781Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A personal learning log covering VSCode extension development, architecture decisions, what broke, and publishing to the Marketplace. Written to track my own progress and as a reference for later.</em></p><p><a href="https://github.com/Adredrs23/cd-senext">https://github.com/Adredrs23/cd-senext</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*PTjdUgnglEPeLlRjQUvurQ.png" /></figure><h3>Why I Built This</h3><p>I write these posts as a way to track what I’m learning and have something to come back to later. This one covers building Senext — a VSCode extension that detects hardcoded secrets in your editor. It’s a project I built to learn how VSCode extensions work end to end, from the dev environment to shipping on the Marketplace.</p><p>The post is long and covers everything: the config files, the architecture, what broke, and the full publish flow. Use the headings to jump to whatever you need.</p><h3>What Senext Does</h3><p>Senext watches your open files and detects sensitive content in real time. When it finds something, two things happen simultaneously:</p><ol><li><strong>Inline highlight</strong> — the secret gets a red background with a hover tooltip explaining exactly what was detected</li><li><strong>Problems panel entry</strong> — the same panel where TypeScript errors live, so it integrates with your existing workflow with no new UI to learn</li></ol><p>It detects 19 patterns out of the box across three categories:</p><pre>| Category | Patterns |<br>|---|---|<br>| API Keys | AWS Access Key ID, AWS Secret Key, GCP API Key, Stripe (secret + publishable), SendGrid, OpenAI, Anthropic |<br>| Tokens | GitHub PAT / OAuth / App tokens, npm token, Slack token, Slack webhook URL, JWT |<br>| Connection Strings | MongoDB, PostgreSQL, MySQL, Redis (with embedded credentials) |</pre><p>Everything runs <strong>locally</strong>. No server. No telemetry. The matched text never leaves your machine.</p><h3>The Project Config</h3><p>Before getting into the architecture, it helps to understand the tooling — because VSCode extensions have a different setup than a typical Node.js project.</p><h3>package.json — two consumers, one file</h3><p>For a VSCode extension, package.json is read by both npm and VSCode directly. They care about different fields.</p><p><strong>npm reads</strong> the scripts and devDependencies:</p><pre>&quot;scripts&quot;: {<br>  &quot;vscode:prepublish&quot;: &quot;npm run compile&quot;,<br>  &quot;compile&quot;: &quot;tsc -p ./&quot;,<br>  &quot;watch&quot;: &quot;tsc -watch -p ./&quot;,<br>  &quot;test&quot;: &quot;node ./out/test/runTest.js&quot;<br>}</pre><p>vscode:prepublish is a hook that vsce (the VSCode packaging tool) calls automatically before packaging. It ensures you never publish stale compiled output.</p><p><strong>VSCode reads</strong> the manifest fields:</p><pre>&quot;activationEvents&quot;: [&quot;onStartupFinished&quot;],<br>&quot;main&quot;: &quot;./out/extension.js&quot;,<br>&quot;contributes&quot;: {<br>  &quot;commands&quot;: [...]<br>}</pre><p>activationEvents: [&quot;onStartupFinished&quot;] is important — it means the extension loads <em>after</em> VSCode is fully ready, not eagerly on every window open. Without this, your extension contributes to slow startup times.</p><p>main points to the compiled output in out/. VSCode never touches src/ directly.</p><p>contributes.commands is how you register commands that appear in the Command Palette. They must be declared here even if you register them programmatically in code — or they won&#39;t show up.</p><h3>.vscode/tasks.json — the background compiler</h3><pre>{<br>  &quot;type&quot;: &quot;npm&quot;,<br>  &quot;script&quot;: &quot;watch&quot;,<br>  &quot;problemMatcher&quot;: &quot;$tsc-watch&quot;,<br>  &quot;isBackground&quot;: true,<br>  &quot;presentation&quot;: { &quot;reveal&quot;: &quot;never&quot; },<br>  &quot;group&quot;: { &quot;kind&quot;: &quot;build&quot;, &quot;isDefault&quot;: true }<br>}</pre><p>This runs tsc -watch as a persistent background task. problemMatcher: &quot;$tsc-watch&quot; parses tsc&#39;s output and pipes TypeScript errors directly into the Problems panel. Setting &quot;isDefault&quot;: true in the build group is what lets launch.json reference it as ${defaultBuildTask} without naming it explicitly.</p><h3>.vscode/launch.json — the debug launcher</h3><pre>{<br>  &quot;name&quot;: &quot;Run Extension&quot;,<br>  &quot;type&quot;: &quot;extensionHost&quot;,<br>  &quot;request&quot;: &quot;launch&quot;,<br>  &quot;args&quot;: [&quot;--extensionDevelopmentPath=${workspaceFolder}&quot;],<br>  &quot;outFiles&quot;: [&quot;${workspaceFolder}/out/**/*.js&quot;],<br>  &quot;preLaunchTask&quot;: &quot;${defaultBuildTask}&quot;<br>}</pre><p>type: &quot;extensionHost&quot; is not a generic Node.js debugger. It spawns a full second VSCode window — the <strong>Extension Development Host</strong> — with your extension loaded into it. This is how all VSCode extensions are developed.</p><p>preLaunchTask runs the watch task first, waits for the initial compile, then opens the host window. outFiles maps compiled JS back to TypeScript source so breakpoints in src/ files actually work.</p><h3>The Dev Loop</h3><pre>Press F5<br>  → tsc watch compiles src/ → out/<br>  → Extension Development Host window opens<br>  → Open any file in the EDH<br>  → Senext activates, scans, highlights<br><br>Edit a src/ file and save<br>  → tsc watch recompiles automatically<br>  → Press Cmd+R in the EDH to reload<br>  → Changes take effect immediately</pre><p>No stop-and-restart. The watch task keeps out/ current; Cmd+R in the EDH picks up the latest build.</p><blockquote><strong><em>Notes to Self</em></strong></blockquote><ul><li>activationEvents: [&quot;onStartupFinished&quot;] loads after VSCode is ready, not eagerly — keeps startup fast</li><li>main points to out/extension.js (compiled output), not src/ — VSCode never reads TypeScript directly</li><li>tasks.json and launch.json compose, not compete: tasks runs tsc -watch in background, launch opens the Extension Development Host. Both are needed.</li></ul><h3>The Architecture</h3><p>The extension is built around a three-stage pipeline:</p><pre>Scan → Diagnose → Decorate</pre><p>Each stage is a separate module. extension.ts orchestrates them but owns none of their logic.</p><pre>extension.ts  (orchestrator)<br>     │<br>     ├──► detector.ts       — scans text, returns matches<br>     ├──► diagnostics.ts    — writes matches to Problems panel<br>     └──► decorator.ts      — applies inline visual highlights<br>               ▲<br>         patterns/index.ts  — aggregates all SensitivePattern entries<br>               │<br>     ┌─────────┼─────────┐<br>  apiKeys.ts  tokens.ts  connectionStrings.ts</pre><h3>Patterns</h3><p>Every detectable secret is a SensitivePattern object:</p><pre>interface SensitivePattern {<br>  id: string;<br>  name: string;<br>  regex: RegExp;<br>  severity: &#39;error&#39; | &#39;warning&#39; | &#39;info&#39;;<br>  message: string;<br>}</pre><p>Patterns are split by category into separate files and aggregated into allPatterns in src/patterns/index.ts. Adding a new pattern takes 8 lines and zero knowledge of the rest of the codebase. detector.ts picks it up automatically via the spread — no other file needs to change.</p><h3>Detection</h3><pre>export function scanDocument(document: vscode.TextDocument): DetectionResult[] {<br>  const text = document.getText();<br>  const results: DetectionResult[] = [];  for (const pattern of allPatterns) {<br>    pattern.regex.lastIndex = 0; // critical — see next section<br>    let match: RegExpExecArray | null;<br>    while ((match = pattern.regex.exec(text)) !== null) {<br>      results.push({<br>        pattern,<br>        range: new vscode.Range(<br>          document.positionAt(match.index),<br>          document.positionAt(match.index + match[0].length)<br>        ),<br>        matchedText: match[0],<br>      });<br>    }<br>  }<br>  return results;<br>}</pre><h3>Diagnostics vs. Decorations</h3><p>Two separate VSCode APIs handle output, and both are necessary.</p><p><strong>DiagnosticCollection</strong> writes to the Problems panel. Diagnostics survive focus changes, show in the status bar count, and integrate with CI tools. This is the &quot;permanent record&quot; signal — it stays until you explicitly clear it.</p><p><strong>TextEditorDecorationType</strong> applies the inline red background. It&#39;s the immediate visual that catches your eye while editing.</p><p>Together they cover both surfaces: you can’t hide the diagnostic by switching files, and you can’t miss the decoration while looking at the file.</p><h3>Scan Triggers</h3><pre>| Event | Behavior |<br>|---|---|<br>| File open | Debounced 500ms |<br>| Text change | Debounced 500ms — resets on every keystroke |<br>| File save | Immediate — document is stable, no debounce needed |<br>| File close | Diagnostics cleared for that URI |<br>| Extension activates | Immediate scan of all visible editors |</pre><p>Debounce is per-document-URI via Map&lt;string, NodeJS.Timeout&gt;. Typing in one file doesn&#39;t reset the timer for another.</p><blockquote><strong><em>Notes to Self</em></strong></blockquote><ul><li>Both DiagnosticCollection and TextEditorDecorationType are needed — diagnostics survive focus changes and appear in Problems panel; decorations give the immediate inline visual. Neither alone is enough.</li><li>Adding a new pattern only requires editing the relevant file in src/patterns/. detector.ts picks it up automatically via the spread in index.ts — no other file needs changing.</li></ul><h3>What Broke (And How I Fixed It)</h3><h3>The Regex Statefulness Bug</h3><p>This one cost me an afternoon.</p><p>JavaScript regex with the /g flag is stateful — lastIndex persists between calls on the same regex object. Each pattern in Senext is a module-level constant, which means the same regex instance gets reused across every document scan.</p><p>What happened: the first document I scanned worked perfectly. The second document would sometimes miss matches at the start of the file. The third would behave differently again. The failures were inconsistent and position-dependent, which made them hard to trace.</p><p>The root cause: after scanning document A, regex.lastIndex was left at some offset into A&#39;s text. When I started scanning document B, the regex resumed from that offset — skipping everything before it.</p><p>The fix is one line before each scan loop:</p><pre>pattern.regex.lastIndex = 0;</pre><p>Simple. But the reason it’s easy to miss is that it only fails on the <em>second</em> scan of a document, not the first. If you only test by opening one file and scanning once, you’ll never see it.</p><h3>False Positives</h3><p>Regex-based secret detection has an inherent limitation: it can’t understand context. The AWS Secret Key pattern ([A-Za-z0-9+/]{40}) will match any 40-character base64-looking string — including hashes, test data, and Lorem Ipsum-adjacent content.</p><p>I made two deliberate choices to manage this:</p><p><strong>Severity levels</strong> — patterns with higher false positive rates get warning instead of error. AWS Secret Key is a warning; AWS Access Key ID (which starts with the distinctive AKIA prefix) is an error. Users learn to trust error diagnostics and treat warning as &quot;worth a look.&quot;</p><p><strong>Specificity over recall</strong> — I’d rather miss an unusual secret format than flag common code patterns as secrets. For services with distinctive prefixes (GitHub’s ghp_, npm&#39;s npm_, OpenAI&#39;s sk-), the patterns are tight. For generic formats, I err toward higher thresholds.</p><p>False positives are a real problem in this space. If the tool cries wolf too often, developers turn it off. Calibrating severity took more iteration than writing the patterns themselves.</p><blockquote><strong><em>Notes to Self</em></strong></blockquote><ul><li>Reset regex.lastIndex = 0 before every document scan — /g flag regex is stateful and will skip matches at the start of the second document if you don&#39;t reset</li><li>False positive calibration is ongoing work, not a one-time setup. Use error for patterns with distinctive prefixes, warning for broad patterns that could match non-secrets</li></ul><h3>Publishing to the Marketplace</h3><p>Getting the extension in front of other developers required a different kind of work than building it.</p><h3>vsce — the packaging tool</h3><pre>npm install -g @vscode/vsce</pre><p>vsce handles everything: packaging, validation, and publishing. Before ever pushing to the Marketplace, package locally and install it as a .vsix to verify the packaged version behaves exactly like the dev version:</p><pre>vsce package           # produces cd-senext-0.1.0.vsix<br>vsce ls                # lists every file being bundled — check this carefully</pre><p>vsce ls matters. Without a .vscodeignore, it bundles src/, docs/, node_modules/ — everything. Add .vscodeignore to exclude non-runtime files:</p><pre>.vscode/<br>src/<br>docs/<br>node_modules/<br>tsconfig.json<br>**/*.map<br>**/*.ts<br>!out/**</pre><h3>Publisher Setup</h3><p>Publishing requires a Microsoft account, an Azure DevOps organization, and a Personal Access Token scoped to <strong>Marketplace → Manage</strong>. Then create a publisher at marketplace.visualstudio.com/manage — the publisher ID is permanent and becomes part of your extension&#39;s fully qualified name.</p><h3>package.json Fields That Affect the Listing</h3><p>The Marketplace listing is generated from your package.json and README.md. Fields that matter for discoverability:</p><pre>&quot;description&quot;: &quot;...&quot;,          // appears in search results — be specific<br>&quot;keywords&quot;: [&quot;security&quot;, ...], // drives search ranking<br>&quot;categories&quot;: [&quot;Linters&quot;],     // determines which tab you appear in<br>&quot;publisher&quot;: &quot;your-id&quot;,        // must match your account exactly<br>&quot;repository&quot;: { &quot;url&quot;: &quot;...&quot; },// marketplace links to it<br>&quot;icon&quot;: &quot;assets/icon.png&quot;,     // 128×128 PNG — significant visual difference<br>&quot;galleryBanner&quot;: {<br>  &quot;color&quot;: &quot;#1a1a2e&quot;,<br>  &quot;theme&quot;: &quot;dark&quot;<br>}</pre><p>Your README.md is the listing page body. Write it for someone who found your extension via search and has 10 seconds to decide whether to install it.</p><h3>Automating Releases with GitHub Actions</h3><p>Rather than running vsce publish manually from my machine every time I release, I automated it with a GitHub Actions workflow that triggers on every GitHub Release:</p><pre>name: Publish to Marketplace<br>on:<br>  release:<br>    types: [created]</pre><pre>jobs:<br>  publish:<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: write     # required to upload the .vsix as a release asset<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: &#39;20&#39;<br>          cache: &#39;npm&#39;<br>      - run: npm ci<br>      - run: npm install -g @vscode/vsce<br>      - run: npm run compile<br>      - run: vsce package<br>      - uses: softprops/action-gh-release@v2  # uploads .vsix to the GitHub Release<br>        with:<br>          files: &#39;*.vsix&#39;<br>      - run: vsce publish<br>        env:<br>          VSCE_PAT: ${{ secrets.VSCE_PAT }}  # stored as a GitHub repo secret</pre><p>The VSCE_PAT secret is the Azure DevOps Personal Access Token, stored in the repo&#39;s GitHub Secrets (Settings → Secrets and variables → Actions). The workflow compiles, packages, attaches the .vsix to the GitHub Release as a downloadable asset, and publishes to the Marketplace — all without touching my local machine.</p><p>One gotcha: softprops/action-gh-release needs permissions: contents: write at the job level. GitHub Actions defaults to read-only. Without this, you get: Resource not accessible by integration.</p><h3>Versioning</h3><p>Bump the version in package.json before creating a release. When you create a GitHub Release tagged v0.2.0, the Actions workflow fires, picks up whatever version is in package.json, and publishes that. If the versions don&#39;t match, vsce will complain.</p><p>For manual publishing (local testing only):</p><pre>vsce publish patch   # 0.1.0 → 0.1.1<br>vsce publish minor   # 0.1.0 → 0.2.0<br>vsce publish major   # 0.1.0 → 1.0.0</pre><blockquote><strong><em>Notes to Self</em></strong></blockquote><ul><li>Bump version in package.json and commit before creating the GitHub Release — vsce reads the version from the file at publish time, not from the git tag</li><li>permissions: contents: write is required on the job in publish.yml or the .vsix upload fails with &quot;Resource not accessible by integration&quot;</li><li>The Azure DevOps PAT lives in GitHub repo Secrets as VSCE_PAT — set it under Settings → Secrets and variables → Actions</li></ul><h3>What I Learned</h3><p><strong>The VSCode extension API is well-designed.</strong> The event model covers every meaningful file state transition. DiagnosticCollection and TextEditorDecorationType are simple, well-documented APIs that do exactly what you expect.</p><p><strong>package.json has two jobs.</strong> Treating it as just an npm manifest costs you — the VSCode-specific fields (activationEvents, contributes, main) are equally important and affect runtime behavior in production.</p><p><strong>The tasks/launch split is intentional.</strong> Tasks handle long-running background processes like tsc -watch. Launch configs handle one-shot operations like opening the Extension Development Host. They compose — you need both for a smooth dev loop.</p><p><strong>False positive calibration is real work.</strong> Regex can match anything that looks like a secret. The difference between a useful security tool and an annoying one is severity calibration and pattern specificity. I spent more time on this than on writing the detection logic itself.</p><p><strong>Automate the release pipeline early.</strong> Manual vsce publish from your local machine works, but it means the extension is only as consistent as your local setup. GitHub Actions makes releases reproducible and keeps the PAT off your machine.</p><p><strong>permissions: contents: write is not optional.</strong> If you use softprops/action-gh-release and forget this, you&#39;ll chase the error in CI for longer than you&#39;d like.</p><h3>What’s Next</h3><p>The current version detects and highlights. A few things that would make it genuinely indispensable:</p><ul><li><strong>.senextignore</strong> — allowlist known-safe patterns. Test files often have dummy credentials that should never fire. Right now there&#39;s no way to suppress a false positive without removing the pattern entirely.</li><li><strong>Per-category settings</strong> — a user settings panel to toggle each pattern category. If you’re working on a JWT-heavy auth service, you probably don’t want every token flagged as a warning.</li><li><strong>Status bar count</strong> — a live count of detected secrets in the status bar, visible without opening the Problems panel. Small thing, big UX improvement.</li><li><strong>Quick fix code actions</strong> — a light-bulb action that offers to replace MONGO_URI = &quot;mongodb://user:pass@host&quot; with MONGO_URI = process.env.MONGO_URI. This would close the loop from detection to remediation.</li></ul><h3>Wrapping Up</h3><p>Building this taught me more about the VSCode extension API than I expected going in. The config files — tasks.json, launch.json, package.json — took the longest to understand. Not because they&#39;re complex, but because each one has two jobs and it&#39;s not obvious at first which job belongs where.</p><p>The regex statefulness bug cost an afternoon. The GitHub Actions permissions error cost another. Both were completely findable in the docs — I just didn’t know to look.</p><p>Next on the list: add a test suite and .senextignore support. Future me — check if those exist before starting from scratch.</p><p><em>A learning project. TypeScript, VSCode Extension API, GitHub Actions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed56477cbd55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-time Collaborative Whiteboard — (Frontend) with Next.js]]></title>
            <link>https://medium.com/@adredars/building-a-real-time-collaborative-whiteboard-frontend-with-next-js-7c6b2ef1e072?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c6b2ef1e072</guid>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[collaboration-tools]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Sun, 04 May 2025 12:51:27 GMT</pubDate>
            <atom:updated>2025-05-04T12:54:02.533Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Real-time Collaborative Whiteboard — (Frontend) with Next.js and Fabric.js: A Step-by-Step Guide</h3><p>Have you ever wanted to create your own collaborative whiteboard application like Miro or Google Jamboard or Excalidraw? In this comprehensive tutorial, I’ll walk you through building a real-time collaborative whiteboard from scratch, where multiple users can draw, create shapes, and interact simultaneously.</p><blockquote>SIDENOTE: This blog is a just the Frontend implementation of the Whiteboard I’m trying to recreate here. So it will be helpful if you go through the backend part as well to get the complete grasp of things. Attached is the Backend article. Thankyou.</blockquote><p><a href="https://medium.com/@adredars/building-a-real-time-collaborative-whiteboard-backend-with-nestjs-and-socket-io-2229f7bf73bd">Medium</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*IG_yRve6jGBw4VMZ" /></figure><h3>What We’ll Build</h3><p>Our collaborative whiteboard will include these powerful features:</p><ul><li>Real-time drawing and shape manipulation across multiple users</li><li>Various drawing tools (pencil, rectangle, ellipse, line)</li><li>Instant collaboration between users via WebSockets</li><li>Responsive canvas that automatically adapts to window size</li><li>Clean, maintainable code architecture</li></ul><p>By the end of this tutorial, you’ll have a fully functional collaborative whiteboard application that you can extend with additional features!</p><h3>Tech Stack</h3><p>We’ll use a modern tech stack that combines powerful libraries for an optimal development experience:</p><ul><li><strong>Next.js</strong>: A React framework that provides an excellent foundation for our application</li><li><strong>Fabric.js</strong>: A powerful HTML5 canvas library that makes working with canvas elements much easier</li><li><strong>Socket.IO</strong>: For real-time bidirectional communication between clients</li><li><strong>TypeScript</strong>: Providing type safety and improving developer experience</li></ul><h3>Step 1: Setting Up the Project</h3><p>Let’s start by creating a new Next.js project with TypeScript:</p><pre>npx create-next-app@latest whiteboard-app --typescript<br>cd whiteboard-app</pre><p>Next, we’ll install the required dependencies:</p><pre>npm install fabric socket.io-client</pre><p>Then, we’ll create the necessary directory structure for our project:</p><pre>mkdir -p src/components/Whiteboard src/hooks src/types</pre><p>This structure helps us organize our code in a clean, maintainable way. The components directory will contain our UI components, hooks will contain custom React hooks for canvas and socket handling, and types will contain TypeScript type definitions.</p><h3>Step 2: Creating the Canvas Hook</h3><p>The useCanvas hook will be responsible for initializing and managing our Fabric.js canvas. It handles canvas creation, window resizing, and object deletion through keyboard events.</p><p>Create src/hooks/useCanvas.ts:</p><pre>import { useEffect, useRef, useState } from &#39;react&#39;;<br>import { Canvas, FabricObject } from &#39;fabric&#39;;<br>import { ExtendedFabricObject } from &#39;@/types/global.types&#39;;<br>import { generateId } from &#39;@/components/Whiteboard/Whiteboard.utils&#39;;<br><br>export const useCanvas = () =&gt; {<br>    const canvasRef = useRef&lt;HTMLCanvasElement&gt;(null);<br>    const [fabricCanvas, setFabricCanvas] = useState&lt;Canvas | null&gt;(null);<br>    useEffect(() =&gt; {<br>        const init = () =&gt; {<br>            const canvasEl = canvasRef.current;<br>            if (!canvasEl) return;<br>            FabricObject.prototype.toObject = (function (toObject) {<br>                return function (this: FabricObject, properties: string[] = []) {<br>                    return toObject.call(this, [...properties, &#39;id&#39;]);<br>                };<br>            })(FabricObject.prototype.toObject);<br>            const canvas = new Canvas(canvasEl, {<br>                backgroundColor: &#39;#fff&#39;,<br>            });<br>            canvas.setDimensions({<br>                width: window.innerWidth,<br>                height: window.innerHeight - 80,<br>            });<br>            canvas.renderAll();<br>            // Add unique IDs to objects when they&#39;re created<br>            canvas.on(&#39;object:added&#39;, (e: { target: ExtendedFabricObject }) =&gt; {<br>                if (!e.target) return;<br>                if (!e.target.id) {<br>                    e.target.id = generateId();<br>                }<br>            });<br>            setFabricCanvas(canvas);<br>            const resize = () =&gt; {<br>                canvas.setDimensions({<br>                    width: window.innerWidth,<br>                    height: window.innerHeight - 80,<br>                });<br>                canvas.renderAll();<br>            };<br>            const handleKeyDown = (e: KeyboardEvent) =&gt; {<br>                if (e.key === &#39;Delete&#39; || e.key === &#39;Backspace&#39;) {<br>                    const active = canvas.getActiveObject();<br>                    if (active) {<br>                        canvas.remove(active);<br>                        canvas.renderAll();<br>                    }<br>                }<br>            };<br>            window.addEventListener(&#39;resize&#39;, resize);<br>            window.addEventListener(&#39;keydown&#39;, handleKeyDown);<br>            return () =&gt; {<br>                window.removeEventListener(&#39;resize&#39;, resize);<br>                window.removeEventListener(&#39;keydown&#39;, handleKeyDown);<br>                // Remove canvas event listeners<br>                canvas.off(&#39;object:added&#39;);<br>                if (canvas) {<br>                    canvas.dispose();<br>                    setFabricCanvas(null);<br>                }<br>            };<br>        };<br>        const cleanup = init();<br>        return cleanup;<br>    }, []);<br>    return { canvasRef, fabricCanvas };<br>};</pre><p>This hook does several important things:</p><ol><li><strong>Canvas Initialization</strong>: It creates a new Fabric.js canvas and sets its dimensions based on the window size.</li><li><strong>Object ID Generation</strong>: It extends Fabric.js objects to include unique IDs, which is crucial for real-time synchronization.</li><li><strong>Event Handling</strong>: It sets up event listeners for window resizing and keyboard shortcuts (Delete/Backspace to remove selected objects).</li><li><strong>Cleanup</strong>: It properly cleans up event listeners and disposes of the canvas when the component unmounts.</li></ol><p>The hook returns a reference to the canvas element and the Fabric.js canvas instance, which we’ll use throughout our application.</p><h3>Step 3: Implementing Real-time Communication</h3><p>Next, let’s implement real-time communication with Socket.IO. The useSocket hook will handle all socket events for synchronizing canvas objects between users.</p><p>Create src/hooks/useSocket.ts:</p><pre>import { useEffect, useRef, useState } from &#39;react&#39;;<br>import { io, Socket } from &#39;socket.io-client&#39;;<br>import { Canvas, util } from &#39;fabric&#39;;<br>import {<br>    ExtendedFabricObject,<br>    SerializedObjectData,<br>    SocketDetails,<br>} from &#39;@/types/global.types&#39;;<br><br>export const useSocket = (canvas: Canvas | null) =&gt; {<br>    const socketRef = useRef&lt;Socket | null&gt;(null);<br>    const [socketDetails, setSocketDetails] = useState&lt;SocketDetails&gt;(null);<br>    useEffect(() =&gt; {<br>        const init = async () =&gt; {<br>            if (!canvas) return;<br>            const socket = await io(&#39;http://localhost:8080&#39;);<br>            socketRef.current = socket;<br>            socket.on(&#39;connect&#39;, () =&gt; {<br>                setSocketDetails({<br>                    clientId: socket.id,<br>                });<br>            });<br>            // Listen for canvas events and emit to socket<br>            const handleObjectAdded = (e: { target: ExtendedFabricObject }) =&gt; {<br>                if (!e.target || e.target.__skipEmit) return;<br>                socket.emit(&#39;object:added&#39;, e.target.toJSON());<br>            };<br>            const handleObjectModified = (e: { target: ExtendedFabricObject }) =&gt; {<br>                if (!e.target || e.target.__skipEmit) return;<br>                socket.emit(&#39;object:modified&#39;, e.target.toJSON());<br>            };<br>            const handleObjectRemoved = (e: { target: ExtendedFabricObject }) =&gt; {<br>                if (!e.target || e.target.__skipEmit) return;<br>                socket.emit(&#39;object:removed&#39;, e.target.toJSON());<br>            };<br>            canvas.on(&#39;object:added&#39;, handleObjectAdded);<br>            canvas.on(&#39;object:modified&#39;, handleObjectModified);<br>            canvas.on(&#39;object:removed&#39;, handleObjectRemoved);<br>            // Listen for events from server<br>            socket.on(&#39;object:added&#39;, (objectData: SerializedObjectData) =&gt; {<br>                util<br>                    .enlivenObjects([objectData])<br>                    .then(([obj]) =&gt; {<br>                        const extendedObj = obj as ExtendedFabricObject;<br>                        if (<br>                            !canvas<br>                                .getObjects()<br>                                .find((o) =&gt; (o as ExtendedFabricObject).id === extendedObj.id)<br>                        ) {<br>                            extendedObj.__skipEmit = true;<br>                            canvas.add(extendedObj);<br>                            canvas.renderAll();<br>                        }<br>                    })<br>                    .catch(console.error);<br>            });<br>            socket.on(&#39;object:modified&#39;, (objectData: SerializedObjectData) =&gt; {<br>                const obj = canvas<br>                    .getObjects()<br>                    .find(<br>                        (o) =&gt; (o as ExtendedFabricObject).id === objectData.id<br>                    ) as ExtendedFabricObject;<br>                if (obj) {<br>                    obj.__skipEmit = true;<br>                    obj.set({ ...objectData });<br>                    canvas.renderAll();<br>                }<br>            });<br>            socket.on(&#39;object:removed&#39;, (objectData: SerializedObjectData) =&gt; {<br>                const obj = canvas<br>                    .getObjects()<br>                    .find(<br>                        (o) =&gt; (o as ExtendedFabricObject).id === objectData.id<br>                    ) as ExtendedFabricObject;<br>                if (obj) {<br>                    obj.__skipEmit = true;<br>                    canvas.remove(obj);<br>                    canvas.renderAll();<br>                }<br>            });<br>            socket.on(&#39;canvas:clear&#39;, () =&gt; {<br>                canvas.clear();<br>            });<br>            socket.on(<br>                &#39;object:sync&#39;,<br>                (payload: { objects: SerializedObjectData[] }) =&gt; {<br>                    util.enlivenObjects(payload.objects).then((objects) =&gt; {<br>                        canvas.clear();<br>                        objects.forEach((obj) =&gt; {<br>                            const extendedObj = obj as ExtendedFabricObject;<br>                            extendedObj.__skipEmit = true;<br>                            canvas.add(extendedObj);<br>                        });<br>                        canvas.renderAll();<br>                    });<br>                }<br>            );<br>            return () =&gt; {<br>                // Remove canvas event listeners<br>                canvas.off(&#39;object:added&#39;, handleObjectAdded);<br>                canvas.off(&#39;object:modified&#39;, handleObjectModified);<br>                canvas.off(&#39;object:removed&#39;, handleObjectRemoved);<br>                // Remove socket event listeners<br>                socket.off(&#39;object:added&#39;);<br>                socket.off(&#39;object:removed&#39;);<br>                socket.off(&#39;object:modified&#39;);<br>                socket.off(&#39;object:sync&#39;);<br>                if (socketRef.current) {<br>                    socketRef.current.disconnect();<br>                    socketRef.current = null;<br>                }<br>            };<br>        };<br>        init();<br>    }, [canvas]);<br>    return { socketDetails };<br>};</pre><p>This hook is quite complex, but it’s the backbone of our collaborative functionality:</p><ol><li><strong>Socket Connection</strong>: It establishes a connection to our Socket.IO server.</li><li><strong>Object Synchronization</strong>: It sets up event listeners for local canvas changes (object:added, object:modified, object:removed) and emits these changes to other clients.</li><li><strong>Remote Updates</strong>: It listens for changes from other clients and applies them to the local canvas.</li><li><strong>Infinite Loop Prevention</strong>: It uses the __skipEmit flag to prevent infinite loops when applying changes from remote clients.</li><li><strong>Full Canvas Sync</strong>: It handles full canvas synchronization when a new user joins.</li></ol><p>The __skipEmit flag is particularly important; without it, applying remote changes would trigger local events, which would then be emitted back to other clients, creating an infinite loop.</p><h3>Step 4: Creating Drawing Tools</h3><p>Now, let’s implement the tools that users will use to interact with the canvas. The useToolHandlers hook will handle different drawing tools like rectangles, lines, and ellipses.</p><p>Create src/hooks/useToolHandlers.ts:</p><pre>import { useCallback } from &#39;react&#39;;<br>import {<br>    Canvas,<br>    Rect,<br>    Line,<br>    Ellipse,<br>    TPointerEvent,<br>    TPointerEventInfo,<br>} from &#39;fabric&#39;;<br>import { Tool } from &#39;../components/Toolbar/Toolbar.types&#39;;<br><br>export const useToolHandlers = (<br>    canvas: Canvas | null,<br>    tool: Tool,<br>    brushColor: string,<br>    brushSize: number<br>) =&gt; {<br>    let startX = 0;<br>    let startY = 0;<br>    let shape: Rect | Line | Ellipse | null = null;<br>    const handleMouseDown = useCallback(<br>        (opt: TPointerEventInfo&lt;TPointerEvent&gt;) =&gt; {<br>            if (!canvas) return;<br>            const pointer = canvas.getPointer(opt.e);<br>            startX = pointer.x;<br>            startY = pointer.y;<br>            switch (tool) {<br>                case &#39;rectangle&#39;:<br>                    shape = new Rect({<br>                        left: startX,<br>                        top: startY,<br>                        fill: &#39;transparent&#39;,<br>                        stroke: brushColor,<br>                        strokeWidth: brushSize,<br>                        width: 0,<br>                        height: 0,<br>                    });<br>                    break;<br>                case &#39;line&#39;:<br>                    shape = new Line([startX, startY, startX, startY], {<br>                        stroke: brushColor,<br>                        strokeWidth: brushSize,<br>                    });<br>                    break;<br>                case &#39;ellipse&#39;:<br>                    shape = new Ellipse({<br>                        left: startX,<br>                        top: startY,<br>                        rx: 0,<br>                        ry: 0,<br>                        fill: &#39;transparent&#39;,<br>                        stroke: brushColor,<br>                        strokeWidth: brushSize,<br>                    });<br>                    break;<br>            }<br>        },<br>        [canvas, tool, brushColor, brushSize]<br>    );<br>    const handleMouseMove = useCallback(<br>        (opt: TPointerEventInfo&lt;TPointerEvent&gt;) =&gt; {<br>            if (!canvas || !shape) return;<br>            const pointer = canvas.getPointer(opt.e);<br>            switch (tool) {<br>                case &#39;rectangle&#39;: {<br>                    const rect = shape as Rect;<br>                    rect.set({<br>                        width: Math.abs(pointer.x - startX),<br>                        height: Math.abs(pointer.y - startY),<br>                        left: Math.min(startX, pointer.x),<br>                        top: Math.min(startY, pointer.y),<br>                    });<br>                    break;<br>                }<br>                case &#39;line&#39;: {<br>                    const line = shape as Line;<br>                    line.set({ x2: pointer.x, y2: pointer.y });<br>                    break;<br>                }<br>                case &#39;ellipse&#39;: {<br>                    const ellipse = shape as Ellipse;<br>                    ellipse.set({<br>                        rx: Math.abs(pointer.x - startX) / 2,<br>                        ry: Math.abs(pointer.y - startY) / 2,<br>                        left: Math.min(startX, pointer.x),<br>                        top: Math.min(startY, pointer.y),<br>                    });<br>                    break;<br>                }<br>            }<br>            if (shape.canvas) {<br>                canvas.renderAll();<br>            } else {<br>                canvas.add(shape);<br>            }<br>        },<br>        [canvas, tool]<br>    );<br>    const handleMouseUp = useCallback(() =&gt; {<br>        if (!canvas || !shape) return;<br>        switch (tool) {<br>            case &#39;rectangle&#39;: {<br>                const rect = shape as Rect;<br>                if (rect.width !== 0 &amp;&amp; rect.height !== 0) {<br>                    if (shape.canvas) {<br>                        canvas.remove(shape);<br>                    }<br>                    canvas.add(shape);<br>                    canvas.renderAll();<br>                }<br>                break;<br>            }<br>            case &#39;line&#39;: {<br>                const line = shape as Line;<br>                if (line.x2 !== startX || line.y2 !== startY) {<br>                    if (shape.canvas) {<br>                        canvas.remove(shape);<br>                    }<br>                    canvas.add(shape);<br>                    canvas.renderAll();<br>                }<br>                break;<br>            }<br>            case &#39;ellipse&#39;: {<br>                const ellipse = shape as Ellipse;<br>                if (ellipse.rx !== 0 &amp;&amp; ellipse.ry !== 0) {<br>                    if (shape.canvas) {<br>                        canvas.remove(shape);<br>                    }<br>                    canvas.add(shape);<br>                    canvas.renderAll();<br>                }<br>                break;<br>            }<br>        }<br>        shape = null;<br>    }, [canvas, tool]);<br>    return { handleMouseDown, handleMouseMove, handleMouseUp };<br>};</pre><p>This hook implements the drawing logic for our shape tools:</p><ol><li><strong>Mouse Down</strong>: When the user starts drawing, it creates a new shape (rectangle, line, or ellipse) at the starting position.</li><li><strong>Mouse Move</strong>: As the user drags the mouse, it updates the shape’s dimensions based on the current pointer position.</li><li><strong>Mouse Up</strong>: When the user releases the mouse, it finalizes the shape and adds it to the canvas if it has valid dimensions.</li></ol><p>The hook returns three event handlers that will be attached to the canvas in our main component. Each tool has its own specific logic for creating and manipulating shapes.</p><h3>Step 5: Building the Main Component</h3><p>Now, let’s create the main whiteboard component that will bring everything together. This component will handle the UI, tool selection, and coordinate the various hooks we’ve created.</p><p>Create src/components/Whiteboard/Whiteboard.tsx:</p><pre>&#39;use client&#39;;<br><br>import { useCallback, useEffect, useMemo, useState } from &#39;react&#39;;<br>import { PencilBrush } from &#39;fabric&#39;;<br>import { Button } from &#39;@/components/ui/button&#39;;<br>import { Input } from &#39;@/components/ui/input&#39;;<br>import { Slider } from &#39;@/components/ui/slider&#39;;<br>import { WhiteboardState } from &#39;./Whiteboard.types&#39;;<br>import { Tool } from &#39;../Toolbar/Toolbar.types&#39;;<br>import { useCanvas } from &#39;@/hooks/useCanvas&#39;;<br>import { useSocket } from &#39;@/hooks/useSocket&#39;;<br>import { useToolHandlers } from &#39;@/hooks/useToolHandlers&#39;;<br>export const Whiteboard = () =&gt; {<br>    const { canvasRef, fabricCanvas } = useCanvas();<br>    const { socketDetails } = useSocket(fabricCanvas);<br>    const [state, setState] = useState&lt;WhiteboardState&gt;({<br>        tool: &#39;select&#39;,<br>        brushColor: &#39;#000000&#39;,<br>        brushSize: 5,<br>        socketDetails,<br>    });<br>    const toolOptions = useMemo(<br>        () =&gt; [&#39;select&#39;, &#39;draw&#39;, &#39;rectangle&#39;, &#39;line&#39;, &#39;ellipse&#39;, &#39;clear&#39;] as Tool[],<br>        []<br>    );<br>    const handleToolClick = useCallback(<br>        (t: Tool) =&gt; () =&gt; setState((prev) =&gt; ({ ...prev, tool: t })),<br>        [setState]<br>    );<br>    const handleColorChange = useCallback(<br>        (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt;<br>            setState((prev) =&gt; ({ ...prev, brushColor: e.target.value })),<br>        []<br>    );<br>    const handleSizeChange = useCallback(<br>        (val: number[]) =&gt; setState((prev) =&gt; ({ ...prev, brushSize: val[0] })),<br>        []<br>    );<br>    const { handleMouseDown, handleMouseMove, handleMouseUp } = useToolHandlers(<br>        fabricCanvas,<br>        state.tool,<br>        state.brushColor,<br>        state.brushSize<br>    );<br>    // Handle tool changes<br>    useEffect(() =&gt; {<br>        if (!fabricCanvas) return;<br>        // Cleanup function to remove all event listeners<br>        const cleanup = () =&gt; {<br>            // Only disable drawing mode and selection, don&#39;t clear the canvas<br>            fabricCanvas.isDrawingMode = false;<br>            fabricCanvas.selection = false;<br>            // Remove event listeners<br>            fabricCanvas.off(&#39;mouse:down&#39;);<br>            fabricCanvas.off(&#39;mouse:move&#39;);<br>            fabricCanvas.off(&#39;mouse:up&#39;);<br>            // Make objects non-selectable for non-select tools<br>            if (state.tool !== &#39;select&#39;) {<br>                fabricCanvas.forEachObject((obj) =&gt; (obj.selectable = false));<br>            }<br>        };<br>        // Clean up previous tool&#39;s settings<br>        cleanup();<br>        switch (state.tool) {<br>            case &#39;draw&#39;: {<br>                fabricCanvas.isDrawingMode = true;<br>                const brush = new PencilBrush(fabricCanvas);<br>                brush.color = state.brushColor;<br>                brush.width = state.brushSize;<br>                fabricCanvas.freeDrawingBrush = brush;<br>                break;<br>            }<br>            case &#39;select&#39;: {<br>                fabricCanvas.selection = true;<br>                fabricCanvas.forEachObject((obj) =&gt; (obj.selectable = true));<br>                break;<br>            }<br>            case &#39;clear&#39;: {<br>                fabricCanvas.clear();<br>                fabricCanvas.backgroundColor = &#39;#fff&#39;;<br>                fabricCanvas.renderAll();<br>                break;<br>            }<br>            default: {<br>                fabricCanvas.on(&#39;mouse:down&#39;, handleMouseDown);<br>                fabricCanvas.on(&#39;mouse:move&#39;, handleMouseMove);<br>                fabricCanvas.on(&#39;mouse:up&#39;, handleMouseUp);<br>                break;<br>            }<br>        }<br>        return cleanup;<br>    }, [<br>        state.tool,<br>        state.brushColor,<br>        state.brushSize,<br>        handleMouseDown,<br>        handleMouseMove,<br>        handleMouseUp,<br>        fabricCanvas,<br>    ]);<br>    // Update socket details in state when they change<br>    useEffect(() =&gt; {<br>        setState((prev) =&gt; ({ ...prev, socketDetails }));<br>    }, [socketDetails]);<br>    return (<br>        &lt;div className=&#39;p-2&#39;&gt;<br>            &lt;div className=&#39;flex items-center gap-3 bg-gray-100 px-4 py-2 shadow-md sticky top-0 z-10&#39;&gt;<br>                {toolOptions.map((t) =&gt; (<br>                    &lt;Button<br>                        key={t}<br>                        variant={state.tool === t ? &#39;default&#39; : &#39;outline&#39;}<br>                        onClick={handleToolClick(t)}<br>                    &gt;<br>                        {t.charAt(0).toUpperCase() + t.slice(1)}<br>                    &lt;/Button&gt;<br>                ))}<br>                &lt;div className=&#39;flex items-center gap-3 ml-6&#39;&gt;<br>                    &lt;label className=&#39;text-sm&#39;&gt;Color:&lt;/label&gt;<br>                    &lt;Input<br>                        type=&#39;color&#39;<br>                        value={state.brushColor}<br>                        onChange={handleColorChange}<br>                        className=&#39;w-10 h-10 p-0 border-none&#39;<br>                    /&gt;<br>                    &lt;label className=&#39;text-sm&#39;&gt;Size:&lt;/label&gt;<br>                    &lt;Slider<br>                        min={1}<br>                        max={20}<br>                        step={1}<br>                        value={[state.brushSize]}<br>                        onValueChange={handleSizeChange}<br>                        className=&#39;w-32&#39;<br>                    /&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;canvas<br>                ref={canvasRef}<br>                className=&#39;border border-gray-300 rounded shadow w-full h-[calc(100vh-80px)]&#39;<br>            /&gt;<br>            {state.socketDetails?.clientId &amp;&amp; (<br>                &lt;div className=&#39;fixed bottom-4 right-4 z-50 p-3 bg-black text-white text-sm rounded-xl shadow-xl opacity-90&#39;&gt;<br>                    🧩 Connected as:{&#39; &#39;}<br>                    &lt;span className=&#39;font-mono text-green-300&#39;&gt;<br>                        {state.socketDetails.clientId}<br>                    &lt;/span&gt;<br>                &lt;/div&gt;<br>            )}<br>        &lt;/div&gt;<br>    );<br>};</pre><p>This component is the heart of our application:</p><ol><li><strong>Hooks Integration</strong>: It uses all the hooks we’ve created (useCanvas, useSocket, useToolHandlers) to manage the canvas and its interactions.</li><li><strong>Tool Management</strong>: It handles tool selection, color picking, and brush size adjustment.</li><li><strong>Tool Behavior</strong>: It configures the canvas based on the selected tool (drawing mode, selection, event listeners).</li><li><strong>UI Rendering</strong>: It renders the toolbar, canvas, and connection status indicator.</li></ol><p>The component maintains a state object that includes the current tool, brush color, brush size, and socket details. When any of these change, it updates the canvas configuration accordingly.</p><h3>Step 6: Creating the Toolbar</h3><p>Let’s create a separate toolbar component to keep our code organized.</p><p>Create src/components/Whiteboard/Toolbar.tsx:</p><pre>import { Tool } from &#39;../components/Toolbar/Toolbar.types&#39;;<br>import styles from &#39;./Toolbar.module.css&#39;;<br><br>interface ToolbarProps {<br>    onToolSelect: (tool: Tool) =&gt; void;<br>}<br>export const Toolbar = ({ onToolSelect }: ToolbarProps) =&gt; {<br>    const tools: { name: string; tool: Tool }[] = [<br>        { name: &#39;Pencil&#39;, tool: &#39;pencil&#39; },<br>        { name: &#39;Rectangle&#39;, tool: &#39;rectangle&#39; },<br>        { name: &#39;Circle&#39;, tool: &#39;circle&#39; },<br>        { name: &#39;Select&#39;, tool: &#39;select&#39; },<br>        { name: &#39;Clear&#39;, tool: &#39;clear&#39; },<br>    ];<br>    return (<br>        &lt;div className={styles.toolbar}&gt;<br>            {tools.map(({ name, tool }) =&gt; (<br>                &lt;button<br>                    key={tool}<br>                    className={styles.toolButton}<br>                    onClick={() =&gt; onToolSelect(tool)}<br>                &gt;<br>                    {name}<br>                &lt;/button&gt;<br>            ))}<br>        &lt;/div&gt;<br>    );<br>};</pre><p>While this toolbar component is provided in the code, our main Whiteboard component actually already includes the toolbar functionality inline. This separate component could be useful if you want to further modularize your code or add more advanced toolbar features.</p><h3>Step 7: Setting Up Types</h3><p>To ensure type safety throughout our application, let’s define the necessary TypeScript interfaces.</p><p>Create src/types/global.types.ts:</p><pre>export interface ExtendedFabricObject extends fabric.Object {<br>    id: string;<br>    __skipEmit?: boolean;<br>}<br><br>export interface SocketDetails {<br>    clientId: string;<br>}<br>export interface SerializedObjectData {<br>    id: string;<br>    type: string;<br>    [key: string]: any;<br>}</pre><p>These type definitions are crucial for our application:</p><ol><li><strong>ExtendedFabricObject</strong>: Extends the Fabric.js object interface to include our custom properties (ID and __skipEmit flag).</li><li><strong>SocketDetails</strong>: Contains information about the socket connection (client ID).</li><li><strong>SerializedObjectData</strong>: Represents the serialized data of a canvas object that will be transmitted over the socket.</li></ol><p>TypeScript’s type checking helps us catch errors early and provides better code completion in our IDE.</p><h3>Step 8: Running the Application</h3><p>Now that we’ve implemented all the necessary components, let’s run our application:</p><ol><li>Start the development server:</li></ol><pre>npm run dev</pre><ol><li>Start the Socket.IO server (in a separate terminal):</li></ol><pre>node server.js</pre><ol><li>Open your browser to <a href="http://localhost:3000/">http://localhost:3000</a></li></ol><p>You should now see your collaborative whiteboard application! Open it in multiple browser windows to test the real-time collaboration features.</p><h3>Best Practices and Tips</h3><h3>1. Separation of Concerns</h3><p>Our code follows the principle of separation of concerns:</p><ul><li>Canvas operations are encapsulated in useCanvas</li><li>Socket communication is handled in useSocket</li><li>Tool functionality is managed in useToolHandlers</li></ul><p>This makes our code easier to understand, test, and maintain.</p><h3>2. Event Management</h3><p>Proper event management is critical in a real-time application:</p><ul><li>The __skipEmit flag prevents event loops</li><li>Event listeners are properly cleaned up to prevent memory leaks</li><li>Error handling is implemented for socket and canvas operations</li></ul><h3>3. Performance Considerations</h3><p>To maintain good performance, consider:</p><ul><li>Batching canvas updates when possible</li><li>Using efficient object serialization</li><li>Implementing proper cleanup to avoid memory leaks</li></ul><h3>Common Issues and Solutions</h3><h3>1. Event Loops</h3><p><strong>Problem</strong>: Changes trigger multiple events that cascade into an infinite loop.</p><p><strong>Solution</strong>: The __skipEmit flag prevents this by marking objects that are updated due to remote events, so they don&#39;t trigger additional socket emissions.</p><h3>2. Object Synchronization</h3><p><strong>Problem</strong>: Objects getting out of sync between different clients.</p><p><strong>Solution</strong>: Unique IDs for each object and proper serialization ensure that objects stay synchronized across clients.</p><h3>3. Performance Issues</h3><p><strong>Problem</strong>: The canvas becomes slow with many objects.</p><p><strong>Solution</strong>: Implement object grouping, batch updates, and consider implementing canvas layers for complex drawings.</p><h3>Next Steps</h3><p>Here are some ways you could extend this project:</p><ol><li>Add more drawing tools (text, arrows, freeform paths)</li><li>Implement user cursors to see where other users are working</li><li>Add undo/redo functionality using a command pattern</li><li>Implement object locking to prevent conflicts</li><li>Add chat functionality for better collaboration</li><li>Implement persistence to save and load boards</li></ol><h3>Conclusion</h3><p>We’ve successfully built a fully functional collaborative whiteboard application using Next.js, Fabric.js, and Socket.IO! The key factors that made this possible were:</p><ul><li>A well-designed architecture with proper separation of concerns</li><li>Efficient event handling to prevent loops and conflicts</li><li>Strong typing with TypeScript for better code quality</li><li>Real-time communication using Socket.IO</li><li>Powerful canvas manipulation with Fabric.js</li></ul><p>This architecture provides a solid foundation that you can build upon to add more advanced features. The patterns we’ve used — custom hooks, component composition, and event handling — can be applied to many other types of collaborative applications.</p><p>Building real-time collaborative applications can be challenging, but with the right architecture and tools, it becomes much more manageable. I hope this tutorial has given you a good starting point for your own collaborative projects!</p><h3>Resources</h3><ul><li><a href="http://fabricjs.com/docs/">Fabric.js Documentation</a></li><li><a href="https://socket.io/docs/">Socket.IO Documentation</a></li><li><a href="https://nextjs.org/docs">Next.js Documentation</a></li><li><a href="https://reactjs.org/docs/hooks-intro.html">React Hooks Documentation</a></li></ul><blockquote>By the way this is far from completion. I have more features to add to this, have a complete idea and I will keep on pushing on updates onto the GitHub repo so please keep checking it out if you like my efforts. Thankyou.</blockquote><p><a href="https://github.com/Adredrs23/exclone">GitHub - Adredrs23/exclone</a></p><p>I hope you got something interesting out of this and I know I need to work on the Keycloak part. That’ll surely be next if you are awaiting it. Ill deliver on my promise. Until then Happy coding! 🔥🔥🔥</p><p>If you found this tutorial helpful, please clap and share it with others! Feel free to leave comments if you have any questions or suggestions for improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c6b2ef1e072" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time Collaborative Whiteboard — (Backend) with NestJS and Socket.IO:]]></title>
            <link>https://medium.com/@adredars/building-a-real-time-collaborative-whiteboard-backend-with-nestjs-and-socket-io-2229f7bf73bd?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/2229f7bf73bd</guid>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[collaboration-tools]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Sun, 04 May 2025 12:50:42 GMT</pubDate>
            <atom:updated>2025-05-04T12:50:42.520Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Real-Time Collaborative Whiteboard — (Backend) with NestJS and Socket.IO: A Step-by-Step Guide</h3><p>Real-time collaboration features have become essential in modern web applications. Whether it’s document editing, project management, or creative tools, users expect to see changes instantly as their teammates work. In this article, I’ll guide you through building a real-time collaborative whiteboard application using NestJS and Socket.IO, where multiple users can draw simultaneously and see each other’s changes instantly.</p><blockquote>SIDENOTE: This blog is a just the Backend implementation of the Whiteboard I’m trying to recreate here. So it will be helpful if you go through the frontend part as well to get the complete grasp of things. Attached is the frontend article. Thankyou.</blockquote><p><a href="https://medium.com/@adredars/building-a-real-time-collaborative-whiteboard-frontend-with-next-js-7c6b2ef1e072">Medium</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*IG_yRve6jGBw4VMZ" /></figure><p>This learning project will help you understand hopefully the fundamentals of Sockets in Nestjs atleast that’s what I’m going for. Hope you find it helpful. I’m not trying to create something new here, just trying to recreate existing solutions in order to learn and keep a go to reference for future projects.</p><p>Please find the GitHub repo here in order to extend or go through the details that are missing here maybe:</p><p><a href="https://github.com/Adredrs23/exclone-server">GitHub - Adredrs23/exclone-server</a></p><h3>Prerequisites</h3><p>Before we begin, make sure you have:</p><ul><li>Node.js installed (v14 or higher)</li><li>Basic knowledge of TypeScript</li><li>Understanding of WebSocket concepts</li><li>Familiarity with NestJS framework</li></ul><h3>Project Setup</h3><p>Let’s start by creating a new NestJS project. NestJS provides a powerful CLI that makes setting up new projects a breeze:</p><pre>npm i -g @nestjs/cli<br>nest new exclone-server<br>cd exclone-server</pre><p>These commands install the NestJS CLI globally, create a new project named “exclone-server”, and navigate into the project directory. NestJS uses TypeScript by default and sets up a basic project structure with all the necessary configurations.</p><h3>Understanding the Architecture</h3><p>Our collaborative whiteboard application will follow a client-server architecture where:</p><ol><li>The server maintains the current state of all whiteboard objects</li><li>Clients connect via WebSockets to receive updates and send their own changes</li><li>When a client makes a change, it’s sent to the server and then broadcast to all other connected clients</li></ol><p>This architecture ensures that all clients stay in sync with a single source of truth.</p><h3>Core Components</h3><p>Our application consists of two main components:</p><ol><li><strong>Whiteboard Gateway</strong> — Handles real-time drawing operations</li><li><strong>Event Log Service</strong> — Tracks and logs all whiteboard events</li></ol><p>Let’s implement each component in detail.</p><h3>1. Whiteboard Gateway</h3><p>The WhiteboardGateway is the heart of our application. It handles all real-time communication between clients using Socket.IO as the transport layer. Here&#39;s the complete implementation:</p><pre>import {<br>  SubscribeMessage,<br>  WebSocketGateway,<br>  WebSocketServer,<br>  OnGatewayConnection,<br>  OnGatewayDisconnect,<br>  MessageBody,<br>  ConnectedSocket,<br>} from &#39;@nestjs/websockets&#39;;<br>import { Server, Socket } from &#39;socket.io&#39;;<br>import { EventLogService } from &#39;../event-log/event-log.service&#39;;<br><br>type WhiteboardObject = {<br>  id: string;<br>  props: Record&lt;string, unknown&gt;;<br>  [key: string]: unknown;<br>};<br>@WebSocketGateway({ cors: true })<br>export class WhiteboardGateway<br>  implements OnGatewayConnection, OnGatewayDisconnect<br>{<br>  @WebSocketServer()<br>  server: Server;<br>  constructor(private readonly eventLogService: EventLogService) {}<br>  private objects: Record&lt;string, WhiteboardObject&gt; = {};<br>  handleConnection(client: Socket) {<br>    this.eventLogService.log(&#39;client:connected&#39;, { clientId: client.id });<br>    this.eventLogService.log(&#39;client:syncing&#39;, {<br>      objects: Object.values(this.objects),<br>    });<br>    console.log(&#39;client:connected and syncing&#39;, { clientId: client.id });<br>    client.emit(&#39;object:sync&#39;, { objects: Object.values(this.objects) });<br>  }<br>  handleDisconnect(client: Socket) {<br>    this.eventLogService.log(&#39;client:disconnected&#39;, { clientId: client.id });<br>    console.log(&#39;client:disconnected&#39;, { clientId: client.id });<br>  }<br>  @SubscribeMessage(&#39;object:added&#39;)<br>  handleObjectAdded(<br>    @MessageBody() data: WhiteboardObject,<br>    @ConnectedSocket() client: Socket,<br>  ) {<br>    this.eventLogService.log(&#39;object:added&#39;, data);<br>    this.objects[data.id] = data;<br>    client.broadcast.emit(&#39;object:added&#39;, data);<br>  }<br>  @SubscribeMessage(&#39;object:modified&#39;)<br>  handleObjectModified(<br>    @MessageBody() data: WhiteboardObject,<br>    @ConnectedSocket() client: Socket,<br>  ) {<br>    this.eventLogService.log(&#39;object:modified&#39;, data);<br>    if (this.objects[data.id]) {<br>      this.objects[data.id] = {<br>        ...this.objects[data.id],<br>        props: {<br>          ...this.objects[data.id].props,<br>          ...data.props,<br>        },<br>      };<br>      client.broadcast.emit(&#39;object:modified&#39;, data);<br>    }<br>  }<br>  @SubscribeMessage(&#39;object:removed&#39;)<br>  handleObjectRemoved(<br>    @MessageBody() data: WhiteboardObject,<br>    @ConnectedSocket() client: Socket,<br>  ) {<br>    this.eventLogService.log(&#39;object:removed&#39;, data);<br>    delete this.objects[data.id];<br>    client.broadcast.emit(&#39;object:removed&#39;, data);<br>  }<br>  @SubscribeMessage(&#39;canvas:clear&#39;)<br>  handleCanvasClear(@ConnectedSocket() client: Socket) {<br>    this.eventLogService.log(&#39;canvas:clear&#39;, {});<br>    this.objects = {};<br>    client.broadcast.emit(&#39;canvas:clear&#39;);<br>  }<br>}</pre><p>Let’s break down what’s happening in this gateway:</p><ul><li>The @WebSocketGateway() decorator marks this class as a WebSocket gateway with CORS enabled for development purposes.</li><li>We implement OnGatewayConnection and OnGatewayDisconnect interfaces to handle client connections and disconnections.</li><li>The @WebSocketServer() decorator injects the Socket.IO server instance.</li><li>We maintain an in-memory store of all whiteboard objects in the objects property.</li><li>When a new client connects, we immediately send them the current state of the whiteboard through the object:sync event.</li><li>We use @SubscribeMessage() decorators to handle different events from clients:</li><li>object:added: When a new object is drawn</li><li>object:modified: When an existing object is modified</li><li>object:removed: When an object is deleted</li><li>canvas:clear: When the entire canvas is cleared</li></ul><p>For each client action, we:</p><ol><li>Log the event</li><li>Update our server-side state</li><li>Broadcast the change to all other connected clients (using client.broadcast.emit())</li></ol><p>This ensures that all clients are kept in sync with the same whiteboard state.</p><h3>2. Event Log Service</h3><p>I dont know why I created this. Only hope was that this will help me someday help with logs or something, at the least I got the hang of creating REST API with this along with the Socket Gateway.</p><p>The EventLogService helps us track and debug whiteboard events. It maintains a log of recent events that can be useful for debugging and monitoring:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import dayjs from &#39;dayjs&#39;;<br>import timezone from &#39;dayjs/plugin/timezone&#39;;<br>import utc from &#39;dayjs/plugin/utc&#39;;<br><br>dayjs.extend(utc);<br>dayjs.extend(timezone);<br>const dateToUser = (date: string) =&gt; {<br>  return dayjs(date).format(&#39;YYYY-MM-DD HH:mm:ss&#39;);<br>};<br>@Injectable()<br>export class EventLogService {<br>  private readonly eventLogs: any[] = [];<br>  log(eventName: string, payload: any) {<br>    const newLog = {<br>      event: eventName,<br>      timestamp: dateToUser(new Date().toISOString()),<br>      payload,<br>    };<br>    this.eventLogs.push(newLog);<br>    if (this.eventLogs.length &gt; 100) {<br>      this.eventLogs.shift();<br>    }<br>  }<br>  getLogs() {<br>    return this.eventLogs;<br>  }<br>  clearLogs() {<br>    this.eventLogs.length = 0;<br>  }<br>}</pre><p>This service:</p><ul><li>Uses the DayJS library for timestamp formatting</li><li>Maintains a circular buffer of the 100 most recent events</li><li>Provides methods for logging events, retrieving logs, and clearing logs</li></ul><p>The log entries include the event name, a formatted timestamp, and the event payload. This can be extremely helpful for debugging collaboration issues or tracking user actions.</p><h3>3. Application Module</h3><p>The AppModule ties everything together, registering our services and gateways:</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { WhiteboardGateway } from &#39;./whiteboard/whiteboard.gateway&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>import { EventLogService } from &#39;./event-log/event-log.service&#39;;<br><br>@Module({<br>  imports: [ConfigModule.forRoot()],<br>  controllers: [AppController],<br>  providers: [AppService, WhiteboardGateway, EventLogService],<br>})<br>export class AppModule {}</pre><p>Here, we:</p><ul><li>Import the ConfigModule to handle environment variables</li><li>Register our WhiteboardGateway and EventLogService as providers</li><li>Include the default AppController and AppService that come with NestJS</li></ul><h3>WebSocket Events Flow</h3><p>To understand how our application works, let’s examine the WebSocket events flow:</p><h3>Client to Server Events:</h3><ul><li>object:added - When a client adds a new drawing object</li><li>object:modified - When a client modifies an existing object</li><li>object:removed - When a client removes an object</li><li>canvas:clear - When a client clears the entire canvas</li></ul><h3>Server to Client Events:</h3><ul><li>object:sync - Initial object synchronization for new clients (includes all current objects)</li><li>object:added - Notification about new objects added by other clients</li><li>object:modified - Notification about object modifications by other clients</li><li>object:removed - Notification about object removals by other clients</li><li>canvas:clear - Notification about canvas clearing by other clients</li></ul><h3>Data Structure</h3><p>The WhiteboardObject type defines the structure of our drawing objects:</p><pre>type WhiteboardObject = {<br>  id: string;<br>  props: Record&lt;string, unknown&gt;;<br>  [key: string]: unknown;<br>};</pre><p>This flexible structure allows us to store various types of drawing objects (rectangles, circles, lines, text, etc.) with different properties. The props field can contain object-specific attributes like position, size, color, rotation, etc.</p><h3>Running the Application</h3><ol><li>Install dependencies:</li></ol><pre>npm install</pre><ol><li>Start the development server:</li></ol><pre>npm run start:dev</pre><ol><li>The server will run on <a href="http://localhost:3000/">http://localhost:3000</a></li></ol><p>Once the server is running, you can connect to it from a frontend application using the Socket.IO client library.</p><h3>Client-Side Implementation Considerations</h3><p>While this article focuses on the server-side implementation, here are some considerations for the client side:</p><ol><li>Use the Socket.IO client library to connect to the server</li><li>Implement event handlers for all server events</li><li>Emit events to the server when local changes are made</li><li>Consider optimistic updates for better user experience</li></ol><h3>Best Practices and Considerations</h3><ol><li><strong>Error Handling</strong>: Always implement proper error handling for WebSocket events. Socket.IO can disconnect unexpectedly, and we should handle reconnections gracefully.</li><li><strong>Security</strong>: The current implementation enables CORS for development purposes. For production, you should implement proper authentication and authorization.</li><li><strong>Performance</strong>: With many clients and objects, broadcasting every change can become inefficient. Consider implementing:<br>- Object batching (sending multiple changes at once)<br>- Delta updates (sending only what changed)<br>- Throttling updates for rapid changes</li><li><strong>Scalability</strong>: For production use, the in-memory storage will not scale well across multiple server instances. Consider implementing:<br>- Redis for shared state<br>- Database persistence for object storage<br>- Horizontal scaling with sticky sessions or shared state</li></ol><h3>Future Improvements</h3><ol><li><strong>Persistent Storage</strong>: Implement database storage for whiteboard objects to survive server restarts</li><li><strong>User Authentication</strong>: Add user authentication and authorization to restrict access to whiteboards</li><li><strong>Room-based Collaboration</strong>: Implement separate rooms for different whiteboards, allowing multiple whiteboards to exist simultaneously</li><li><strong>Object Versioning</strong>: Add version control for objects to prevent conflicts</li><li><strong>Undo/Redo</strong>: Implement undo/redo functionality by tracking object history</li><li><strong>Cursor Tracking</strong>: Show other users’ cursors to improve collaboration awareness</li></ol><h3>Conclusion</h3><p>In this article, we’ve built a real-time collaborative whiteboard backend using NestJS and Socket.IO. The implementation demonstrates how to handle real-time drawing operations, maintain object state, and synchronize changes across multiple clients.</p><p>The WebSocket architecture provides the low-latency, bidirectional communication needed for collaborative applications. NestJS gives us a structured way to build our backend with TypeScript, while Socket.IO handles the complexities of real-time messaging.</p><p>This project serves as a foundation that you can extend with additional features like authentication, persistence, and more complex collaboration tools. The principles demonstrated here can be applied to other real-time collaborative applications beyond whiteboards.</p><p>Remember that real-time systems come with their own challenges around consistency, latency, and scalability. Always test your implementation thoroughly under realistic conditions before deploying to production. And we shall navigate these waters together soon.</p><p>Until then Happy coding! 🔥🔥🔥</p><p><em>If you found this article helpful, feel free to follow me for more content on web development, real-time applications, and collaborative tools.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2229f7bf73bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time Stock Ticker System with Rust and NATS to learn Rust basics]]></title>
            <link>https://medium.com/@adredars/building-a-real-time-stock-ticker-system-with-rust-and-nats-to-learn-rust-basics-0f6ac1789a9f?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f6ac1789a9f</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nats-streaming]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 19:47:42 GMT</pubDate>
            <atom:updated>2025-04-06T19:47:42.081Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a quick stock ticker mock app to play with Rust’s async capabilities and message-based architecture in order to quickly understand the basics of creating an app with Rust. Lets get onboard to the Rust Hype train.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*5flMtVGWyL-tO13F_vhQEQ.png" /><figcaption>RUST with NATS</figcaption></figure><h3>🚀 Introduction</h3><p>In this post, I’ll walk you through my journey of building a real-time stock ticker system using Rust and NATS. This project demonstrates how to create a scalable, message-based architecture that can handle real-time financial data. We’ll explore asynchronous programming, message brokers, and how to structure a Rust project with multiple components using <strong>Rust</strong>, <strong>NATS</strong>, <strong>PostgreSQL</strong>, and <strong>WebSockets</strong>. Sounds intense? Don’t worry — I’ll walk you through it step by step.</p><p>We’ll start by simulating stock data and streaming it efficiently using NATS (a blazing fast messaging system), then process that data using a Rust consumer. You’ll learn how to:</p><ul><li>Set up a <strong>publisher</strong> that sends mock stock prices</li><li>Create a <strong>consumer</strong> to receive and persist the data</li><li>Store that data in <strong>PostgreSQL </strong>(In Works)</li><li>Build an <strong>aggregator service</strong> to analyze and serve real-time stock trends</li><li>Use <strong>WebSockets</strong> for pushing updates live to a frontend (In Works)</li><li>And sprinkle in <strong>Axum</strong>, Rust’s web framework, for building APIs</li></ul><p>If you’re learning Rust and looking for a real-world, hands-on project, this is it. Whether you’re a backend enthusiast or just curious about how trading platforms work under the hood — you’re going to love this journey.</p><p>We will not try to be a perfectionist with authorization and other strategies rather we will focus more on learning the internals of Rust, NATs and Axum. So this might look a bit half cooked for some experienced Rust devs as we are using command line arguments, in-memory auth states etc. Please bear me with me. Apologies before offending you. 😁😁</p><p>Let’s get started! 🚦</p><p>Whether you’re a Rust enthusiast looking to build something practical or a developer interested in financial data systems, this post will guide you through the process step by step.</p><h3>What We’re Building</h3><p>Our stock ticker system consists of four main components:</p><ol><li><strong>Publisher</strong>: Generates simulated stock prices and publishes them to a message broker</li><li><strong>Consumer</strong>: Subscribes to stock price updates and displays them</li><li><strong>Authentication Service</strong>: Manages user authorization</li><li><strong>Aggregator Service</strong>: Collects, processes, and provides access to aggregated data</li></ol><p>The system uses a publish-subscribe pattern with NATS (Neural Autonomic Transport System) as the message broker, allowing for real-time data distribution with loose coupling between components.</p><h3>Key Concepts You’ll Learn</h3><p>Throughout this project, we’ll explore several important concepts in modern software development:</p><h3>1. Asynchronous Programming</h3><p>We’ll dive into Rust’s async/await syntax and the Tokio runtime, learning how to write non-blocking code that efficiently handles concurrent operations. This is crucial for building responsive systems that can process real-time data without getting bogged down.</p><h3>2. Message-Based Architecture</h3><p>By using NATS as our message broker, we’ll implement a publish-subscribe pattern that decouples our components. This approach allows for better scalability, as new consumers can be added without modifying existing code.</p><h3>3. Microservices Communication</h3><p>Our system consists of multiple services that need to communicate with each other. We’ll explore different communication patterns, from direct HTTP calls to message-based interactions, and understand when to use each approach.</p><h3>4. Thread Safety and Concurrency</h3><p>Rust’s ownership model and concurrency primitives like Arc and Mutex will be used to safely share data between threads. We&#39;ll learn how to design thread-safe data structures that can be accessed by multiple components simultaneously.</p><h3>5. API Design</h3><p>We’ll build RESTful APIs using Axum, learning how to structure endpoints, handle requests and responses, and manage application state in a web server context.</p><h3>6. Project Organization</h3><p>The project will demonstrate how to structure a Rust application with multiple binaries and a shared library crate, showing best practices for code organization and reuse.</p><h3>7. Error Handling</h3><p>We’ll implement robust error handling throughout the system, using Rust’s Result type to propagate errors and handle edge cases gracefully.</p><p>By the end of this project, you’ll have a solid understanding of how to build a distributed system with Rust, with components that can be developed, tested, and deployed independently.</p><h4>📌 <strong>System Architecture Overview</strong></h4><p>Below is a visual representation of the data flow in our real-time stock ticker system. From publishing mock stock data to serving it live on a frontend:</p><blockquote><em>Publisher → NATS → Consumer → PostgreSQL </em>(In Works) <em>→ Aggregator → WebSocket </em>(In Works)<em> → Frontend </em>(In Works)</blockquote><h3>Project Setup</h3><p>Let’s start by setting up our Rust project:</p><pre>cargo new stock-ticker<br>cd stock-ticker</pre><h3>Core Dependencies</h3><p>We’ll need several dependencies for our project. Let’s add them to our Cargo.toml:</p><pre>[package]<br>name = &quot;stock-ticker&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2024&quot;</pre><pre>[[bin]]<br>name = &quot;publisher&quot;<br>path = &quot;src/bin/publisher.rs&quot;</pre><pre>[[bin]]<br>name = &quot;consumer&quot;<br>path = &quot;src/bin/consumer.rs&quot;</pre><pre>[[bin]]<br>name = &quot;auth_service&quot;<br>path = &quot;src/bin/auth_service.rs&quot;</pre><pre>[[bin]]<br>name = &quot;aggregator&quot;<br>path = &quot;src/bin/aggregator.rs&quot;</pre><pre>[dependencies]<br>async-nats = &quot;0.39.0&quot;<br>axum = { version = &quot;0.8.1&quot;, features = [&quot;macros&quot;] }<br>chrono = &quot;0.4.40&quot;<br>futures = &quot;0.3.30&quot;<br>rand = &quot;0.9.0&quot;<br>reqwest = { version = &quot;0.12.12&quot;, features = [&quot;json&quot;] }<br>serde = { version = &quot;1.0.219&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1.0.140&quot;<br>sqlx = { version = &quot;0.8.3&quot;, features = [&quot;postgres&quot;, &quot;runtime-tokio-native-tls&quot;] }<br>tokio = { version = &quot;1.44.0&quot;, features = [&quot;full&quot;] }<br>tracing = &quot;0.1.41&quot;<br>tracing-subscriber = &quot;0.3.19&quot;</pre><pre>[lib]<br>name = &quot;stock_ticker&quot;<br>path = &quot;src/lib.rs&quot;</pre><p>This configuration sets up multiple binary targets for our different services and includes all the dependencies we’ll need.</p><h3>Project Structure</h3><p>We’ll organize our project with a library crate for shared code and multiple binary targets for our services:</p><pre>stock-ticker/<br>├── Cargo.toml<br>├── src/<br>│   ├── lib.rs<br>│   ├── types.rs<br>│   └── bin/<br>│       ├── publisher.rs<br>│       ├── consumer.rs<br>│       ├── auth_service.rs<br>│       └── aggregator.rs<br>└── docs/<br>    ├── publisher.md<br>    ├── consumer.md<br>    ├── auth_service.md<br>    ├── aggregator.md<br>    └── timeline.md</pre><p>Let’s start by creating our shared data structures in the library crate:</p><pre>// src/lib.rs<br>pub mod types;</pre><pre>// src/types.rs<br>use serde::{Deserialize, Serialize};</pre><pre>#[derive(Serialize, Deserialize, Debug, Clone)]<br>pub struct StockPrice {<br>    pub symbol: String,<br>    pub price: f64,<br>    pub timestamp: String,<br>}</pre><pre>#[derive(Debug, Clone, Serialize)]<br>pub struct AggregatedStats {<br>    pub total: f64,<br>    pub count: usize,<br>    pub average: f64,<br>    pub latest: f64,<br>}</pre><pre>#[derive(Clone, Default)]<br>pub struct AggregatedState {<br>    pub raw_data: std::sync::Arc&lt;std::sync::Mutex&lt;std::collections::HashMap&lt;String, Vec&lt;StockPrice&gt;&gt;&gt;&gt;,<br>    pub stats_data: std::sync::Arc&lt;std::sync::Mutex&lt;std::collections::HashMap&lt;String, AggregatedStats&gt;&gt;&gt;,<br>}</pre><h3>Building the Publisher</h3><p>The publisher is responsible for generating simulated stock prices and publishing them to NATS. Let’s implement it:</p><pre>// src/bin/publisher.rs<br>use async_nats::connect;<br>use chrono::Utc;<br>use rand::distr::{Distribution, Uniform};<br>use rand::rng;<br>use serde_json;<br>use tokio::time::{Duration, sleep};</pre><pre>use stock_ticker::types::StockPrice;</pre><pre>async fn generate_random_price() -&gt; f64 {<br>    let mut rng = rng();<br>    let price_range = Uniform::new(100.0, 500.0).expect(&quot;Failed to create uniform distribution&quot;);<br>    price_range.sample(&amp;mut rng)<br>}</pre><pre>#[tokio::main]<br>async fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {<br>    // Connect to NATS server asynchronously<br>    let client = connect(&quot;nats://127.0.0.1:4222&quot;).await?;</pre><pre>    let symbols = vec![&quot;AAPL&quot;, &quot;GOOGL&quot;, &quot;AMZN&quot;, &quot;MSFT&quot;, &quot;TSLA&quot;];</pre><pre>    loop {<br>        for symbol in &amp;symbols {<br>            let stock_price = StockPrice {<br>                symbol: symbol.to_string(),<br>                price: generate_random_price().await,<br>                timestamp: Utc::now().to_rfc3339(),<br>            };</pre><pre>            // Serialize struct to JSON<br>            let message = serde_json::to_string(&amp;stock_price)?;</pre><pre>            // Publish to NATS asynchronously<br>            client.publish(&quot;stock_prices&quot;, message.into()).await?;</pre><pre>            println!(&quot;📤 Published: {:?}&quot;, stock_price);<br>        }</pre><pre>        // Sleep asynchronously for 2 seconds before generating new prices<br>        sleep(Duration::from_secs(2)).await;<br>    }<br>}</pre><p>This publisher:</p><ol><li>Connects to a NATS server</li><li>Generates random stock prices for predefined symbols</li><li>Serializes the data to JSON</li><li>Publishes it to the “stock_prices” topic</li><li>Repeats the process every 2 seconds</li></ol><h3>Building the Consumer</h3><p>The consumer subscribes to the “stock_prices” topic and displays the received data:</p><pre>// src/bin/consumer.rs<br>use async_nats::ConnectOptions;<br>use futures::StreamExt;<br>use reqwest;<br>use serde_json;<br>use std::env;</pre><pre>use stock_ticker::types::StockPrice;</pre><pre>#[tokio::main]<br>async fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {<br>    let args: Vec&lt;String&gt; = env::args().collect();<br>    if args.len() &lt; 2 {<br>        eprintln!(&quot;Usage: consumer &lt;email&gt;&quot;);<br>        return Ok(());<br>    }</pre><pre>    let email = &amp;args[1];<br>    let auth_url = format!(&quot;http://localhost:3001/is-authorized?email={}&quot;, email);</pre><pre>    let res = reqwest::get(&amp;auth_url).await?.json::&lt;bool&gt;().await?;</pre><pre>    if !res {<br>        println!(&quot;❌ Access denied for {}&quot;, email);<br>        return Ok(());<br>    }</pre><pre>    println!(&quot;✅ Access granted. Connecting to NATS...&quot;);</pre><pre>    // Connect to the NATS server asynchronously<br>    let client = ConnectOptions::new()<br>        .connect(&quot;nats://127.0.0.1:4222&quot;)<br>        .await?;</pre><pre>    println!(&quot;Connected to NATS at nats://127.0.0.1:4222&quot;);</pre><pre>    // Subscribe to &quot;stock_prices&quot; topic<br>    let mut subscriber = client.subscribe(&quot;stock_prices&quot;).await?;<br>    println!(&quot;Subscribed to &#39;stock_prices&#39;...&quot;);</pre><pre>    // Loop over incoming messages<br>    while let Some(message) = subscriber.next().await {<br>        let payload = String::from_utf8_lossy(&amp;message.payload);</pre><pre>        match serde_json::from_str::&lt;StockPrice&gt;(&amp;payload) {<br>            Ok(stock_price) =&gt; {<br>                println!(&quot;📥 Received: {:?}&quot;, stock_price);<br>            }<br>            Err(e) =&gt; {<br>                eprintln!(&quot;❌ Failed to parse message: {}&quot;, e);<br>            }<br>        }<br>    }</pre><pre>    Ok(())<br>}</pre><p>The consumer:</p><ol><li>Takes an email address as a command-line argument</li><li>Checks if the email is authorized via the auth service</li><li>Connects to NATS if authorized</li><li>Subscribes to the “stock_prices” topic</li><li>Deserializes and displays incoming messages</li></ol><h3>Building the Authentication Service</h3><p>The authentication service provides a simple HTTP API for user registration and authorization:</p><pre>// src/bin/auth_service.rs<br>use axum::extract::Query;<br>use axum::{<br>    Router,<br>    extract::Json,<br>    extract::State,<br>    routing::{get, post},<br>};<br>use serde::{Deserialize, Serialize};<br>use std::{<br>    collections::HashSet,<br>    net::SocketAddr,<br>    sync::{Arc, Mutex},<br>};</pre><pre>#[derive(Debug, Deserialize, Serialize, Clone)]<br>struct Registration {<br>    email: String,<br>}</pre><pre>#[derive(Clone)]<br>struct AppState {<br>    authorized_emails: Arc&lt;Mutex&lt;HashSet&lt;String&gt;&gt;&gt;,<br>}</pre><pre>#[tokio::main]<br>async fn main() {<br>    let state = AppState {<br>        authorized_emails: Arc::new(Mutex::new(HashSet::new())),<br>    };</pre><pre>    let app = Router::new()<br>        .route(&quot;/register&quot;, post(register))<br>        .route(&quot;/is-authorized&quot;, get(is_authorized))<br>        .route(&quot;/list-emails&quot;, get(list_emails))<br>        .with_state(state);</pre><pre>    let addr = SocketAddr::from(([127, 0, 0, 1], 3001));<br>    println!(&quot;🔐 Auth service running on http://{}&quot;, addr);</pre><pre>    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();<br>    println!(&quot;Listening on {}&quot;, addr);<br>    axum::serve(listener, app).await.unwrap();<br>}</pre><pre>async fn register(<br>    State(state): State&lt;AppState&gt;,<br>    Json(payload): Json&lt;Registration&gt;,<br>) -&gt; &amp;&#39;static str {<br>    let mut auth_list = state.authorized_emails.lock().unwrap();<br>    auth_list.insert(payload.email);<br>    &quot;✅ Registered&quot;<br>}</pre><pre>async fn is_authorized(<br>    State(state): State&lt;AppState&gt;,<br>    Query(params): Query&lt;Registration&gt;,<br>) -&gt; Json&lt;bool&gt; {<br>    let auth_list = state.authorized_emails.lock().unwrap();<br>    Json(auth_list.contains(&amp;params.email))<br>}</pre><pre>async fn list_emails(State(state): State&lt;AppState&gt;) -&gt; Json&lt;Vec&lt;String&gt;&gt; {<br>    let auth_list = state.authorized_emails.lock().unwrap();<br>    Json(auth_list.iter().cloned().collect())<br>}</pre><p>The authentication service:</p><ol><li>Maintains a thread-safe list of authorized email addresses</li><li>Provides endpoints for registration, authorization checks, and listing authorized emails</li><li>Uses Axum for the HTTP API</li></ol><h3>Building the Aggregator Service</h3><p>The aggregator service collects stock price data, calculates statistics, and provides access to both raw and aggregated data:</p><pre>// src/bin/aggregator.rs<br>use async_nats::ConnectOptions;<br>use axum::extract::Path;<br>use axum::{Json, Router, extract::State, routing::get};<br>use futures::StreamExt;<br>use reqwest;<br>use std::{collections::HashMap, env, net::SocketAddr};<br>use stock_ticker::types::{AggregatedState, AggregatedStats, StockPrice};<br>use tokio::task;</pre><pre>#[tokio::main]<br>async fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {<br>    let args: Vec&lt;String&gt; = env::args().collect();<br>    if args.len() &lt; 2 {<br>        eprintln!(&quot;Usage: aggregator &lt;email&gt;&quot;);<br>        return Ok(());<br>    }</pre><pre>    let email = &amp;args[1];<br>    let auth_url = format!(&quot;http://localhost:3001/is-authorized?email={}&quot;, email);</pre><pre>    let res = reqwest::get(&amp;auth_url).await?.json::&lt;bool&gt;().await?;</pre><pre>    if !res {<br>        eprintln!(&quot;❌ Access denied for {}&quot;, email);<br>        return Ok(());<br>    }</pre><pre>    println!(&quot;✅ Access granted. Starting aggregator service...&quot;);</pre><pre>    let state = AggregatedState::default();</pre><pre>    // Spawn listener<br>    let nats_state = state.clone();<br>    task::spawn(async move {<br>        if let Err(err) = start_nats_listener(nats_state).await {<br>            eprintln!(&quot;NATS listener error: {:?}&quot;, err);<br>        }<br>    });</pre><pre>    // Set up API<br>    let app = Router::new()<br>        .route(&quot;/aggregate&quot;, get(get_stats))<br>        .route(&quot;/raw&quot;, get(get_raw))<br>        .route(&quot;/aggregate/{symbol}&quot;, get(get_stats_for_symbol))<br>        .route(&quot;/raw/{symbol}&quot;, get(get_raw_for_symbol))<br>        .with_state(state.clone());</pre><pre>    let addr = SocketAddr::from(([127, 0, 0, 1], 3002));<br>    println!(&quot;📊 Aggregator service running on http://{}&quot;, addr);</pre><pre>    let listener = tokio::net::TcpListener::bind(addr).await?;<br>    axum::serve(listener, app).await?;</pre><pre>    Ok(())<br>}</pre><pre>// GET /aggregate → returns only the stats<br>async fn get_stats(State(state): State&lt;AggregatedState&gt;) -&gt; Json&lt;HashMap&lt;String, AggregatedStats&gt;&gt; {<br>    let data = state.stats_data.lock().unwrap();<br>    Json(data.clone())<br>}</pre><pre>// GET /raw → returns the raw stock price list<br>async fn get_raw(State(state): State&lt;AggregatedState&gt;) -&gt; Json&lt;HashMap&lt;String, Vec&lt;StockPrice&gt;&gt;&gt; {<br>    let raw = state.raw_data.lock().unwrap();<br>    Json(raw.clone())<br>}</pre><pre>async fn start_nats_listener(state: AggregatedState) -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {<br>    let client = ConnectOptions::new()<br>        .connect(&quot;nats://127.0.0.1:4222&quot;)<br>        .await?;</pre><pre>    println!(&quot;📡 Aggregator connected to NATS.&quot;);</pre><pre>    let mut subscriber = client.subscribe(&quot;stock_prices&quot;).await?;<br>    while let Some(message) = subscriber.next().await {<br>        let payload = String::from_utf8_lossy(&amp;message.payload);<br>        if let Ok(stock) = serde_json::from_str::&lt;StockPrice&gt;(&amp;payload) {<br>            {<br>                let mut raw_map = state.raw_data.lock().unwrap();<br>                raw_map<br>                    .entry(stock.symbol.clone())<br>                    .or_default()<br>                    .push(stock.clone());<br>            }</pre><pre>            {<br>                let mut stats_map = state.stats_data.lock().unwrap();<br>                let stats = stats_map<br>                    .entry(stock.symbol.clone())<br>                    .or_insert(AggregatedStats {<br>                        total: 0.0,<br>                        count: 0,<br>                        average: 0.0,<br>                        latest: 0.0,<br>                    });</pre><pre>                stats.total += stock.price;<br>                stats.count += 1;<br>                stats.latest = stock.price;<br>                stats.average = stats.total / stats.count as f64;<br>            }<br>        }<br>    }</pre><pre>    Ok(())<br>}</pre><pre>// GET /aggregate/:symbol → return stats for 1 symbol<br>async fn get_stats_for_symbol(<br>    State(state): State&lt;AggregatedState&gt;,<br>    Path(symbol): Path&lt;String&gt;,<br>) -&gt; Json&lt;Option&lt;AggregatedStats&gt;&gt; {<br>    let data = state.stats_data.lock().unwrap();<br>    Json(data.get(&amp;symbol).cloned())<br>}</pre><pre>// GET /raw/:symbol → return raw stock data for 1 symbol<br>async fn get_raw_for_symbol(<br>    State(state): State&lt;AggregatedState&gt;,<br>    Path(symbol): Path&lt;String&gt;,<br>) -&gt; Json&lt;Option&lt;Vec&lt;StockPrice&gt;&gt;&gt; {<br>    let data = state.raw_data.lock().unwrap();<br>    Json(data.get(&amp;symbol).cloned())<br>}</pre><p>The aggregator service:</p><ol><li>Checks authorization with the auth service</li><li>Subscribes to the “stock_prices” topic to collect data</li><li>Maintains both raw data and calculated statistics</li><li>Provides REST API endpoints for accessing the data</li><li>Uses thread-safe state management with Arc&lt;Mutex&lt;&gt;&gt;</li></ol><h3>Running the System</h3><p>Now that we have all our components, let’s run the system:</p><ol><li>Start the NATS server (required)</li></ol><p>2. Start the authentication service:</p><ul><li>cargo run --bin auth_service</li></ul><p>3. Register a user with the auth service:</p><ul><li>curl -X POST http://127.0.0.1:3001/register \ -H &quot;Content-Type: application/json&quot; \ -d &#39;{&quot;email&quot;: &quot;user@example.com&quot;}&#39;</li></ul><p>4. Run the publisher:</p><ul><li>cargo run --bin publisher</li></ul><p>5. Run the consumer with an authorized email:</p><ul><li>cargo run --bin consumer user@example.com</li></ul><p>6. Run the aggregator with an authorized email:</p><ul><li>cargo run --bin aggregator user@example.com</li></ul><p>7. Access the aggregator API:</p><ul><li>curl <a href="http://127.0.0.1:3002/aggregate">http://127.0.0.1:3002/aggregate</a></li></ul><h3>Key Technical Concepts</h3><h3>Asynchronous Programming with Tokio</h3><p>Rust’s async/await syntax combined with the Tokio runtime allows us to write non-blocking code that efficiently handles many concurrent operations. This is crucial for a system that needs to process real-time data.</p><pre>#[tokio::main]<br>async fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {<br>    // Async code here<br>}</pre><h3>Message-Based Architecture with NATS</h3><p>NATS provides a lightweight, high-performance messaging system that enables loose coupling between components. Our publisher doesn’t need to know about consumers, and consumers don’t need to know about each other.</p><pre>// Publishing<br>client.publish(&quot;stock_prices&quot;, message.into()).await?;</pre><pre>// Subscribing<br>let mut subscriber = client.subscribe(&quot;stock_prices&quot;).await?;</pre><h3>Thread Safety with Arc and Mutex</h3><p>Rust’s ownership model combined with Arc (Atomic Reference Counting) and Mutex (Mutual Exclusion) allows us to safely share data between threads:</p><pre>#[derive(Clone)]<br>struct AppState {<br>    authorized_emails: Arc&lt;Mutex&lt;HashSet&lt;String&gt;&gt;&gt;,<br>}</pre><h3>HTTP API with Axum</h3><p>Axum provides a modern, ergonomic web framework for building HTTP APIs in Rust:</p><pre>let app = Router::new()<br>    .route(&quot;/register&quot;, post(register))<br>    .route(&quot;/is-authorized&quot;, get(is_authorized))<br>    .with_state(state);</pre><h3>Project Evolution</h3><p>Our project evolved through several phases:</p><ol><li><strong>Initial Setup</strong>: Setting up the project structure and dependencies</li><li><strong>Publisher Implementation</strong>: Creating the data structure and publisher service</li><li><strong>Consumer Implementation</strong>: Building the consumer to display stock prices</li><li><strong>Authentication Service</strong>: Adding user authorization</li><li><strong>Project Structure Refinement</strong>: Organizing code into a library crate</li><li><strong>Aggregator Service</strong>: Adding data aggregation and API access</li><li><strong>Documentation</strong>: Creating comprehensive documentation</li></ol><h3>Conclusion</h3><p>Building this stock ticker system demonstrated the power of Rust’s async capabilities and message-based architecture. The combination of Rust’s performance and safety features with NATS’s reliable messaging makes it suitable for production-grade financial applications.</p><p>The code is structured to be maintainable and extensible, making it a good foundation for building more complex financial data processing systems.</p><h3>Resources</h3><ul><li><a href="https://doc.rust-lang.org/book/">Rust Book</a></li><li><a href="https://tokio.rs/docs/overview">Tokio Documentation</a></li><li><a href="https://docs.nats.io/">NATS Documentation</a></li><li><a href="https://docs.rs/axum/latest/axum/">Axum Documentation</a></li></ul><p><strong>Thanks for reading!</strong> If you found this post helpful, feel free to share it with others who might be interested in Rust. I hope you enjoyed it — I’ll be back next time with improvements and new concepts added to this project.</p><p>For your reference, here’s the git repo —</p><p><a href="https://github.com/Adredrs23/rust-pub-sub/tree/feature/adred/pub-sub-auth-with-binaries">https://github.com/Adredrs23/rust-pub-sub/tree/feature/adred/pub-sub-auth-with-binaries</a></p><p>Until then, happy coding! 🔥🔥🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f6ac1789a9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Microfrontends using Webpack’s Module Federation]]></title>
            <link>https://medium.com/@adredars/react-microfrontends-using-webpacks-module-federation-83ece891b20e?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/83ece891b20e</guid>
            <category><![CDATA[error-boundaries]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <category><![CDATA[module-federation]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 09:06:37 GMT</pubDate>
            <atom:updated>2024-12-08T09:06:37.503Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will help you setup microfrontend react application from scratch without using the create-react-app command using webpack’s module federation plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WMHUj-qRD9IhPFd-.png" /></figure><h4>Getting started with Babel and Webpack</h4><p>We will start by installing some of the dependencies that are must for our react application to work. Use the following command in the terminal to get started.</p><p>Start a fresh project using npm init. This will generate your package.json and then move forward to install the mentioned packages.</p><p>React and ReactDOM are the pre-requisites obviously as this is a react project.</p><pre>npm init<br><br>npm install react react-dom<br>npm install webpack webpack-cli webpack-dev-server html-webpack-plugin babel-loader @babel/core @babel/preset-env @babel/preset-react -D</pre><ul><li>webpack - Bundler for the app.</li><li>webpack-cli - Command line tool to run Webpack.</li><li>webpack-dev-server - Server for running your app locally.</li><li>html-webpack-plugin - Plugin to generate an index.html file.</li><li>babel-loader - Transpile ES6/React JSX code to plain JS.</li><li>@babel/core, @babel/preset-env, @babel/preset-react - Babel-related packages to support React.</li></ul><p>Once you are done with this, lets create a .babelrc file in the root of your project. This file helps define the transpilation configuration for babel, we will be extending the default configuration with some of the presets for react as shown below.</p><pre>// .babelrc<br><br>{<br>  &quot;presets&quot;: [&quot;@babel/preset-env&quot;, &quot;@babel/preset-react&quot;]<br>}</pre><p>Another important configuration that you need to provide is the bundler that knows how to read every file and emit a bundled piece of code that your browser can understand and run it. To do that we will be using the webpack bundler and below is the configuration that we are going to provide to it.</p><p>Add a webpack.common.js file in the root of the project. I generally prefer to divide my webpack config into common, dev and production for maintainability.</p><p>To do that we make use of webpack-merge, install it using the following command as dev dependency.</p><pre>npm install webpack-merge -D</pre><pre>// webpack.common.js<br><br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);<br>const { ModuleFederationPlugin } = require(&#39;webpack&#39;).container;<br>const path = require(&#39;path&#39;);<br>const deps = require(&#39;./package.json&#39;).dependencies;<br><br>module.exports = {<br> entry: &#39;./index.js&#39;,<br> output: {<br>  path: path.resolve(__dirname, &#39;../dist&#39;),<br>  publicPath: &#39;auto&#39;, // or simply &#39;/&#39; if you are struggling to see the<br>  // page in react-router-dom approach with historyApi<br> },<br> resolve: {<br>  extensions: [&#39;.jsx&#39;,&#39;.js&#39;],<br> },<br> module: {<br>  rules: [<br>    {<br>      test: /\.(js|jsx)$/,<br>      exclude: /node_modules/,<br>      use: {<br>        loader: &#39;babel-loader&#39;,<br>      },<br>    },<br>  ],<br> },<br>};<br></pre><p>Here are some key points for this config —</p><blockquote>1. entry: &#39;./index.js&#39;</blockquote><blockquote><strong>Purpose</strong>: This is the entry point for your application. Webpack starts bundling from this file.</blockquote><blockquote><strong>Explanation</strong>: The &#39;./index.js&#39; file will be the root of the dependency graph. Webpack will start from this file and include all dependencies that are imported within it (directly or indirectly).</blockquote><blockquote>2. output: { ... }</blockquote><blockquote><strong>Purpose</strong>: This section defines how and where Webpack should output the final bundled files.</blockquote><blockquote><strong>path: path.resolve(__dirname, &#39;../dist&#39;)</strong>:</blockquote><blockquote><strong>Explanation</strong>: This specifies the output directory where the bundled files will be saved. path.resolve creates an absolute path, and __dirname refers to the directory where this configuration file is located.</blockquote><blockquote>path.resolve(__dirname, &#39;../dist&#39;) ensures that the bundled files are placed in a dist directory, which is located one level above the current directory (relative to the Webpack configuration file).</blockquote><blockquote><strong>publicPath: &#39;auto&#39;</strong>:</blockquote><blockquote><strong>Explanation</strong>: This setting determines the base URL for all assets within your app, especially for things like images, scripts, and fonts that are referenced in your JavaScript.</blockquote><blockquote>&#39;auto&#39; is a new feature in Webpack 5 and will automatically determine the correct public path based on the environment (e.g., whether you&#39;re running in development or production). It simplifies handling assets in both local and CDN scenarios.</blockquote><blockquote>3. resolve: { ... }</blockquote><blockquote><strong>Purpose</strong>: This tells Webpack how to resolve module imports.</blockquote><blockquote><strong>extensions: [&#39;.jsx&#39;, &#39;.js&#39;]</strong>:</blockquote><blockquote><strong>Explanation</strong>: This specifies the file extensions Webpack will attempt to resolve when it encounters an import or require statement without an explicit file extension.</blockquote><blockquote>This means if you import SomeComponent from &#39;./SomeComponent&#39;, Webpack will look for SomeComponent.jsx, then SomeComponent.js in that order.</blockquote><blockquote>4. module: { rules: [ ... ] }</blockquote><blockquote><strong>Purpose</strong>: This section defines how Webpack should handle different types of files when bundling.</blockquote><blockquote><strong>test: /\.(js|jsx)$/</strong>:</blockquote><blockquote><strong>Explanation</strong>: This is a regular expression that tells Webpack which files to apply this rule to. In this case, it matches .js and .jsx files (JavaScript and JSX files).</blockquote><blockquote><strong>exclude: /node_modules/</strong>:</blockquote><blockquote><strong>Explanation</strong>: This prevents Webpack from processing files inside the node_modules directory. Since dependencies in node_modules are usually already precompiled or written in a format that Webpack can process natively, we typically exclude them to improve performance.</blockquote><blockquote><strong>use: { loader: &#39;babel-loader&#39; }</strong>:</blockquote><blockquote><strong>Explanation</strong>: This tells Webpack to use babel-loader for transforming JavaScript and JSX files.</blockquote><blockquote>babel-loader uses Babel to transpile modern JavaScript (and JSX) into code that can run on older browsers (depending on your Babel configuration). It ensures compatibility with older versions of JavaScript.</blockquote><pre>// webpack.dev.js<br><br>const { merge } = require(&#39;webpack-merge&#39;);<br>const commonConfig = require(&#39;./webpack.common&#39;);<br>const path = require(&#39;path&#39;);<br><br>module.exports = merge(commonConfig, {<br> mode: &#39;development&#39;,<br> devServer: {<br>  static: {<br>   directory: path.join(__dirname, &#39;../dist&#39;),<br>  },<br>  port: 3005,<br>  hot: true,<br>  historyApiFallback: true,<br> },<br> devtool: &#39;inline-source-map&#39;,<br>});</pre><p>Important point to focus on the <strong>historyApiFallback </strong>configuration as I broke my head for hours to understand why my client side routing always redirected me to 404. If only I knew this before.🤷‍♂️</p><blockquote>1. merge(commonConfig, { ... })</blockquote><blockquote><strong>Purpose</strong>: The merge function is used to combine two configuration objects. It typically comes from the webpack-merge package.</blockquote><blockquote><strong>Explanation</strong>: The commonConfig contains shared settings (like entry, output, module rules, etc.) that apply to both development and production builds. The second argument is an object containing development-specific settings, which will override or extend commonConfig where necessary.</blockquote><blockquote>2. mode: &#39;development&#39;</blockquote><blockquote><strong>Purpose</strong>: This key tells Webpack to run in <strong>development mode</strong>.</blockquote><blockquote><strong>Explanation</strong>: In <strong>development mode</strong>, Webpack optimizes for a faster build and better debugging experience. It will not minify the output (as it would in production mode), and will include source maps and other helpful features for debugging. This is a common setting for local development or testing environments.</blockquote><blockquote>3. devServer: { ... }</blockquote><blockquote><strong>Purpose</strong>: The devServer key configures Webpack’s <strong>development server</strong>. This server serves your bundled files during development and provides useful features like hot-reloading and live reloading.</blockquote><blockquote><strong>static: { directory: path.join(__dirname, &#39;../dist&#39;) }</strong>:</blockquote><blockquote><strong>Explanation</strong>: This tells the Webpack DevServer where to serve static files from. Here, it is serving the contents of the dist directory (which is where the Webpack bundles are output).</blockquote><blockquote>path.join(__dirname, &#39;../dist&#39;) ensures that the server serves files from the correct location relative to the Webpack config file.</blockquote><blockquote><strong>port: 3005</strong>:</blockquote><blockquote><strong>Explanation</strong>: This specifies the port number on which the development server should run. By default, Webpack DevServer runs on port 8080, but here it is set to 3005.</blockquote><blockquote><strong>hot: true</strong>:</blockquote><blockquote><strong>Explanation</strong>: This enables <strong>Hot Module Replacement (HMR)</strong>. HMR allows modules to be replaced in the browser without a full reload, providing a smoother development experience. Only the updated parts of the app are replaced, so you don’t lose the app state during development.</blockquote><blockquote><strong>historyApiFallback: true</strong>:</blockquote><blockquote><strong>Explanation</strong>: This setting is useful for single-page applications (SPA) that use the HTML5 History API (i.e., client-side routing). When you refresh a page with a URL that doesn’t directly map to a file on the server (e.g., /profile), the server will redirect all requests to index.html, allowing the front-end routing to handle the URL.</blockquote><blockquote>Without this, refreshing a route like /profile might result in a 404 error because Webpack DevServer wouldn’t know about routes that are handled client-side.</blockquote><blockquote>4. devtool: &#39;inline-source-map&#39;</blockquote><blockquote><strong>Purpose</strong>: This setting controls how source maps are generated.</blockquote><blockquote><strong>Explanation</strong>: In <strong>development mode</strong>, devtool: &#39;inline-source-map&#39; tells Webpack to include a source map in the output, and it will be embedded as a <strong>data URL</strong> within the JavaScript bundle itself. This allows you to debug the original source code (like your unminified JavaScript or JSX) directly in the browser&#39;s developer tools, making it easier to trace errors back to the original code.</blockquote><blockquote><strong>inline-source-map</strong> is a good choice for development because it is fast and provides full debugging support.</blockquote><blockquote>There are other types of source maps, like eval-source-map, cheap-source-map, etc., each offering different trade-offs between build speed and source map detail.</blockquote><pre>// webpack.prod.js<br><br>const { merge } = require(&#39;webpack-merge&#39;);<br>const commonConfig = require(&#39;./webpack.common&#39;);<br>const path = require(&#39;path&#39;);<br><br>module.exports = merge(commonConfig, {<br> mode: &#39;production&#39;,<br> output: {<br>  filename: &#39;[name].[contenthash].js&#39;, // Cache-busting filenames<br>  path: path.resolve(__dirname, &#39;../dist&#39;),<br>  clean: true, // Cleans the /dist folder on every build<br> },<br> optimization: {<br>  minimize: true, // Enables minification<br>  splitChunks: {<br>   chunks: &#39;all&#39;, // Splits vendor and common modules<br>  },<br> },<br>});</pre><p>Looking at the production configuration, it is very evident that the bundled files are hashed, minified and optimized for performance.</p><p>Below given is the package.json file of the completed setup for your reference. Important points are the scripts as they configured to serve webpack bundled content based on the dev or prod config.</p><pre>// package.json<br><br>{<br> &quot;name&quot;: &quot;ums-mf-shell&quot;,<br> &quot;version&quot;: &quot;1.0.0&quot;,<br> &quot;description&quot;: &quot;&quot;,<br> &quot;main&quot;: &quot;index.js&quot;,<br> &quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;webpack serve --config webpack.dev.js&quot;,<br>  &quot;build&quot;: &quot;webpack --config webpack.prod.js&quot;<br> },<br> &quot;keywords&quot;: [],<br> &quot;author&quot;: &quot;&quot;,<br> &quot;license&quot;: &quot;ISC&quot;,<br> &quot;devDependencies&quot;: {<br>  &quot;@babel/core&quot;: &quot;^7.25.7&quot;,<br>  &quot;@babel/preset-env&quot;: &quot;^7.25.7&quot;,<br>  &quot;@babel/preset-react&quot;: &quot;^7.25.7&quot;,<br>  &quot;@types/react&quot;: &quot;^18.3.11&quot;,<br>  &quot;@types/react-dom&quot;: &quot;^18&quot;,<br>  &quot;babel-loader&quot;: &quot;^9.2.1&quot;,<br>  &quot;html-webpack-plugin&quot;: &quot;^5.6.0&quot;,<br>  &quot;ts-loader&quot;: &quot;^9.4.3&quot;,<br>  &quot;typescript&quot;: &quot;^5.6.2&quot;,<br>  &quot;webpack&quot;: &quot;^5.95.0&quot;,<br>  &quot;webpack-cli&quot;: &quot;^5.1.4&quot;,<br>  &quot;webpack-dev-server&quot;: &quot;^5.1.0&quot;,<br>  &quot;webpack-merge&quot;: &quot;^6.0.1&quot;<br> },<br> &quot;dependencies&quot;: {<br>  &quot;@reduxjs/toolkit&quot;: &quot;^2.3.0&quot;,<br>  &quot;axios&quot;: &quot;^1.7.7&quot;,<br>  &quot;keycloak-js&quot;: &quot;^26.0.4&quot;,<br>  &quot;react&quot;: &quot;^18.3.1&quot;,<br>  &quot;react-dom&quot;: &quot;^18&quot;,<br>  &quot;react-error-boundary&quot;: &quot;^4.0.13&quot;,<br>  &quot;react-redux&quot;: &quot;^9.1.2&quot;,<br>  &quot;react-router-dom&quot;: &quot;^6.27.0&quot;<br> }<br>}</pre><h4>Adding Typescript support</h4><p>Start by adding the right dependencies then adding the tsconfig.json file in the root and modifying the webpack config to support typescript.</p><pre>npm install typescript ts-loader @types/react @types/react-dom -D</pre><pre>// tsconfig.json<br>{<br> &quot;compilerOptions&quot;: {<br>  &quot;target&quot;: &quot;ES5&quot;,<br>  &quot;lib&quot;: [&quot;DOM&quot;, &quot;ES6&quot;],<br>  &quot;jsx&quot;: &quot;react-jsx&quot;,<br>  &quot;module&quot;: &quot;ESNext&quot;,<br>  &quot;moduleResolution&quot;: &quot;node&quot;,<br>  &quot;strict&quot;: true,<br>  &quot;esModuleInterop&quot;: true,<br>  &quot;skipLibCheck&quot;: true,<br>  &quot;forceConsistentCasingInFileNames&quot;: true<br> },<br> &quot;include&quot;: [&quot;src&quot;, &quot;bootstrap.tsx&quot;],<br> &quot;exclude&quot;: [&quot;node_modules&quot;]<br>}</pre><pre>// webpack.common.js<br><br>module: {<br>  rules: [<br>    {<br>      test: /\.(ts|tsx)$/, // Handle TypeScript files<br>      exclude: /node_modules/,<br>      use: {<br>        loader: &#39;ts-loader&#39;,<br>      },<br>    },<br>  ],<br>},<br>...,<br>...,<br>resolve: {<br>  extensions: [&#39;.ts&#39;, &#39;.tsx&#39;, &#39;.js&#39;, &#39;.jsx&#39;], // Add TypeScript extensions<br>},</pre><p>In the webpack, we are modifying the rule to process the ts and tsx file instead of the js/jsx using the ts-loader. Loaders are external modules that can be installed, they tell you how to process and bundle specific type of file. Similarly for adding css/scss support you will require a different loader.</p><p>Obviously, you need to rename your .js/.jsx files to correct .ts or .tsx files.</p><h4>Adding Microfrontend support</h4><blockquote>Configuration for the Shell application.</blockquote><pre>plugins: [<br>  new HtmlWebpackPlugin({<br>   template: &#39;./public/index.html&#39;,<br>  }),<br>  new ModuleFederationPlugin({<br>   name: &#39;mfShell&#39;,<br>   filename: &#39;remoteEntry.js&#39;,<br>   remotes: {<br>    mfApp: &#39;mfApp@http://localhost:3006/remoteEntry.js&#39;,<br>   },<br>   exposes: {<br>    &#39;./ErrorBoundary&#39;: &#39;./src/ErrorBoundary&#39;,<br>    &#39;./ProtectedRoute&#39;: &#39;./src/ProtectedRoute&#39;,<br>   },<br>   shared: {<br>    react: { singleton: true, requiredVersion: deps.react },<br>    &#39;react-dom&#39;: { singleton: true, requiredVersion: deps[&#39;react-dom&#39;] },<br>   },<br>  }),<br> ],</pre><ul><li>We are using the native <strong>ModuleFederationPlugin</strong> from Webpack 5&#39;s container package.</li><li>name — The name of your remote app.</li><li>filename — The entry point that other apps will load to use your exposed modules.</li><li>remotes — Define external apps that you want to consume modules from (none for now).</li><li>shared — Shared dependencies between apps, which prevents duplication of libraries like React. This makes sure that React and ReactDOM are shared between the host and remote applications to avoid multiple instances.</li><li>exposes — Expose internal modules for other apps to consume. You expose components or modules from the remote application for other apps to use.</li></ul><p>Let me explain the above configuration in simple terms. So basically you want to generate a remoteEntry.js file that helps other microfrontends know what exactly the configuration is and how to interact with it. You want to expose certain components or parts of your app which other microfrontends can import and make use of. These can simply be components, whole apps, or even basic utility functions. Declare what you want to expose using the export key by mentioning the path of the exposed entity.</p><p>Another import aspect is the name key. This will be used to identify the app so make sure you name this correctly.</p><p>Remotes key help you to declare which other microfrontends are being consumed by this current app. Generally you declare it with the line below.</p><pre>remotes: {<br>  mfApp: &#39;mfApp@http://localhost:3006/remoteEntry.js&#39;,<br>},</pre><p>Notice that the key is mfApp which is also used in the url to define the location of the aforementioned mfApps remoteEntry file. This implies that the name declared in the mfApp’s configuration is mfApp and the filename is remoteEntry.js that exposes the details about the mfe. Also, you can choose to name remoteEntry.js any name using the filename key but this is kind of the convention in the microfrontend space. This configuration in the mfShell means that this microfrontend depends on some functionality provided by mfApp microfrontend which is running on localhost:3006 and the file name to read it is remoteEntry.js.</p><blockquote>Configuration for the child application.</blockquote><pre>plugins: [<br>  new ModuleFederationPlugin({<br>   name: &#39;mfApp&#39;,<br>   filename: &#39;remoteEntry.js&#39;,<br>   exposes: {<br>    &#39;./Button&#39;: &#39;./src/Button&#39;,<br>    &#39;./Images&#39;: &#39;./src/Images&#39;,<br>   },<br>   remotes: {<br>    mfShell: &#39;mfShell@http://localhost:3005/remoteEntry.js&#39;,<br>   },<br>   shared: {<br>    react: { singleton: true, requiredVersion: deps.react },<br>    &#39;react-dom&#39;: { singleton: true, requiredVersion: deps[&#39;react-dom&#39;] },<br>   },<br>  }),<br> ],</pre><p>Now that you are clear with the configuration, it is easy to understand that this microfrontend app is named mfApp which is the child application making use of mfShell application as it parents and how do we know it — because of the remotes key making it obvious that this application looks for a remote of mfShell application hosted on localhost:3005 exposing details through again remoteEntry.js.</p><p>Another important thing to note is that the mfApp itself is exposing some components for other microfrontends to use which are Button and Images in this case.</p><p>Another key point to note is that the shared config mentions that react and react-dom are being shared between these to apps and have the same version mentioned in the package.json file above viz 18.</p><blockquote>Note: You can always remove the semver declarations and lock the versions to a specific number to have consistency and accidental version inconsistency issues.</blockquote><h4>How to use the Components/Functionalities from exposed microfrontends.</h4><p>First thing that you need to configure to use the functions from imported microfrontend is to make sure that the importer app needs to know the typescript declaration of the things being imported.</p><p>This is one of the limitation of working with microfrontends. One needs to redeclare types of imported functionality in order to get type consistency. This is error prone so make sure you do it with care.</p><blockquote>Adding declarations.d.ts file in the src root scope</blockquote><pre>declare module &#39;mfShell/ProtectedRoute&#39; {<br>  export const ProtectedRoute: React.ComponentType&lt;{<br>    children: React.ReactNode;<br>  }&gt;;<br>}</pre><p>The contents of the file implies that mfShell is exposing the ProtectedRoute component as mentioned in the <em>exposes</em> config of mfShell which will be available as <em>mfShell/ProtectedRoute </em>path. We are simply defining the types for this function and trying to mimic the type for it as we did it in the mfShell. Basically you have to let mfApp know the type for it by replicating the type in declarations file globally.</p><blockquote>Using it in components</blockquote><p>Below is an example of how to use it in App.tsx component of mfApp</p><pre>import React, { lazy } from &#39;react&#39;;<br>import { Images } from &#39;./Images&#39;;<br>import { createBrowserRouter, RouterProvider } from &#39;react-router-dom&#39;;<br>const ProtectedRoute = lazy(() =&gt;<br> import(&#39;mfShell/ProtectedRoute&#39;).then((mod) =&gt; ({<br>  default: mod.ProtectedRoute,<br> }))<br>);<br><br>const router = createBrowserRouter([<br> {<br>  path: &#39;/&#39;,<br>  element: &lt;h1&gt;Unprotected Page&lt;/h1&gt;,<br> },<br> {<br>  path: &#39;/images&#39;,<br>  element: (<br>   &lt;div&gt;<br>    &lt;h1&gt;Hello from Module Federation App from the child!!!&lt;/h1&gt;<br>    &lt;ProtectedRoute&gt;<br>     &lt;Images /&gt;<br>    &lt;/ProtectedRoute&gt;<br>   &lt;/div&gt;<br>  ),<br> },<br>]);<br>export const App: React.FC = () =&gt; &lt;RouterProvider router={router} /&gt;;</pre><p>Notice the ProtectedRoute component being imported using Reacts lazy import. One more thing to note is that as I have exported the component not as default and as a named export I had to define the default as mod.ProtectedRoute. If it was simple default export you can skip the default assignment. This is how the lazy import for named exports work in React. Once imported you can use it simply as another component in your JSX.</p><h4>Handling crashes using ErrorBoundaries</h4><p>Now that you have two microfrontends exposing and consuming the features, it is very much possible that one of them goes down due to various reasons and your app can crash as that feature is no longer actively served from the respective microfrontend application. To tackle this it is always a good idea to prevent it using Error Boundaries.</p><p>I would like to refer this awesome video from Jack that helps you understand every topic that I mentioned above in greater detail. He also talks about ErrorBoundaries. Go have a look.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlKKsjpH09dU%3Fstart%3D1886%26feature%3Doembed%26start%3D1886&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlKKsjpH09dU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlKKsjpH09dU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/595f052799032b5d8512e8f832cc75c4/href">https://medium.com/media/595f052799032b5d8512e8f832cc75c4/href</a></iframe><pre>import { ErrorBoundary as ReactErrorBoundary } from &#39;react-error-boundary&#39;;<br><br>export const ErrorFallback: React.ComponentType&lt;{ error: Error }&gt; = ({<br> error,<br>}) =&gt; (<br> &lt;div&gt;<br>  &lt;h1&gt;Something went wrong!!!&lt;/h1&gt;<br>  &lt;pre&gt;{error.message}&lt;/pre&gt;<br> &lt;/div&gt;<br>);<br><br>export const ErrorBoundary: React.ComponentType&lt;{<br> children: React.ReactNode;<br>}&gt; = ({ children }) =&gt; (<br> &lt;ReactErrorBoundary FallbackComponent={ErrorFallback}&gt;<br>  {children}<br> &lt;/ReactErrorBoundary&gt;<br>);</pre><p>I have used react-error-boundary library to create a custom component to handle error states. You can always create your own from scratch as mentioned in the video too.</p><p>I have placed this in my shell application and exposed it so as to make it available in other apps. To use it just simply lazy import it as mentioned above and wrap the functionality that can go down.</p><p>ErrorBoundary basically looks for error in the subtree which is wrapped with it and shows the fallback in case of errors.</p><p>In the below example from another mf-app-test, one can see the Button and ErrorBoundary component being imported and used from two different microfrontends namely mfApp and mfShell respectively. Also, the Button component is being wrapped with ErrorBoundary to handle errors and crashes gracefully.</p><pre>import React from &#39;react&#39;;<br><br>const ErrorBoundary = React.lazy(() =&gt;<br> import(&#39;mfShell/ErrorBoundary&#39;).then((mod) =&gt; ({<br>  default: mod.ErrorBoundary,<br> }))<br>);<br><br>const Button = React.lazy(() =&gt;<br> import(&#39;mfApp/Button&#39;).then((mod) =&gt; ({<br>  default: mod.Button,<br> }))<br>);<br><br>export const App: React.FC = () =&gt; (<br> &lt;div&gt;<br>  &lt;h1&gt;Hello from Module Federation App from the child test!!!&lt;/h1&gt;<br>  &lt;ErrorBoundary&gt;<br>   &lt;Button label=&#39;Test&#39; /&gt;<br>  &lt;/ErrorBoundary&gt;<br> &lt;/div&gt;<br>);</pre><h4>Conclusion</h4><p>Finally, we have come to the end of it. Now you have a running application with webpacks module federation with the power of microfrontends under the hood. You now understand how to configure module federation for microfrontend, exposing functionalities and consuming it, defining types when importing them and graceful error handling with ErrorBoundaries.</p><p>Refer this github repo if you want to see the complete source for this. It also includes some other material but this is the one.</p><p><a href="https://github.com/Adredrs23/next-mono/tree/main">GitHub - Adredrs23/next-mono</a></p><p>We are not even close to the end but this is the conclusion for this chapter. Explore on how to pass data between these mf apps and figure out your own best practices. Maybe I’ll write on that in the future too.</p><p>Until then, Happy Coding. 🔥🔥🔥🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83ece891b20e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IAM using Keycloak and React.]]></title>
            <link>https://medium.com/@adredars/iam-using-keycloak-and-react-5c4b05b0f6b0?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c4b05b0f6b0</guid>
            <category><![CDATA[identityaccess-management]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 08:18:51 GMT</pubDate>
            <atom:updated>2024-11-10T08:18:51.999Z</atom:updated>
            <content:encoded><![CDATA[<p>This series will feature concepts of Keycloak and its fundamentals to give you a base foundation on how to add authorization in your next React app. In this blog, we will dive into the pre-requisites of Keycloak, understanding what and how it does. In the next one, we will use OpenID connect protocol offered by Keycloak to integrate basic authentication and authorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*sFYXfY77bfWj52rVcJadIA.png" /></figure><h4>What is Keycloak?</h4><p>Keycloak is a simple authentication and authorization server precisely and IAM — Identity and Access Management tool that can be quickly setup for your personal or organizational level projects. It is widely considered as the first choice for any production level project due to its simplicity and open source nature.</p><p><a href="https://www.keycloak.org/">Keycloak</a></p><h4>Installing and getting Keycloak running</h4><p>Most preferrable way of quickly spinning up a Keycloak server is to get it running on docker.</p><p>It is a single line command as mentioned in their documentation. You can always go ahead and set it up without Docker. We will use it with Docker here. <a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a></p><pre>docker run -p 8080:8080 -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:26.0.5 start-dev</pre><p>A little info about the command — you are pulling the latest docker image of Keycloak from the docker registry and running it on port 8080 with admin user created with username <em>admin</em> and password <em>admin</em>. You can always modify the command to set your own credentials.</p><h4>Understanding concepts of Keycloak</h4><p><a href="https://www.keycloak.org/getting-started/getting-started-docker">Docker</a></p><p>Read the above documents to create your first realm, client, user and flow setup. But lets understand them first so you have clarity on what, why and hows?</p><p>In brief,</p><h4>Realms: The Core Container</h4><p>In Keycloak, a <em>realm</em> is a core, isolated container for managing identities, security settings, and resources for a specific application or set of applications. Each realm operates independently, which makes it ideal for multi-tenant applications or organizations that require separate security contexts. Realms contain all configuration data for authentication, users, and applications within that scope, allowing organizations to create separate environments (like “dev,” “test,” or “prod”) or individual realms for each client.</p><h4>Clients: Representing Applications</h4><p>A <em>client</em> in Keycloak represents an application or service that requires authentication and authorization services. When you create a client, you define how it interacts with Keycloak, specifying the protocols it supports (like OpenID Connect or SAML) and permissions for accessing Keycloak-protected resources. Clients can be web apps, mobile apps, APIs, or any external systems needing user or application-level authentication, making this setup versatile for various application types.</p><h4>Users: Defining Identity and Roles</h4><p><em>Users</em> are the individuals who interact with Keycloak-protected applications. Keycloak handles user creation, identity management, and role assignment, and supports integrations with identity providers (IdPs) for federated authentication. By managing users within realms, you can define roles and attributes specific to the applications within each realm, enabling a granular approach to access control that aligns with application-specific requirements.</p><h4>Authentication Flows: Customizable Login Processes</h4><p><em>Authentication flows</em> in Keycloak are customizable sequences of actions that dictate how users authenticate, including login, registration, and two-factor authentication. These flows are modular, allowing admins to configure steps like password checks, OTP validation, and identity brokering. This flexibility is invaluable when tailoring user experiences to specific security policies, providing seamless integration with enterprise or regulatory authentication standards.</p><p>In short,</p><p><strong>Realms</strong> help you keep your concerns separated and define the overall scope and configuration for the environment or app your are on. Multi-tenant app behavior is the soul of this.</p><blockquote>The <strong>multi</strong>-<strong>tenancy</strong> concept is that numerous users share computational, networking, and storage resources without seeing each other’s data.</blockquote><p>Note: Master realm is off limits. Don’t do anything in this one unless you know what you are dealing with. Master realm is for Keycloak to manage its screws. Always create a new realm and build upon that.</p><p>After you have created a new realm, some important setting for you to know are present in the realm settings in the sidebar. In general tab, you can modify realm name and other settings but important one is the endpoints link at the bottom. There you see, openid and saml endpoints, these two are the protocols that keycloak support for authentication and authorization. Also, in theme tab you can set the whole new theme for the realm which allows you to modify the look and feel of various pages of the flow like login, reset-password, etc. In sessions and tokens tab, you can specify the lifespan of various token parameters. Explore more in order to understand Keycloak realm in depth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*RsRjOZ9JNBmjkjGJ4HYKog.png" /><figcaption>Endpoints link in Realm Settings</figcaption></figure><p><strong>Clients</strong> basically represents who is connecting to your realm. Consumers can be distinguished and configured for by creating separate clients. Clients can be public or confidential. Confidential clients required client secret to connect to the server. Every client can have their own set of rules.</p><p>Creating client is a straight forward process but you need to keep certain points in mind. On the capability config tab, client authentication switch allows you to set the access type of the client viz public or confidential — confidential clients required client secret to connect to that you can grab from the credentials tab when the client is created.</p><h4>Public vs. Confidential Clients</h4><ul><li><strong>Public Clients</strong>: These clients (like single-page applications) do not need to authenticate themselves with a client secret. They can obtain access tokens via authorization code flow, implicit flow, etc. For public clients, the access token itself is sufficient to access the UserInfo endpoint.</li><li><strong>Confidential Clients</strong>: These clients (like server-side applications) are trusted with a client secret. While they usually authenticate themselves when requesting tokens, they do not need to send the client ID and secret along with requests to the UserInfo endpoint if they are providing a valid access token.</li></ul><p>Note: Client secret is sensitive data, store it securely and do not expose it to the outer world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*Lnwm63qWmfmenAg_5ohVgQ.png" /><figcaption>Capability config tab of creating new client</figcaption></figure><p>Also, on the same screen you will asked to select the authentication flow for the client.</p><h4>What are SSO protocols and flows?</h4><p>I’ll be using this great snippet from the article below as it nicely lays down what SSO protocols and flows are in Keycloak.</p><p><a href="https://www.thomasvitale.com/keycloak-authentication-flow-sso-client/">Keycloak Authentication Flows, SSO Protocols and Client Configuration</a></p><h4>SSO Protocols</h4><p><a href="https://openid.net/connect/?ref=thomasvitale.com">OpenID Connect</a> (OIDC) is the preferred method. It’s a modern protocol built on top of the OAuth 2.0 framework. <a href="https://www.keycloak.org/docs/latest/server_admin/index.html?ref=thomasvitale.com#_saml">SAML</a> is an older authentication protocol, which gained popularity in the world of SOAP services. It relies on XML documents containing assertions about the user, while OIDC makes use of JWT (JSON Web Token) in the form of identity tokens and access tokens.</p><ul><li><strong>Authorization Code Flow</strong> for browser-based applications like SPAs (Single Page Applications) or server-side application;</li><li><strong>Implicit Flow</strong> for browser-based application, less secure than the previous one, not recommended and deprecated in OAuth 2.1;</li><li><strong>Client Credentials Grant</strong> for REST clients like web services, it involves storing a secret, so the client is supposed to be trustworthy;</li><li><strong>Resource Owner Password Credentials Grant</strong> for REST clients like interfaces to mainframes and other legacy systems which cannot support modern authentication protocols, it involves sharing credentials with another service, caution here.</li></ul><p>On the login settings tab, you need to provide some valid URLs for Keycloak to work with. I’m connecting from a backend service to this client which is running on 8000 port. So I want Keycloak to allows requests originating from web origin <a href="http://localhost:8000/*">http://localhost:8000/*</a> and after correct authentication redirecting to the right service, again in this case back to the same url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*oFh1yz7o9pE3zccXP_3NxA.png" /></figure><p><strong>Users</strong> is simply the onboarded users in your realm. Here, you can define the scopes, roles, credentials and required actions for the user. For now create a simple test user with basic credentials of your liking with temporary password set to off.</p><p>Also, here is the OAuth2.0 flow simply explained by ByteByteGo author Alex Xu. Thought it might help!</p><p><a href="https://www.linkedin.com/posts/alexxubyte_systemdesign-coding-interviewtips-activity-7261251028207988736-mrMD?utm_source=share&amp;utm_medium=member_desktop">Alex Xu on LinkedIn: #systemdesign #coding #interviewtips | 15 comments</a></p><h4>JWTs</h4><p>Another critical part is JSON web tokens. Your access and refresh tokens received in OpenID protocol are JWTs that you will decode to get the user details out and then process with the your business logic.</p><p><a href="https://jwt.io/">JSON Web Tokens - jwt.io</a></p><h4>Where to store these JWTs?</h4><p>To persist the user session on our React frontend we must store these tokens somewhere. Possible options available are</p><ol><li>In memory — like in React state or redux state.</li><li>Local/Session Storage.</li><li>Cookies.</li></ol><h4>Memory Storage</h4><ul><li><strong>Pros</strong>: Keeps tokens secure by not persisting them beyond the session, minimizing exposure to attacks such as cross-site scripting (XSS).</li><li><strong>Cons</strong>: Tokens are lost on page refresh, so you need a strategy to re-authenticate or refresh the session.</li><li><strong>Use Case</strong>: Suitable for Single Page Applications (SPAs) that can quickly re-initialize Keycloak and refresh tokens on page load.</li></ul><h4>Secure Contexts (e.g., localStorage or sessionStorage)</h4><ul><li><strong>Pros</strong>: Simplifies token management since data is persisted during browser sessions.</li><li><strong>Cons</strong>: Exposes tokens to potential XSS attacks. Use additional safeguards, like Content Security Policy (CSP), to mitigate risks.</li><li><strong>Use Case</strong>: Useful for simpler SPAs where security measures are in place to prevent XSS.</li></ul><h4>HTTP-Only Cookies</h4><ul><li><strong>Pros</strong>: More secure than localStorage or sessionStorage since the browser does not expose them to JavaScript, reducing the risk of XSS attacks.</li><li><strong>Cons</strong>: More complex setup, requiring backend support to manage cookies securely (e.g., setting HttpOnly and Secure flags).</li><li><strong>Use Case</strong>: Ideal if your application involves server-side rendering or sensitive token handling with backend interactions.</li></ul><h4>Cookie Security Properties</h4><blockquote>HttpOnly Attribute:</blockquote><p>This attribute ensures that the cookie is not accessible via JavaScript (document.cookie). Only the server can read or write this cookie.<br>This is used to mitigate cross-site scripting (XSS) attacks since client-side scripts cannot access cookies marked with this attribute.</p><blockquote>Secure Attribute:</blockquote><p>This ensures that the cookie is only sent to the server over secure HTTPS connections. It prevents the cookie from being sent over unencrypted HTTP, protecting it from network eavesdropping.</p><blockquote>SameSite Attribute:</blockquote><p>SameSite controls whether the cookie is sent with cross-site requests. Setting this to Strict or Lax prevents the cookie from being sent with third-party requests, reducing the risk of cross-site request forgery (CSRF) attacks.</p><h4>Best Practices:</h4><ul><li><strong>Always encrypt tokens</strong> if you decide to persist them in any storage.</li><li><strong>Limit token lifespan</strong> by using short-lived access tokens and refresh tokens for re-authorization.</li><li><strong>Use Content Security Policy (CSP)</strong> headers to prevent XSS.</li><li><strong>Monitor and refresh tokens</strong> securely to ensure sessions remain valid without manual user intervention.</li></ul><p>We will prefer the cookie based approach as it is more robust and secure, plus you get the benefit of using it seamlessly if you have a Micro-frontend architecture.</p><h3>Upcoming</h3><p>What we will do in our next blog is go on a step by step journey showcasing how you can set everything up from scratch and all the gotchas that you might encounter in doing so.</p><p>We will make use of :</p><ol><li>mfe-realm — to manage all the configurations scoped to our application.</li><li>mfe-client-be — a backend client configuration for our NestJs backend service to connect to. This service will do all the steps like logging the user in, getting the tokens and setting them up as the cookie, also refreshing tokens.</li><li>nestjs-service — to do all the backend heavy lifting.</li><li>react-app — multiple micro-frontend apps interacting with the backend to get the users identity.</li></ol><h3>Conclusion</h3><p>Till now you are familiarized with the concepts needed to integrate Keycloak IAM with you application.</p><p>Refine any rough edges you might have with the resources available and see you in the next one.</p><p>Till then, happy coding.🔥🔥🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c4b05b0f6b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React professional project structure and standards boilerplate/template.]]></title>
            <link>https://medium.com/@adredars/react-professional-project-structure-and-standards-boilerplate-template-2acdcdece139?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/2acdcdece139</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[codebase]]></category>
            <category><![CDATA[standards]]></category>
            <category><![CDATA[react-boilerplate]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 05:59:54 GMT</pubDate>
            <atom:updated>2024-09-12T05:59:54.300Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the document which will help you create a base boilerplate, professional and simple standards template for your next React project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCR4NKWzHo0I5bu9rEpnUA.png" /></figure><h3>Points to consider while laying out a professional codebase for React projects.</h3><ol><li>React fundamental standards</li><li>Basic naming conventions</li><li>Project setup &amp; configuration file standards</li><li>Sensitive files</li><li>Folder structure best practices</li><li>Git related standards <br>- Branch naming <br>- Commit message naming convention</li><li>Typescript standards <br>- Types/interfaces <br>- Enums <br>- File naming</li><li>Import export standards</li><li>Accessibility based element usage</li><li>CSS/SCSS standards</li></ol><h4>React fundamental standards</h4><blockquote>Component naming and folder structure</blockquote><ol><li>Every component must be encompassed in their own folder named ComponentName.</li><li>The format for naming the folder would be PascalCase</li><li>Component folder will consist of the logically related files, this may include files like<br><em>index.ts <br>Component.tsx <br>Component.types.ts / types.ts ?decide <br>Component.scss <br>constants.ts (optional)</em></li></ol><blockquote>tsx vs ts</blockquote><p>Extension names for files must be used mindfully, make sure any file that doesn’t include any jsx should always be ending with .ts</p><blockquote>Function or arrow function for component naming</blockquote><p>Always prefer arrow function syntax for naming the functional component.</p><blockquote>Defining Prop types for functional components</blockquote><p>Make sure names prop types for component always end with Props, so the name of the prop type would look like ComponentProps.</p><blockquote>Exporting component and other types</blockquote><p>Make sure the component and any relevant type constants are exported as named exports. Refrain from using default exports, unless extremely required in case of lazy loading use cases or otherwise.</p><blockquote>React fragments</blockquote><p>Make sure to remove unnecessary fragments.</p><blockquote>Key prop</blockquote><p>Make sure key prop are unique and doesn’t use indexes. If you really want to make sure that you prefix or suffix it with suitable uniquely identifiable slug.</p><blockquote>IMR</blockquote><p>import React from ‘react’; statement is not required</p><blockquote>Ordering of hooks, variables, functions and effects.</blockquote><p>Please stick to the following order when declaring said objects: <br>1. Hooks <br>2. Variables <br>3. Functions <br>4. Effects</p><blockquote>Naming of variables</blockquote><ol><li>Component name should be in PascalCase</li><li>Variable name should be camelCase <br>NOTE: If variable is constant, it should be named in SCREAMING_SNAKE_CASE as SOME_CONSTANT_VARIABLE_NAME</li><li>Hooks should follow the rules of hooks and named accordingly — [state, setState] <br>Note: If the variable is a Boolean, always avoid double negation in naming. Example — <br>[isActive, setIsActive] and not [isNotActive, setIsNotActive].</li><li>Effects should be in order of <br>Mount ([]) <br>Dependencies ([dependentState]) <br> All ()</li></ol><blockquote>const vs let usage</blockquote><p>Use const for function and constants. <br>Strictly use let for variables which will be reassigned.</p><h4>Basic naming conventions</h4><blockquote>Folder names</blockquote><p>All folder names should be smallcase with an exception to component folders. Only component folders will have PascalCase</p><blockquote>File names</blockquote><p>File naming convention changes as per the type of file.<br>All file names should be smallcase and end with ts if not returning any jsx, exception to this rule are if filename is a component or in any way returning jsx then it should be PascalCase.tsx <br>Some examples,</p><ul><li>RandomComponent.tsx</li><li>RandomComponent.types.ts</li><li>useSomeHook.ts</li><li>constants.ts</li><li>random-component.scss</li><li>index.ts</li><li>.someconfigfilerc</li><li>.someconfigfile.json</li><li>.env.environmentname</li></ul><blockquote>Variable Names</blockquote><p>All variable name should follow camelCasing, unless it is a constant then it should follow SCREAMING_SNAKE_CASING.<br>State variables should follow React’s state nomenclature rule .<br>Custom hook files and variables should have the prefix ‘use’ in them and follow Example: useCustomHook.ts <br>Avoid Double Negation: If the variable is a Boolean, always avoid double negation in naming. <br>Example — [isActive, setIsActive] and not [isNotActive, setIsNotActive].</p><blockquote>Types and enums</blockquote><p>Component prop names should always end with the suffix ‘Props’ and should be PascalCase. <br>Enum names should always end with the suffix ‘Enum’ and should be PascalCase. <br>Example — ComponentProps and SomeConstantEnum</p><blockquote>Web Route Names</blockquote><p>All route should be hyphenated and small case. So your route will look something like: <br>/product/some-long-key/resource?key=”value”&amp;another-key=”value”</p><h4>Project setup &amp; configuration file standards</h4><blockquote>.gitignore</blockquote><p>— it is the file which indicates what should be pushed to git repo, add files or folders in this to ignore them from pushing it to remote repo. <br>NOTE: Do not remove any configuration if you are not familiar with what it does. Please reach out to someone to get clarity. <br>Please maintain the order while adding files or folders to ignore</p><ul><li>External dependencies</li><li>Folders</li><li>Files</li><li>Testing suite related folders/files</li><li>Lock files</li><li>Production folders/files</li><li>Environment related files</li><li>Miscellaneous</li></ul><blockquote>Environment files</blockquote><p>— Nomenclature wise it should always start with .env and follow the pattern of .env.name <br>Generally, I keep 5 files namely local, development, staging, production and test. One can keep an env file each for the environment being used.</p><ul><li>Please add the env variables respective to the their environments. <br>Name of the variables defined should be same in all the environments, with an exception of environment specific variables required for that particular environment.</li><li>All environment variables should follow the format of <br>REACT_APP_ENV_VARIABLE_NAME=”SOMEVALUE”</li><li>Make sure all the env files are present in .gitignore as they contain sensitive content like tokens, API keys, etc.</li></ul><blockquote>package.json and package-lock.json</blockquote><ul><li>package.json — help to identify the dependencies and devDependencies required for the project, it also helps in registering scripts. <br>Please remove any unused dependencies/libraries/packages from either dependencies or devDependencies or both. <br>Make sure any package which is not required in runtime should always be part of devDependencies, these usually includes <a href="http://twitter.com/types/package">@types/package</a>, or dev experience improvement tools.</li><li>package-lock.json — help to list the actual package version resolved. Please don’t modify this directly. Also, this shouldn’t be pushed to git remote repo. Should be in .gitignore.</li></ul><blockquote>eslint, prettier, tsconfig, webpack, babel, commitlint and npm</blockquote><p>While editing any of these files be extra cautious and add necessary comments wherever required to explain to other what these rules do.</p><ul><li>eslint — contains all the eslinter rules. Mostly no need of modifications unless there is some rule to be removed or configured.</li><li>prettier — .prettierrc and .prettierignore are preconfigured to format the codebase correctly. One can modify the rules if want to change things personally but require PR to push the change for everyone. .prettierignore will define which files/folders are ignored from these formatting rules.</li><li>tsconfig — standard ts configuration rules are applied, please enable and disable rules based on clarification and discussions with team. Stay away from this file if you don’t know what’s going on!!</li><li>Webpack — webpack is sole bunder that helps bundling the code base into one, it also defines the rules for Micro Frontend architecture. Please refrain from making changes to this unless you are sure of what you are doing. Also, after change please test the project is running and up without any issues.</li><li>Babel — .babelrc configures all the rules to transpile to code to js.</li><li>Commitlint — helps defines rules for commit messages</li><li>Npm — .npmrc is defined to register the tokens to access the npm registry. For now, it simply contains font-awesome setup.</li><li>.github — defines the template for Pull requests. Don’t modify.</li><li>Husky — has the rules for commit rules <br>Pre-commit — command to run lint-staged, lint and format before commit and block commit if check fails <br>Commit-msg — command to run commit message format rules. If commit message is not the right format will disallow committing.</li></ul><h4>Sensitive files</h4><p>Any sensitive files should be prevented from being pushed to git. <br>These include files like env, any credentials files for external libraries like firebase, font awesome etc.</p><h4>Folder structure best practices</h4><p>Make sure this is an opinionated structure. One can always modify the suggested folder structure as per the libraries and technologies being used, custom to their use case.</p><ul><li>All folder names are small case.</li><li>src folder contains all the code.</li><li>public contains the public code and assets, this will also include any sitemaps, robots.txt, etc.</li><li>src folder is divided into logical spaces.</li><li>assets hold all the assets that include audio, image and scss. Place your assets only in this folder.</li><li>common folder is space to keep all your common components, utility files.</li><li>components folder is space to put all component folders and collocate the component related files in the folder as per the rules mentioned before.</li><li>hooks host all the hooks required, if the hook is not global and specific to a module or page create a folder and place the hook there.</li><li>pages folder help divide the application into separate page component. As the page is a component internally, stick to component file and folder naming rules.</li><li>redux holds the redux related slices and hooks, Stick to component naming rules.</li><li>routes hold the route components</li><li>widgets hold the widget modules.</li><li>declaration.d.ts — is used to define module definition. Note: Do not create .d.ts files unless you are intentionally declaring or registering new types.</li><li>remoteTypes.d.ts — help define remote types for the project. This generally includes mfe module registration. <br>Note: Every folder will contain one special index.ts file that will be used for named export strategy for better import management. More on this will be explained in the import/export section.</li></ul><h4>Git related standards</h4><blockquote>Branch naming convention</blockquote><p>The standard is pretty straight-forward, and all the branch names will follow this convention. Benefit of using this approach is that it will highlight the need of the branch, who’s the owner of the branch and exactly what the branch is made for. <br><em>So the structure is — type/owner/ticket-no/branch-name-with-description <br>Type — will be feat, refactor, hotfix, revert. <br>Owner — will specify the name of assigned person working on the task. <br>Ticket number — specify the ticket number for the mentioned task. (This could be optional) <br>Branch Name — It will be the short description and name of the branch. If there’s a ticket id then do prefix it. <br>Example — feat/adred/T101/dashboard-chart-ui-flickering-fix</em></p><blockquote>Commit messages naming convention</blockquote><p>This uses commitlint package’s default configuration rules can be modified as per discussion <br>The structure is type: lowercase description of the commit <br>Type — ci, chore, docs, ticket, feat, fix, perf, refactor, revert, style</p><h4>Typescript standards</h4><ul><li>Types or interfaces — always use type to write the types for your components, instead of interfaces.</li><li>Enums — use enums wherever required, maintained in types file or separate enum file.</li><li>File naming — Component.types.ts is the convention for naming the files. <br>For type and enum names use PascalCasing.</li></ul><h4>Import export standards</h4><blockquote>Exporting</blockquote><ul><li>For exporting, use index.ts to export all the components, functions, types, etc to be exported. Every collocated exportable will be exported from a single file viz index.ts of the same folder by using the export * from ‘file.ts’ or by explicitly defining export {somethingToExport} from ‘file.ts’. <br>Remember to export both component exportables and types exportables.</li><li>Make sure everything is named exports and not default exported.</li><li>Use default export when there is necessity for lazy loading or other cases. <br>For managing default export make a modification in the index.ts. <br>Export the component as export default ComponentName; in the file and in index.ts use export {default as ComponentName, otherExportable, anotherExportable} from ‘file.ts’ <br>The reason for having named exports via index.ts file is that it brings two advantages <br>- Better intelli-sense with editors <br>- Exactly exporting what you need and shorter imports</li></ul><blockquote>Importing</blockquote><ul><li>Importing is made simpler using index.ts exporting strategy as it disheartens use of long specific path imports.</li><li>Imports should follow particular order as specified by import rule set in the eslint config. Currently the order is: <br>- React import <br>- External modules, this even includes mfe imports <br>- <a href="http://twitter.com/src">@src</a> modules, external to the present working directory <br>- Internal modules, part of the present working directory <br>- CSS/SCSS imports <br>Types file can be imported specifically or from the owner folder ie in the below example what is shown works or the other acceptable way would be import type {Notification} from ‘<a href="http://twitter.com/src/widgets">@src/widgets</a>/Notification’; provided the type is exported from the index.ts of Notification folder or even shorted just the ‘<a href="http://twitter.com/src/widgets">@src/widgets</a>’.</li></ul><h4>Accessibility focused element usage</h4><ul><li>Please stick to HTML5 semantic and rules for using tags and elements. <br>use aside for side containers, main for the main content, header, footer, etc elements instead of blindly using div tags.</li><li>Use block elements and inline elements carefully, don’t use one and use CSS to modify the display type for it.</li><li>Use headers tags in the correct order. <br>h1 -&gt; h2 -&gt; h3 -&gt; h4 -&gt; h5 -&gt; h6 in this exact order. Don’t skip any one for example h4 after h1. It should be continuous.</li><li>There should be only one h1 tag per page.</li><li>Be alert when copying content from any place for example Figma or Adobe XD it might introduce special characters.</li><li>Don’t use &amp;nbsp; for non-breaking spaces. Instead use template literals.</li></ul><h4>CSS/SCSS standards</h4><ul><li>Use hyphenated-class-names for styling</li><li>Use &amp; operator in scss to refer to the parent style and extend it.</li><li>Common functions can be made into mixins or sass functions to make it reusable.</li><li>Prefer css variables and scss variables instead of hardcoding values.</li><li>Make use of <a href="http://twitter.com/import">@import</a> rule to integrate separate SCSS files together.</li><li>Breakdown long SCSS files into separate files and combine them with <a href="http://twitter.com/import">@import</a>.</li><li>Should we follow BEM convention for naming SCSS classes</li><li>Refrain from using heights with absolute values it will restrict the ui to be completely responsive.</li><li>For responsiveness, prefer mobile-first approach.</li><li>Define the breakpoints<br>Use media values defined in the breakpoints file and refrain from using other values.</li><li>Use line-height value in multiple values instead of absolute values. Example — 1, 1.5 instead of 14px</li><li>Make sure any CSS property defined are compatible with older versions. Use caniuse to verify compatibility.</li><li>Strictly, AVOID using !important.</li><li>Define z-index defaults</li><li>Refrain using random high values. <br>Example — prefer -1, 0, 1, 2, 3, 4, 5 instead of 99999</li><li>Define fonts file and default</li><li>Define typography file and default</li><li>Define resets file and defaults</li><li>Define variables file and defaults for<br>- Shadows <br>- Opacity <br>- Animation transitions <br>- Animation keyframes</li></ul><h4>Conclusion</h4><p>Hopefully, the above structure provides a better starting point in terms of standards for a new industry ready React project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2acdcdece139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Desktop isn’t starting after updating to the latest version.]]></title>
            <link>https://medium.com/@adredars/docker-desktop-isnt-starting-after-updating-to-the-latest-version-ab461c55b91b?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab461c55b91b</guid>
            <category><![CDATA[docker-desktop]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[wsl]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 11:23:03 GMT</pubDate>
            <atom:updated>2024-07-19T11:23:03.578Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are also facing the weird issue with Docker Desktop not starting and giving you the error ‘No distros found’. Try the following solution.</p><h4>Diagnosing the error and when it occurs.</h4><p>When you update your Docker Desktop after some time, you expect it to work magically as it used to and start the application without any issues. But no, you are doomed with the following error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*1DUDhg2SPfyv5aGrLciTlQ.png" /></figure><p>By the looks of it, seems like the WSL itself is unable to start and fetch the list of available distros installed in your system.</p><h4>The solution</h4><p>I started by checking if WSL itself is working by checking its version using the following command in the command prompt.</p><pre>wsl --version</pre><p>If it produces an output with a WSL version like below that means the WSL is correctly installed and working.</p><pre>wsl -v<br>WSL version: 2.2.4.0<br>// Other details</pre><p>Next, I go by updating my WSL instance by typing the following command.</p><pre>wsl --update</pre><p>The above command updates the WSL to the latest version. Make sure that you always restart your system after a WSL update.</p><p>After a successful restart, I tried starting my Docker Desktop again.</p><p>This time, we got a different error. I do not have the screenshot for the same but the following was the error message in a nutshell.</p><pre>wsl.exe --terminate docker-desktop  <br>There is no distribution with the supplied name</pre><h4>The solution continued.</h4><p>Looking at the message I immediately thought of trying it in cmd and it produced the exact error.</p><pre>wsl.exe --terminate docker-desktop<br>There is no distribution with the supplied name.<br>Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND</pre><p>The first thing to do after this error was received was to check if the distro was present and if present what is the state. So I ran the following command and it produced the following output.</p><pre>wsl -l -v<br>  NAME                   STATE           VERSION<br>* Ubuntu-22.04           Running         2<br>  docker-desktop         Uninstalling    2<br>  Ubuntu                 Stopped         2<br>  docker-desktop-data    Running         2</pre><p>So the distro was present but it was stuck at uninstalling. That was the problem. I just need to terminate the stuck distro somehow.</p><p>A little research led me to this command.</p><pre>wsl --unregister docker-desktop</pre><p>So what it does is unregister the distro from the local machine and allow Docker Desktop to recreate it when the user tries to start the application again.</p><p>After running the command, running wsl -l -v produces the following result.</p><pre>wsl -l -v<br>  NAME                   STATE           VERSION<br>* Ubuntu-22.04           Running         2<br>  Ubuntu                 Stopped         2<br>  docker-desktop-data    Running         2</pre><p>Indicating that docker-desktop is not present and running anymore.</p><p>All you need to do now is start the Docker Desktop application again and hopefully, it should do the trick.</p><h4>Reference:</h4><p>Found the below Github discussion after breaking my head for an hour and resolving the issue. Timing has always been a problem with me.</p><p><a href="https://github.com/docker/for-win/issues/6971">Docker Desktop fails to start with WSL2 based engine enabled · Issue #6971 · docker/for-win</a></p><h4>Conclusion</h4><p>Use the unregister command and try restarting the application and hope that It works.</p><p>See you next time. Keep debugging! Until then, a little bit of happy coding.😭🥲🔥</p><blockquote><strong>Credits and Mentions:</strong><br>Many thanks to <a href="https://medium.com/@gaurang.m">https://medium.com/@gaurang.m</a> for lending a helping hand every time I say “Mere Saath Hi Kyu Hota hai!”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab461c55b91b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You will never write Form Validations the old way!]]></title>
            <link>https://medium.com/@adredars/you-will-never-write-form-validations-the-old-way-69f3f75feee5?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/69f3f75feee5</guid>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 19:51:30 GMT</pubDate>
            <atom:updated>2024-07-14T19:57:35.527Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post will talk about how validation libraries like Zod help you write complex validation logic easily and help save a lot of time and effort so you can focus on more challenging tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*zbjcb-QokiubbS7v" /></figure><h3>What is Zod?</h3><p><a href="https://zod.dev/">Intro | Zod</a></p><p>As they’ve mentioned in their documentation, Zod is a typescript-focused schema validation library. It helps you validate the data structure you are expecting or sending out.</p><p>An interesting part of Zod is that the syntax is so familiar and user-friendly to people who do have prior experience with Typescript, Mongo or GraphQl where you need to work with Schemas.</p><p>It gels so well with TypeScript that it provides Type Inference so that you only define the schema once for Zod and use the Type Inference offered to infer the types for static type checking. Frankly, I feel this is the best part about it.</p><p>What we’ll try to achieve in this blog is to replace the common form validation logic that we often need to write to successfully validate our forms in React. But before that, I would like to link some articles that I found helpful in achieving so.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9UVPk0Ulm6U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9UVPk0Ulm6U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9UVPk0Ulm6U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a833fe74801de307524e8ed64c3500f/href">https://medium.com/media/0a833fe74801de307524e8ed64c3500f/href</a></iframe><ul><li><a href="https://medium.com/@iamaamunir/ultimate-guide-to-schema-validation-with-zod-14e5b1906585">Ultimate Guide To Schema Validation with Zod</a></li><li><a href="https://stackademic.com/blog/form-validation-with-zod">Form Validation with Zod</a></li></ul><h3>The Old way</h3><p>If you go with this particular commit, you will see how one might go about doing validations the old way.</p><p><a href="https://github.com/Adredrs23/next-ums/commit/7bb87b12c01031c2ee225738d5e26ae797f7ea9d#diff-450060ae3bbbaf119babca9223e235b303a54bd82c6f596d2acfa30bc010dcd1">chore: adding the base template for the Add user form with zod schema... · Adredrs23/next-ums@7bb87b1</a></p><p>Some snippets from the same code commit.</p><pre>const handleNextStep = () =&gt; {<br>  const validationErrors: UserPartialType = {};<br><br>  if (currentStep === 1) {<br>   if (!formData.name) {<br>    validationErrors.name = &#39;Name is required&#39;;<br>   }<br>   if (!formData.email) {<br>    validationErrors.email = &#39;Email is required&#39;;<br>   } else if (!isValidEmail(formData.email)) {<br>    validationErrors.email = &#39;Invalid email address&#39;;<br>   }<br>   if (!formData.phone) {<br>    validationErrors.phone = &#39;Phone is required&#39;;<br>   }<br>   if (!formData.address) {<br>    validationErrors.address = &#39;Address is required&#39;;<br>   }<br>  } else {<br>   if (!formData.role) {<br>    validationErrors.role = &#39;Role is required&#39;;<br>   }<br>   if (!formData.github) {<br>    validationErrors.github = &#39;Github is required&#39;;<br>   }<br>   if (!formData.linkedin) {<br>    validationErrors.linkedin = &#39;LinkedIn is required&#39;;<br>   }<br>   if (!formData.skypeid) {<br>    validationErrors.skypeid = &#39;Skype ID is required&#39;;<br>   }<br>   if (!formData.dob) {<br>    validationErrors.dob = &#39;Date of Birth is required&#39;;<br>   }<br>   if (!formData.doj) {<br>    validationErrors.doj = &#39;Date of Joining is required&#39;;<br>   }<br>  }<br><br>  if (Object.keys(validationErrors).length &gt; 0) {<br>   setErrors(validationErrors);<br>   return;<br>  }<br><br>  setCurrentStep(currentStep + 1);<br>  setErrors(null);<br> };</pre><p>To give you a little bit of idea about the project this is in. The Nextjs application is a standard User Management System where on the action panel one can choose to add more users to the system. When the user clicks on the <em>Add User</em> button in the panel, a modal pops up with some basic fields to be filled. It is a stepper form involving 2 steps, one taking the basic details of the user and another taking social details. I have attached the screenshot for the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*Y0gMNwW7Evt6NkJxWJ4Zbg.png" /><figcaption>Add User Form Step 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*WNPdu9U1eZdvKv1yV0bozQ.png" /><figcaption>Add User Form Step 2</figcaption></figure><p>By the way, I did not spend time creating these Modals and UIs by myself. Instead, I used v0.dev which is an AI tool to create the simplistic-looking UIs by providing suitable prompts. You can copy the code of the output you like, it produces it in React and supports Tailwind for styling which is what I&#39;m going for in this project.</p><p><a href="https://v0.dev/">v0 by Vercel - Build Agents, Apps, and Websites with AI</a></p><p>Let&#39;s see how we can use Zod in our favor.</p><h3>The Zod Way!</h3><p>We start by creating the Schema which will look something like this.</p><pre>import { z } from &#39;zod&#39;;<br>import validator from &#39;validator&#39;;<br><br>// import { exactlyNYearsAgoDate } from &#39;@/utlls&#39;;<br><br>export const userSchema = z.object({<br> name: z<br>  .string()<br>  .min(1, { message: &#39;Name is required!&#39; })<br>  .max(50, { message: &#39;Name is too long&#39; }),<br> email: z.string().email({ message: &#39;Invalid email address&#39; }),<br> // phone: z<br> //  .string()<br> //  .min(10, &#39;Phone number is too short&#39;)<br> //  .max(15, &#39;Phone number is too long&#39;),<br> phone: z<br>  .string()<br>  .refine(validator.isMobilePhone, { message: &#39;Invalid phone number&#39; }),<br> address: z<br>  .string()<br>  .min(1, { message: &#39;Address is required&#39; })<br>  .max(100, { message: &#39;Address is too long&#39; }),<br> role: z<br>  .string()<br>  .min(1, { message: &#39;Role is required&#39; })<br>  .max(10, { message: &#39;Role is too long&#39; }),<br> github: z<br>  .string()<br>  .url()<br>  .min(1, { message: &#39;Github is required&#39; })<br>  .max(50, { message: &#39;Github is too long&#39; }),<br> linkedin: z<br>  .string()<br>  .url()<br>  .min(1, { message: &#39;LinkedIn is required&#39; })<br>  .max(100, { message: &#39;LinkedIn is too long&#39; }),<br> skypeid: z<br>  .string()<br>  .min(1, { message: &#39;Skype ID is required&#39; })<br>  .max(50, { message: &#39;Skype ID is too long&#39; }),<br> // dob: z.date().max(exactlyNYearsAgoDate(18)).min(new Date(&#39;1900-01-01&#39;)),<br> dob: z.string().date(),<br> doj: z.string().date(),<br>});<br><br>export const UserSchemaPartial = userSchema.partial();<br><br>export const AddUserStep1Schema = userSchema.pick({<br> name: true,<br> email: true,<br> phone: true,<br> address: true,<br>});<br><br>export const AddUserStep2Schema = userSchema.pick({<br> role: true,<br> github: true,<br> linkedin: true,<br> skypeid: true,<br> dob: true,<br> doj: true,<br>});</pre><p>So the userSchema defines the field and the type it has but the magic of Zod is that you can also define what I like the call them as Constraints for your fields. If you want your name to have a minimum of 1 character or a maximum of 20 characters, use the methods min and max offered by them. Go to the documentation to find out all about them. You can also tag around the messages you would like to print when the validation fails.</p><p>That is pretty much it. It is that simple to define the validation constraints for your form fields.</p><p>As it is Typescript compatible, you can see I have used Partial and Pick methods to satisfy conditions specific to my use case. Also, I did not make an effort to write the Types for it. See below, I have generated the types from the Zod schema itself.</p><pre>import { z } from &#39;zod&#39;;<br><br>import { userSchema, UserSchemaPartial } from &#39;./zodSchemas&#39;;<br><br>export type UserType = z.infer&lt;typeof userSchema&gt;;<br><br>export type AddUserFormData = UserType;<br><br>export type UserPartialType = z.infer&lt;typeof UserSchemaPartial&gt;;</pre><p>Yup, you guessed it right. Now we are ready to write the validation logic.</p><p>Given below is the important snippet.</p><pre>const [errors, setErrors] =<br>  useState&lt;ZodFormattedError&lt;UserPartialType&gt; | null&gt;(null);<br><br> const [formData, setFormData] = useState&lt;UserType&gt;({<br>  name: &#39;&#39;,<br>  email: &#39;&#39;,<br>  phone: &#39;&#39;,<br>  address: &#39;&#39;,<br>  role: &#39;&#39;,<br>  github: &#39;&#39;,<br>  linkedin: &#39;&#39;,<br>  skypeid: &#39;&#39;,<br>  dob: &#39;&#39;,<br>  doj: &#39;&#39;,<br> });<br><br>const validate = () =&gt; {<br>  if (currentStep === 1) {<br>   const { name, email, phone, address } = formData;<br><br>   const result = AddUserStep1Schema.safeParse({<br>    name,<br>    email,<br>    phone,<br>    address,<br>   });<br><br>   if (!result.success) {<br>    const errors = result.error.format();<br>    console.log(errors);<br>    setErrors(errors);<br>    return false;<br>   }<br>  } else {<br>   const result = AddUserStep2Schema.safeParse(formData);<br>   if (!result.success) {<br>    const errors = result.error.format();<br>    console.log(errors);<br>    setErrors(errors);<br>    return false;<br>   }<br>  }<br><br>  return true;<br> };</pre><p>Refer to this for the complete code</p><p><a href="https://github.com/Adredrs23/next-ums/blob/2f67cbbb0e378010f78ae0a1df5bde542a8fa686/src/components/AddUserModal/AddUserModal.tsx">next-ums/src/components/AddUserModal/AddUserModal.tsx at 2f67cbbb0e378010f78ae0a1df5bde542a8fa686 · Adredrs23/next-ums</a></p><p>Go through the complete code to understand if there are any gaps but in a nutshell what I&#39;m trying to achieve is to write the validation logic using the Zod’s safeParse method. If it produces errors then store that error in the state and pass the error state value to the Error component for the respective input field. Along with this, the part to focus on is that the validate function doesn&#39;t use the complete <em>userSchema</em> to parse the formData rather we split them into parts as required by the step of the form and parse it with <em>AddUserStep1Schema</em> or <em>AddUserStep2Schema </em>which we conveniently picked out from the <em>userSchema.</em></p><p>If you have a closer look at, the phone field in the schema, we have used refine() to provide the validation from an external library which in this case is validator.js. This adds to Zod’s flexibility.</p><p>We are using the errors.format() to convert the errors produced into a presentable way for our users. One can play with the format() or flatten() or go a step further to specify their custom ErrorMap to suit their needs. Explained very well in the docs below and in the third article linked in the reference section of this blog post.</p><p>This is not where it ends though, you can also refer to their Error Handling guide to expand upon the error correctly.</p><ul><li><a href="https://zod.dev/?id=error-handling">TypeScript-first schema validation with static type inference</a></li><li><a href="https://zod.dev/ERROR_HANDLING">TypeScript-first schema validation with static type inference</a></li></ul><h3>In Conclusion</h3><p>Using Zod simplifies your code, and removes the redundant and mediocre work done to handle validation not only for forms but other data structures. It works well with Typescript so no need to redeclare Zod schema and then Typescript schema, instead infer it from the former.</p><p>Thus Zod helps you achieve more in less. <br>See you next time with another article on another interesting topic. Yeah-yeah I know, working on articles of Svelte and React-Keycloak-Hasura series. Stay tuned for those as well.</p><p>Until then, Happy coding!🔥🔥🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69f3f75feee5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part -1: Working with React, KeyCloak, and Urql.]]></title>
            <link>https://medium.com/@adredars/part-1-working-with-react-keycloak-and-urql-4d7fac03ca80?source=rss-53569232c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d7fac03ca80</guid>
            <category><![CDATA[hasura]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Adred]]></dc:creator>
            <pubDate>Mon, 27 May 2024 06:11:52 GMT</pubDate>
            <atom:updated>2024-05-27T06:11:52.230Z</atom:updated>
            <content:encoded><![CDATA[<p>In this series of blogs, we will dive into some new stacks that will help us create applications with GraphQL and KeyCloak as our AuthNAuth services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCkzmuOLLi5rUE_2XrAEgw.jpeg" /></figure><p>For this one, we will simply create a basic application and get everything running and in the next one, we will set up KeyCloak and URQL auth-exchange in detail.</p><h4>Setting up a new React project with Vite</h4><pre>pnpm create vite@latest react-kc - template react-ts<br>pnpm i<br>pnpm dev</pre><h4>Setting up the Hasura project on the cloud.</h4><p>Reference Docs: <a href="https://hasura.io/docs/latest/getting-started/getting-started-cloud/">https://hasura.io/docs/latest/getting-started/getting-started-cloud/</a></p><ol><li>Create a new project with Hasura.</li><li>Add a new database of your liking,</li><li>I tried the new Neon free offering for Postgres.</li><li>Create the todos table with the following schema</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*NytNoMMqVOzx7MGY4XWY3Q.png" /></figure><p>5. And users table with the following schema</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*kkBE1MPeUMmctDy8W-wlvw.png" /></figure><h4>Setting up URQL &amp; Redux</h4><pre>pnpm add urql<br>pnpm add @reduxjs/toolkit<br>pnpm add redux</pre><p>First of all, create a URQL client as shown below.</p><pre>// src/urql/client.ts<br>import { Client, cacheExchange, fetchExchange } from &quot;urql&quot;;<br><br>export const client = new Client({<br> url: &#39;http://localhost:3000/graphql&#39;,<br> exchanges: [cacheExchange, fetchExchange],<br>});</pre><pre>// src/urql/components/UrqlClientProvider.tsx<br><br>import { Provider } from &quot;urql&quot;;<br>import { client } from &quot;../client&quot;;<br><br>// An HOC that provides the client to the component tree<br>export const withClient = (Component: React.ComponentType) =&gt; {<br> // eslint-disable-next-line @typescript-eslint/no-explicit-any<br> return (props: any) =&gt; {<br>   return (<br>   &lt;Provider value={client}&gt;<br>     &lt;Component {…props} /&gt;<br>   &lt;/Provider&gt;<br>   );<br> };<br>};</pre><p>And then modify your App.tsx as shown below.</p><pre>import { withClient } from &#39;./urql&#39;;<br>import &#39;./App.css&#39;<br><br>function App() {<br>   return (<br>     &lt;&gt;<br>      Main<br>     &lt;/&gt;<br>   )<br>}<br><br>export const AppWithClient = withClient(App);<br><br>export default AppWithClient;</pre><h4>Setting up GraphQL, Graphql-codegen</h4><p>Reference: <a href="https://github.com/hasura/graphqurl">https://github.com/hasura/graphqurl</a></p><pre>pnpm add graphql<br>pnpm add -D typescript @graphql-codegen/cli<br>pnpm add -D graphqurl<br>pnpm add env-cmd</pre><p>Get the React codegen preset file from the following link. Add the following codegen.ts file configuration to the root of your project.</p><pre>import { CodegenConfig } from &#39;@graphql-codegen/cli&#39;<br><br>const config: CodegenConfig = {<br>  schema: &#39;schema.graphql&#39;,<br>  documents: [&#39;src/**/*.tsx&#39;],<br>  ignoreNoDocuments: true, // for better experience with the watcher<br>  generates: {<br>    &#39;./src/types/generated/&#39;: {<br>      preset: &#39;client&#39;,<br>    },<br>  },<br>}<br><br>export default config</pre><p>Add the following scripts in your package.json<br>REFERENCE: <a href="https://github.com/toddbluhm/env-cmd?tab=readme-ov-file#using-custom-env-file-path">https://github.com/toddbluhm/env-cmd?tab=readme-ov-file#using-custom-env-file-path</a></p><pre>&quot;generate&quot;: &quot;graphql-codegen&quot;,<br>&quot;prestart&quot;: &quot;pnpm generate&quot;,<br>&quot;predev&quot;: &quot;pnpm generate&quot;,<br>&quot;getschema&quot;: &quot;env-cmd -f .env -x gq $VITE_HASURA_ENDPOINT -H \&quot;X-Hasura-Admin-Secret: $VITE_HASURA_GRAPHQL_ADMIN_SECRET\&quot; - introspect &gt; schema.graphql&quot;</pre><p>Add a .env file that looks like this.</p><pre>VITE_HASURA_ENDPOINT=YOUR_HASURA_ENDPOINT<br>VITE_HASURA_GRAPHQL_ADMIN_SECRET=YOUR_HASURA_SECRET</pre><p>Run the <em>pnpm getschema</em> command to get the schema from Hasura stored in schema.graphql which the codegen will take up to generate types for your project. <br>Use the command <em>pnpm generate</em> to generate the types.</p><p>Modify the client as below to incorporate the changes for connecting to your Hasura server.</p><pre>import { Client, cacheExchange, fetchExchange } from &#39;urql&#39;<br>t<br>export const client = new Client({<br>  url: import.meta.env.VITE_HASURA_ENDPOINT,<br>  exchanges: [cacheExchange, fetchExchange],<br>  fetchOptions: () =&gt; {<br>    // const token = getToken();<br><br>    return {<br>    // headers: { authorization: token ? `Bearer ${token}` : &#39;&#39; },<br>    headers: {<br>        &#39;x-hasura-admin-secret&#39;: import.meta.env<br>        .VITE_HASURA_GRAPHQL_ADMIN_SECRET,<br>      },<br>    }<br>  },<br>})</pre><blockquote>Note: For now we are using the ‘x-hasura-admin-secret’ which is highly insecure to keep in the env but later on we will replace it with JWT token when we set up the KeyCloak JWT authentication.</blockquote><p>If everything goes well, adding the following Todos component in your App.tsx will get this output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_HA_iN5XYB3ZBPcclo1MQ.png" /><figcaption>Output when there’s no data present in the users and todos table.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7z63oTEFqoGHuqS1rRNnbQ.png" /><figcaption>Output when there’s data present in the users and todos table.</figcaption></figure><pre>// src/components/Todos.tsx<br><br>import { useQuery } from &#39;urql&#39;<br>import dayjs from &#39;dayjs&#39;<br><br>import { graphql } from &#39;../../types/generated&#39;<br>import { Get_TodosQuery } from &#39;../../types/generated/graphql&#39;<br><br>const GET_USERS_QUERY_DOCUMENT = graphql(/* GraphQL */ `<br>  query Get_TODOS {<br>    todos {<br>      id<br>      is_completed<br>      todo_name<br>      updated_at<br>      updated_by<br>      created_by<br>      created_at<br>      todos_users_created_by_reln {<br>        name<br>        id<br>      }<br>      todos_users_updated_by_reln {<br>        id<br>        name<br>      }<br>    }<br>  }<br>`)<br><br>export const Todos = () =&gt; {<br>  const [result] = useQuery&lt;Get_TodosQuery&gt;({<br>    query: GET_USERS_QUERY_DOCUMENT,<br>  })<br><br>  const { data, fetching, error } = result<br><br>  console.log(data, error)<br>  if (fetching) return &lt;p&gt;Loading...&lt;/p&gt;<br><br>  if (error) return &lt;p&gt;Oh no... {error.message}&lt;/p&gt;<br><br>  if (!data || !data.todos || data.todos.length === 0) {<br>    return &lt;p&gt;No data&lt;/p&gt;<br>  }<br><br>  return (<br>    &lt;ul&gt;<br>      {data.todos.map(todo =&gt; (<br>        &lt;li key={todo.id}&gt;<br>          {todo.todo_name} ||{&#39; &#39;}<br>          {dayjs(todo.updated_at).format(&#39;DD MMM YYYY HH:mm:ss&#39;)} ||{&#39; &#39;}<br>          {todo.todos_users_updated_by_reln.name} ||<br>          {dayjs(todo.created_at).format(&#39;DD MMM YYYY HH:mm:ss&#39;)} ||{&#39; &#39;}<br>          {todo.todos_users_created_by_reln.name} || {todo.is_completed + &#39;&#39;}<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  )<br>}</pre><h4>Conclusion</h4><p>If everything works well, you’ll have a Hasura GraphQL Engine running on the cloud with Neon Postgres as the database. You’ll also have a React typescript project running with types generation for Hasura schema using Graphqurl to fetch the schema and generate types using Graphql codegen.</p><p>When I see you next time, we will dive deeper into KeyCloak and Redux which will help us set up the auth policies for the project using the URQL exchanges specifically auth-exchange.</p><p>Till then, Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d7fac03ca80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>