<?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 AlMonther Abdulhafeez on Medium]]></title>
        <description><![CDATA[Stories by AlMonther Abdulhafeez on Medium]]></description>
        <link>https://medium.com/@ealmonzer667?source=rss-157b1ac92a88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g5i8y_xC0veLZPXdWYunLA.jpeg</url>
            <title>Stories by AlMonther Abdulhafeez on Medium</title>
            <link>https://medium.com/@ealmonzer667?source=rss-157b1ac92a88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:54:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ealmonzer667/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[Architecture & Production Setup Guide: Electron + Next.js + TypeScript + Tailwind CSS]]></title>
            <link>https://medium.com/@ealmonzer667/architecture-production-setup-guide-electron-next-js-typescript-tailwind-css-e88098f44a47?source=rss-157b1ac92a88------2</link>
            <guid isPermaLink="false">https://medium.com/p/e88098f44a47</guid>
            <category><![CDATA[desktop-app]]></category>
            <category><![CDATA[electronjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[AlMonther Abdulhafeez]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 17:14:56 GMT</pubDate>
            <atom:updated>2026-07-31T15:50:19.501Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a production-grade desktop application with Electron and Next.js combines powerful native operating system capabilities with modern web development practices. To establish a maintainable, fully type-safe, and secure production codebase, developers must prioritize strict process isolation, ensure reliable static exports for offline functionality, and enforce a clean directory architecture from day one.</p><blockquote><em>Real-World Motivation: Why Move from Web to Desktop?<br>A common scenario that leads developers to Electron is needing true file system control. For example, when building a local media or document management tool, web storage mechanisms quickly become a bottleneck due to storage quotas and browser sandboxing. Wrapping your Next.js and Tailwind stack inside Electron lets you manage local disk files directly through Node.js while building the UI with the web tools you already know.</em></blockquote><h3>1. Detailed Architectural Strategy</h3><p>Electron applications are structured to run across two primary runtime environments, split intentionally to preserve security and efficiency:</p><ol><li><strong>Main Process (Node.js Runtime):</strong> Acts as the backend core of the application. It controls the application lifecycle, orchestrates native window creation, configures OS-level menus, manages the system tray, and executes highly privileged operations like system commands or direct file system access.</li><li><strong>Renderer Process (Chromium &amp; Next.js):</strong> Handles the frontend user interface. To run reliably offline as a self-contained binary without needing a background Node web server, Next.js must be configured in <strong>Static Export mode</strong> (utilizing output: ‘export’).</li><li><strong>Preload Script (The Security Gatekeeper):</strong> Functions as a secure, type-safe communication bridge between the Main and Renderer processes via contextBridge and ipcRenderer, ensuring web code never gains direct access to underlying Node.js capabilities.</li></ol><p>The core interaction model is illustrated below:</p><pre>┌─────────────────────────────────────────────────────────┐<br>│ MAIN PROCESS │<br>│ (Node.js Runtime: Window Control, File System, OS) │<br>└───────────────────────────┬─────────────────────────────┘<br> │ Preload Bridge (IPC)<br>┌───────────────────────────▼─────────────────────────────┐<br>│ RENDERER PROCESS │<br>│ (Chromium Runtime: Next.js App Router, Tailwind CSS) │<br>└─────────────────────────────────────────────────────────┘</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpDzJYwsNKsNje8yoiwBJQ.jpeg" /><figcaption>main layers</figcaption></figure><h3>2. Directory Structure (src/ Architecture)</h3><p>Organizing your code strictly inside the src/ folder isolates the Main, Preload, and Renderer domains. This architectural separation prevents client-side Next.js bundles from accidentally importing Node.js modules, which would break the frontend build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pngOsePzd3tKFerFRcu8Hw.jpeg" /></figure><pre>my-electron-app/<br>├── src/<br>│ ├── main/ # Electron Main Process (Node.js backend)<br>│ │ ├── index.ts # Main entry point &amp; BrowserWindow lifecycle management<br>│ │ ├── ipc/ # Inter-Process Communication handler modules<br>│ │ │ └── system.ts<br>│ │ └── utils/ # Node-side utilities and helpers<br>│ │<br>│ ├── preload/ # Secure Preload Bridge domain<br>│ │ └── index.ts # Exposes explicit window APIs via contextBridge<br>│ │<br>│ └── renderer/ # Next.js Frontend App Router UI<br>│ ├── app/ # Frontend pages, routing, layouts<br>│ │ ├── globals.css # Tailwind CSS configuration directives &amp; globals<br>│ │ ├── layout.tsx<br>│ │ └── page.tsx<br>│ ├── components/ # Reusable user interface components<br>│ ├── hooks/ # React hooks for custom lifecycle and IPC listening<br>│ └── types/ # TypeScript window global configurations &amp; IPC schemas<br>│<br>├── public/ # App icons, splash screens, asset storage<br>├── dist/ # Bundled JavaScript output for Main &amp; Preload processes<br>├── out/ # Statically exported standalone Next.js client assets<br>├── electron-builder.yml # Native multi-platform packager settings<br>├── next.config.ts # Next.js build export paths and static properties<br>├── tailwind.config.ts # Tailwind CSS scan paths and customization definitions<br>├── tsconfig.json # Root TypeScript strict environment configuration<br>└── package.json # Script automation runner, definitions &amp; dependencies</pre><h3>3. Step-by-Step Setup Guide</h3><h3>Step 1: Initialize Project &amp; Dependencies</h3><p>Initialize a new project environment and install the required core, development, frontend, and style dependencies:</p><pre>mkdir my-electron-app &amp;&amp; cd my-electron-app<br>npm init -y<br># Core dependencies<br>npm install electron-serve<br># Development dependencies<br>npm install -D electron electron-builder typescript @types/node @types/react @types/react-dom tsup concurrently wait-on<br># Next.js, React, and Tailwind dependencies<br>npm install next react react-dom<br>npm install -D tailwindcss postcss autoprefixer</pre><h3>Alternative Bootstrapping Strategy: Automated Project Initialization</h3><p>For a streamlined workspace configuration, utilize create-next-app to programmatically scaffold the application infrastructure. This method automates the initialization of the App Router, TypeScript environment, and Tailwind CSS directives within a structured src/ directory, minimizing manual overhead.</p><p><strong>1. Scaffold the Next.js Frontend:</strong></p><pre>npx create-next-app@latest my-electron-app \<br> - typescript \<br> - tailwind \<br> - eslint \<br> - app \<br> - src-dir \<br> - import-alias &quot;@/*&quot;<br>cd my-electron-app</pre><p><strong>2. Integrate Electron Runtime &amp; Tooling:</strong></p><pre># Production asset delivery service<br>npm install electron-serve<br># Desktop binaries and build orchestration suites<br>npm install -D electron electron-builder tsup concurrently wait-on @types/node</pre><p><strong>3. Restructure Frontend Directories:</strong></p><p>Create a renderer directory within src/ and migrate the generated app/ and components/ directories into src/renderer/ to maintain strict architectural separation.</p><p><strong>Note on Configuration Integrity:</strong> While manual initialization via npm init provides granular control, the create-next-app utility ensures immediate architectural compatibility, enforcing consistent CSS compilation, strict type definitions, and internal path mapping aliases.</p><h3>Step 2: Configure TypeScript (tsconfig.json)</h3><p>Enforce type safety across all sub-folders by configuring compiler features and path mapping aliases targeting the src/ directories:</p><pre>{<br>&quot;compilerOptions&quot;: {<br>&quot;target&quot;: &quot;ES2022&quot;,<br>&quot;module&quot;: &quot;ESNext&quot;,<br>&quot;moduleResolution&quot;: &quot;bundler&quot;,<br>&quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],<br>&quot;allowJs&quot;: true,<br>&quot;skipLibCheck&quot;: true,<br>&quot;strict&quot;: true,<br>&quot;noEmit&quot;: true,<br>&quot;esModuleInterop&quot;: true,<br>&quot;resolveJsonModule&quot;: true,<br>&quot;isolatedModules&quot;: true,<br>&quot;jsx&quot;: &quot;preserve&quot;,<br>&quot;incremental&quot;: true,<br>&quot;baseUrl&quot;: &quot;.&quot;,<br>&quot;paths&quot;: {<br>&quot;@main/*&quot;: [&quot;src/main/*&quot;],<br>&quot;@preload/*&quot;: [&quot;src/preload/*&quot;],<br>&quot;@renderer/*&quot;: [&quot;src/renderer/*&quot;],<br>&quot;@/*&quot;: [&quot;src/renderer/*&quot;]<br>}<br>},<br>&quot;include&quot;: [&quot;src/**/*&quot;],<br>&quot;exclude&quot;: [&quot;node_modules&quot;, &quot;dist&quot;, &quot;out&quot;]<br>}</pre><h3>Step 3: Configure Next.js (next.config.ts)</h3><p>To seamlessly pack Next.js inside an Electron context, configure compilation parameters to output static assets directly to a folder Electron can bundle:</p><pre>import type { NextConfig } from &#39;next&#39;;<br>const nextConfig: NextConfig = {<br>output: &#39;export&#39;,<br>distDir: &#39;../../out&#39;, // Outputs compiled files to /out at the project root<br>images: {<br>unoptimized: true, // Required for static exports<br>},<br>};<br>export default nextConfig;</pre><h3>Step 4: Configure Tailwind CSS</h3><p>Initialize Tailwind configuration to scan the exact paths containing components and layout elements inside src/renderer:</p><pre>// tailwind.config.ts<br>import type { Config } from &#39;tailwindcss&#39;;<br>const config: Config = {<br>content: [<br>&#39;./src/renderer/app/**/*.{js,ts,jsx,tsx,mdx}&#39;,<br>&#39;./src/renderer/components/**/*.{js,ts,jsx,tsx,mdx}&#39;,<br>],<br>theme: {<br>extend: {},<br>},<br>plugins: [],<br>};<br>export default config;<br>Add the essential utility directives to src/renderer/app/globals.css:<br>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><h3>4. Electron Process Implementation</h3><h3>1. The Preload Script (src/preload/index.ts)</h3><p>Context isolation must remain continuously active. Expose explicit, minimal frontend listeners and invoke pathways using contextBridge:</p><pre>import { contextBridge, ipcRenderer } from &#39;electron&#39;;<br>export const API = {<br>getSystemInfo: () =&gt; ipcRenderer.invoke(&#39;system:get-info&#39;),<br>onNotification: (callback: (message: string) =&gt; void) =&gt; {<br>const subscription = (_: any, value: string) =&gt; callback(value);<br>ipcRenderer.on(&#39;system:notification&#39;, subscription);<br>return () =&gt; ipcRenderer.removeListener(&#39;system:notification&#39;, subscription);<br>},<br>};<br>contextBridge.exposeInMainWorld(&#39;electronAPI&#39;, API);<br>export type ElectronAPI = typeof API;</pre><p>Ensure TypeScript visibility by declaring global bindings in</p><pre>src/renderer/types/global.d.ts:<br>import { ElectronAPI } from &#39;@/preload&#39;;<br>declare global {<br>interface Window {<br>electronAPI: ElectronAPI;<br>  }<br>}</pre><h3>2. The Main Process (src/main/index.ts)</h3><p>Configure the core application file to cleanly resolve development server loading or fall back to static file delivery paths during build states:</p><pre>import { app, BrowserWindow, ipcMain } from &#39;electron&#39;;<br>import path from &#39;path&#39;;<br>import serve from &#39;electron-serve&#39;;<br>const isDev = !app.isPackaged;<br>const loadApp = serve({ directory: path.join(__dirname, &#39;../../out&#39;) });<br>let mainWindow: BrowserWindow | null = null;<br>async function createWindow() {<br>mainWindow = new BrowserWindow({<br>width: 1200,<br>height: 800,<br>webPreferences: {<br>preload: path.join(__dirname, &#39;../preload/index.js&#39;),<br>contextIsolation: true,<br>nodeIntegration: false,<br>  },<br>});<br>if (isDev) {<br>await mainWindow.loadURL(&#39;http://localhost:3000&#39;);<br>mainWindow.webContents.openDevTools();<br>} else {<br>await loadApp(mainWindow);<br>  }<br>}<br>// IPC Handlers<br>ipcMain.handle(&#39;system:get-info&#39;, () =&gt; {<br>return {<br>platform: process.platform,<br>arch: process.arch,<br>version: app.getVersion(),<br>  };<br>});<br>app.whenReady().then(createWindow);<br>app.on(&#39;window-all-closed&#39;, () =&gt; {<br>if (process.platform !== &#39;darwin&#39;) app.quit();<br>});</pre><h3>5. Development &amp; Build Automation Scripts</h3><p>Leverage tsup compilation suites to pack Main and Preload scripts to /dist while simultaneously guiding the static Next.js UI export routine into the target /out workspace.</p><p>Configure package.json orchestration fields:</p><pre>{<br>&quot;name&quot;: &quot;my-electron-app&quot;,<br>&quot;version&quot;: &quot;1.0.0&quot;,<br>&quot;main&quot;: &quot;dist/main/index.js&quot;,<br>&quot;scripts&quot;: {<br>&quot;dev:next&quot;: &quot;next dev -p 3000 src/renderer&quot;,<br>&quot;dev:electron&quot;: &quot;tsup src/main/index.ts src/preload/index.ts - out-dir dist - watch - onSuccess \&quot;electron .\&quot;&quot;,<br>&quot;dev&quot;: &quot;concurrently -k \&quot;npm run dev:next\&quot; \&quot;wait-on http://localhost:3000 &amp;&amp; npm run dev:electron\&quot;&quot;,<br>&quot;build:main&quot;: &quot;tsup src/main/index.ts src/preload/index.ts - out-dir dist&quot;,<br>&quot;build:renderer&quot;: &quot;next build src/renderer&quot;,<br>&quot;build&quot;: &quot;npm run build:main &amp;&amp; npm run build:renderer&quot;,<br>&quot;package&quot;: &quot;npm run build &amp;&amp; electron-builder&quot;<br>  }<br>}</pre><h3>6. Development Workflow &amp; Scaling Rules</h3><h3>Route Management</h3><p>In Static Export environments, path mapping resolves locally via file paths:</p><ul><li>Avoid dynamic server components or functions like getServerSideProps.</li><li>Rely exclusively on client-side state hooks (useSWR, TanStack Query) or direct Electron IPC callbacks for asynchronous state management.</li><li>Enforce standard Hash-based or explicit relative navigation parameters to prevent local asset breaks in product deployments.</li></ul><h3>State Management &amp; Storage</h3><p>Combine local runtime modules with durable system backend tools:</p><ol><li><strong>UI Context State:</strong> Handle presentation state directly via Zustand or React Context within the src/renderer framework.</li><li><strong>Durable Application Parameters:</strong> Commit durable data layers through the Main process with libraries like electron-store. Do not use browser localStorage, which is volatile and easily purged by native runtime sweeping tasks.</li></ol><h3>Packaging for Release</h3><p>Establish an electron-builder.yml configuration file at the root level:</p><pre>appId: com.yourcompany.app<br>productName: MyElectronApp<br>directories:<br>output: release<br>files:<br>- dist/**/*<br>- out/**/*<br>- package.json<br>mac:<br>category: public.app-category.utilities<br>target: - dmg<br>- zip<br>win:<br>target: - nsis<br>- zip</pre><h3>7. Next Steps</h3><p>To scale this initial architectural foundation up to an enterprise-grade production standard, consider integrating the following advanced workflows:</p><ol><li><strong>Custom Frameless Title Bar:</strong> Design an integrated title bar component matching your brand guidelines using Tailwind CSS, wired directly into window modification handlers over secure IPC routines (e.g., minimize, maximize, and exit triggers).</li><li><strong>Durable Auto-Updater Pipeline:</strong> Embed the native electron-updater layer inside src/main to systematically watch for, download, and apply silent update iterations in the background across production environments.</li><li><strong>Strict Runtime Request Validation:</strong> Introduce Zod verification pipelines inside your primary main process listeners to structurally validate every payload coming across the IPC bridge, ensuring robust security.</li></ol><h3>The Process Role Breakdown</h3><p>Write all execution logic inside the Main process scope (src/main). Never place heavy backend functionality in the Preload domain — it must serve strictly as a thin, highly secure data channel.</p><h4>1. Main (Backend)</h4><ul><li><strong>Location:</strong> src/main/</li><li><strong>Role &amp; Responsibilities:</strong> Executes all backend services. Connects directly to localized data nodes (SQLite/Prisma), drives disk file operations, reads system paths, handles application shells, and safely runs native background tasks.</li></ul><h4>2. Preload (Bridge)</h4><ul><li><strong>Location:</strong> src/preload/</li><li><strong>Role &amp; Responsibilities:</strong> Serves as the isolated gatekeeper. Contains no heavy logic or deep computations. It strictly captures actions issued by the Next.js renderer and passes them over IPC to the Main runtime.</li></ul><h4>3. Renderer (UI)</h4><ul><li><strong>Location:</strong> src/renderer/</li><li><strong>Role &amp; Responsibilities:</strong> Renders the frontend view layer. Built entirely with Next.js components, layouts, styling frameworks, and custom React hooks that interact via the global window.electronAPI object.</li></ul><pre>┌─────────────────┬─────────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐<br>│ Process Name    │ Source Location │ Role &amp; Primary Responsibilities                                                                                                       │<br>├─────────────────┼─────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤<br>│ Main (Backend)  │ src/main/       │ Executes all backend services. Connects directly to localized data nodes (SQLite/Prisma), drives disk file operations, etc.           │<br>│ Preload (Bridge)│ src/preload/    │ Serves as the isolated gatekeeper. Contains no heavy logic. Strictly captures actions and passes them over IPC to Main.               │<br>│ Renderer (UI)   │ src/renderer/   │ Renders the frontend view layer. Built with Next.js components and hooks that interact via the global window.electronAPI object.      │<br>└─────────────────┴─────────────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘</pre><h3>Recommended Clean Coding Patterns</h3><p>Keep operations organized by separating underlying system logic into explicit Services files, isolated completely from the IPC Event Listeners.</p><h3>1. Write the Backend Logic in src/main</h3><p>Write dedicated operations logic inside a centralized file service component:</p><pre>// src/main/services/fileService.ts<br>import fs from &#39;fs/promises&#39;;<br>import path from &#39;path&#39;;<br>export class FileService {<br>static async readUserData(filename: string) {<br>// Handles true node disk access workflows<br>const filePath = path.join(process.cwd(), &#39;data&#39;, filename);<br>const content = await fs.readFile(filePath, &#39;utf-8&#39;);<br>return JSON.parse(content);<br>  }<br>}</pre><p>Bind your system actions securely inside the main routing event file:</p><pre>// src/main/ipc/fileHandlers.ts<br>import { ipcMain } from &#39;electron&#39;;<br>import { FileService } from &#39;../services/fileService&#39;;<br>export function registerFileHandlers() {<br>ipcMain.handle(&#39;files:read-data&#39;, async (_, filename: string) =&gt; {<br>return await FileService.readUserData(filename);<br>  });<br>}</pre><h3>2. Expose the Bridge in src/preload</h3><p>Keep the preload definition file perfectly lean, acting purely as a transparent structural forwarding target:</p><pre>// src/preload/index.ts<br>import { contextBridge, ipcRenderer } from &#39;electron&#39;;<br>contextBridge.exposeInMainWorld(&#39;electronAPI&#39;, {<br>readUserData: (filename: string) =&gt; ipcRenderer.invoke(&#39;files:read-data&#39;, filename),<br>});</pre><h3>3. Call it from Next.js (src/renderer)</h3><p>Invoke the window method securely inside your interactive web page view components:</p><pre>// src/renderer/app/page.tsx<br>&#39;use client&#39;;<br>import { useState } from &#39;react&#39;;<br>export default function Dashboard() {<br>const [data, setData] = useState&lt;any&gt;(null);<br>const handleLoadData = async () =&gt; {<br>// Next.js client calls -&gt; Preload bridge forwarder -&gt; Main listener execution<br>const result = await window.electronAPI.readUserData(&#39;user-settings.json&#39;);<br>setData(result);<br>};<br>return (<br>&lt;div className=&quot;p-6&quot;&gt;<br>&lt;button<br>onClick={handleLoadData}<br>className=&quot;px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700&quot;<br>&gt;<br>Load User Data<br>&lt;/button&gt;<br>{data &amp;&amp; &lt;pre&gt;{JSON.stringify(data, null, 2)}&lt;/pre&gt;}<br>&lt;/div&gt;<br>  );<br>}</pre><h3>Why you should never put backend code in Preload</h3><ol><li><strong>Security Degradation:</strong> Code running inside a preload script shares runtime access with web APIs and limited Node tasks. Placing secret keys, database handlers, or raw filesystem modification modules directly into preload drastically inflates your client attack vulnerability.</li><li><strong>Performance Penalties:</strong> Preload handlers fire every time a separate frame or child layout container initializes. Embedding database link pooling or heavy backend initialization steps here significantly slows down window painting speeds.</li></ol><p><strong>Architectural Complications:</strong> Keeping processing nodes confined inside src/main permits the isolated testing of core logic using lightweight Node.js test engines (like Vitest or Jest) without needing full, resource-heavy Electron shell environments to initialize.</p><p>Building desktop applications with web technologies used to mean sacrificing process isolation or wrestling with fragile build configurations. With this architecture in place, you now have a rock-solid, fully type-safe foundation that leverages the full power of Next.js and Electron without cutting security corners. From here, the canvas is yours — whether you’re building rich offline dashboards, integrating local databases, or crafting custom window chrome.</p><p>Happy coding, and go build something incredible!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e88098f44a47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Headless GraphQL in Next.js: A Guide to Proxies, Codegen, and Caching]]></title>
            <link>https://medium.com/@ealmonzer667/mastering-headless-graphql-in-next-js-a-guide-to-proxies-codegen-and-caching-a1c092633a35?source=rss-157b1ac92a88------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c092633a35</guid>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[AlMonther Abdulhafeez]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 17:12:02 GMT</pubDate>
            <atom:updated>2025-12-22T22:06:47.451Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>By [The Hirease Team]</strong></p><p>Building a “Headless” frontend with Next.js and GraphQL sounds simple on paper: npm install @apollo/client, Write a query, and ship it.</p><p>But in production, the cracks start to show.</p><ul><li><strong>Security:</strong> How do you handle HttpOnly cookies when your GraphQL client is running in the browser?</li><li><strong>Reliability:</strong> What happens when the backend renames a field, and your frontend builds successfully but crashes at runtime?</li><li><strong>Performance:</strong> How do you avoid the “Waterfall” of loading spinners when fetching nested data?</li></ul><p>At <strong>Hirease</strong>, we learned that moving from REST to GraphQL isn’t just about changing endpoints — it’s about changing your <strong>contract</strong>.</p><p>This guide breaks down our production architecture into three pillars:</p><ol><li><strong>The Architect:</strong> Securing the connection via a Backend-for-Frontend (BFF) Proxy.</li><li><strong>The Toolsmith:</strong> Automating trust with Codegen and strict Type Safety.</li><li><strong>The Optimizer:</strong> Leveraging Server Components and Normalized Caching for maximum speed.</li></ol><h3><strong>First: The Architect (Security &amp; Infrastructure)</strong></h3><p>​The first challenge in a “Headless” architecture is how to connect securely. A common mistake is letting the browser call the upstream GraphQL API directly, exposing your infrastructure to the world. To solve this, we need a gatekeeper.</p><h3><strong>The (BFF) Proxy Pattern:</strong></h3><p>The <strong>BFF</strong> <strong>pattern</strong> means having a backend layer that sits between the frontend and the main backend services.</p><p>In Hirease, this layer is implemented via the GraphQL Proxy Route.</p><figure><img alt="proxy route" src="https://cdn-images-1.medium.com/max/1024/1*GdBgZsvCcM2LGK2MHZVvgQ.png" /></figure><p><strong><em>Why Do We Use a Proxy Instead of Calling the Backend Directly?</em></strong></p><p><strong>1. Avoiding CORS (Cross-Origin Resource Sharing)</strong></p><figure><img alt="without proxy" src="https://cdn-images-1.medium.com/max/1024/1*cSjKFUlPzreLwQ2bs4ufLw.png" /></figure><figure><img alt="with proxy" src="https://cdn-images-1.medium.com/max/1024/1*Gg0oLfZruUqrzlDk-ulVDw.png" /></figure><p><strong>2. Token Security with HttpOnly Cookies</strong></p><figure><img alt="(Without HttpOnly) Insecure" src="https://cdn-images-1.medium.com/max/1024/1*ShDrB3e3bJqH7D8crl3wnA.png" /></figure><figure><img alt="(HttpOnly Cookies) Secure" src="https://cdn-images-1.medium.com/max/1024/1*5zHWpCs7s6qiH7lkc_PnzA.png" /></figure><p><strong>3. Backend URL Abstraction</strong></p><p>Frontend only calls:</p><figure><img alt="api route for graphql proxy" src="https://cdn-images-1.medium.com/max/695/1*M1ZVrDy8YOQEAK34QXmwrg.png" /></figure><p>This allows:</p><blockquote>infrastructure changes</blockquote><blockquote>environment switching</blockquote><blockquote>Hiding internal topology</blockquote><p><strong>4. Transformation Layer</strong></p><p>The proxy can:</p><blockquote>Add headers</blockquote><blockquote>Sanitize or transform requests</blockquote><blockquote>Log requests</blockquote><blockquote>Add auth rules</blockquote><blockquote>Add rate limiting or caching later</blockquote><p><strong>5. Security Benefits</strong></p><figure><img alt="Security Benefits" src="https://cdn-images-1.medium.com/max/1024/1*vPa9CB3QQbtqwFdXasy9Ig.png" /></figure><h3><strong>Authentication Handshake Flow:</strong></h3><figure><img alt="Login and Token Issuance" src="https://cdn-images-1.medium.com/max/1024/1*qpFwpSB8FkEMqSrQC2UgqA.png" /></figure><figure><img alt="Authenticated Token Refresh" src="https://cdn-images-1.medium.com/max/1024/1*92uSsGif4OMFRMKOHFZdEQ.png" /></figure><p><strong>Token Refresh Flow</strong></p><p>If: accessToken expires, refreshToken sis till valid</p><p>Middleware triggers a refresh flow</p><figure><img alt="Token Refresh Flow" src="https://cdn-images-1.medium.com/max/1024/1*pvo24Oyh8s0wzYHZ8L-Meg.png" /></figure><p>The refresh endpoint returns a new access token and updates cookies.</p><h3><strong>GraphQL vs REST: Strategic Justification</strong></h3><figure><img alt="GraphQL vs REST: Strategic Justification" src="https://cdn-images-1.medium.com/max/1024/1*63ZqzNiYqPqop31X24UAoQ.png" /></figure><p><strong>REST Problems:</strong></p><ol><li>Over-fetching: REST returns many unused fields</li></ol><p>2. Under-fetching: Dozens of requests.</p><p>3. Too many endpoints: REST needs 50–100 endpoints</p><h3><strong>Why GraphQL Fits Hirease Perfectly</strong></h3><pre>company(id: $id) {<br>name<br>jobs {<br>  title<br>  review {<br>    rate<br>    comment<br>    }<br>  }<br>}</pre><blockquote><strong>Only gets the fields the UI needs</strong></blockquote><blockquote><strong>Perfect for relational data: Nested results in one request.</strong></blockquote><blockquote><strong>Fast for mobile: Lower bandwidth, fewer requests.</strong></blockquote><blockquote><strong>Easy to evolve frontend without backend updates: Just add/remove fields in queries.</strong></blockquote><blockquote><strong>Strong typing: GraphQL schema auto-generated TypeScript.</strong></blockquote><p><strong>The Architect’s Dilemma.</strong> We have established a secure, optimized highway for our data. But a secure connection doesn’t guarantee safe code. Without strict contracts, we are just shipping data faster to a frontend that might crash if a single field name changes.</p><p>This brings us to our second pillar: ensuring that what we fetch is exactly what we expect.</p><h3>Second: The Toolsmith: Engineering Trust in Your Data Layer</h3><p>In the “Architect” section, we defined <em>why</em> we use GraphQL. Now, we must determine <em>how</em> we wield it.</p><p>We have all been there. You are building a feature, the backend team says the API is ready, and you start typing out your interface:</p><pre>interface User {<br> id: string;<br> name: string;<br> email: string;<br> // … guessing the rest?<br>}</pre><p>Two weeks later, the app crashes in production because the backend engineer renamed the name to fullName, and your TypeScript compiler — your first line of defense — didn’t say a word.</p><p>Treating GraphQL like a “better REST” leaves its biggest superpower on the table: <strong>Introspection</strong>. Scaling a frontend codebase requires moving from manual guessing to automated guarantees. Here is how to evolve developer experience (DX) from fragile to bulletproof.</p><h3>1. The “Any” Trap: Stop Guessing, Start Generating</h3><p>In many codebases, auditing documentation reveals a smoking gun: guides that explicitly teach developers to bypass type safety to “get things moving”.</p><h3>The “Before” Reality: The Ticking Time Bomb</h3><p>Manually writing queries and typing results as any or loose interfaces is a common anti-pattern.</p><pre>// ❌ The Fragile Way: A production crash waiting to happen<br>// Telling TypeScript to ignore errors removes your safety net.<br>{data.filterCompanies.companies.map((company: any) =&gt; ( // ←- The &quot;Any&quot; Trap<br> &lt;div key={company.id}&gt;<br> {/* If the backend renames &#39;companyName&#39; to &#39;name&#39;, this breaks silently */}<br> &lt;h2&gt;{company.companyName}&lt;/h2&gt;<br> &lt;p&gt;{company.industry}&lt;/p&gt;<br> &lt;/div&gt;<br>))}</pre><p>If you are using TypeScript but defining your API types by hand, you are doing double the work for half the safety.</p><h3>The Solution: GraphQL Code Generator</h3><p>The standard solution is <strong>@graphql-codegen/cli</strong>. Instead of writing types, tooling should scan query strings and compare them against the live backend schema.</p><figure><img alt="GraphQL Codegen flow" src="https://cdn-images-1.medium.com/max/1024/1*5JYasdf4YpHvD_CpYOsxGw.png" /></figure><p>The “After” Reality: Automated Guarantees</p><p>Stop writing manual useQuery hooks. Run a script to generate custom hooks that know exactly what the backend returns.</p><pre>// ✅ The Robust Way: Generated, strict, and safe<br>// This hook is generated automatically based on your query file.<br>import { useFilterCompaniesQuery } from &#39;@/graphql/generated/hooks&#39;;<br>const CompanySearch = () =&gt; {<br> // &#39;data&#39; is automatically typed based on the schema. No guessing.<br> const { data } = useFilterCompaniesQuery({<br> variables: { input: { limit: 10 } }<br> });<br> return (<br> &lt;div&gt;<br> {/* VS Code autocompletes &#39;companyName&#39; here. */}<br> {/* If you type &#39;name&#39;, the build fails immediately. */}<br> {data?.filterCompanies.companies.map((company) =&gt; (<br> &lt;div key={company.id}&gt;{company.companyName}&lt;/div&gt;<br> ))}<br> &lt;/div&gt;<br> )<br>}</pre><h3>2. Death to the “Queries” Folder: Co-location</h3><p>In standard MVC frameworks, it feels natural to centralize data fetching logic (e.g., a lib/queries folder). In component-based architecture like React, this is an anti-pattern that leads to <strong>“Zombie Data.”</strong></p><h3>The Problem</h3><p>When data dependencies are separated from UI components, developers often delete a component (e.g., CompanyCard.tsx) but forget to remove its specific data requirements (e.g., logoUrl) from the global query file. Over time, queries become bloated monsters, over-fetching data that nobody uses.</p><figure><img alt="comparison between Centralized Queries and Co-located Fragments" src="https://cdn-images-1.medium.com/max/1024/1*d_v0A4Qphui2z3XbDXeg-w.png" /></figure><h3>The Strategy: Fragment Co-location</h3><p>A robust architecture moves to “Component-Driven” data requirements. If a component needs data, <strong>it</strong> defines the requirement using a GraphQL <strong>Fragment</strong>, not the parent page.</p><ul><li><strong>The Child Component</strong> declares <em>what</em> it needs.</li><li><strong>The Parent Component</strong> composes those needs into a query.</li></ul><pre>// src/components/companies/CompanyCard.tsx<br>// The component owns its data requirement fragment<br>import { gql } from &#39;@apollo/client&#39;;<br>export const COMPANY_CARD_FRAGMENT = gql`<br> fragment CompanyCardData on Company {<br> id<br> companyName<br> logoUrl<br> }<br>`;</pre><p>This ensures that <strong>if you delete the component, you delete its data requirement.</strong> The graph stays lean and maintainable.</p><h3>3. Bringing the Playground to the Editor</h3><p>Context switching is the enemy of flow. A common source of friction is forcing developers to leave their IDE, open a browser URL to an external GraphQL Playground, test a query, and then copy-paste it back into the code. This manual loop is where typos are born.</p><h3>The Fix: In-Editor Introspection</h3><p>The solution is to bring the playground’s power into the editor using a .graphqlrc configuration file and the <strong>VS Code GraphQL extension</strong>.</p><p>By linking the editor directly to the backend schema, you gain powerful features without opening a browser:</p><ul><li><strong>Autocomplete:</strong> Type user. And see a list of available fields.</li><li><strong>Validation:</strong> Querying a field that doesn’t exist results in an immediate red squiggly line.</li><li><strong>Documentation:</strong> Hover over a field to see comments and deprecation warnings from backend engineers.</li></ul><figure><img alt="VS Code GraphQL extension." src="https://cdn-images-1.medium.com/max/1024/1*9w0_ZGO4sk8D6288WN0Mrg.png" /></figure><h3>Summary</h3><p>By treating an API contract as a strict artifact rather than a loose agreement, engineering teams can transform the “Toolsmith” role from a janitor cleaning up type errors to an architect ensuring they never happen.</p><ul><li><strong>Don’t type it.</strong> Generate it.</li><li><strong>Don’t separate it.</strong> Co-locate it.</li><li><strong>Don’t guess it.</strong> Introspect it.</li></ul><h3>The Toolsmith’s Toolkit (Resources)</h3><p>For the engineering team, here are the libraries we are standardizing on:</p><p><strong>Tool: GraphQL Code Generator</strong></p><p><strong>Purpose: </strong>Generates TypeScript types from the Schema</p><p><strong>Documentation: </strong><a href="https://the-guild.dev/graphql/codegen">The Guild Docs</a></p><p><strong>VS Code GraphQL: </strong>Adds “Intellisense” to the editor</p><p><a href="https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql">Marketplace Link</a></p><p><strong>Apollo Fragments: </strong>For splitting queries by component</p><p><a href="https://www.apollographql.com/docs/react/data/fragments/">Apollo Fragments Guide</a></p><p><strong>Ready to Scale?</strong> At this stage, we have a <strong>secure connection</strong> (The Architect) and <strong>bulletproof type safety</strong> (The Toolsmith). The application is stable and developer-friendly.</p><p>But for the user, “stable” isn’t enough. They demand “instant.” A type-safe loading spinner is still just a loading spinner. In the final section, we shift our focus from the <em>developer experience</em> to the <em>user experience</em>.</p><h3>Third: The Optimizer: Performance, Caching, and Production Hardening</h3><p>This final phase of the front-end engineering pipeline focuses on maximizing speed, responsiveness, and stability to deliver a world-class user experience. With a secure, scalable architecture established (Part 1) and a streamlined developer experience in place (Part 2), the core challenge shifts to optimizing the client-server interaction within our Next.js application, especially concerning our external NestJS GraphQL API.</p><h3>1. Eliminating the Network Waterfall with Next.js Features</h3><p>The greatest bottleneck for a data-intensive front-end is often the “network waterfall,” where component rendering must wait sequentially for data dependencies to resolve. Because our Next.js application is responsible for fetching data from an external GraphQL server, we must strategically leverage modern React and Next.js features to overcome this latency.</p><h4>Strategy: Server Components for Initial Fetch</h4><p>By utilizing the Next.js <strong>App Router</strong> pattern, we treat the initial, critical data load as a server-side task. Rather than mounting a client-side GraphQL provider at the root and waiting for the client to hydrate before initiating a network request (the traditional client-side waterfall), we can:</p><ol><li><strong>Initiate Fetch on the Server:</strong> For data-heavy pages (like company profiles or job listings), we use <strong>React Server Components (RSC)</strong> to execute GraphQL queries <em>before</em> the component is streamed to the client. This shifts the network time from the user’s slow client connection to our fast Next.js server.</li><li><strong>Performance Impact:</strong> This fundamentally eliminates the wait time for client-side JavaScript to boot up. The resulting HTML is delivered with the data already present, dramatically improving the <strong>Time-to-First-Contentful-Paint (TFFCP)</strong> and ensuring the user sees meaningful content immediately.</li></ol><figure><img alt="Image 1: Performance Comparison: Client-Side vs. Server Components" src="https://cdn-images-1.medium.com/max/1024/1*Uql6HuB1f1DREVj2_Mrkpw.jpeg" /></figure><p>We reserve client components and client-side hooks for interactive elements, mutations, and local state management.</p><h3>2. Deepening Responsiveness with Normalized GraphQL Caching</h3><p>For all subsequent client-side interactions — including navigation, form submissions, and component updates — optimizing network trips is crucial. Standard browser caching is ineffective for GraphQL’s primary use of POST requests, making the client’s internal cache critical for perceived performance.</p><h4>Utilizing the Client’s Normalized Cache</h4><p>Our application configures the GraphQL client (as seen in src/lib/apollo-client.ts) to use a <strong>normalized cache</strong>. This cache is an in-memory graph database that stores every retrieved entity (e.g., a Company, Job, or Review) based on a combination of its unique ID and __typename fields.</p><ul><li><strong>The Optimization:</strong> When a component requests data that already exists in the cache, the client fulfills the request <strong>instantly</strong> without incurring a network round-trip. This instantaneous data reuse eliminates redundant fetching and makes client-side application transitions feel immediate and responsive, which is essential for a rich data experience like Hirease.</li></ul><figure><img alt="Image 2: Normalized GraphQL Cache Structure" src="https://cdn-images-1.medium.com/max/1024/1*IA-3bKAFgJp-X0EOXs3jeg.jpeg" /></figure><p>Furthermore, following a successful mutation (e.g., liking a post), we can write directly to the normalized cache to update related components instantly, ensuring all parts of the UI are consistent without waiting for a full refetch.</p><h3>3. Production Hardening: Network Insulation and Resilience</h3><p>Delivering a fast experience is only half the battle; the front-end must also be stable and resilient to external failures.</p><h4>Next.js API Proxy for Backend Insulation</h4><p>All communication with the external NestJS GraphQL backend is channeled through a dedicated Next.js API Route, such as src/app/api/graphql-proxy/route.ts. This proxy layer serves two key purposes:</p><ul><li><strong>Security and Authentication:</strong> It provides a secure boundary for managing and refreshing authentication tokens (cookies, headers) without exposing sensitive logic directly to the client-side code.</li><li><strong>Edge Caching &amp; Control:</strong> It acts as a singular point to enable performance enhancements like <strong>Edge Caching</strong> for highly repeatable static GraphQL queries, reducing latency and direct load on the external backend.</li></ul><figure><img alt="Image 3: Next.js API Proxy Architecture for External GraphQL" src="https://cdn-images-1.medium.com/max/1024/1*4DG4kkulm4p5POreqiHNvw.jpeg" /></figure><h4>Implementing Graceful Failure</h4><p>To ensure stability, we enforce layered error handling:</p><ol><li><strong>Network/Data Errors:</strong> Failures arising from the GraphQL request (4xx, 5xx) are caught locally within the component’s data-fetching logic. This allows us to display specific, contextual error messages (e.g., “Could not load this section, try again”) without affecting the rest of the application.</li><li><strong>Rendering Errors:</strong> For unexpected runtime exceptions in the React rendering tree, we utilize a global <strong>React Error Boundary</strong> (src/app/error.tsx). This catches component crashes and renders a safe fallback UI, preventing a blank “white screen of death” and ensuring that unaffected parts of the application (like the navigation) remain functional, thereby providing a resilient and graceful user experience.</li><li>This is the full, detailed set of instructions for a design tool or image generation AI to create the three required diagrams for the article. These descriptions correct previous errors and ensure all technical terms (like <strong>GraphQL</strong>) are correct.</li></ol><h3>Conclusion: The “Contract-First” Mindset</h3><p>Moving to “Headless” Next.js with GraphQL is not just a technology swap; it is a shift in responsibility.</p><ul><li><strong>The Architect</strong> taught us that the frontend is now responsible for its own security perimeter via Proxies.</li><li><strong>The Toolsmith</strong> taught us that we can no longer trust manual types; we must generate our guarantees.</li><li><strong>The Optimizer</strong> taught us that performance is a deliberate architectural choice, leveraging Server Components to kill waterfalls before they start.</li></ul><p>By treating the API not just as a data source, but as a <strong>strict contract</strong>, we transformed the Hirease frontend from a fragile consumer into a robust, high-performance application.</p><p><em>Ready to modernize your stack? Stop guessing your API, and start generating your trust.</em></p><p><strong>The Other Half of the Equation: The Backend Architecture</strong></p><p>We’ve explored how the frontend masterfully consumes the GraphQL contract. But a robust contract needs a powerful provider.</p><p>To get the full picture of the Hirease architecture, dive into the companion article on the backend engineering side. Discover how we designed the scalable NestJS API that powers this experience, moving from schema definitions to complex, flexible query architectures.</p><p>👉 Read: <a href="https://medium.com/@batta25.fe/designing-a-scalable-graphql-api-in-nestjs-from-schema-contracts-to-flexible-query-architecture-6650eb5d4236">Designing a Scalable GraphQL API in NestJS: From Schema Contracts to Flexible Query Architecture</a></p><p>Special thanks to the amazing team whose hard work and dedication made this article <a href="https://medium.com/u/1bc284a126d">ZiadNasser</a> - <a href="https://medium.com/u/9bfbbfb6d49a">mohammed farrag</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c092633a35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code Simplified.]]></title>
            <link>https://medium.com/@ealmonzer667/clean-code-simplified-6e0a56f35e44?source=rss-157b1ac92a88------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e0a56f35e44</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[AlMonther Abdulhafeez]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 22:23:58 GMT</pubDate>
            <atom:updated>2024-09-26T08:59:17.221Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This is a Simplified Guide to Clean Code: With a Focus on JavaScript &amp; TypeScript</strong></p><p><strong>Clean Code</strong> is a coding philosophy that aims to make your code easy to read, understand, and maintain. Writing clean code is essential for developing software that others (and even you) can work with efficiently in the future. Clean code helps prevent bugs, saves time, and fosters collaboration among developers.</p><p><strong>Principles of Clean Code (General)</strong></p><ol><li><strong>Readability</strong><br>Your code should be easily understandable by others, even those unfamiliar with the project. This means using meaningful names, and clear structures, and avoiding overly complex logic.</li></ol><p><strong>2. Simplicity</strong><br>Complex code can take more work to maintain and debug. Aim for simple solutions, even if they take a little more time to plan.</p><p><strong>3. DRY (Don’t Repeat Yourself)</strong><br>Repetitive code increases the chance of bugs and makes maintenance harder. Instead, write reusable functions or components to minimize duplication.</p><p><strong>4. KISS (Keep It Simple, Stupid)</strong><br>Simplicity should be a priority. Avoid adding unnecessary features or overengineering solutions.</p><p><strong>5. Consistency</strong><br>Stick to consistent naming, formatting, and structure. This makes it easier to navigate through the codebase.</p><h3>Community-Accepted Coding Standards and Style Guide</h3><p>When writing JavaScript and TypeScript, following widely accepted coding standards makes your code more readable and ensures consistency across teams. One highly-regarded reference is the <strong>Google TypeScript Style Guide</strong>:</p><ul><li><strong>Google TypeScript Style Guide</strong><br><a href="https://google.github.io/styleguide/tsguide.html">Google’s TypeScript Guide</a> offers comprehensive best practices for writing scalable and maintainable TypeScript code. It covers a wide range of topics, including naming conventions, code formatting, and error handling. Adopting a recognized style guide helps teams follow consistent patterns and maintain a uniform codebase.</li></ul><h4>Specific Examples for JavaScript</h4><ol><li><strong>Use camelCase for Variable and Function Names</strong><br>JavaScript traditionally uses camelCase for naming variables and functions. This means starting with a lowercase letter and capitalizing each subsequent word.</li></ol><pre>let userName = &quot;John&quot;;<br>function fetchData() { /*...*/ }</pre><p><strong>2. Use snake_case for Object Properties</strong><br>For properties within objects, snake_case is a common practice, making it easier to differentiate between variables and object keys.</p><pre>const user = {<br>  first_name: &quot;John&quot;,<br>  last_name: &quot;Doe&quot;,<br>  email_address: &quot;john.doe@example.com&quot;<br>};</pre><p><strong>3. Indent Code with Two Spaces</strong><br>Consistent indentation makes your code more readable. In JavaScript, it’s common to use two spaces for indentation.</p><pre>function displayUser(user) {<br>  if (user.isActive) {<br>    console.log(user.name);<br>  }<br>}</pre><p><strong>4. Put Opening Braces on the Same Line as the Function or Class Declaration</strong><br>Keep your opening braces on the same line as the statement. This improves readability and aligns with common practices in JavaScript.</p><pre>function addNumbers(a, b) {<br>  return a + b;<br>}<br><br>class User {<br>  constructor(name) {<br>    this.name = name;<br>  }<br>}</pre><h3><strong>JavaScript and TypeScript-Specific Clean Code Practices</strong></h3><p>While the general principles apply to all languages, JavaScript (JS) and TypeScript (TS) have their own nuances that require specific attention when writing clean code.</p><h4>1. Use Descriptive Variable and Function Names</h4><ul><li>Avoid single-letter or vague variable names like x or data. Instead, use descriptive names like userDetails, isLoggedIn, or fetchUserData.</li><li>Functions should describe what they do: getUserById() Is clearer than getData().</li><li><strong>Example (Bad):</strong></li></ul><pre>let d = new Date();<br>let x = user.map(u =&gt; u.name);</pre><p><strong>Example (Good):</strong></p><pre>let currentDate = new Date();<br>let userNames = users.map(user =&gt; user.name);</pre><h4>2. Avoid Magic Numbers</h4><p>Hard-coded values (magic numbers) make code difficult to understand. Replace them with named constants.</p><p><strong>Example (Bad):</strong></p><pre>const total = price * 1.15; // What is 1.15?</pre><p><strong>Example (Good):</strong></p><pre>const TAX_RATE = 1.15;<br>const total = price * TAX_RATE;</pre><h4>3. Comment with Purpose</h4><p>Comments should explain <strong>why</strong> something is done, not <strong>what</strong>. The code should already be readable enough to know what it does.</p><p><strong>Example (Bad):</strong></p><pre>// Increment index by 1<br>index = index + 1;</pre><p><strong>Example (Good):</strong></p><pre>// Adjust index to point to the next element in the list<br>index = index + 1;</pre><h4>4. Use ES6+ Syntax (JavaScript Best Practices)</h4><p>Take advantage of modern JavaScript features like const, let, and arrow functions. These improve readability and reduce bugs.</p><p><strong>Use </strong><strong>const and </strong><strong>let</strong></p><ul><li>Always declare variables with const when their value won&#39;t change, and use let when it will.</li></ul><p><strong>Example (Good):</strong></p><pre>const MAX_RETRIES = 5;<br>let retryCount = 0;</pre><p><strong>Use Arrow Functions</strong></p><ul><li>Arrow functions provide a cleaner syntax, especially for callbacks and one-liners.</li></ul><p><strong>Example:</strong></p><pre>users.forEach(user =&gt; console.log(user.name));</pre><h4>5. TypeScript: Use Types Effectively</h4><p>TypeScript allows for type safety, which helps avoid errors and improve readability. Always annotate types for clarity.</p><p><strong>Example (Bad):</strong></p><pre>function add(a, b) {<br>  return a + b;<br>}</pre><p><strong>Example (Good):</strong></p><pre>function add(a: number, b: number): number {<br>  return a + b;<br>}</pre><ul><li><strong>Avoid </strong><strong>any</strong>: Using any type defeats the purpose of TypeScript’s type checking. Instead, be specific with types.</li></ul><p><strong>Example (Bad):</strong></p><pre>function fetchData(url: any): any {<br>  // logic<br>}</pre><p><strong>Example (Good):</strong></p><pre>function fetchData(url: string): Promise&lt;Response&gt; {<br>  // logic<br>}</pre><h4>6. Keep Functions Small</h4><p>Functions should do one thing and do it well. If a function does too much, break it into smaller, reusable functions.</p><p><strong>Example (Bad):</strong></p><pre>function processUserData(user) {<br>  // Save user data<br>  // Send email to user<br>  // Log user activity<br>}</pre><p><strong>Example (Good):</strong></p><pre>function saveUserData(user) { /*...*/ }<br>function sendWelcomeEmail(user) { /*...*/ }<br>function logUserActivity(user) { /*...*/ }</pre><h4>7. Handle Errors Gracefully</h4><p>In both JS and TS, error handling is crucial. Use try-catch blocks for error-prone code and provide informative messages.</p><p><strong>Example:</strong></p><pre>try {<br>  const data = await fetchData(url);<br>} catch (error) {<br>  console.error(&#39;Failed to fetch data:&#39;, error);<br>}</pre><h4>8. Follow Consistent Code Formatting</h4><ul><li>Use tools like <strong>Prettier</strong> or <strong>ESLint</strong> to enforce consistent style and avoid bikeshedding (unnecessary debates over trivial issues).</li><li>Set up rules for indentation, semicolons, and spacing.</li></ul><p><strong>Example:</strong></p><pre> const user = {<br>  name: &#39;John Doe&#39;,<br>  age: 30<br>};</pre><h3>Conclusion</h3><p>Writing clean code in JavaScript and TypeScript requires a balance between clarity, simplicity, and structure. By following these principles and leveraging modern JS/TS features, you can create code that is easy to maintain, understand, and scale.</p><p>Remember: <strong>Clean code is not just about writing code that works — it’s about writing code that others (and your future self) can easily read, understand, and build upon.</strong></p><h3>References</h3><ol><li><a href="https://www.freecodecamp.org/news/how-to-write-clean-code/">How to Write Clean Code (FreeCodeCamp)</a></li><li><a href="https://blog.codacy.com/coding-standards/">Coding Standards (Codacy Blog)</a></li><li><a href="https://blog.codacy.com/what-is-clean-code/">What is Clean Code (Codacy Blog)</a></li><li><a href="https://google.github.io/styleguide/tsguide.html">Google TypeScript Style Guide</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e0a56f35e44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Leaf & Bloom: Our Journey from Idea to 10/10]]></title>
            <link>https://medium.com/@ealmonzer667/building-leaf-bloom-our-journey-from-idea-to-10-10-63451aa8e775?source=rss-157b1ac92a88------2</link>
            <guid isPermaLink="false">https://medium.com/p/63451aa8e775</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[plants]]></category>
            <category><![CDATA[workflow]]></category>
            <dc:creator><![CDATA[AlMonther Abdulhafeez]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 14:37:34 GMT</pubDate>
            <atom:updated>2024-09-24T14:37:34.906Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>By AlMonther Abdulhafeez &amp; </strong><a href="https://medium.com/@gehadgamal84"><strong>Gehad Gamal</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvxxaBnIqtyy2eX3wkkmSg.jpeg" /></figure><p>As two passionate plant lovers, we knew we wanted to create something that went beyond the typical e-commerce platform. With a shared love for houseplants and plant care, we envisioned a space where people could not only buy plants but also share their experiences, get expert tips, and connect with other plant enthusiasts. That’s how <strong>Leaf &amp; Bloom</strong> was born — a community-driven plant platform designed to bring nature closer to people’s homes.</p><h3>The Beginning: From Idea to ReactJS</h3><p>When we first started this project, we only had one concrete decision: we would use <strong>ReactJS</strong>. It was our first major project using React, so the excitement was paired with a steep learning curve. The initial days were all about getting familiar with component-based development. While we were still figuring out the best way to structure our app, we began adding features gradually, even some that weren’t part of our initial plan.</p><h3>The Design Evolution: Iterations, Challenges, and Discoveries</h3><p>One of the biggest parts of the journey was evolving the design. We started with a simple layout, but it quickly grew as we stumbled upon powerful tools like <strong>TailwindCSS</strong>. The flexibility of Tailwind allowed us to create a sleek, modern UI that could be easily adapted as we added more features. Its responsive design capabilities were crucial in ensuring the platform looked great on all devices.</p><p>We also explored other design tools like <strong>Framer Motion</strong> for smooth animations, and even incorporated <strong>3D models</strong> using <strong>React-Three-Fiber</strong>. The background wasn’t just an afterthought — we unified it with a random leaf animation that brought a natural, dynamic feel to the entire platform.</p><h3>Learning and Adapting: The Tech Stack</h3><p>With the UI in place, we dove into enhancing the functionality. <strong>Firebase Firestore</strong> became our go-to for storing posts, comments, and likes, while <strong>Firebase Authentication</strong> made user login secure and seamless. We made sure the community section was easy to use, allowing users to create profiles and engage in plant-related discussions.</p><p>We had some fun with the tech stack:</p><ul><li><strong>Redux</strong> helped us manage the state for our shopping cart and product listings.</li><li><strong>EmailJS</strong> enabled direct communication, especially for email notifications.</li><li>We used <strong>Lucide React</strong> for beautifully customizable icons, and even experimented with components from libraries like <strong>shadcn</strong> and <strong>aceternity</strong>, incorporating a few elements that fit perfectly into our design.</li></ul><h3>Structure and Workflow: Building the Right Way</h3><p>We were careful to maintain a clean and efficient project structure. Separating concerns like search functionality, filtering, and card components was key to keeping the app scalable. We also stored items in a JSON file to simplify data management during development.</p><p>For navigation, we implemented <strong>private routes</strong> for user-specific pages. It wasn’t just about the code — it was about making the experience seamless for the user.</p><h3>Teamwork and Workflow: Commit, Discuss, Improve</h3><p>Even though it was just the two of us, we embraced a professional workflow. Our process included:</p><ul><li>Creating <strong>issues</strong> and branching off of the <strong>dev branch</strong>.</li><li>Following commit conventions like feat:, fix:, and style: to keep track of progress.</li><li>Regular <strong>pull requests</strong> to the dev branch before merging into production.</li></ul><p>Using <strong>Vercel</strong> for deployment made continuous integration easy, and we even secured our API keys in .env files for a smooth production launch.</p><h3>The Moment of Truth: Presentation and Feedback</h3><p>Yesterday, we presented <strong>Leaf &amp; Bloom</strong> as our graduation project. The feedback was beyond anything we had imagined — our mentor gave us a perfect score of <strong>10/10</strong> and called it the best project they had reviewed in a while! The comment that stuck with us? “I think I’ll go buy a plant right now.” 😊</p><p>That feedback meant the world to us, and it reaffirmed that all our hard work had paid off.</p><h3>What’s Next for Leaf &amp; Bloom?</h3><p>This project isn’t done. We plan to keep working on it because we love both the idea and the teamwork. We have so many plans — building out our own API, improving search functionality with more filters, adding user profiles, and maybe even incorporating plant care reminders!</p><p>We’ve already gotten incredible feedback from friends and fellow developers, and we’re excited to continue evolving <strong>Leaf &amp; Bloom</strong>.</p><h3>Conclusion: A Labor of Passion</h3><p>This journey has been more than just building a project — it’s been a labor of passion. We’ve grown not only as developers but also as teammates and plant enthusiasts. <strong>Leaf &amp; Bloom</strong> is a passion project that will keep growing, and we’re excited to see where it takes us next.</p><p>Thank you for reading about our journey. We hope our story inspires others to create, collaborate, and grow — whether it’s with code or plants!</p><p>If you have any questions or would like us to dive deeper into any part of this journey — whether it’s React, TailwindCSS, Workflow, Firebase, or something else — feel free to reach out! We’d love to share more details or provide resources to help you along your own development path.</p><h3><strong>Contact</strong></h3><p>For any inquiries, please reach out to us at:</p><p><strong>Gehad</strong></p><ul><li><a href="https://github.com/Gehadazzam">Github</a></li><li><a href="/service/mailto:gehadgamalazzam@gmail.com">gehadgamalazzam@gmail.com</a></li><li><a href="https://x.com/Gehad1984">Twitter Account</a></li><li><a href="https://www.frontendmentor.io/profile/Gehadazzam">Frontend Mentor</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvxxaBnIqtyy2eX3wkkmSg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvxxaBnIqtyy2eX3wkkmSg.jpeg" /></figure><p><strong>AlMonther</strong></p><p>- <a href="https://github.com/AlMonther9">Github</a><br>- <a href="/service/mailto:ealmonzer667@gmail.com">ealmonzer667@gmail.com</a><br>- <a href="https://x.com/AlMonther_N">Twitter Account</a><br>- <a href="https://www.frontendmentor.io/profile/AlMonther9">Frontend Mentor</a></p><p>Visit our live site: <a href="https://leaf-bloom.vercel.app/">Leaf &amp; Bloom</a></p><p><a href="https://github.com/AlMonther9/leaf-bloom">Github repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63451aa8e775" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>