<?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 Paria Heidari on Medium]]></title>
        <description><![CDATA[Stories by Paria Heidari on Medium]]></description>
        <link>https://medium.com/@paria-heidari?source=rss-f1640215b83f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ILBEBPDAeayJY-SJ3o84Zw.jpeg</url>
            <title>Stories by Paria Heidari on Medium</title>
            <link>https://medium.com/@paria-heidari?source=rss-f1640215b83f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:34:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paria-heidari/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[From Local Development to Production: Understanding Docker, Azure, and the Decisions In Between]]></title>
            <link>https://paria-heidari.medium.com/from-local-development-to-production-understanding-docker-azure-and-the-decisions-in-between-c46b0189a7c2?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46b0189a7c2</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 13:23:33 GMT</pubDate>
            <atom:updated>2026-10-14T14:18:31.699Z</atom:updated>
            <content:encoded><![CDATA[<p>The real engineering challenge is understanding why a tool is needed, which problem it solves, and what trade-offs it introduces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cduAbDV-YSK0TcLB3qv8Hg.png" /><figcaption>Local development → production on Azure</figcaption></figure><h3>Introduction</h3><p>Building an application is only part of software engineering. A production application also needs a runtime environment, networking, identity, access control, configuration, secrets management, deployment automation, monitoring, and a plan for when things fail.</p><p>Docker and Microsoft Azure solve different parts of this problem. Docker packages and runs applications in containers. Azure provides the infrastructure and managed services to run, secure, scale, and operate them. Understanding how they fit together is worth more than memorizing commands.</p><p>This article walks through the decisions involved in taking an application from a laptop to production, including a few lessons I learned.</p><h3>Understand the Architecture</h3><p><strong>Start with the application, not the tools</strong></p><p>Before choosing Docker, a database, or a cloud service, understand what the application must do and how it will be run.</p><ul><li><strong>Functional:</strong> what should it do? Accept input, store data, authenticate users, call external services.</li><li><strong>Non-functional:</strong> how well must it work? Performance, security, availability, scalability, accessibility, maintainability.</li><li><strong>Operational:</strong> how will the team run it? Local development, testing, deployment, logging, configuration, secrets, recovery.</li></ul><p>A typical web application has a frontend, a backend API, a database, external services (an identity provider, payment APIs), and the infrastructure that connects them. Each of these has different needs for scaling, security, and cost.</p><p>The first principle is simple: <strong>start with the smallest architecture that meets your functional, security, performance, and operational requirements.</strong> You can add complexity later. Removing it is much harder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*MF8_HGHEAZs3jscmBmvm1Q.png" /><figcaption>The main layers</figcaption></figure><h3>What Problem Does Docker Solve?</h3><p>Applications depend on more than source code: a runtime, libraries, OS packages, environment variables, and configuration. The classic failure is “it works on my machine” but breaks in CI or production because something underneath is different.</p><p>Docker reduces this by packaging the application and its runtime dependencies into a reproducible <strong>image</strong>:</p><p>Source Code → Dockerfile → Image → Container</p><p><strong>The four core Docker concepts</strong></p><ul><li><strong>Dockerfile:</strong> the build instructions: base image, dependencies, build steps, start command.</li><li><strong>Image:</strong> the built, versioned artifact. Build it once, test it, and deploy the same image everywhere.</li><li><strong>Container:</strong> a running instance of an image, with its own isolated processes, filesystem, and network.</li><li><strong>Registry:</strong> where images are stored and distributed (Docker Hub, Azure Container Registry).</li></ul><p>A minimal Dockerfile for a Node.js app:</p><pre>FROM node:20.11.1<br>WORKDIR /app <br>COPY package*.json ./ <br>RUN npm ci <br>COPY ..<br>RUN npm run build <br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><h4>Container networking: the most common source of confusion</h4><p>Consider a frontend, an API, and a database running in containers:</p><p>Browser → localhost:8080 → Frontend Container → http://backend:8000 → Backend Container → database:5432 → Database Container</p><p>There are two different networking contexts.<br><strong>From your machine,</strong> you reach a container through a published port, such as localhost:8080.</p><p><strong>From another container,</strong> you use the service name and the container’s port, such as database:5432.</p><p>Inside a container, localhost means that container, not your laptop and not another container. Many &quot;connection refused&quot; errors come down to this.</p><p>Also, publishing a port only maps traffic. The application must actually listen on that port inside the container, and on 0.0.0.0, not only on 127.0.0.1.</p><h4>Docker Compose for local development, and its limits</h4><p>Docker Compose defines a multi-service environment in one file, so a new developer can start the frontend, API, and database with a single command. That alone makes onboarding much faster.</p><p>But a Compose file is a development tool, not a production strategy. Two things to know:</p><ul><li>depends_on controls <strong>start order, not readiness.</strong> Your API can start before the database accepts connections. Use health checks, and build retry logic into the application.</li><li>Production needs decisions Compose doesn’t make: high availability, managed storage, backups, network isolation, secrets, scaling.</li></ul><h3>Moving to Azure: choosing where to run</h3><p>Azure organizes everything in a hierarchy, and permissions and billing follow it:</p><p>Microsoft Entra Tenant → Managment Group (optional) → Subscriptions → Resource Groups → Resources</p><ul><li><strong>Tenant:</strong> the organization’s identity boundary.</li><li><strong>Subscription:</strong> the boundary for billing, quotas, and access. Separate subscriptions per environment are a common pattern.</li><li><strong>Resource group:</strong> related resources that share a lifecycle.</li><li><strong>Resource:</strong> a single service, such as a web app, a database, or a Key Vault.</li></ul><p>Choosing compute is a trade-off between control and operational effort:</p><ul><li><strong>App Service:</strong> a simple web app with minimal operations, but less control over the runtime.</li><li><strong>Container Apps:</strong> containers without running Kubernetes yourself, with fewer configuration options than AKS.</li><li><strong>AKS (Azure Kubernetes Service):</strong> full orchestration for many services, but you own cluster operations.</li><li><strong>Virtual Machines:</strong> full control of the operating system, but you own patching, scaling, and security.</li></ul><p>For data, prefer managed services (Azure Database for PostgreSQL, Azure SQL). Backups, patching, and high availability are hard to do well yourself.</p><h4>Identity: Entra ID, RBAC, PIM, and Managed Identity</h4><p>Security is not only about passwords. It’s about <strong>who or what can do what, and for how long.</strong></p><p><strong>Microsoft Entra ID: authentication and identity<br></strong>It manages identities for users, groups, applications, and workloads. A few identifiers commonly appear in application configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*JgBulDyleUX9s5uiQLjz6A.png" /></figure><p><strong>Azure RBAC</strong> determines what an identity can do to Azure resources and at which scope.<br><strong>PIM (Privileged Identity Management)</strong> makes privileged access eligible rather than permanent. A developer activates a role when needed, often with MFA, a justification, or approval, and the access expires automatically.</p><p>Developer → Eligible for privileged → Requests activation → MFA / Justification / Approval → Temporary privileged → Access expires</p><p><strong>Managed Identity</strong> gives a running application its own identity, so it can reach other Azure services without anyone handling credentials.</p><p>A healthy pattern: <strong>humans use PIM for temporary access; applications use managed identities for permanent access.</strong></p><p>An <strong>app registration</strong> is the definition of an application, created once in the tenant that owns it. An <strong>enterprise application</strong> is that app’s instance in each tenant that uses it, and that’s usually where you control who may sign in. In multi-tenant setups, check which tenant your users actually authenticate through.</p><h4>Configuration and Secrets</h4><p>Not all configuration is secret:</p><ul><li><strong>Ordinary configuration:</strong> environment name, public API endpoints, log level.</li><li><strong>Secrets:</strong> database credentials, API keys, encryption keys, certificates, signing secrets.</li></ul><p>Secrets should never be committed to source control or baked into images. <strong>Azure Key Vault</strong> stores them, controlled by identity and, where needed, network rules.</p><p>But storing a secret is only half the job. <strong>Secrets have a lifecycle:</strong> they expire, get rotated, and get revoked. Know who owns each one, when it expires, and how the application picks up a new value. Where possible, replace secrets entirely with managed identities or certificates.</p><h3>CI/CD: build once, promote everywhere</h3><p>A pipeline makes releases repeatable:</p><p>Code Commit → Lint / Type Check → Automated Tests → Build Application → Build Container Image → Scan / Validate → Push to Registry → Deploy → Smoke Tests / Health Checks → Monitor</p><p>The most important principle: build the image once, tag it with the commit SHA, and promote that same image through dev, test, and production. Only configuration should change between environments. If you rebuild for each environment, you’re not deploying what you tested.</p><h4>Monitoring, Reliability, and Cost</h4><p>A successful deployment doesn’t mean a healthy system. Azure Monitor and Application Insights collect the signals you need:</p><ul><li><strong>Logs:</strong> what happened?</li><li><strong>Metrics:</strong> how is the system performing?</li><li><strong>Traces:</strong> where is time spent across service calls?</li><li><strong>Alerts:</strong> what needs attention now?</li></ul><p>Think through failures before they happen:</p><ul><li>What if the database is unavailable?</li><li>What if an external API is slow?</li><li>What if a deployment introduces a bug? How do you roll back?</li><li>What if traffic suddenly spikes?</li><li>What if a secret expires?</li></ul><p>And treat cost as a design input, not an afterthought. Always-on resources, oversized databases, and unused environments add up quietly.</p><h3>Conclusion</h3><p>Docker gives you a consistent, reproducible way to package and run software. Azure gives you managed infrastructure, identity, security, and observability around it. Neither is the goal in itself.</p><p>The goal is a system the team can <strong>build, deploy, secure, observe, and recover</strong>, with every tool chosen because it solves a real problem. Start small, make your decisions explicit, and let the requirements, not the hype, shape the architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46b0189a7c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Realtime NGO Tech Talent Pipeline Platform]]></title>
            <link>https://paria-heidari.medium.com/realtime-ngo-tech-talent-pipeline-platform-47c7b03a7896?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c7b03a7896</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[event-driven-systems]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 15:50:54 GMT</pubDate>
            <atom:updated>2026-08-14T10:14:55.435Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TalentAtlas</strong> is a real-time, event-driven talent pipeline platform that connects underrepresented developers in European tech — career-changers, self-taught engineers — with hiring companies through structured campaigns, active advocacy, and continuous pipeline management. Instead of passively collecting applications, TalentAtlas actively manages the entire hiring journey from candidate discovery to final placement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aT396dxiEE4F8dBNeLOMoQ.png" /></figure><p><strong>CANDIDATE</strong> — Job seeker. Passive. They don’t apply themselves, the NGO enrolls them. <br><strong>COORDINATOR</strong> — Does not find jobs. They run campaigns that match candidates to companies. They advocate, follow up, manage the pipeline. The coordinator is the intermediary. <br><strong>COMPANY</strong> — Does not post jobs in TalentAtlas. They post in their own ATS — Application Tracking System (Greenhouse, Lever, Workday). TalentAtlas just integrates with it via webhook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-zZUkQUK-YHyvbVFk_3cg.jpeg" /></figure><p>The actual flow is:</p><pre>1. Company has an open role in their own ATS (outside TalentAtlas)<br>         ↓<br>2. Coordinator creates a Campaign in TalentAtlas<br>   linked to that company + role<br>   e.g. &quot;React Developers — Career Changers Q3 2026 @ Celonis&quot;<br>         ↓<br>3. Coordinator enrolls candidates from the pool into that campaign<br>         ↓<br>4. Company logs into TalentAtlas, sees ONLY their curated candidate pool<br>   moves candidates: Interview → Offer → Hired<br>         ↓<br>5. Company&#39;s ATS fires a webhook → TalentAtlas records the placement</pre><pre>                 ┌──────────────────────────┐<br>                 │        Auth0             │<br>                 │ (Login / JWT / RBAC)     │<br>                 └──────────┬───────────────┘<br>                            │<br>                            ▼<br>┌────────────────────────────────────────────────────┐<br>│                  Next.js Frontend                 │<br>│────────────────────────────────────────────────────│<br>│ UI Layer                                           │<br>│ - Dashboards                                       │<br>│ - Campaign UI                                      │<br>│ - Candidate UI      <br>│ - Company UI                              │<br>│                                                    │<br>│ State Layer                                        │<br>│ - TanStack Query (server state)                   │<br>│ - Local state (UI only)                           │<br>│                                                    │<br>│ Realtime Layer                                    │<br>│ - WebSocket client                                │<br>│ - RxJS event streams                              │<br>│ - deduplication + buffering                       │<br>└───────────────┬────────────────────────────────────┘<br>                │<br>                ▼<br>        ┌──────────────────────┐<br>        │   API Gateway / BFF  │<br>        │----------------------│<br>        │ Auth validation      │<br>        │ RBAC enforcement     │<br>        │                      │<br>        └───────┬──────────────┘<br>                │<br>     ┌──────────┼────────────────────────────┐<br>     ▼          ▼                            ▼<br>┌────────┐  ┌──────────────┐        ┌────────────────┐<br>│ REST   │  │ WebSocket    │        │ Third-party    │<br>│ APIs   │  │ Gateway      │        │ APIs           │<br>└──┬─────┘  └──────┬───────┘        └────────────────┘<br>   │               │<br>   ▼               ▼<br>┌──────────────────────────────┐<br>│        Event Bus             │<br>│ (Kafka / Redis Streams)      │<br>└──────────────┬───────────────┘<br>               ▼<br>     ┌──────────────────────┐<br>     │ Processing Layer     │<br>     │----------------------│<br>     │ dedupe events       │<br>     │ CQRS projection     │<br>     │ analytics builder    │<br>     └─────────┬────────────┘<br>               ▼<br>     ┌──────────────────────┐<br>     │   Databases          │<br>     │----------------------│<br>     │ Postgres (write)     │<br>     │ Read DB / cache      │<br>     │ Redis (fast data)    │<br>     └──────────────────────┘</pre><p>Data Flow</p><p>User Action -&gt; API (TanStack Query — Server state catching) -&gt; BE writes DB -&gt; Event emitted -&gt; Even Bus -&gt; Websocket push -&gt; Rxjs process -&gt; dedupe + batch -&gt; Update query catch -&gt; React reRender</p><p>I’ve decided to implement it inside my current portfolio using a route group instead of standing up a separate app.</p><p><strong>Install the core dependencies</strong></p><ul><li>Auth0 — Identity, Authentication, RBAC (Role-Base access control)</li><li>TanStack Query</li><li>WebSocket client</li><li>RxJS</li></ul><h3>Configure Auth0</h3><h4>Step 1: Create the Application in Auth0</h4><p>Create a Tenant and Integrate into my application.<br>Dashboard → <strong>Applications → Create Application → Regular Web Application</strong>.</p><p><strong>Why:</strong> Regular Web App = server-side authorization code flow. The SDK exchanges the code for tokens on the Next.js server and stores them in an encrypted cookie — the browser never sees raw tokens. (An SPA type would push token handling to the browser, which doesn’t fit how Server Components work.)</p><h4>Step 2: Set the Application URIs</h4><p>In that app’s Settings: (local)</p><ul><li><strong>Allowed Callback URLs:</strong> <a href="http://localhost:3000/auth/callback">http://localhost:3000/auth/callback</a></li><li><strong>Allowed Logout URLs:</strong> <a href="http://localhost:3000/talent-atlas">http://localhost:3000/talent-atlas</a></li><li><strong>Allowed Web Origins:</strong> <a href="http://localhost:3000/">http://localhost:3000</a></li></ul><p><strong>Why:</strong> Auth0 only redirects back to URLs on these allow-lists.</p><h4>Step 3: Set environment variables</h4><p>From <strong>Settings</strong>, copy Domain, Client ID, Client Secret into .env.local:</p><pre>AUTH0_DOMAIN=dev-xxxx.us.auth0.com<br>AUTH0_CLIENT_ID=...<br>AUTH0_CLIENT_SECRET=...<br>AUTH0_SECRET=&lt;openssl rand -hex 32&gt;<br>APP_BASE_URL=http://localhost:3000</pre><p><strong>Why: </strong>AUTH0_SECRET encrypts/signs the session cookie — without it the SDK can’t create or read sessions at all. The other four identify which Auth0 app/tenant you’re talking to.</p><h4>Step 4: Create the client instance</h4><p>src/lib/auth0/auth0.ts</p><pre>import { Auth0Client } from &quot;@auth0/nextjs-auth0/server&quot;;<br>export const auth0 = new Auth0Client();</pre><p><strong>Why:</strong> Auth0Client auto-reads the five env vars above. This single instance is what every server file imports to get sessions or build login/logout URLs.</p><h4>Step 5: Mount the auth routes</h4><p>src/proxy.ts— calling auth0.middleware(request).</p><p><strong>Why:</strong> this one call wires up /auth/login, /auth/logout, /auth/callback, /auth/profile, /auth/access-token automatically. Skip this and every auth link 404s.<br>(Next.js 16 renamed the middleware.ts convention to proxy.ts).</p><h3>Session</h3><h4>Step 6: What session means here</h4><p>After login, the SDK writes an encrypted cookie containing the ID/access/refresh tokens. There’s no server-side session store — the cookie is the session.</p><p><strong>Why:</strong> Server Components are stateless per request. The cookie is how the server “remembers” you between requests.</p><h4>Step 7: Read it server-side — reusable helper</h4><p>src/lib/auth0/session.ts</p><pre>import { auth0 } from &#39;@/lib/auth0/auth0&#39;;<br>import { redirect } from &#39;next/navigation&#39;;<br>import { routes as ROUTE } from &#39;@/lib/routes/routes&#39;;<br><br>export async function getSessionOrRedirect() {<br>  const session = await auth0.getSession();<br><br>  if (!session) {<br>    redirect(<br>      `/auth/login?returnTo=${process.env.APP_BASE_URL?.replace(/\/$/, &#39;&#39;)}${ROUTE.talentAtlasDashboard}`,<br>    );<br>  }<br>  return session;<br>}</pre><p><strong>Why:</strong></p><ul><li>Any future server component that needs “logged in” reuses this instead of duplicating it.</li><li>It’s the natural extension point for roles later — getSession() → requireRole(ROLES.ADMIN) becomes a one-function change instead of touching every component.</li></ul><h4>Step 8: The cacheComponents rule — in my application</h4><p>getSession() calls cookies() internally, which Next.js treats as &quot;dynamic.&quot; With cacheComponents: true, dynamic reads must happen in an async component that&#39;s: wrapped in &lt;Suspense&gt; by its parent.</p><p><strong>Why:</strong> skip this and you get the “Runtime data accessed outside Suspense” error. In Next.js, APIs like cookies() make a component dynamic because they depend on request-specific data. With caching enabled, dynamic logic must be isolated into a separate async Server Component in its own file. That component is then wrapped in &lt;Suspense&gt; by a parent, so the static parts of the page can be cached while the dynamic part streams independently.Auth0Provider</p><h4>Step 9: What it’s for</h4><ul><li>Auth0Provider (from @auth0/nextjs-auth0/client) is a React Context provider that exposes useUser() to <strong>Client Components</strong>. Server Components don&#39;t need it — they call getSession() directly.</li><li>Use it in a client component — wrap it around whatever part of the tree contains the client component that needs useUser()</li></ul><p><strong>Why:</strong> Client Components can’t call server-only code (getSession() would error if used in a &#39;use client&#39; file). useUser() is the client-safe equivalent, fetching /auth/profile under the hood. This is the client-side mirror of session.user — for interactive UI that needs auth state without a full page reload.</p><h3>Configure Auth0 — Logged in with roles</h3><h4>Step 1 — Create the roles in Auth0</h4><p>Dashboard → <strong>User Management → Roles → Create Role</strong>. Add admin, company, coordinator, candidate.</p><p><strong>Why:</strong> roles are objects in Auth0’s system — they must exist before we can assign them to a user or reference them anywhere else.</p><h4>Step 2— Assign roles</h4><p>For exampleadmin:<br>Dashboard → <strong>User Management → Users</strong> → your user → <strong>Roles</strong> tab → Assign Role → admin.</p><h4>Step 3— Add a Login Action that puts roles into the token</h4><p>Dashboard → <strong>Actions → Library → Build Custom</strong>, trigger = “Login / Post Login”:</p><pre>exports.onExecutePostLogin = async (event, api) =&gt; {<br>  const namespace = &#39;https://my-app.com&#39;;<br>  if (event.authorization) {<br>    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);<br>  }<br>};</pre><p>Deploy it, then drag it into the <strong>Login</strong> flow (Actions → Triggers → Post Login).</p><p><strong>Why:</strong> Auth0 deliberately keeps tokens minimal — assigning a role doesn’t put it in the token. This Action is the bridge that says “yes, include roles.” A custom namespace (your domain) is required by the OIDC spec for non-standard claims.</p><h4>Step 4 — Map the namespaced claim into a clean session property</h4><p>Update src/lib/auth0/auth0.ts</p><pre>import { Auth0Client } from &#39;@auth0/nextjs-auth0/server&#39;;<br>import { decodeJwt } from &#39;jose&#39;;<br><br>const ROLES_CLAIM = &#39;https://my-app.com/roles&#39;;<br><br>export const auth0 = new Auth0Client({<br>  async beforeSessionSaved(session, idToken) {<br>    if (!idToken) return session;<br><br>    const claims = decodeJwt(idToken);<br><br>    return {<br>      ...session,<br>      user: {<br>        ...session.user,<br>        roles: (claims[ROLES_CLAIM] as string[]) ?? [],<br>      },<br>    };<br>  },<br>});</pre><p><strong>Why: </strong>When we log in with google account, Auth0 asks Google “who is this person?” and gets back basic profile info — name, email, picture. That’s what goes into session.user.</p><p>The roles live in a completely separate place — Auth0’s own database, not Google’s. Auth0 doesn’t automatically include them in the session because not every app needs roles, and adding extra data to every session cookie has a cost. beforeSessionSaved is our chance to say: &quot;before you save the session, also grab the roles from the token and add them in.&quot; After that, every time someone logs in, roles are baked into their session cookie from the start.<br>beforeSessionSaved is a hook that runs once at /auth/callback, giving us the raw ID token before the session is encrypted and stored in the cookie. This is the only place in the SDK where we can bridge that gap.</p><h4>Step 5— Log out and back in, then read the claim</h4><p>Sessions are issued at login time, so existing sessions won’t have the new claim. Log out, log back in, then check:</p><p><strong>Why:</strong> Confirms the full chain (Dashboard role → Action → token → your app) actually works before you build anything on top of it.</p><h3><strong>RBAC: roles.ts + withAuth.ts</strong></h3><p>Define role constants and an API route wrapper that checks the session role before executing the handler. The wrapper (WithAuth.ts) solves route-level authorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDE97su5Vgpu5ptkhNbnNA.png" /></figure><p>If we add auth protection after building the route, we have to touch every route twice. Auth wrapper first, routes second — we write it once and use it everywhere.</p><p><strong>Middleware/proxy handles authentication, not authorization.</strong></p><p>Our middleware answers: <em>“Is this user logged in?”</em> — and redirects to login if not. But it cannot answer: <em>“Is this logged-in user allowed to do THIS specific thing?” </em>A candidate could log in successfully and then hit POST /api/talent-atlas/candidate with a valid session cookie. Middleware would let them through. Without withAuth, nothing stops them.</p><p><strong>401 vs 403 — why both:</strong></p><ul><li>401 Unauthorized = “we don’t know who you are” (no session)</li><li>403 Forbidden = “we know who you are, but you’re not allowed” (wrong role)</li></ul><pre>Middleware → Authentication (login check)<br>Route wrapper → Authorization (role check)<br>Handler → Business logic</pre><p><strong>WithAuth as a Higher-Order Function (HOF)</strong></p><p>A function that takes another function and returns a new function.</p><p><strong>Without HOF</strong>: request → handler()<br><strong>With HOF</strong>: request → withAuth → session check → role check → handler()</p><pre>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br>import { hasAnyRole, type Role } from &#39;@/lib/auth0/roles&#39;;<br>import { auth0 } from &#39;@/lib/auth0/auth0&#39;;<br><br>type BaseSession = NonNullable&lt;Awaited&lt;ReturnType&lt;typeof auth0.getSession&gt;&gt;&gt;;<br>type AppSession = BaseSession &amp; {<br>  user: BaseSession[&#39;user&#39;] &amp; { roles: Role[] };<br>};<br>type RouteHandlerContext = {<br>  params: { [key: string]: string };<br>};<br><br>type AuthHandler = (<br>  req: NextRequest,<br>  ctx: RouteHandlerContext,<br>  session: AppSession,<br>) =&gt; Promise&lt;Response&gt;;<br><br>export function withAuth(allowedRoles: Role[], authHandler: AuthHandler) {<br>  const handler = async (req: NextRequest, ctx: RouteHandlerContext) =&gt; {<br>    const session = (await auth0.getSession()) as AppSession;<br><br>    if (!session) {<br>      return NextResponse.json({ error: &#39;Unauthorized&#39; }, { status: 401 });<br>    }<br>    if (!hasAnyRole(session.user.roles, allowedRoles)) {<br>      return NextResponse.json({ error: &#39;Forbidden&#39; }, { status: 403 });<br>    }<br>    return authHandler(req, ctx, session);<br>  };<br><br>  return handler;<br>}</pre><p><strong>Why this is a good pattern:</strong></p><ul><li>Centralized security — No duplicated auth logic in every route.</li><li>Consistent behavior — All APIs behave the same.</li><li>Safer by default — We cannot forget to check roles.</li><li>Clean business logic — handlers only focus on domain logic.</li></ul><p>We use a withAuth higher-order function to enforce authorization at the route level. Middleware handles authentication, but not fine-grained authorization, so the wrapper ensures role-based access control per endpoint. The HOF pattern allows us to inject session and authorization logic into handlers without duplicating code, while maintaining type safety and separation of concerns.</p><h3>TanStack Query hook</h3><blockquote>Stop syncing server data by hand — Use global brain for server-state</blockquote><p>The setup order is:<br>- Install @tanstack/react-query <br>- Create a QueryClientinstance — this is a cache/store<br>- Wrap the app with QueryClientProvider — passing that client<br>- Use hooks (useQuery, useMutation) anywhere inside the provider</p><p><strong>Create QueryClient<br></strong>Without StaleTime: 1000 * 60, TanStack refetches every time the user switches browser tabs. For some data that changes every few minutes (not every second), that wastes network requests.</p><pre>import { QueryClient } from &#39;@tanstack/react-query&#39;;<br><br>export function createQueryClient() {<br>  return new QueryClient({<br>    defaultOptions: {<br>      queries: {<br>        // data is fresh for 60s — no refetch on tab<br>        staleTime: 1000 * 60,<br>        // prevents double-fetches<br>        refetchOnWindowFocus: false,<br>      },<br>    },<br>  });<br>}</pre><p><strong>TanStack Query setup (QueryProvider)</strong></p><blockquote>A TanStack Query setup (QueryProvider) in TanStack Query is the global wrapper that gives the React app a shared caching + server-state system. TanStack handles: caching (same data doesn’t re-fetch on navigation), deduplication (two components requesting the same data = one network request).</blockquote><pre>&#39;use client&#39;;<br><br>import { QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { ReactQueryDevtools } from &#39;@tanstack/react-query-devtools&#39;;<br>import { createQueryClient } from &#39;@/lib/query/queryClient&#39;;<br>import { ReactNode, useState } from &#39;react&#39;;<br><br>export default function QueryProvider({ children }: { children: ReactNode }) {<br>  const [queryClient] = useState(() =&gt; createQueryClient());<br><br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      {children}<br>      &lt;ReactQueryDevtools initialIsOpen={false} /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><p><strong>Why</strong> useState(()=&gt; new QueryClient()) <br>Creating a QueryClient directly inside a React component is unsafe because React Strict Mode may render components twice in development, resulting in multiple cache instances and inconsistent query state. The correct approach is to either define the QueryClient as a module-level singleton or initialize it using a useState lazy initializer, ensuring the instance remains stable across renders.</p><p><em>The </em><em>() =&gt; lazy initializer means it only runs </em><strong><em>once</em></strong><em> on first render, not on every re-render — The arrow function delays execution — React only calls it on the first render and stores the result for the lifetime of the component.</em></p><p><strong>QueryProvider wraps the whole layout and not individual pages:<br></strong>TanStack shares the cache across all components inside the same QueryClientProvider . If we put the provider in each page, each page gets its own cache — navigating between pages throws away cached data and refetches from scratch.</p><pre>import { Auth0Provider } from &#39;@auth0/nextjs-auth0&#39;;<br>import { TalentAtlasHeader } from &#39;@/components/features/talentAtlas/TalentAtlasHeader&#39;;<br>import QueryProvider from &#39;@/components/providers/QueryProvider&#39;;<br><br>export default function TalentAtlasAppLayout({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  return (<br>    &lt;div className=&quot;flex h-screen flex-col overflow-hidden&quot;&gt;<br>      &lt;TalentAtlasHeader /&gt;<br>        ....<br><br>        &lt;Auth0Provider&gt;<br>          &lt;QueryProvider&gt;<br>            &lt;main className=&quot;flex-1 overflow-y-auto bg-white p-8&quot;&gt;<br>              {children}<br>            &lt;/main&gt;<br>          &lt;/QueryProvider&gt;<br>        &lt;/Auth0Provider&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3><strong>TanStack hooks: campaigns, candidates, companies</strong></h3><p><strong>Why three separate routes instead of one: </strong>Each entity (campaigns, candidates, companies) has different role permissions. Campaigns might be public to all staff; candidates might be Coordinator-only. Separate routes = separate access control.</p><p>We organized TanStack Query keys in a clear structure to make cache updates easier. Higher-level keys can refresh all related data in a specific area, while smaller nested keys can update only specific items, such as candidates or campaigns. This is especially useful after data changes, because we only refresh the parts that are affected instead of reloading everything. This reduces unnecessary API calls and makes the UI faster and smoother.</p><pre>export const queryKeys = {<br>  all: [&#39;talent-atlas&#39;] as const,<br>  campaigns: [&#39;talent-atlas&#39;, &#39;campaigns&#39;] as const,<br>  candidates: [&#39;talent-atlas&#39;, &#39;candidates&#39;] as const,<br>  companies: [&#39;talent-atlas&#39;, &#39;companies&#39;] as const,<br>};</pre><p>The useQuery hook, We give it a unique queryKey and a queryFn (an asynchronous API call), and it manages the life cycle of that request automatically.</p><ul><li><strong>When to use:</strong> Whenever a component needs to fetch data from an API and show it on the UI.</li><li><strong>Core capability:</strong> It tracks loading, error, and success states so we don’t have to use useState and useEffect.</li></ul><p>For example: useCandidates() hook</p><pre>import { useMutation, useQuery, useQueryClient } from &#39;@tanstack/react-query&#39;;<br>import { queryKeys } from &#39;@/lib/query/queryKeys&#39;;<br>import { MOCK_CANDIDATES } from &#39;@/data/talentAtlasMockData&#39;;<br><br>type candidate = (typeof MOCK_CANDIDATES)[number];<br><br>const fetchCandidates = async () =&gt; {<br>  const res = await fetch(&#39;/api/talent-atlas/candidates&#39;);<br>  if (!res.ok) throw new Error(`Candidates fetch failed ${res.status}`);<br>  return res.json();<br>};<br><br>export function useCandidates() {<br>  return useQuery&lt;candidate[]&gt;({<br>    queryKey: queryKeys.candidates,<br>    queryFn: fetchCandidates,<br>  });<br>}<br>// Create a new candidate and invalidate the candidates query to refetch the updated list<br>const createCandidate = async (newCandidate: candidate) =&gt; {<br>  const res = await fetch(&#39;/api/talent-atlas/candidates&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify(newCandidate),<br>  });<br>  if (!res.ok) throw new Error(`Create candidate failed ${res.status}`);<br>  return res.json();<br>};<br><br>export function useCreateCandidate() {<br>  const queryClient = useQueryClient();<br>  return useMutation({<br>    mutationFn: createCandidate,<br>    onSuccess: () =&gt; {<br>      queryClient.invalidateQueries({ queryKey: queryKeys.candidates });<br>    },<br>  });<br>}</pre><p>queryClient.invalidateQueries({ queryKey }) – Marks data as old and forces useQuery hooks watching that key to reload. After a successful POST, invalidate the candidates cache — this triggers useCandidates() to refetch automatically so the new candidate appears in the list without a manual refresh.</p><h3><strong>Node.js WebSocket server</strong></h3><p>Node.js — a JavaScript runtime that lets us run JS on the server<br>Websocket — a communication protocol for real-time connection.<br><strong>HTTP:</strong><br>Request -&gt; Response-&gt; Connection closes<br>Stateless, short-lived, not real-time<br><strong>WebSocket:</strong><br>Connect-&gt; Stay open -&gt; continuous messages<br>Stateful, persistent, real-time</p><p>Next.js (UI + API)<br> ↓ HTTP<br>Node.js WebSocket server (real-time engine)<br> ↓<br>browser live updates</p><p>A WebSocket server in Node.js enables <strong>two-way, real-time communication</strong> between a client (like a browser) and your server. Unlike standard HTTP requests, the connection stays open. In practice, WebSockets run inside a Node.js process using a library like ws, allowing the server to maintain active connections and push updates to clients without HTTP polling.</p><p><strong>The UI needs to update in real-time when data changes — without user refresh or polling.</strong></p><p><strong>What problem WebSocket solves<br></strong>We used WebSockets to enable real-time synchronization of candidate, campaign, and feedback updates across multiple clients without polling or refetching, ensuring the UI stays instantly consistent with backend state changes.</p><p><strong>Why a separate server and not Next.js API routes: </strong>Next.js API routes are HTTP — they open a connection, return a response, and close. WebSocket connections stay open indefinitely. Next.js’s server model doesn’t support persistent connections in the same process. A separate Node.js server runs alongside Next.js: Next.js on port 3000, WebSocket on port 4000.</p><p><strong>WebSocket Server Setup<br></strong>Install the ws package npm install ws<br>Create a server file in /src/server/ws-server.ts<br>Create a Custom React Hook /src/hooks/useWebSocket.ts<br>Consumes the hook in react components</p><p>We built a standalone Node.js WebSocket server because Next.js API routes are stateless HTTP — they can’t hold persistent connections. The server maintains a Set of connected clients and broadcasts structured JSON events every 2 seconds. Each event has a unique eventId which the frontend uses for deduplication — if the same event arrives twice due to a reconnect or retry, the RxJS pipeline drops the duplicate before it reaches TanStack. The three event types map to different parts of the TanStack cache so the UI updates without making any HTTP requests.</p><pre>import { WebSocketServer, WebSocket } from &#39;ws&#39;;<br>import { TYPES, type WsEvent } from &#39;@/types/ws.types&#39;;<br>import {<br>  MOCK_CAMPAIGNS,<br>  MOCK_CANDIDATES,<br>  MOCK_COMPANIES,<br>  MOCK_FEEDBACKS,<br>  DECISIONS,<br>} from &#39;@/data/talentAtlasMockData&#39;;<br><br>const PORT = Number(process.env.NEXT_PUBLIC_WS_PORT) || 4000;<br>const wss = new WebSocketServer({ port: PORT });<br><br>console.log(`WebSocket server running on ws://localhost:${PORT}`);<br><br>const clients = new Set&lt;WebSocket&gt;();<br>let eventCounter = 0;<br><br>// Tracks whether each client responded to the last ping.<br>// WeakMap avoids monkey-patching the WebSocket object.<br>const isAlive = new WeakMap&lt;WebSocket, boolean&gt;();<br>const HEARTBEAT_INTERVAL = 30_000;<br><br>function pick&lt;T&gt;(arr: readonly T[]): T {<br>  return arr[Math.floor(Math.random() * arr.length)];<br>}<br><br>// Broadcast a WS event to all connected clients<br>function broadcast(event: WsEvent) {<br>  const message = JSON.stringify(event);<br>  clients.forEach((client) =&gt; {<br>    if (client.readyState === WebSocket.OPEN) {<br>      client.send(message);<br>    }<br>  });<br>}<br><br>wss.on(&#39;connection&#39;, (socket) =&gt; {<br>  clients.add(socket);<br>  isAlive.set(socket, true);<br>  socket.on(&#39;pong&#39;, () =&gt; isAlive.set(socket, true));<br>  console.log(&#39;Client connected. Total:&#39;, clients.size);<br><br>  socket.send(<br>    JSON.stringify({<br>      type: &#39;connected&#39;,<br>      payload: { message: &#39;Connected to TalentAtlas WebSocket server&#39; },<br>      timestamp: Date.now(),<br>    } satisfies WsEvent),<br>  );<br><br>  // Relay real events sent by API routes to all connected clients<br>  socket.on(&#39;message&#39;, (raw) =&gt; {<br>    try {<br>      const event = JSON.parse(raw.toString()) as WsEvent;<br>      broadcast(event);<br>    } catch {<br>      console.warn(&#39;[WS] Failed to parse client message:&#39;, raw.toString());<br>    }<br>  });<br><br>  socket.on(&#39;close&#39;, () =&gt; {<br>    clients.delete(socket);<br>    console.log(&#39;Client disconnected. Total:&#39;, clients.size);<br>  });<br><br>  socket.on(&#39;error&#39;, (err) =&gt; {<br>    console.error(&#39;Socket error:&#39;, err.message);<br>    clients.delete(socket);<br>  });<br>});<br><br>// Ping every client on an interval. If a client hasn&#39;t responded to the<br>// previous ping by the time the next one fires, it is silently dead — terminate it.<br>setInterval(() =&gt; {<br>  wss.clients.forEach((socket) =&gt; {<br>    if (!isAlive.get(socket)) {<br>      socket.terminate();<br>      return;<br>    }<br>    isAlive.set(socket, false);<br>    socket.ping();<br>  });<br>}, HEARTBEAT_INTERVAL);<br><br>// Simulate real events every 2 seconds<br>setInterval(() =&gt; {<br>  eventCounter++;<br><br>  const eventType = TYPES[eventCounter % 3];<br><br>  if (eventType === &#39;candidate_updated&#39;) {<br>    const candidate = pick(MOCK_CANDIDATES);<br>    broadcast({<br>      type: &#39;candidate_updated&#39;,<br>      eventId: `evt-${eventCounter}`,<br>      payload: {<br>        candidateId: candidate.id,<br>        candidateName: candidate.full_name,<br>        stage: candidate.stage,<br>        campaignId: candidate.campaign_id,<br>      },<br>      timestamp: Date.now(),<br>    });<br>  } else if (eventType === &#39;campaign_updated&#39;) {<br>    const campaign = pick(MOCK_CAMPAIGNS);<br>    broadcast({<br>      type: &#39;campaign_updated&#39;,<br>      eventId: `evt-${eventCounter}`,<br>      payload: {<br>        campaignId: campaign.id,<br>        campaignTitle: campaign.title,<br>        applied_count: campaign.applied_count + Math.floor(Math.random() * 3),<br>        hired_count: campaign.hired_count,<br>      },<br>      timestamp: Date.now(),<br>    });<br>  } else {<br>    const candidate = pick(MOCK_CANDIDATES);<br>    const company = pick(MOCK_COMPANIES);<br>    broadcast({<br>      type: &#39;company_feedback&#39;,<br>      eventId: `evt-${eventCounter}`,<br>      payload: {<br>        candidateId: candidate.id,<br>        company: company.name,<br>        feedback: pick(MOCK_FEEDBACKS),<br>        decision: pick(DECISIONS),<br>      },<br>      timestamp: Date.now(),<br>    });<br>  }<br><br>  console.log(<br>    `Broadcast: ${eventType} [evt-${eventCounter}] to ${clients.size} client(s)`,<br>  );<br>}, 20000);<br><br>// Clean shutdown on Ctrl+C<br>process.on(&#39;SIGINT&#39;, () =&gt; {<br>  console.log(&#39;\nShutting down...&#39;);<br>  wss.close(() =&gt; process.exit(0));<br>});</pre><p><strong>Key Considerations for Production</strong></p><ul><li><strong>Heartbeats / Pings</strong>: Web connections can silently drop without triggering the close event. Implement a ping/pong heartbeat interval to detect and clean up &quot;dead&quot; clients.</li><li><strong>Security</strong>: Always use wss:// (WebSocket Secure) in production to encrypt traffic via TLS/SSL, preventing man-in-the-middle attacks.</li></ul><p><strong>How to implement them:</strong><br><strong>Server</strong> (ws-server.ts): pings every client every 30s via socket.ping(). If a client doesn&#39;t respond with a pong by the next interval, socket.terminate() removes the dead connection. The browser&#39;s native WebSocket handles the pong automatically — no client code needed.</p><p><strong>Client</strong> (useRealtimeSync.ts): reads NEXT_PUBLIC_WS_URL first, so production can use wss:// while dev stays on ws://localhost.</p><p><strong>Frontend WebSocket hook<br></strong>How to Connect from the Browser (Client-Side). We don’t need any external libraries in the browser; HTML5 has built-in WebSocket support.</p><p>Without the hook, every component that needs live events would have to:</p><ul><li>Open a WebSocket connection</li><li>Parse incoming messages</li><li>Close the connection on unmount</li><li>Handle reconnection</li></ul><p>With the hook, all of that is hidden. The component only sees lastEvent — a typed event that arrives automatically every 2 seconds from the server.</p><p>A React hook that opens a WebSocket connection to our server, manages reconnection on disconnect. It handles mounting, event listeners, state updates, and cleanups automatically when components unmount.</p><p><strong>In simple words:</strong> We put all the WebSocket logic in one place — useWebSocket — so components don&#39;t have to deal with it directly. When you visit the page, it connects. When you leave, it disconnects. Without this, the connection stays open forever even when no one is using it.</p><p><strong>Reconnection:</strong> If the connection drops, it tries again. First after 1 second, then 2, then 4, then 8 — it waits longer each time so it doesn’t spam the server with retries.</p><p><strong>Callback instead of state:</strong> Instead of storing events internally and returning them, the hook calls onEvent directly for each message.</p><pre>&#39;use client&#39;;<br><br>import { useEffect, useRef, useCallback } from &#39;react&#39;;<br>import type { WsEvent } from &#39;@/types/ws.types&#39;;<br><br>interface UseWebSocketOptions {<br>  url: string;<br>  onEvent: (event: WsEvent) =&gt; void;<br>  enabled?: boolean;<br>}<br><br>export function useWebSocket({<br>  url,<br>  onEvent,<br>  enabled = true,<br>}: UseWebSocketOptions) {<br>  const wsRef = useRef&lt;WebSocket | null&gt;(null);<br>  const reconnectDelay = useRef(1000);<br>  const isCleaningRef = useRef(false);<br><br>  const onEventRef = useRef(onEvent);<br>  useEffect(() =&gt; {<br>    onEventRef.current = onEvent;<br>  }, [onEvent]);<br><br>  const connect = useCallback(() =&gt; {<br>    if (!enabled) return;<br><br>    const ws = new WebSocket(url);<br>    wsRef.current = ws;<br><br>    ws.onopen = () =&gt; {<br>      console.log(&#39;[WS] Connected&#39;);<br>      reconnectDelay.current = 1000; // reset backoff on successful connection<br>    };<br><br>    ws.onmessage = (messageEvent) =&gt; {<br>      try {<br>        const event = JSON.parse(messageEvent.data) as WsEvent;<br>        onEventRef.current(event);<br>      } catch {<br>        console.warn(&#39;[WS] Failed to parse message:&#39;, messageEvent.data);<br>      }<br>    };<br><br>    ws.onclose = () =&gt; {<br>      // skip reconnect if we closed intentionally (unmount or StrictMode)<br>      if (isCleaningRef.current) return;<br>      console.log(<br>        `[WS] Disconnected. Reconnecting in ${reconnectDelay.current}ms...`,<br>      );<br>      // exponential backoff: 1s → 2s → 4s → 8s → max 30s<br>      setTimeout(() =&gt; {<br>        reconnectDelay.current = Math.min(reconnectDelay.current * 2, 30_000);<br>        connect();<br>      }, reconnectDelay.current);<br>    };<br><br>    ws.onerror = () =&gt; {<br>      if (isCleaningRef.current) return;<br>      console.error(&#39;[WS] Error: could not connect to&#39;, url);<br>      ws.close(); // triggers onclose → reconnect<br>    };<br>  }, [url, enabled]);<br><br>  useEffect(() =&gt; {<br>    isCleaningRef.current = false; // reset flag on remount (StrictMode)<br>    connect();<br><br>    return () =&gt; {<br>      isCleaningRef.current = true;<br>      wsRef.current?.close();<br>    };<br>  }, [connect]);<br>}</pre><h3>RxJS event pipeline</h3><p>An RxJS Subject that receives raw WebSocket events, deduplicates them, batches them with buffer Time , and emits clean arrays of events for the UI to consume.</p><p><strong>Why We Don’t Update the UI Directly from the WebSocket<br></strong>When events arrive in bursts, updating the UI on every single message means unnecessary re-renders, duplicate updates, and stale data overwriting fresh data.<br>So we added a pipeline between the raw socket and the cache. Every incoming event passes through three steps:</p><ol><li><strong>Deduplicate</strong> — we drop any event we’ve already seen</li><li><strong>Batch</strong> — we collect events for 200ms, then deliver them as one group</li><li><strong>Coalesce</strong> — if the same candidate updated twice in that window, we keep only the latest</li></ol><p>One batch. One cache update. One re-render. That’s exactly why we created /src/lib/realtime/wsStream.ts. RxJS sits between the WebSocket and TanStack Query, so the data is clean and efficient before it ever reaches React.</p><pre>import { Subject, filter, bufferTime, map } from &#39;rxjs&#39;;<br>import type { WsEvent } from &#39;@/types/ws.types&#39;;<br><br>// The single shared event stream for the entire app.<br>// All WebSocket events flow through here.<br>export const wsEvents$ = new Subject&lt;WsEvent&gt;();<br><br>// Bounded deduplication set — prevents memory leak on long sessions<br>const SEEN_EVENTS = new Set&lt;string&gt;();<br>const MAX_SEEN = 10_000;<br><br>function isDuplicate(event: WsEvent): boolean {<br>  if (!(&#39;eventId&#39; in event)) return false;<br>  if (SEEN_EVENTS.has(event.eventId)) {<br>    console.warn(&#39;[WS] Duplicate event dropped:&#39;, event.eventId);<br>    return true;<br>  }<br>  SEEN_EVENTS.add(event.eventId);<br>  if (SEEN_EVENTS.size &gt; MAX_SEEN) {<br>    const oldest = SEEN_EVENTS.values().next().value;<br>    if (oldest !== undefined) SEEN_EVENTS.delete(oldest);<br>  }<br>  return false;<br>}<br><br>function getEntityId(event: WsEvent): string {<br>  if (event.type === &#39;candidate_created&#39;) return event.payload.candidateId;<br>  if (event.type === &#39;candidate_updated&#39;) return event.payload.candidateId;<br>  if (event.type === &#39;campaign_updated&#39;) return event.payload.campaignId;<br>  if (event.type === &#39;company_feedback&#39;) return event.payload.candidateId;<br>  return String(event.timestamp);<br>}<br><br>// Pipeline: deduplicate → batch → coalesce → emit arrays<br>export const cleanEvents$ = wsEvents$.pipe(<br>  filter((event) =&gt; !isDuplicate(event)), // drop duplicate eventIds<br>  bufferTime(200), // collect events for 200ms<br>  filter((batch) =&gt; batch.length &gt; 0), // skip empty 200ms windows<br>  map((batch) =&gt; {<br>    // If the same entity was updated multiple times in the 200ms window,<br>    // keep only the latest update<br>    const latestById = new Map&lt;string, WsEvent&gt;();<br>    for (const event of batch) {<br>      latestById.set(getEntityId(event), event);<br>    }<br>    return Array.from(latestById.values());<br>  }),<br>);</pre><p><strong>Connecting the Pipeline to the Cache</strong></p><p>Once the clean events leave the pipeline, we need something to receive them and apply them to the app’s data cache. That’s what /src/hooks/talent-atlas/useRealtimeSync.ts does.</p><p><strong>wsEvents$ — the entry point<br></strong>A Subject is both a producer and consumer. You push events in with .next(event), subscribers receive them. The $ suffix is RxJS convention for &quot;this is an Observable/stream.&quot;</p><p><strong>isDuplicate — deduplication<br></strong>Every broadcast event has an eventId. This function checks if we&#39;ve seen that ID before. If yes → drop it. If no → remember it and pass it through.</p><p>The bounded set (MAX_SEEN = 10_000): a Set that never shrinks would leak memory on long sessions. When it hits 10,000 entries, the oldest one is evicted to make room — so memory stays bounded.</p><p><strong>cleanEvents$ — the pipeline</strong></p><pre>wsEvents$<br>  → filter isDuplicate      remove events we&#39;ve already seen<br>  → bufferTime(200)         wait 200ms, collect everything that arrived into an array<br>  → filter batch.length &gt; 0 skip the tick if nothing arrived<br>  → map (coalesce)          for each entity, keep only the latest update</pre><p>bufferTime is the key operator — instead of reacting to each event individually, we collect a batch and process them together.</p><p>useRealtimeSync updates the TanStack cache directly via useQueryClient(). The cache is already available everywhere because QueryProvider wraps the whole app higher up. So RealtimeProvider just needs to be somewhere inside that tree — it doesn&#39;t matter if it wraps children or sits beside them.</p><pre>&#39;use client&#39;;<br>import { useEffect } from &#39;react&#39;;<br>import { useQueryClient } from &#39;@tanstack/react-query&#39;;<br>import { useWebSocket } from &#39;@/hooks/useWebSocket&#39;;<br>import { wsEvents$, cleanEvents$ } from &#39;@/lib/realtime/wsStream&#39;;<br>import { queryKeys } from &#39;@/lib/query/queryKeys&#39;;<br>import type { WsEvent } from &#39;@/types/ws.types&#39;;<br>import type { CandidateFeedback } from &#39;@/hooks/talent-atlas/useCandidates&#39;;<br><br>// Connects WS server → RxJS pipeline → TanStack cache<br>// Drop this hook once in the (app) layout — one connection for the entire app<br>export function useRealtimeSync() {<br>  const queryClient = useQueryClient();<br><br>  // Subscribe RxJS pipeline output to TanStack cache<br>  useEffect(() =&gt; {<br>    const sub = cleanEvents$.subscribe((batch) =&gt; {<br>      for (const event of batch) {<br>        applyEventToCache(queryClient, event);<br>      }<br>    });<br>    return () =&gt; sub.unsubscribe();<br>  }, [queryClient]);<br><br>  // Feed raw WS events into the RxJS Subject<br>  const wsUrl = process.env.NEXT_PUBLIC_WS_URL ??<br>    `ws://localhost:${process.env.NEXT_PUBLIC_WS_PORT ?? 4000}`;<br><br>  useWebSocket({<br>    url: wsUrl,<br>    onEvent: (event) =&gt; wsEvents$.next(event),<br>  });<br>}<br><br>function applyEventToCache(<br>  queryClient: ReturnType&lt;typeof useQueryClient&gt;,<br>  event: WsEvent,<br>) {<br>  switch (event.type) {<br>    case &#39;candidate_updated&#39;: {<br>      queryClient.setQueryData(<br>        queryKeys.candidates,<br>        (old: { id: string; stage: string }[] = []) =&gt;<br>          old.map((c) =&gt;<br>            c.id === event.payload.candidateId<br>              ? { ...c, stage: event.payload.stage }<br>              : c,<br>          ),<br>      );<br>      break;<br>    }<br>    case &#39;campaign_updated&#39;: {<br>      queryClient.setQueryData(<br>        queryKeys.campaigns,<br>        (<br>          old: {<br>            id: string;<br>            applied_count: number;<br>            hired_count: number;<br>          }[] = [],<br>        ) =&gt;<br>          old.map((c) =&gt;<br>            c.id === event.payload.campaignId<br>              ? {<br>                  ...c,<br>                  applied_count: event.payload.applied_count,<br>                  hired_count: event.payload.hired_count,<br>                }<br>              : c,<br>          ),<br>      );<br>      break;<br>    }<br>    case &#39;candidate_created&#39;: {<br>      queryClient.setQueryData(<br>        queryKeys.candidates,<br>        (<br>          old: {<br>            id: string;<br>            full_name: string;<br>            email: string;<br>            stage: string;<br>            campaign_id: string;<br>          }[] = [],<br>        ) =&gt; [<br>          {<br>            id: event.payload.candidateId,<br>            full_name: event.payload.fullName,<br>            email: event.payload.email,<br>            stage: event.payload.stage,<br>            campaign_id: event.payload.campaignId,<br>          },<br>          ...old,<br>        ],<br>      );<br>      break;<br>    }<br>    case &#39;company_feedback&#39;: {<br>      queryClient.setQueryData(<br>        queryKeys.candidates,<br>        (old: { id: string; latestFeedback?: CandidateFeedback }[] = []) =&gt;<br>          old.map((c) =&gt;<br>            c.id === event.payload.candidateId<br>              ? {<br>                  ...c,<br>                  latestFeedback: {<br>                    company: event.payload.company,<br>                    feedback: event.payload.feedback,<br>                    decision: event.payload.decision,<br>                  },<br>                }<br>              : c,<br>          ),<br>      );<br>      break;<br>    }<br>  }<br>}</pre><p><strong>RealtimeProvider — Mounting the Pipeline in the App</strong></p><p>Hooks in React can only live inside components. So to activate the realtime pipeline at the app level, we created RealtimeProvider — a component with one job: call useRealtimeSync() and render nothing.</p><pre>export function RealtimeProvider() {<br>  useRealtimeSync();<br>  return null;<br>}</pre><p>We drop it once into the Talent Atlas layout. From that point on, the WebSocket connection is open, the pipeline is running, and every page in the app receives live updates — without any page needing to think about it.</p><p><strong>How It All Fits Together: Building a Real-Time Recruitment Dashboard with WebSockets, RxJS, and TanStack Query</strong></p><ul><li><strong>WS server</strong> (npm run ws:server) — a standalone Node.js process that broadcasts mock recruitment events every 2 seconds, simulating real-time data until a live backend is connected</li><li><strong>useWebSocket</strong> — opens the WebSocket connection and keeps it alive with exponential backoff reconnection (1s → 2s → 4s → max 30s)</li><li><strong>wsStream</strong> — an RxJS pipeline that processes raw events before they reach the UI: deduplicates by eventId, batches over a 200ms window, and coalesces multiple updates to the same entity into one</li><li><strong>useRealtimeSync</strong> — subscribes to the cleaned event stream and applies each event directly to the TanStack Query cache, triggering a UI update with no network request</li><li><strong>RealtimeProvider</strong> — a render-nothing component that mounts useRealtimeSync once in the Talent Atlas layout, giving every page a shared live connection</li><li><strong>Candidates API</strong> — POST /api/talent-atlas/candidates writes to an in-memory store and notifies the WS server so all connected clients see the new candidate instantly</li><li><strong>Dev auth bypass</strong> — withAuth skips session validation in NODE_ENV=development, so API routes work locally without a live Auth0 session</li></ul><pre>1. WS SERVER<br>   broadcasts event every 2s (mock setInterval)<br>           ↓<br>2. useWebSocket — ws.onmessage<br>   receives raw text, JSON.parse → typed WsEvent<br>           ↓<br>3. wsEvents$  (RxJS Subject)<br>   useRealtimeSync calls wsEvents$.next(event)<br>   — this is the entry point into the RxJS pipeline<br>           ↓<br>4. filter(isDuplicate)<br>   drops events with a seen eventId<br>           ↓<br>5. bufferTime(200ms)<br>   collects all events that arrive within 200ms into an array<br>           ↓<br>6. filter(batch.length &gt; 0)<br>   skips empty 200ms windows (nothing arrived)<br>           ↓<br>7. map — coalesce by entity<br>   if the same candidate/campaign updated twice in that 200ms,<br>   keep only the latest one<br>           ↓<br>8. cleanEvents$  (Observable&lt;WsEvent[]&gt;)<br>   emits a deduplicated, batched array<br>           ↓<br>9. useRealtimeSync — cleanEvents$.subscribe<br>   loops through the batch, calls applyEventToCache per event<br>           ↓<br>10. queryClient.setQueryData<br>    patches TanStack Query cache in place<br>           ↓<br>11. React UI re-renders<br>    any component using useCandidates / useCampaigns<br>    sees the new data automatically</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c7b03a7896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Architecture to Code: Implementing The Interactive Features]]></title>
            <link>https://paria-heidari.medium.com/from-architecture-to-code-implementing-the-interactive-features-8f17b0643219?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f17b0643219</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api-integration]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 16:23:35 GMT</pubDate>
            <atom:updated>2026-03-24T12:06:11.648Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://paria-heidari.medium.com/next-js-portfolio-architecture-modular-scalable-and-maintainable-7a92437bef8a">first part</a> of this series, I explored the architecture and folder structure behind my Next.js portfolio. <br>In this article, I focus on the implementation layer — how everything comes together in practice. This includes building interactive galleries, implementing filtering, and connecting the data layer to the UI.</p><h4>In this article, I’ll cover:</h4><ul><li><strong>Data relationships and design decisions</strong> — How I structured the database and set up relationships for the app.</li><li><strong>API layer implementation</strong> — How I built a single server-side layer in Next.js to handle all data fetching, so pages and components only focus on what to show.</li><li><strong>Integrating external content </strong>(Medium RSS)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNKXKgvLdXuZW8n8YaOhIg.png" /></figure><h3><strong>Data Relationships and Design Decisions</strong></h3><p>Before writing any implementation code, it’s critical to clearly define the data structure. <br>My website organizes photos using a <em>Photo</em> <em>→ Subcategory → Category </em>hierarchy to support flexible filtering without duplicating data.</p><h4>Data Model</h4><blockquote>Each entity follows a simple relationship: <br><strong>Photo → Subcategory → Category</strong></blockquote><p>This means:</p><ul><li>A photo belongs to a subcategory</li><li>A subcategory belongs to a category</li></ul><p>Why this structure?</p><ul><li>Avoids data duplication</li><li>Keeps the database normalized</li><li>Makes updates easier and safer</li></ul><p>Instead of storing both category_id and subcategory_id on the Photo, the category is derived through the subcategory. This ensures consistency across the system.</p><h4>Indexing for Performance</h4><p>To optimize filtering performance, I added indexes on key relational fields.</p><p><strong>Indexes used</strong></p><ul><li>photos.subcategory_id → for fast photo filtering</li><li>subcategories.category_id → for resolving category-level queries</li></ul><p><strong>Why indexing matters</strong></p><ul><li>Without index → full table scan (<strong>linear search</strong>)</li><li>With index → fast lookup (<strong>similar to binary search</strong>)</li></ul><h4>Best practices</h4><ul><li>Avoid indexing every column</li><li>Only index fields used in queries</li></ul><p>This keeps reads fast while avoiding unnecessary overhead on writes.</p><h3>Backend Setup with Supabase</h3><p>For the backend, I used Supabase, which provides a managed PostgreSQL database, storage, and API layer. This allowed me to focus on building features without managing infrastructure as well as use a typed, scalable backend out of the box.</p><p><strong>Key advantages: </strong>Type safety <br>Supabase can generate TypeScript types directly from the database schema. <br>By generating types directly from the database schema:</p><ul><li>Queries become type-safe</li><li>Refactoring becomes safer and more predictable</li><li>Frontend and backend stay in sync.</li></ul><h3>Project Setup</h3><p><strong>Choose how you want to use Supabase</strong></p><p>In my case, I chose to connect my app/project to Supabase using the client library.</p><ul><li><strong>Framework:</strong> Next.js</li><li><strong>Variant:</strong> App Router</li><li><strong>Install dependencies</strong></li></ul><pre>npm install @supabase/supabase-js</pre><h4><strong>Environment variables</strong></h4><p>Create environment variables for Supabase keys .env.local</p><pre>NEXT_PUBLIC_SUPABASE_URL= ...<br>NEXT_PUBLIC_SUPABASE_PUBLISHABLE_DEFAULT_KEY= ...</pre><h4>Supabase Client Setup</h4><p>@/lib/supabase/client.tsand @/lib/supabase/server.ts</p><pre>import { createBrowserClient } from &#39;@supabase/ssr&#39;<br>import type { Database } from &#39;@/types/database.types&#39;<br><br>export function createClient() {<br>  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL<br>  const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY<br><br>  if (!supabaseUrl || !supabaseKey) {<br>    throw new Error(&#39;Missing Supabase environment variables. Please check your .env.local file.&#39;)<br>  }<br><br>  return createBrowserClient&lt;Database&gt;(supabaseUrl, supabaseKey)<br>}</pre><pre>import { createServerClient } from &#39;@supabase/ssr&#39;<br>import { cookies } from &#39;next/headers&#39;<br>import type { Database } from &#39;@/types/database.types&#39;<br><br>const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;<br>const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_DEFAULT_KEY;<br><br>if (!supabaseUrl || !supabaseKey) {<br>  throw new Error(&#39;Missing Supabase environment variables. Please check your .env.local file.&#39;)<br>}<br><br>export async function createClient() {<br>  const cookieStore = await cookies()<br><br>  return createServerClient&lt;Database&gt;(<br>    supabaseUrl!,<br>    supabaseKey!,<br>    {<br>      cookies: {<br>        getAll() {<br>          return cookieStore.getAll()<br>        },<br>        setAll(cookiesToSet) {<br>          try {<br>            cookiesToSet.forEach(({ name, value, options }) =&gt;<br>              cookieStore.set(name, value, options)<br>            )<br>          } catch {<br>            // The `setAll` method was called from a Server Component.<br>            // This can be ignored if you have middleware refreshing<br>            // user sessions.<br>          }<br>        },<br>      },<br>    }<br>  )<br>}</pre><h4>Type Generation Script</h4><p>Add Script to package.json — to update data type after changing database structure. One command built from three parts: load env → start a shell → run Supabase with a redirect.</p><pre>&quot;supabase:types&quot;: &quot;dotenv -e .env.local -- sh -c &#39;supabase gen types typescript --project-id \&quot;$SUPABASE_PROJECT_ID\&quot; &gt; src/types/database.types.ts&#39;&quot;</pre><h3>API Layer Design</h3><p>In a Next.js + Supabase app, pages and components should primarily focus on <em>what to display</em>, not <em>how to talk to the database</em>. To achieve this, it’s best to have one centralized server-side API layer that handles database interactions.</p><p>For example, I can create a module in @/lib/api/photos.ts that wraps Supabase reads from the database. The Supabase client is created in a separate file, e.g., @/lib/supabase/server.ts using createClient().</p><p>This approach ensures that one module owns the contract between my Postgres schema and my app. Whenever the gallery’s data requirements change, I only need to update the queries (and regenerate types) in this single module. Pages can then import reusable functions. This keeps data access predictable and consistent across my app.</p><p><strong>Example: Fetching All Photos</strong></p><pre>export async function getAllPhotos() {<br>  const supabase = await createClient();<br><br>  const query = supabase<br>    .from(&quot;photos&quot;)<br>    .select(&quot;*, subcategory:subcategories(*)&quot;)<br>    .eq(&quot;published&quot;, true)<br>    .order(&quot;display_order&quot;, { ascending: true });<br><br>  type GetAllPhotosResult = QueryData&lt;typeof query&gt;;<br><br>  const { data, error } = await query;<br>  if (error) {<br>    logPostgrestError(&quot;Error fetching photos:&quot;, error);<br>    return [] as GetAllPhotosResult;<br>  }<br><br>  return (data ?? []) as GetAllPhotosResult;<br>}</pre><p>When I request all photos, I ask the database for a single type of answer in one HTTP request. Supabase’s API (PostgREST) converts the JavaScript query chain: .from(&quot;photos&quot;).select(...).eq(...)into an actual database query behind the scenes.</p><p><strong>Query pattern used in every function: <br></strong>createClient() -&gt; build query -&gt; filter (eq/in) -&gt; sort (order) -&gt; safe return. keeps return types aligned with query shape: QueryData&lt;typeof query&gt; so return shapes follow each select(...).</p><p><strong>Error handling strategy: <br></strong>This approach solves two different problems at once.</p><ul><li>Using structured PostgREST logs (message, details, hint, code) tell exactly what broke, so actionable error info for developers.</li><li>Return safe fallback data for the UI — returning [] prevents the whole page from crashing when one query fails.</li></ul><pre>const logPostgrestError = (<br>  context: string,<br>  error: { message: string; details?: string; hint?: string; code?: string }<br>) =&gt; {<br>  console.error(context, {<br>    message: error.message,<br>    details: error.details,<br>    hint: error.hint,<br>    code: error.code,<br>  });<br>}</pre><h4><strong>Displaying Medium Articles in the App</strong></h4><p><strong>Displaying Medium Articles in the App</strong></p><p>I want to integrate the feed of my own profile on Medium with my own website to show stories. I don’t copy them into the database; I read <a href="https://help.medium.com/hc/en-us/articles/214874118-Using-RSS-feeds-of-profiles-publications-and-topics">Medium</a>’s public RSS feed and turn each item into a simple object the UI understands.</p><p>RSS is a standard list a website can publish of its latest posts. Think of it as a machine-readable — not meant for humans to read in the browser, but for apps and other sites to pull updates.</p><p>Under src/lib/api/mediumArticles/<br>fetchMediumFeed.ts — talk to the network — builds the RSS URL for @username, then calls rss2json—a service that turns RSS XML into JSON so we don’t parse XML by hand, so get raw feed data, map to MediumArticle.</p><pre>const rssUrl = `https://medium.com/feed/@${username}`;<br>const apiUrl = `https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(rssUrl)}`;</pre><p>I cache the fetch for about an hour so I’m not hitting the Medium API every time someone loads the page.</p><pre><br>const response = await fetch(apiUrl, {<br>  next: { revalidate: 3600 },<br>});</pre><p>On the articles page, the All / Web / AI buttons filter that list on the client using keywords I defined — matching Medium’s tags. For some tabs, we also check the title or excerpt.</p><p>For example, the Web and AI tabs filter the list with their keywords: we first check Medium’s tags on each post, and for Web we also allow matches in the title or excerpt. A post appears on a tab if any of that tab’s keywords match under these rules. All of this logic lives in @/lib/api/mediumArticles, so the rest of the app just imports from one place.</p><pre>export async function getMediumArticles(username: string): Promise&lt;MediumArticle[]&gt; {<br>  try {<br>    const rssUrl = `https://medium.com/feed/@${username}`;<br>    const apiUrl = `https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(rssUrl)}`;<br><br>    const response = await fetch(apiUrl, {<br>      next: { revalidate: 3600 },<br>    });<br><br>    if (!response.ok) {<br>      throw new Error(`Failed to fetch Medium articles: ${response.status}`);<br>    }<br><br>    const mediumArticles: RSS2JSONResponse = await response.json();<br><br>    if (mediumArticles.status !== &#39;ok&#39;) {<br>      throw new Error(&#39;RSS feed parsing failed&#39;);<br>    }<br><br>    return mediumArticles.items.map((item) =&gt; ({<br>      title: item.title,<br>      link: item.link,<br>      pubDate: item.pubDate,<br>      author: item.author,<br>      thumbnail: item.thumbnail || extractImageFromContent(item.content),<br>      description: cleanDescription(item.description),<br>      categories: item.categories || [],<br>      guid: item.guid,<br>      readTime: calculateReadTime(item.content),<br>    }));<br>  } catch (error) {<br>    console.error(&#39;Error fetching Medium articles:&#39;, error);<br>    return [];<br>  }<br> }</pre><p>Some items are normalized for the UI:</p><ul><li>If there’s no thumbnail, extractImageFromContent grabs the first &lt;img&gt; from the body or falls back to a placeholder.</li><li>cleanDescription strips HTML from the excerpt and trims it (~150 chars).</li><li>calculateReadTime strips HTML, counts words, and estimates minutes at 200 WPM.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f17b0643219" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js Portfolio Architecture: Modular, Scalable, and Maintainable]]></title>
            <link>https://paria-heidari.medium.com/next-js-portfolio-architecture-modular-scalable-and-maintainable-7a92437bef8a?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a92437bef8a</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 12:53:52 GMT</pubDate>
            <atom:updated>2026-03-23T16:36:19.542Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a portfolio is more than showcasing work — it’s an opportunity to design an architecture that is scalable, maintainable, and performant. In this post, I walk through the technology stack and key architectural decisions behind my Next.js portfolio, highlighting how I approached modularity, data flow, and system design.</p><p><em>To keep my project organized and ensure I made architectural decisions at every stage, I created this mind map. It served as a roadmap from initial concept through database design, frontend and system architecture, to implementation and maintenance. The structure helped me stay focused and make informed trade-offs while developing my Next.js portfolio.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVC8bDPjqst0U9xdbRwPBg.png" /><figcaption>Full-Stack Project Blueprint: From Product Vision to Implementation</figcaption></figure><h3>Tech Stack Overview</h3><p>I chose technologies that balance <strong>performance, developer experience, and scalability</strong>. Here’s a breakdown:</p><h4><strong>Framework: Next.js</strong></h4><p>Next.js provide the flexibility of server-side rendering (SSR) and static site generation (SSG). The key benefits for portfolio:<br><strong>Fast first load </strong>— Pages are pre-build on the server rather than in the browser, reduicing initial javascript execution.<br><strong>SEO-friendly </strong>— Google and other search engines can index pre-rendered content more efficiently.<br><strong>App router &amp; Server components </strong>— Enable react to run on server with streaming support, so pages can load incrementaly (think “side-by-side”) without waiting for the entire page.<br><strong>Code splitting</strong> — Only the requested page is send to the client, reducing bundle size.<br><strong>SSG &amp; ISR </strong>(Incremental Static Regeneration) — Static pages are generated at build time, making frequent content accessible almost instancly to users.<br><strong>Edge runtime</strong> — Pages can execute at the edge, close to the user, further reducing latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTu0dOnSENuceqy2MTynbw.png" /><figcaption>Next.js Rendering Strategies: Request Flow Comparison Between SSG, SSR, and Edge Runtime</figcaption></figure><h4>How I Decide Between SSR, SSG, and Edge in My Portfolio</h4><p>When choosing a rendering strategy in Next.js, I focus on how dynamic the data is and where the logic should run.<br><strong>SSG</strong> — Used for static pages like the portfolio and landing sections to ensure fast load times and good SEO.<br><strong>SSR</strong> — Used when data is fetched dynamically from the Supabase API.<br><strong>Edge — </strong>Runtime was considered, but the current architecture does not require it. It could be useful in the future for features such as authentication middleware, or geo-based routing.</p><h4>Language: TypeScript</h4><ul><li>Provides type safety across the stack.</li><li>Gives confidence during refactors, especially when dealing with data from backend APIs.</li><li>Integrates seamlessly with Next.js and Supabase for strong type inference.</li></ul><h4>Database: Supabase (PostgreSQL + Storage)</h4><p>I chose Supabase for a serverless, fully managed backend:</p><ul><li>PostgreSQL database + file storage.</li><li>TypeScript type generation for safer API interactions.</li><li>Eliminates the need to maintain a custom backend server — don’t have to build or take care of my own backend server. Supabase does it for me.</li></ul><blockquote><strong><em>Trade-off insight:</em></strong><em> Using Supabase simplifies backend management but can limit complex business logic compared to a custom Node.js backend. For a portfolio, the trade-off is worth it for speed and simplicity.</em></blockquote><h4>Build Tool: Turbopack</h4><p>Turbopack handles bundling and rebuilding efficiently:</p><ul><li><strong>Incremental builds</strong> — Only rebuilds files that changed.</li><li><strong>Caching</strong> — Speeds up repeated builds.</li><li><strong>Parallel processing</strong> — Reduces build times on large projects.</li></ul><h4>Styling: Tailwind CSS v4</h4><p>Tailwind CSS allows for fast UI iteration:</p><ul><li><strong>Built-in design tokens</strong> — colors, spacing, and fonts are ready to use.</li><li><strong>Utility-first</strong> — you can style elements with small classes instead of writing a lot of custom CSS.</li><li><strong>Works well with React</strong> — you can use it directly in your components without extra setup.</li></ul><h4>Animations: Framer Motion</h4><p>For interactive elements like the gallery and lightbox:</p><ul><li>Declarative animations — Easier to reason about transitions.</li><li>Smooth performance, integrated with React’s rendering lifecycle.</li></ul><h3>Data Model &amp; Database Design</h3><p>Current database design focuses on organizing photos with categories and subcategories for filtering in the portfolio. In the future, I plan to introduce a “Project” entity to group photos, such as travel trips or photoshoots, which could include descriptions, interactive maps, and additional context for storytelling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bca59sM2UwrUOfVm0QwOcw.png" /><figcaption>Entity–Relationship Diagram (ERD) of the portfolio database built on Supabase PostgreSQL.</figcaption></figure><h3>Frontend Architecture</h3><p>The frontend follows Separation of Concerns: UI components live in src/components/, data fetching and APIs in src/lib/api/, types in src/types/, and static content in src/data/.</p><p>For scalability and reusability, components are small and focused, with barrel files (index.ts) for cleaner imports. The structure is mostly feature-based, with a shared/ folder for primitives like buttons, text blocks, and icons. Pages follow the Next.js App Router with nested routes, including portfolio filtering, ensuring maintainable growth as new features like project storytelling are added.</p><pre>public/<br>docs/<br>src/<br>├── app/<br>│   ├── layout.tsx<br>│   ├── globals.css<br>│   ├── page.tsx<br>│   ├── about/page.tsx<br>│   ├── articles/page.tsx<br>│   └── portfolio/[[...slug]]/page.tsx<br>│<br>├── components/<br>│   ├── Hero/<br>│   ├── Body/<br>│   ├── Header/<br>│   ├── Footer/<br>│   ├── Gallery/<br>│   ├── FeaturedGallery/<br>│   ├── Article/<br>│   ├── LatestArticles/<br>│   └── shared/<br>│       ├── Button/<br>│       ├── TextBlock/<br>│       └── icons/<br>│<br>├── lib/<br>│   ├── api/<br>│   │   ├── photos.ts<br>│   │   └── mediumArticles/<br>│   ├── supabase/<br>│   │   ├── client.ts<br>│   │   └── server.ts<br>│<br>├── types/<br>│   ├── database.types.ts<br>│   └── photo.types.ts<br>│<br>├── data/<br>│   └── data.ts<br>│<br>├── hooks/            # (Planned) shared React hooks<br>├── contexts/         # (Planned) React context providers<br>└── tests/            # (Planned) unit/integration tests</pre><h3>System Architecture</h3><p>System architecture of the portfolio platform, showing how user requests flow from the browser through the Next.js frontend (routes, UI components, and data layer) to external services like Supabase and the Medium API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9dMDVwASmfhCsFCG6-BNg.png" /><figcaption>System architecture of the current portfolio website.</figcaption></figure><p><strong>Planned Upgrade — Brainstorming:</strong> In the future, the architecture will include a Project layer where each project represents a trip or photoshoot.</p><p><strong>Continue to Part 2</strong>: <a href="https://paria-heidari.medium.com/from-architecture-to-code-implementing-the-interactive-features-8f17b0643219">From Architecture to Code: Implementing The Interactive Features</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a92437bef8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top Benefits of Learning AI Fluency]]></title>
            <link>https://paria-heidari.medium.com/top-benefits-of-learning-ai-fluency-dc5aa3dd716c?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc5aa3dd716c</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[agency]]></category>
            <category><![CDATA[aifluency]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 13:22:50 GMT</pubDate>
            <atom:updated>2026-01-28T14:05:43.151Z</atom:updated>
            <content:encoded><![CDATA[<h3>How the AI Fluency Framework Shapes Better Human–AI Collaboration</h3><p>AI Fluency means engaging with AI systems effectively, efficiently, ethically, and safely. It’s not just a technical skill — it’s a new way of working, thinking, and collaborating.</p><p>As AI continues to evolve, consultants and developers must build capabilities that go beyond knowing <em>what tools exist</em>. AI fluency is the ability to collaborate with AI in a way that aligns with goals, values, and responsibilities.</p><p>This article introduces the AI Fluency Framework, built around the “4Ds”:<br> <strong>Delegation, Description, Discernment, and Diligence.</strong></p><p>It also presents the three emerging modes of human–AI collaboration:<br><strong>Automation, Augmentation, and Agency.</strong></p><h3><strong>Three Ways We Collaborate With AI</strong></h3><p>AI systems are no longer just tools we command. They’ve become collaborators — each with different modes of engagement.</p><p><strong>1. Automation: AI Executes Specific Tasks</strong></p><p>You give clear instructions, AI completes the task.</p><p>Examples:</p><ul><li>Summaries</li><li>Simple code generation</li><li>Reformatting text</li><li>Data extraction</li></ul><p><strong>2. Augmentation: Human + AI CoCreation</strong></p><p>You and AI collaborate as thinking partners. AI expands your creativity and reduces cognitive load.</p><p>Examples:</p><ul><li>Brainstorming</li><li>Architecture design</li><li>Writing drafts</li><li>Exploring scenarios</li></ul><p><strong>3. Agency: AI Acts on Your Behalf</strong></p><p>You define the <em>behavior</em>, <em>knowledge</em>, and <em>boundaries</em>.<br> AI then performs work independently within those constraints. You’re not giving commands — you’re giving direction.</p><p>Examples:</p><ul><li>AI agents managing workflows</li><li>AI systems monitoring data and alerting you</li><li>Automated research assistants</li></ul><h3>The AI Fluency Framework: The 4Ds</h3><p>AI Fluency consists of <strong>four core competencies</strong> that apply across all three modes of AI collaboration. These are the skills that allow consultants and developers to work with AI in ways that are accurate, safe, and consistently valuable.</p><figure><img alt="Core AI Competencies" src="https://cdn-images-1.medium.com/max/499/1*mh1e0rBf6HvfiNt2KzassA.png" /><figcaption><a href="https://ringling.libguides.com/ai/framework">https://ringling.libguides.com/ai/framework</a></figcaption></figure><h3>1. <strong>Delegation</strong></h3><p>Deciding What Work AI Should Do — and What You Should Do.</p><p>Delegation is about making thoughtful choices about how to divide work between yourself and AI. The goal isn’t to automate everything — it’s to create the most effective human–AI partnership for any task.</p><p><strong>Three components of Delegation:</strong></p><h4>Problem Awareness Delegation</h4><p>Understanding your goal and the nature of the work.<br> Before involving AI, ask:</p><ul><li>What am I trying to solve?</li><li>Which parts require expertise, context, or judgment?</li></ul><h4>Platform Awareness</h4><p>Knowing what different AI systems can and cannot do.</p><p>Ask:</p><ul><li>Which AI model fits this task?</li><li>What are its strengths, limitations, or risks?</li></ul><h4>Task Delegation</h4><p>Strategically distributing work between human and AI.</p><p>Ask:</p><ul><li>What should I do?</li><li>What should AI handle?</li><li>Where should we collaborate?</li></ul><p><strong>Prompt example:</strong></p><blockquote>Act as an experienced senior consultant who regularly works with AI tools.</blockquote><blockquote>I want to improve how I execute complex tasks / [TASK] by making conscious decisions about which parts to delegate to AI and which parts I should keep ownership of.</blockquote><blockquote>Please help me:</blockquote><blockquote>Define a clear delegation framework for AI-assisted work</blockquote><blockquote>Identify task types that are safe to delegate to AI</blockquote><blockquote>Identify task types that should remain human-led</blockquote><blockquote>Describe where AI output should be reviewed or challenged</blockquote><blockquote>Use concrete examples from software consulting or knowledge work.</blockquote><p>If you want it short …</p><blockquote>I’m designing a delegation plan for my own work / [TASK] to decide what to delegate to AI versus keep myself.</blockquote><blockquote>Can you help me define that split and give practical examples?</blockquote><h3>2. Description</h3><p>Communicating Clearly With AI Systems.</p><p>Description is about crafting instructions that guide AI toward useful, high-quality outcomes — not just what you want, but <em>how</em> you want it.</p><p><strong>Three components of Description:</strong></p><h4>Product Description</h4><p>Clearly defining the output:</p><ul><li>Format</li><li>Style</li><li>Audience</li><li>Level of detail</li><li>Constraints</li></ul><h4>Process Description</h4><p>Process instructions shape the quality of the thinking behind the output. Guiding <em>how</em> the AI should approach the task:</p><ul><li>Step-by-step reasoning</li><li>Frameworks</li><li>Methods</li><li>Requirements</li><li>Examples</li></ul><h4>Performance Description</h4><p>Defining the AI’s behavior during collaboration:</p><ul><li>Do you want it to be concise or detailed?</li><li>Should it challenge your ideas or follow your instructions strictly?</li><li>Should it act as an expert, a coach, or a co-designer?</li></ul><h4>Prompt Example (Delegation + Description)</h4><blockquote>Act as an experienced senior consultant who regularly works with AI tools.</blockquote><blockquote><strong>Context</strong><br> I am a senior full-stack consultant working in a consultancy environment.<br> My work includes client delivery, technical leadership, and decision-making under time and budget constraints.</blockquote><blockquote><strong>Objective</strong><br> I want to improve how I execute complex tasks by deliberately deciding which parts to delegate to AI and which parts I should keep ownership of.</blockquote><blockquote><strong>Why this matters</strong><br> Poor delegation increases delivery risk, reduces quality, and can damage client trust.</blockquote><blockquote><strong>Scope</strong><br> Focus on software consulting and knowledge work (e.g. architecture design, coding, documentation, analysis, communication).</blockquote><blockquote><strong>Security &amp; confidentiality constraints</strong></blockquote><blockquote>Client-facing work requires higher security and confidentiality.</blockquote><blockquote>No sensitive client data should be shared with external AI systems.</blockquote><blockquote>Outputs must be safe for client exposure or clearly marked as internal-only.</blockquote><blockquote>Final client deliverables remain human-owned and reviewed.</blockquote><blockquote><strong>Please help me:</strong></blockquote><blockquote>Define a clear delegation framework for AI-assisted work.</blockquote><blockquote>Identify task types that are safe to delegate to AI.</blockquote><blockquote>Identify task types that should remain human-led.</blockquote><blockquote>Describe where AI output should be reviewed or challenged.</blockquote><blockquote><strong>Output format</strong></blockquote><blockquote>A structured framework or table.</blockquote><blockquote>Concrete examples from software consulting.</blockquote><blockquote>Short, practical explanations (no generic theory).</blockquote><h3>3. Discernment</h3><p>Evaluating AI Outputs, Reasoning, and Behavior. Discernment is the human capability to think critically about what AI produces. Even the most advanced AI requires human oversight.</p><p><strong>Three types of Discernment:</strong></p><h4>Product Discernment</h4><p>Evaluating the <em>output itself</em>:</p><ul><li>Accuracy</li><li>Coherence</li><li>Relevance</li><li>Completeness</li></ul><p>Questions to ask:</p><ul><li>Are there factual errors?</li><li>Does this actually meet my goal?</li></ul><h4>Process Discernment</h4><p>Assessing <em>how</em> the AI approached the task:</p><ul><li>Was the reasoning sound?</li><li>Were steps skipped?</li><li>Did it base conclusions on correct assumptions?</li></ul><h4>Performance Discernment</h4><p>Evaluating AI’s <em>behavior</em> during the interaction:</p><ul><li>Was it responsive to feedback?</li><li>Did it respect the requested tone or expertise level?</li><li>Did it understand and follow the instructions?</li></ul><p>Discernment and Description operate as a continuous feedback loop that elevates both you and the AI</p><h4>Prompt Example (Delegation + Description + Discernment)</h4><blockquote>Act as an experienced senior consultant who regularly works with AI tools.</blockquote><blockquote><strong>Context</strong><br> I am a senior full-stack consultant in a consultancy environment, responsible for client delivery, technical leadership, and risk management.</blockquote><blockquote><strong>Objective</strong><br> I want to improve how I execute complex tasks by deliberately deciding which parts to delegate to AI and which parts must remain human-owned.</blockquote><blockquote><strong>Description of the problem</strong></blockquote><blockquote>My work spans analysis, design, implementation, documentation, and client communication</blockquote><blockquote>Client-facing work requires high security, confidentiality, and accountability</blockquote><blockquote>I remain fully responsible for final decisions and outcomes</blockquote><blockquote><strong>Discernment requirements</strong><br> When proposing delegation options, explicitly consider:</blockquote><blockquote>. Risk of incorrect or misleading output</blockquote><blockquote>. Security and confidentiality implications</blockquote><blockquote>. Impact on client trust and credibility</blockquote><blockquote>. Situations where AI output may sound correct but be contextually wrong</blockquote><blockquote><strong>Please help me:</strong></blockquote><blockquote>Propose a delegation framework for AI-assisted work</blockquote><blockquote>For each task category, indicate:</blockquote><blockquote>. What can be delegated to AI</blockquote><blockquote>. What must remain human-led</blockquote><blockquote>. What requires human review or validation</blockquote><blockquote>Highlight common failure modes where poor judgment leads to misuse of AI</blockquote><blockquote>Recommend decision rules I can apply before using AI on a task</blockquote><blockquote><strong>Output format</strong></blockquote><blockquote>A table separating AI-safe, Human-only, and Hybrid tasks</blockquote><blockquote>Clear rationale for each decision</blockquote><blockquote>Short warnings where discernment is especially critical</blockquote><h3>4. Diligence</h3><p>Ensuring Responsible and Ethical Use of AI. Diligence is about taking responsibility for how you use AI — and how you share the results.</p><p><strong>Three components of Diligence:</strong></p><h4>Creation Diligence</h4><p>Choosing the right AI systems and using them thoughtfully.<br> This includes:</p><ul><li>Data privacy</li><li>Safety</li><li>Reliability</li><li>Context-appropriate use</li></ul><h4>Transparency Diligence</h4><p>Being honest about AI’s role in your work — when needed.<br> Different contexts have different expectations.<br> Ask:</p><ul><li>Who needs to know an AI contributed to this?</li></ul><h4>Development Diligence</h4><p>Taking responsibility for the final outputs.<br> Even if AI helped, <em>you</em> are accountable for:</p><ul><li>Verification</li><li>Accuracy</li><li>Alignment with standards</li><li>Ethical use</li></ul><p>Responsible AI collaboration builds trust — with clients, colleagues, and society.</p><h4>Prompt Example (Delegation + Description + Discernment + Diligence)</h4><blockquote>Act as an experienced senior consultant who regularly works with AI tools.</blockquote><blockquote><strong>Context</strong><br> I am a senior full-stack consultant in a consultancy environment, responsible for client delivery, technical leadership, and risk management.</blockquote><blockquote><strong>Objective</strong><br> I want to improve how I execute complex tasks by deliberately deciding which parts to delegate to AI and which parts must remain human-owned.</blockquote><blockquote><strong>Description of the work</strong></blockquote><blockquote>Tasks include analysis, design, implementation, documentation, and client communication</blockquote><blockquote>Client-facing work requires high security, confidentiality, and accountability</blockquote><blockquote>I remain fully responsible for final decisions and outcomes</blockquote><blockquote><strong>Discernment requirements</strong><br> When proposing delegation options, explicitly consider:</blockquote><blockquote>. Risk of incorrect or misleading output</blockquote><blockquote>. Security and confidentiality implications</blockquote><blockquote>. Impact on client trust</blockquote><blockquote><strong>Diligence requirements</strong><br> When generating recommendations:</blockquote><blockquote>. Be explicit about assumptions and uncertainties</blockquote><blockquote>. Flag areas that require validation or double-checking</blockquote><blockquote>. Avoid speculative or unverifiable claims</blockquote><blockquote>. Prefer conservative, defensible guidance over aggressive optimization</blockquote><blockquote><strong>Please help me:</strong></blockquote><blockquote>Propose a delegation framework for AI-assisted work</blockquote><blockquote>Classify tasks as AI-safe, Human-only, or Hybrid (AI + human review)</blockquote><blockquote>Highlight where diligence is most critical and why</blockquote><blockquote>Provide practical decision rules I can apply before using AI</blockquote><blockquote><strong>Output format</strong></blockquote><blockquote>A structured table</blockquote><blockquote>Clear rationale for each classification</blockquote><blockquote>Short caution notes where mistakes would be costly</blockquote><h4>Prompting by Task Type — Which Prompting Principles to Use (Practical Examples)</h4><ul><li><strong>Delegation</strong> → Decide what AI does vs what you do</li><li><strong>Description</strong> → Clearly explain the problem and context</li><li><strong>Discernment</strong> → Decide what to trust and what to double-check</li><li><strong>Diligence</strong> → Be careful, validate, avoid costly mistakes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiIy2Q9sD3JcUxLn9V6avA.png" /></figure><h3>Why This Matters for Us</h3><p>As AI becomes part of everyday consulting and development work, these skills help us:</p><ul><li>deliver faster and with higher quality,</li><li>collaborate more effectively with AI tools,</li><li>maintain professionalism and transparency, and</li><li>ensure responsible and safe use of AI in client engagements.</li></ul><p>For a deeper dive, check out this detailed outline of the AI fluency framework and its “4D” approach: <a href="https://ringling.libguides.com/ai/framework">https://ringling.libguides.com/ai/framework</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc5aa3dd716c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Gemini Text-to-Text UI in Next.js: API Routes]]></title>
            <link>https://paria-heidari.medium.com/build-a-gemini-text-to-text-ui-in-next-js-api-routes-e5ec4dff2233?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5ec4dff2233</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[google-gemini-ai]]></category>
            <category><![CDATA[nextjs-app-router]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 15:32:43 GMT</pubDate>
            <atom:updated>2025-09-10T12:02:16.927Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Gemini App with Next.js API Routes</h3><p>Integrate Gemini with Next.js, manage API keys safely, and ship a minimal text-to-text UI using CSS Modules — fast, secure, and understandable. <br><a href="https://gemini-ai-apps-nextjs.vercel.app/">Demo</a></p><p><strong>Step 1: Create a new Next.js app</strong></p><pre>npx create-next-app [YOUR_PROJECT_NAME]<br>cd [YOUR_PROJECT_NAME]</pre><p><strong>Step 2: Install the Gemini SDK</strong></p><p>According to the official <a href="https://ai.google.dev/gemini-api/docs/quickstart?lang=javascript">DOC</a>, you should use the @google/genai SDK. With Node.js v18 or later, install it via:</p><pre>npm install @google/genai</pre><p><strong>Step 3: Get a Gemini API key from Google AI Studio<br></strong><a href="https://aistudio.google.com/app/apikey">https://aistudio.google.com/app/apikey</a></p><p>Keep it secret!! Add it to your environment file.</p><pre>GEMINI_API_KEY=YOUR_SECRET_KEY</pre><p><strong>Pro tip</strong>: never expose this key in client-side code or commit it to Git. Restart your dev server after creating/updating the env file.</p><p><strong>Step 4: Create and Implement API route</strong></p><p>In Next.js (App Router), keep server-side route handlers inside the app/api directory.</p><pre>app/<br>  api/<br>    [YOUR_ROUTE_NAME]]/<br>      route.ts  </pre><p><strong>A Gemini Text-to-Text UI</strong> — <strong>Next.js API route example</strong></p><p>app/api/generate-gemini-ai/route.ts</p><p>This example uses the generateContent method to call the Gemini API with the Gemini 2.0 Flash model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*l5Y4aS30-X_tGCuevW_EHg.png" /></figure><p><strong>Quickly test the Gemini API</strong></p><pre>curl -X POST http://localhost:3000/api/generate-gemini-ai \<br>  -H &quot;content-type: application/json&quot; \<br>  -d &#39;{&quot;prompt&quot;:&quot;Summarize: Gemini vs ChatGPT&quot;}&#39;</pre><p><strong>Implement the Client-Side Form</strong></p><p>I added a minimal UI with a simple prompt form. The page (app/page.tsx) stays a server component, and I mount a tiny client component (app/components/PromptForm.tsx).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*yw_JKXOJpGt4WlrLoGsPhw.png" /></figure><p><strong>A Gemini Image-to-Text UI — Next.js API route example</strong></p><p>To send an image to the Gemini API, I pass it as inline base64-encoded data using the generateContent method.<br>In this example, I read a local image file, convert it to a base64 string, and include it in the request using the inlineData format along with its MIME type.<br>No upload or external hosting needed. It’s useful for tasks like Optical Character Recognition (OCR), image captioning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*RJjeUT7V73UfRyMmVlTnlg.png" /></figure><p><strong>Ways to Send Images to Gemini Vision</strong></p><p>There are several ways to pass image data to the generateContent API, depending on your use case:</p><ol><li>Inline base64 image: Read a local image file, convert it to base64, and pass it as inlineData with a MIME type. This works well for quick local testing or server-side processing.</li><li>Image from URL: You can fetch an image from a remote URL, convert it to bytes (base64), and send it inline the same way.</li><li>Using the Files API: For larger or persistent images, you can upload the file using the Gemini Files API.</li><li>Multiple images in one prompt: Gemini also supports multi-image prompts. Just include multiple image parts inside the contents array. These can be a mix of inline images and uploaded file references.</li></ol><p>More details available in the <a href="https://ai.google.dev/gemini-api/docs/image-understanding">official Doc</a>.</p><p>Using Gemini via Vertex AI, the core concepts are the same! whether it’s text, image, or both. Inputs can be sent inline or through the Files API. Vertex also adds production-ready features like dataset and model management, secure API endpoints, and seamless integration with Google Cloud tooling! More details available in the <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/start/quickstart?usertype=apikey">official Doc</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5ec4dff2233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing React Micro Frontend: A Step-by-Step Guide]]></title>
            <link>https://paria-heidari.medium.com/implementing-react-micro-frontend-a-step-by-step-guide-021488ec69c9?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/021488ec69c9</guid>
            <category><![CDATA[implement-microfrontend]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 12:01:28 GMT</pubDate>
            <atom:updated>2025-02-03T14:25:46.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tFyaItlp_niRKSd7Rm6-Q.png" /><figcaption><a href="https://github.com/imatiqul/micro-frontend-react/blob/master/images/MicroFrontend-Architecture-v1.png">https://github.com/imatiqul/micro-frontend-react/blob/master/images/MicroFrontend-Architecture-v1.png</a></figcaption></figure><h3>Step 1: Decide on an Integration Strategy</h3><ul><li><strong>Module Federation</strong> (Webpack 5): Share code and load Micro-Frontends dynamically.</li><li><strong>Iframes</strong>: Isolate Micro-Frontends completely, but with performance drawbacks.</li><li><strong>Web Components</strong>: Build using native browser capabilities.</li></ul><p><strong>Recommendation</strong>: Use Webpack Module Federation for React-based Micro Frontends.</p><h3>Step 2: Create Module Federation applications</h3><p>To implement a React-based Micro Frontend architecture, you’ll need at least two React applications: one acting as the <strong>Host Application</strong> and another as a <strong>Micro-Frontend Application</strong>. Each application will be independent but connected using Webpack&#39;s Module Federation or a similar approach. Give the required names, frameworks, and ports to start creating your template.</p><pre>npx create-mf-app host_app<br>npx create-mf-app micro_fn_app1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*kfPQ1c3blWcHNi2ABr1M_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Qv94R427YCQAnyhroB7T9A.png" /></figure><h3>Step 3: Configure Module Federation</h3><p>You need to configure <strong>Webpack Module Federation</strong> in both applications. This configuration ensures that your applications can share and load code dynamically.</p><h4>3.1: Configure the Micro-Frontend Application</h4><p>In the host application’s Webpack configuration file, set up the Module Federation Plugin as follows:</p><ul><li><strong>name</strong>: A unique name for the Micro Frontend application.</li><li><strong>filename</strong>: The name of the file exposed to other applications.</li><li><strong>exposes</strong>: Specifies which components or modules are available to other applications. in this case: Payment</li><li><strong>shared</strong>: Specifies shared libraries to avoid duplication and version mismatches.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Scr4CryQOi0Tsu266-Q0g.png" /></figure><p><strong>RemoteEntery.js</strong> is the manifest of all of the modules that are exposed by the micro_fn_app1 page application. We can find our <strong>remoteEntery.js</strong> file from the micro_fn_app1 app URL.</p><pre>micro_fn_app1@http://localhost:8001/remoteEntry.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dSzzhvT51FNaHM0Vd4WUA.png" /></figure><h4>3.2 Configure the Host Application</h4><ul><li><strong>name</strong>: The unique identifier for your host application.</li><li><strong>remotes</strong>: Defines the Micro Frontend applications this host will consume. Each key-value pair represents a remote application name and its corresponding remote entry point.</li></ul><p>To integrate the remote Micro Frontend, start by copying the remote URL generated by the Micro Frontend application, such as http://localhost:3001/remoteEntry.js. Then, open the webpack.config.js file in the host application and locate the remotes section within the Module Federation Plugin configuration. Paste the copied URL into this section, mapping it to a name like App1.</p><p>Once you’ve added the URL, restart the host application’s development server npm startto apply the changes. Now, the host application can dynamically load and use any components exposed by the Micro Frontend.</p><p>For instance, you can import components like Payment using import Payment from &#39;app1/Payment&#39; and render them directly in the host application.</p><p>In the host application’s Webpack configuration file, include the Module Federation Plugin. Here’s a sample configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1jBHPXMERbmlXsAnokj9g.png" /></figure><p>By using Webpack Module Federation, you can seamlessly integrate Micro Frontends into a host application by configuring remote URLs and sharing components dynamically. This approach ensures modularity, independent deployment, and scalable architecture for modern web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=021488ec69c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro Frontend Architecture]]></title>
            <link>https://paria-heidari.medium.com/micro-frontend-architecture-24dc889d2806?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/24dc889d2806</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 12:47:08 GMT</pubDate>
            <atom:updated>2025-01-17T12:09:31.458Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast-moving world of web development, it’s important to build applications that can grow and be maintained easily. Micro Frontend Architecture is a way to make this happen by breaking a big application into smaller, manageable parts. In this article, we’ll explain what Micro Frontend Architecture is, why it’s helpful, and how you can use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nj2FiGg8ESWvTYFgSB6sog.png" /><figcaption>Source: <a href="https://leanylabs.com/blog/micro-frontends-overview/">LeanyLabs Blog — Micro Frontends Overview</a>.</figcaption></figure><h3>What is Micro Frontend Architecture?</h3><p>Micro Frontend Architecture means splitting a large application’s frontend into smaller parts called “micro-frontends.” Each micro-frontend is like a mini app that does one job well. These pieces can be built, tested, and updated separately without affecting the rest of the application.</p><h3>Key Features:</h3><ul><li><strong>Separate Teams:</strong> Teams can work on their own part of the app without waiting for others.</li><li><strong>Mix and Match:</strong> Each micro-frontend can use different tools or frameworks.</li><li><strong>Independent Updates:</strong> You can update one part without touching the others.</li><li><strong>Seamless Combination:</strong> All parts come together to look and feel like one app.</li></ul><h3>Why Use Micro Frontend Architecture?</h3><p>Here are some benefits of using micro frontends:</p><ol><li><strong>Work Faster:</strong> Teams can develop different parts of the app at the same time.</li><li><strong>Easier Fixes:</strong> Smaller codebases mean finding and fixing issues is simpler.</li><li><strong>Upgrade in Pieces:</strong> Update or improve one part of the app without redoing everything.</li><li><strong>Team Freedom:</strong> Teams can pick the best tools for their part.</li><li><strong>Reduced Risk:</strong> If one part has a bug, it won’t crash the whole app.</li></ol><h3>Principles of Micro Frontend Architecture</h3><p>To use micro frontends successfully, follow these rules:</p><ol><li><strong>Focus on Business Areas:</strong> Divide the app based on what users need.</li><li><strong>Keep It Independent:</strong> Each part should work on its own.</li><li><strong>Compatible Changes:</strong> Make sure updates don’t break connections between parts.</li><li><strong>Clear Communication:</strong> Use well-defined ways for parts to talk to each other.</li></ol><h3>How to Build Micro Frontends</h3><p>Follow these steps to get started:</p><h3>1. Pick a Strategy</h3><p>There are different ways to combine micro-frontends:</p><ul><li><strong>In the Browser:</strong> Load each part with JavaScript when the user opens the app.</li><li><strong>On the Server:</strong> Put the parts together before sending them to the user.</li><li><strong>At the Edge:</strong> Use content delivery tools to assemble the app close to the user.</li></ul><h3>2. Use Module Federation</h3><p>Module Federation in <strong>Webpack</strong> lets you share code and features between parts easily. It’s a popular choice for combining micro-frontends.</p><h3>3. Share Common Tools</h3><p>Create shared libraries for things like design styles or utilities to avoid duplication.</p><h3>4. Combine the Parts</h3><p>Use a framework or custom tool to bring the micro-frontends together. Make sure the design is consistent.</p><h3>5. Deploy Separately</h3><p>Each micro-frontend should have its own deployment process. Automation tools can help.</p><h3>Tips for Success</h3><ul><li><strong>Start Small:</strong> Try micro frontends with a small project first.</li><li><strong>Keep it Fast:</strong> Optimize the parts so the app loads quickly.</li><li><strong>Communicate Clearly:</strong> Use simple ways for the parts to share data.</li><li><strong>Track Issues:</strong> Set up tools to monitor and fix problems across the app.</li></ul><h3>Challenges of Micro Frontends</h3><p>Here are some potential issues and how to handle them:</p><ol><li><strong>Complex Setup:</strong> Managing many parts can be tricky. Use automation to simplify.</li><li><strong>Slower Loading:</strong> Too many parts can slow down the app. Optimize for performance.</li><li><strong>Look and Feel:</strong> Keep a consistent design across all parts.</li></ol><h3>Conclusion</h3><p>Micro Frontend Architecture is a smart way to build modern web apps. By splitting a big app into smaller pieces, teams can work faster, fix problems more easily, and keep improving without starting from scratch. If you’re ready to take your frontend development to the next level, give micro frontends a try. it’s the future of scalable web apps!</p><p>In the next post, we’ll explore how to build a simple application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24dc889d2806" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Azure Fundamentals; Essential knowledge to prepare for the AZ900 Microsoft Azure…]]></title>
            <link>https://paria-heidari.medium.com/microsoft-azure-fundamentals-essential-knowledge-to-prepare-for-the-az900-microsoft-azure-2a8e0fe99852?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a8e0fe99852</guid>
            <category><![CDATA[az-900-study-material]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Fri, 14 May 2021 12:58:48 GMT</pubDate>
            <atom:updated>2021-05-14T13:10:32.964Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microsoft Azure Fundamentals; Essential knowledge to prepare for the AZ900 Microsoft Azure Fundamentals Exam. Section 2</h3><p>The core solutions and management tools on Azure (part 3) and general security and network security features (part 4) are described. Follow the following links to complete the learning path for Azure Fundamentals part 3 and part 4.</p><p><a href="https://docs.microsoft.com/en-us/learn/paths/az-900-describe-core-solutions-management-tools-azure/">https://docs.microsoft.com/en-us/learn/paths/az-900-describe-core-solutions-management-tools-azure/</a><br><a href="https://docs.microsoft.com/en-us/learn/paths/az-900-describe-general-security-network-security-features/">https://docs.microsoft.com/en-us/learn/paths/az-900-describe-general-security-network-security-features/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*rX6ZrAv2N4HjgxCxry9EuQ.jpeg" /><figcaption>Copyright from knnindia</figcaption></figure><p><strong>Artificial Intelligence</strong></p><p>There are two fundamental approaches to AI:</p><ul><li><strong><em>Deep learning system</em></strong>; that’s modeled on the neural network of the human mind, enabling it to discover, learn, and grow through experience.</li><li><strong><em>Machine Learning</em></strong>; a data science technique that uses existing data to train a model, test it, and then apply the model to new data to forecast future behaviors, outcomes, and trends. Forecasts or predictions can make apps and devices smarter.</li></ul><p><strong>Azure AI Product options</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*us5Q_f8NpeiHzKih-xCeSQ.png" /><figcaption>Copyright from .NET &amp; AZURE COMMUNITY</figcaption></figure><p>A comprehensive set of tools that help organizations build better solutions are created by Microsoft.</p><p><strong>DevOps</strong></p><p>DevOps — Development &amp; Operations — is a new approach that helps technical teams as they work toward common goals. It aims to shorten the systems development life cycle and provide continuous delivery with high software quality. DevOps is a set of practices that combines software development (Dev) and IT operations (Ops).</p><p>There are tools to enable source-code management, continuous integration and continuous delivery (CI/CD), and automating the creation of testing environments which are offered by Microsoft.</p><p><strong>Implementing Azure DevOps</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSLXuF0EbZVbGsBZRBSkOQ.png" /><figcaption>Copyright from .NET &amp; AZURE COMMUNITY — FORTE DIGITAL</figcaption></figure><p><strong>Azure DevOps Product options</strong></p><p><strong><em>Azure DevOps Services</em></strong>;<br>- Azure Boards<br>- Azure Repos<br> Azure Pipelines<br>- Azure Test Plans<br>- Azure Artifacts</p><p><strong><em>Azure GitHub /GitHub Actions</em></strong><br>- GitHub Project Boards<br>- GitHub Repos<br>- GitHub Actions<br>- GitHub Workflow Artifacts</p><p><strong><em>Azure DevTest Labs</em></strong><br>enables an automated means of managing the process of building, setting up, and tearing down virtual machines (VMs) that contain builds of your software projects. ie. Test environments.</p><p><strong>Monitoring Health, Performance, and Usage</strong></p><p>Gaining visibility into the health and performance of the application-hosting environment across all of the cloud’s layers of services is challenging.</p><p>There are three primary Azure monitoring offerings, each of which is aimed at a specific use case and provides a various set of tools, services, programmatic APIs, and more.</p><p><strong><em>Azure Advisor </em></strong>provides recommendations on high availability, security, performance, operational excellence, and reduce cost. The cost recommendations in the following areas: 1.Reducing costs by eliminating unprovisioned Azure ExpressRoute circuits. 2.Buy reserved instances to save money over pay-as-you-go. 3.Right-size or shutdown underutilized virtual machines.</p><p><strong><em>Azure Monitor </em></strong>is a platform for collecting, analyzing, visualizing as well as maximizing performance, availability.<br>Taking action based on the metric and logging data from usage of your web applications.</p><p><strong><em>Azure Service Health </em></strong>provides the health of the Azure services, regions, and resources you rely on. There are several event types that can be monitored by Azure Service Health.</p><p><strong>Planned maintenance </strong>events can affect your availability. <strong>Service issues</strong> are problems in Azure, such as outages, that affect you right now. <strong>Health advisories </strong>are issues that require you to act to avoid service interruption, so Health advisories are announced far in advance to allow you to plan.</p><p><strong>Managing the Azure Services</strong></p><p>A variety of tools and services to manage your cloud environment is offered by Microsoft. There are two categories of management tools at a high level. <strong>Code-based tools </strong>more for operations that you need to perform multiple times, and <strong>visual tools.</strong></p><ul><li><strong><em>Azure PowerShell </em></strong>(code-based); Azure PowerShell is a shell where you can execute commands called cmdlets (pronounced command-lets).</li><li><strong><em>The Azure CLI </em></strong>(code-based); The Azure CLI command-line interface is an executable program where you can execute commands in Bash.</li><li><strong><em>Azure Resource Manager templates</em></strong> (code-based); by ARM templates, you can describe the resources you want to use in a declarative JSON format.</li><li><strong><em>The Azure Portal </em></strong>(visual); A web-based user interface, you can access virtually every feature of Azure.</li></ul><p><strong>Azure Serverless Technologies</strong></p><p>Serverless computing enables developers to build applications faster by eliminating the need for them to manage infrastructure. Azure provides two implementations of Serverless.</p><p><strong><em>Azure Functions</em>;</strong> run small amounts of code known as serverless functions in your favorite language. Runs in response to an event. An example of an event might be an HTTP request.</p><p><strong><em>Azure Logic App</em>;</strong> can execute logic triggered by Azure services without writing any code. The service helps you automate and orchestrate tasks, business processes, and workflows when you need to integrate apps, data, systems, and services across enterprises or organizations.</p><p>You can mix and match services when you are building an orchestration, calling functions from logic apps and calling logic apps from functions.</p><p><strong>Azure Internet of Things Services</strong></p><p>Smart devices are equipped with the kinds of sensors that can connect to the internet and then send their sensor readings to a specific endpoint in Azure via a message. The aggregated data can be converted into reports and alerts. IoT enables devices to gather and then relay information for data analysis. There are many services that can assist and operate end-to-end solutions for IoT on Azure.</p><p><strong><em>Azure IoT Hub</em> </strong>is a managed, highly secure, and reliable service that’s hosted in the cloud. Azure IoT Hub acts as a central message hub for bi-directional communication between your IoT application and the devices it manages.</p><p><strong><em>Azure IoT Central </em></strong>builds on top of IoT Hub by adding a dashboard that allows you to connect, monitor, and manage your IoT devices. It provides to watch the overall performance across all devices in aggregate, and you can set up alerts that send notifications when a specific device needs maintenance.</p><p><strong><em>Azure Sphere </em></strong>creates a highly secure IoT solution for customers that encompasses everything from the hardware and operating system on the device to the secure method of sending messages from the device to the message hub. After validating the authenticity and authenticity of the device by the Azure Sphere system, the device can interact with other Azure IoT services by sending telemetry and error information.</p><p><strong>Protect Against Security Threats on Azure</strong></p><p><strong><em>Azure Security Centre </em></strong>is a monitoring service that provides visibility of your security posture across all of your services, both on Azure and on-premises. The term security posture refers to cybersecurity policies and controls, as well as how well you can predict, prevent, and respond to security threats.<br>Azure Security Centre is available in Free and Standard Tier.</p><p><strong><em>Azure Sentinel </em></strong>provides detect and respond to security threats. Azure Sentinel aggregates security data from many different sources and provides additional capabilities for threat detection and response. Such as:</p><ul><li>Collect data across all users, devices, applications, and infrastructure, both on-premises and from multiple clouds.</li><li>Detect previously undetected threats</li><li>Investigate threats with artificial intelligence</li><li>Respond to incidents rapidly</li></ul><p><strong><em>Azure Key Vault </em></strong>centralized cloud service for storing and managing your application’s secrets. Helps you to protect cryptographic keys and other secrets used by cloud apps and services.</p><p><strong>Secure Network Connectivity on Azure</strong></p><p><strong><em>Azure Firewall </em></strong>is a cloud-based network security service that protects your Azure Virtual Network resources. Azure Firewall provides many features, including:</p><p>-Built-in high availability.<br>- Unrestricted cloud scalability.<br>- Inbound and outbound filtering rules.<br>- Inbound Destination Network Address Translation (DNAT) support.<br>- Azure Monitor logging.</p><p>In general, Azure Firewall create, enforce, and log application and<br>network connectivity policies across subscriptions and virtual networks, In addition, uses a static public IP address for your virtual network resources allowing outside firewalls to identify traffic originating from your virtual network.</p><p><strong><em>Protect from DDoS attacks by using Azure DDoS Protection</em></strong></p><p>Distributed Denial of Service attack is a malicious attack that making the application slow or unresponsive to legitimate users by disrupting normal traffic by flooding a website with large amounts of fake traffic.</p><p>Two tiers of DDoS Protection are offered by Azure.</p><ol><li><em>The basic service</em> tier is automatically enabled for free as part of your Azure subscription.</li><li><em>The standard service</em> tier enables additional mitigation capabilities that are tuned specifically to Azure Virtual Network resources.</li></ol><p><strong><em>An Azure virtual network </em></strong>enables virtual machines and other compute resources to securely communicate with each other</p><p><strong><em>A network security group (NSG) </em></strong>It is possible to filter network traffic to and from Azure resources within a virtual network by NSG.</p><p><a href="https://paria-heidari.medium.com/microsoft-azure-fundamentals-essential-knowledge-to-prepare-for-the-az900-microsoft-azure-3704c648bb82">Microsoft Azure Fundamentals; Essential knowledge to prepare for the AZ900 Microsoft Azure…</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a8e0fe99852" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Azure Fundamentals; Essential knowledge to prepare for the AZ900 Microsoft Azure…]]></title>
            <link>https://paria-heidari.medium.com/microsoft-azure-fundamentals-essential-knowledge-to-prepare-for-the-az900-microsoft-azure-3704c648bb82?source=rss-f1640215b83f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3704c648bb82</guid>
            <category><![CDATA[az-900-study-material]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[azure-services]]></category>
            <dc:creator><![CDATA[Paria Heidari]]></dc:creator>
            <pubDate>Fri, 16 Apr 2021 18:51:43 GMT</pubDate>
            <atom:updated>2021-05-14T12:59:52.493Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microsoft Azure Fundamentals; Essential knowledge to prepare for the AZ900 Microsoft Azure Fundamentals Exam. Section 1</h3><p>The AZ-900 Azure Fundamentals is the entry-level cloud certification for Microsoft Azure. You should get to know the fundamentals of cloud computing, ​Azure Core services, and the Azure Portal. In This article, I am going to explain some useful concepts that can help you to prepare for the exam.</p><p>The core Azure concepts (part 1) and core Azure services (part 2) are described. Follow the following links to complete the learning path for Azure Fundamentals part 1 and Azure Fundamentals part 2.<br><a href="https://docs.microsoft.com/en-us/learn/paths/az-900-describe-cloud-concepts/">https://docs.microsoft.com/en-us/learn/paths/az-900-describe-cloud-concepts/</a><br><a href="https://docs.microsoft.com/en-us/learn/paths/az-900-describe-core-azure-services/">https://docs.microsoft.com/en-us/learn/paths/az-900-describe-core-azure-services/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aelT4Rkcc8fZg_z243KSIQ.png" /><figcaption>Copyright from acloud.guru</figcaption></figure><p>The most commonly used services and features in Azure.</p><ul><li>Compute</li><li>Networking</li><li>Storage</li><li>Mobile</li><li>Databases</li><li>Web</li><li>Internet of Things (IoT)</li><li>Big data</li><li>AI</li><li>DevOps</li></ul><p><strong>Cloud Architecture Terminologies</strong></p><p><strong>Availability</strong> <br>Your ability for your service to remain available <br><strong>Scalability</strong> <br> Increase/decrease your capacity based on the increasing/decreasing demand for traffic, memory, and computing power.<br><strong>Elasticity</strong> <br>Automatically increase/decrease your capacity based on the current demand of traffic, memory, and computing power.<br><strong>Disaster Recovery</strong> <br>To recover from a failure and to prevent the loss of data. The solution that recovers from a disaster is known as Disaster Recovery (RD).</p><p><strong>The total cost of ownership (TCO)</strong></p><p>The image illustrates the Total Cost of Ownership for CAPEX: On-Premise and OPEX: Azure, Cloud Provider</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4YjGPp4akfl9trfaMeDOg.png" /><figcaption>TCP — Copyright from <a href="https://docs.microsoft.com/en-us/dynamics365/get-started/migration/moving-to-the-cloud">Microsoft Doc</a>.</figcaption></figure><p><strong>Cloud Services</strong></p><ol><li>IaaS — Infrastructure as a Service — A cloud provider keeps the hardware up to date, but the cloud tenant is responsible for maintaining the operating system and configuring the network.</li><li>PaaS — Platform as a service — the cloud tenant deploys their applications into the managed hosting environment.</li><li>SaaS — Software as a Service — The cloud tenant only provides their data to the application managed by the cloud provider.</li></ol><p><strong>Azure Data Storage</strong></p><ul><li>Azure Cosmos DB</li><li>Azure SQL Database</li><li>Azure SQL Managed Instance</li><li>Azure Database for MySQL</li><li>Azure Database for PostgreSQL</li><li>Azure Synapse Analytics</li><li>Azure HDInsight</li><li>Azure Databricks</li><li>Azure Data Lake Analytics</li></ul><p><strong>The benefits and usage of</strong></p><ul><li><strong>Azure Cosmos DB</strong> — A globally distributed, multi-model database service. It supports schema-less data, which lets you build highly responsive. Designed for scale with 99.999% availability. Azure Cosmos DB supports SQL, MongoDB, Cassandra, Tables, and Gremlin APIs.</li><li><strong>Azure SQL Database</strong> — Can be used to build data-driven applications and websites. You can migrate your data using Azure Database Migration Service with minimal downtime using Microsoft Data Migration Assistance. It supports both relational data and non-relational structures such as JSON and XML.</li><li><strong>Azure Database for MySQL</strong> — you can use point-in-time restore to recover a server to an earlier state, as far back as 35 days.</li><li>Azure SQL Managed Instance — When databases use Cyrillic characters for collation. Azure SQL Database only uses the default SQL_Latin1_General_CP1_CI_AS server collation.</li></ul><p><strong>Azure database documentation</strong></p><ul><li><a href="https://azure.microsoft.com/product-categories/analytics/">Azure Analytics Services</a></li><li><a href="https://docs.microsoft.com/en-us/azure/cosmos-db/">Azure Cosmos DB documentation</a></li><li><a href="https://docs.microsoft.com/en-us/azure/sql-database/">Azure SQL Database documentation</a></li><li><a href="https://docs.microsoft.com/en-us/azure/azure-sql/managed-instance/">Azure SQL Managed Instance documentation</a></li><li><a href="https://docs.microsoft.com/en-us/azure/mysql/">Azure Database for MySQL documentation</a></li><li><a href="https://docs.microsoft.com/en-us/azure/postgresql/">Azure Database for PostgreSQL documentation</a></li></ul><p><strong>Compute services</strong></p><p>Azure compute is an on-demand computing service for running cloud-based applications. It provides computing resources such as multi-core processors, memory, networking, and operating systems. It also provides serverless computing to run apps without requiring infrastructure setup or configuration. The resources are available on-demand and can typically be made available in minutes or even seconds.</p><p>Depending on your requirements, each service provides different options. Some of the most outstanding services are:</p><ul><li>Azure Virtual Machines</li><li>Azure Container Instances</li><li>Azure App Service</li><li>Azure Functions (or <em>serverless computing</em>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*w3KSuFzHubnfH3VgY2j2AQ.png" /><figcaption>Compute Services — Copyright from <a href="https://docs.microsoft.com/en-us/learn/modules/azure-compute-fundamentals/overview">Microsoft Doc.</a></figcaption></figure><p><strong>Virtual Machine</strong> (VM) is a software emulation of physical computers. VMs include memory, storage, a virtual processor, and networking resources. They host an operating system, and you are able to install and run software just such as a physical computer.</p><p><strong>Containers</strong> are a virtualization environment for running applications. containers do not include an operating system for the app running inside the container. You are able to run multiple instances of a containerized application on a single host machine.</p><p><strong>Kubernetes Services </strong>Kubernetes makes it easy to deploy, manage and scale containerized applications. For instance, you might split a website into a container hosting your front end, another hosting your back end, and a third for storage.</p><p><strong>Azure App Service</strong> is a platform as a service (PaaS) offering. It is possible to quickly build, deploy, and scale enterprise-grade web, mobile, and API apps running on any platform. There are performance, scalability, security, and compliance requirements while using a fully managed platform to perform infrastructure maintenance. With App Service, the most common app service styles can be hosted such as:</p><ul><li>Web apps</li><li>API apps</li><li>WebJobs</li><li>Mobile apps</li></ul><p><strong>Functions</strong> are commonly used when you need to perform work in response to an event (mostly via a REST request), timer, or message from another Azure service.</p><p><strong>Azure Batch</strong> provides large-scale high-performance computing and parallel batch jobs with the ability to scale to tens, hundreds, or thousands of VMs.</p><p><strong>Serverless computing</strong> includes 3 concepts <em>the abstraction of servers</em>, <em>an event-driven scale</em>, and <em>micro-billing</em>. Azure has two implementations of Serverless Compute</p><ol><li><strong>Azure Functions </strong>— which can execute code in almost any programming language.</li><li><strong>Azure Logic App </strong>— can execute logic triggered by Azure services without writing any code. You create Logic App workflows using a visual designer on the Azure portal or in Visual Studio. The workflows are persisted as a JSON file.</li></ol><p><strong>Azure Storage services</strong></p><p>Azure Storage<strong> </strong>is a service that makes it possible to store files, messages, tables, and other types of information. Clients such as websites, mobile apps, desktop applications, and many other types of custom solutions can read data from and write data to Azure Storage.</p><p>The following types of data are supported by Azure Storage</p><ul><li>Structured Data</li><li>Semi-Structured data</li><li>Unstructured data</li></ul><p><strong>Azure Blob Storage </strong>is Object Serverless Storage. Blob storage can manage very large files and large amounts of unstructured files as well as thousands of simultaneous uploads, massive amounts of video, audio, image data, growing log files, backup, disaster recovery.</p><p><strong>Azure Files Storage </strong>You can access and manage files that are shared in the cloud. They are accessible via the industry-standard Server Message Block (SMB) protocol.</p><p><strong>Azure Disk Storage </strong>Chooses SSD or HDD, encryption by default. It provides disks for virtual machines, applications, and other services.</p><p><strong>Azure Blob Access Tiers</strong></p><p>• <strong>Hot access tier</strong>: Optimized for storing data that is accessed frequently (images for your website).</p><p>• <strong>Cool access tier</strong>: Optimized for data that is infrequently accessed and stored for at least 30 days (invoices for your customers).</p><p>• <strong>Archive access tier</strong>: Appropriate for data that is rarely accessed and stored for at least 180 days, with flexible latency requirements (for instance, long-term backups).</p><p><strong>Azure Networking Services</strong></p><ul><li><strong>Azure Virtual Network </strong>provides Azure resources, such as VMs, web apps, and databases, to communicate with each other, with users on the internet, and with your on-premises client computers. <em>An Azure network is a set of resources that links other Azure resources. </em>The following key networking capabilities are provided by Azure virtual networks. The following key networking capabilities are provided by Azure virtual networks.<br>- Communicate between Azure resources<br>- Communicate with on-premises resources<br>- Isolation and segmentation<br>- Internet communications<br>- Route network traffic<br>- Filter network traffic<br>- Connect virtual networks</li><li><strong>Azure VPN Gateway </strong>instances are deployed in Azure Virtual Network instances. The following connectivity is enabled. — A site-to-site VPN connection between an Azure Virtual Network and your local network. — A <em>point-to-site</em> connection between individual devices to virtual networks. — A <em>network-to-network</em> connection between virtual networks to other virtual networks.</li><li><strong>Azure Express Route </strong>has greater bandwidth and higher levels of security. A connection between your on-premises networks into the Microsoft cloud over a private connection.</li></ul><p><a href="https://paria-heidari.medium.com/microsoft-azure-fundamentals-essential-knowledge-to-prepare-for-the-az900-microsoft-azure-2a8e0fe99852">Microsoft Azure Fundamentals; Essential knowledge to prepare for the AZ900 Microsoft Azure…</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3704c648bb82" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>