<?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 Kasun Nadeera on Medium]]></title>
        <description><![CDATA[Stories by Kasun Nadeera on Medium]]></description>
        <link>https://medium.com/@kasunnadeera100?source=rss-5b92357c2c14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1cH2hNqHt-CSjAt90Ne11A.png</url>
            <title>Stories by Kasun Nadeera on Medium</title>
            <link>https://medium.com/@kasunnadeera100?source=rss-5b92357c2c14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:07:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kasunnadeera100/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[Fortifying the MERN Stack: A Blueprint for End-to-End Web Security and OIDC Integration]]></title>
            <link>https://medium.com/@kasunnadeera100/fortifying-the-mern-stack-a-blueprint-for-end-to-end-web-security-and-oidc-integration-d87902cf0040?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/d87902cf0040</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[owasp-api-security-top-10]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[owasp]]></category>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 20:07:17 GMT</pubDate>
            <atom:updated>2026-08-29T20:07:17.446Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How we engineered zero-trust authentication with Auth0, tackled OWASP Top 10 vulnerabilities, and hardened local HTTPS workflows on a student project showcase platform.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWpUqc-sP8O2YqWIl5GaNA.png" /></figure><h3>1. Introduction: The High Stakes of Student Innovation</h3><p>Every semester, hundreds of engineering students build ground-breaking capstone projects, portfolio showcases, and research prototypes. Yet, many of these applications share a common Achilles’ heel: <strong>security is treated as an afterthought</strong>.</p><p>When developing <strong>Project Hall</strong> — a centralized showcase platform built for students to publish their projects, recruit collaborators, and engage with academic communities — our core architectural objective was clear from Day 1: <strong>bake enterprise-grade security directly into the application layer</strong>.</p><p>Modern web architectures cannot rely on basic username/password schemas or loose default server configurations. In this deep dive, we will walk through the complete journey of fortifying a full-stack MERN application against modern threat vectors — from OpenID Connect (OIDC) identity federation with Auth0 to fine-grained access control, OWASP Top 10 mitigations, and resilient cryptographic controls.</p><h3>2. Authentication &amp; Access Control: Identity Federation with Auth0</h3><p>Managing authentication in-house introduces immense risk — credential stuffing, insecure password storage, and complex session management. To establish a zero-trust foundation, we delegated identity management to <strong>Auth0</strong> using <strong>OpenID Connect (OIDC)</strong> and OAuth 2.0 standards.</p><pre>+------------------+         1. Login Redirect         +------------------+<br>|                  | --------------------------------&gt; |                  |<br>|  React Frontend  |                                   |  Auth0 Identity  |<br>|  (Vite + React)  | &lt;-------------------------------- |  Provider (OIDC) |<br>|                  |      2. Authorization Code /      +------------------+<br>+------------------+         ID &amp; Access Token<br>        |<br>        | 3. API Request with Bearer Token<br>        v<br>+------------------+         4. Validate Token (JWKS)  +------------------+<br>|  Express Backend | --------------------------------&gt; | Auth0 JWKS       |<br>|  (Node.js API)   | &lt;-------------------------------- | (.well-known)    |<br>+------------------+         5. Verified Public Key    +------------------+</pre><h4>The Frontend OIDC Flow</h4><p>Using the @auth0/auth0-react SDK, we wrapped the client in an Auth0Provider with an explicit redirect URI (https://localhost:5173/callback) and established an Axios interceptor that requests fresh access tokens silently:</p><pre>// Attaching the bearer token to all outgoing requests<br><br>api.interceptors.request.use(async (config) =&gt; {<br>  if (isAuth0Authenticated) {<br>    const token = await getAccessTokenSilently();<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }<br>  return config;<br>});</pre><p>When users log in, user profile data (such as <strong>Username</strong>, <strong>Full Name</strong>, <strong>Email Address</strong>, <strong>Contact Number</strong>, and <strong>Organization / Business Name</strong>) is extracted via the useAuth0 hook and synchronized gracefully with fallback handling for optional metadata.</p><h4>Backend Token Interception &amp; Access Control (RBAC)</h4><p>On the Express server, incoming requests pass through custom JWT verification middleware using jwks-rsa to dynamically fetch and cache Auth0&#39;s public signing keys from /.well-known/jwks.json.</p><p>Once cryptographically validated, the unique sub (Subject Identifier) claim is extracted and mapped to database entities to enforce strict ownership verification:</p><pre>export const requireProjectOwnership = async (req, res, next) =&gt; {<br>  const projectId = parseInt(req.params.id, 10);<br>  const userId = req.user.dbId || parseInt(req.user.sub, 10);<br><br>  const project = await db(&#39;projects&#39;).where({ id: projectId }).first();<br>  if (!project) return res.status(404).json({ error: &#39;Project not found&#39; });<br><br>  // Only the creator or an Administrator can modify or delete<br>  if (project.created_by !== userId &amp;&amp; req.user.role !== &#39;admin&#39;) {<br>    return res.status(403).json({ error: &#39;Forbidden: You can only modify your own submissions&#39; });<br>  }<br><br>  next();<br>};</pre><h3>3. Mitigating OWASP Top 10 Vulnerabilities</h3><p>Beyond authentication, web applications face a battery of injection, configuration, and state-manipulation threats. Here is how we systematically mitigated the top risk categories:</p><h4>A03: Injection &amp; NoSQL Defense</h4><p>Malicious actors often inject query operators (like {&quot;$gt&quot;: &quot;&quot;} or {&quot;$ne&quot;: null}) to bypass logical database conditions or corrupt JSON payloads.</p><ul><li><strong>Payload Sanitization</strong>: We integrated express-mongo-sanitize to strip and replace prohibited characters ($ and .) across req.body, req.query, and req.params.</li><li><strong>Parameterized Queries</strong>: All database transactions leverage Knex parameterized statements to prevent SQL/NoSQL injection vulnerabilities at the query driver level.</li></ul><h4>A03: Cross-Site Scripting (XSS)</h4><p>User-generated content, such as project titles, descriptions, and comments, represents a prime target for stored XSS payloads.</p><ul><li><strong>Backend Escaping</strong>: We implemented recursive XSS filtering using the xss library in global Express middleware and before saving records to the database.</li><li><strong>Frontend Sanitization</strong>: In React, user-submitted HTML strings are sanitized using <strong>DOMPurify</strong> before rendering, disallowing untrusted JavaScript execution while preserving valid typography.</li></ul><h4>A07: Cross-Site Request Forgery (CSRF) &amp; Strict CORS</h4><ul><li><strong>Origin Whitelisting</strong>: The Express CORS policy restricts incoming traffic strictly to trusted frontend origins (https://localhost:5173) with explicit method and header whitelisting.</li><li><strong>Double-Submit Cookie Pattern</strong>: For cookie-authenticated requests, our custom csrfProtection middleware generates a cryptographically random XSRF-TOKEN cookie and validates the X-CSRF-Token header on state-changing requests (POST, PUT, PATCH, DELETE).</li></ul><h4>A05: Security Misconfiguration &amp; Rate Limiting</h4><ul><li><strong>HTTP Headers with Helmet</strong>: We configured helmet to enforce a strict Content Security Policy (CSP), prevent clickjacking via X-Frame-Options: DENY, and restrict cross-origin embedding policies.</li><li><strong>Brute-Force Rate Limiting</strong>: Using express-rate-limit, we isolated sensitive authentication and submission routes, capping auth attempts at 25 requests per 15 minutes per IP.</li></ul><h4>A06 &amp; A09: Dependency Auditing &amp; Security Logging</h4><ul><li><strong>Automated Auditing</strong>: Running automated npm audit pipelines ensures that third-party CVEs are resolved and dependencies are kept up to date.</li><li><strong>Structured Logging with Winston &amp; Morgan</strong>: We paired HTTP access logging (Morgan) with Winston’s file-based transports (error.log and combined.log). A custom masking filter automatically scrubs passwords, API keys, JWTs, and verification codes before writing logs to disk.</li></ul><h3>4. Engineering Challenges Faced</h3><p>Building secure architectures inevitably brings development friction. Two key hurdles stood out during implementation:</p><h4>(1) Local HTTPS Configuration Across Micro-Services</h4><p>Modern Identity Providers and secure cookie policies (SameSite: None; Secure) strictly require HTTPS. Running HTTPS locally across separate frontend (5173) and backend (5000) ports often causes SSL handshake rejections and self-signed certificate warnings.</p><ul><li><em>Solution</em>: We leveraged in-memory certificate generators (selfsigned) on Express and @vitejs/plugin-basic-ssl on Vite, ensuring both tiers negotiate encrypted TLS channels during development without breaking hot module replacement.</li></ul><h4>(2) Role Boundary Enforcement (Students vs. Admins)</h4><p>Ensuring that students have write permissions exclusively over their own project portfolios while granting administrators broad moderation powers required careful architectural design.</p><ul><li><em>Solution</em>: We decoupled authorization checks into two composable layers — permission checks (requirePermission(&#39;projects:write&#39;)) and ownership checks (requireProjectOwnership). This prevents horizontal privilege escalation without duplicating controller logic.</li></ul><h3>5. Key Learning Outcomes &amp; Conclusion</h3><p>Securing an application is not a checklist item you bolt on right before deployment — it is an <strong>architectural discipline</strong>.</p><p>By approaching Project Hall with a security-first mindset, we demonstrated that modern web apps can achieve both high developer velocity and rigorous defense-in-depth:</p><ol><li><strong>Decouple Identity</strong>: Let battle-tested IdPs like Auth0 handle the complexities of password hashing, MFA, and token issuance.</li><li><strong>Sanitize at the Boundary</strong>: Never trust client inputs; sanitize early, parameterize queries, and escape before rendering.</li><li><strong>Log Intelligently</strong>: Monitor failure patterns and security anomalies without compromising user privacy.</li></ol><h3>🔗 Connect &amp; Explore the Code</h3><p>📦 <strong>GitHub Repository</strong>: <a href="https://github.com/nadeera-se22018/web-project-hall.git">https://github.com/web-project-hall.git</a></p><p><em>If you found this breakdown insightful, feel free to give this article a clap 👏, star the repository on GitHub, and leave your thoughts or questions in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d87902cf0040" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Structure a Scalable React Project (2026 Guide)]]></title>
            <link>https://medium.com/@kasunnadeera100/how-to-structure-a-scalable-react-project-2026-guide-d533298dff24?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/d533298dff24</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Tue, 12 May 2026 12:09:21 GMT</pubDate>
            <atom:updated>2026-05-12T12:09:21.289Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Stop building spaghetti monoliths. Here is the ultimate architectural blueprint for frontend applications that scale effortlessly with your team, your features, and your sanity.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHAMY1EH_ZUjxSfF3SgClQ.png" /></figure><p>We have all been there. You join a new company, clone the frontend repository, run npm install, and open the src folder. Suddenly, a cold sweat breaks out.</p><p>There is a components folder with 150 files inside it. There is a utils.js file that is 3,000 lines long. The state management logic is scattered across Redux, Context API, and random useState hooks. Modifying a simple button component breaks a checkout page you did not even know existed.</p><p>Welcome to the <strong>“Big Ball of Mud”</strong> architecture.</p><p>In the early days of React, Create React App (CRA) gave us a blank canvas. While this lack of opinionated structure was liberating, it became a massive liability for growing teams. Today, in 2026, the frontend ecosystem has matured. With the dominance of Vite, the evolution of React 19, and the rise of Server Components, the way we structure our React applications has fundamentally changed.</p><p>In this comprehensive guide, we will explore the modern blueprint for structuring a scalable, maintainable, and enterprise-grade React project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XgQsK0V_9hnXk0CKpl0Mw.png" /></figure><h3>1. The Core Philosophy: Feature-Driven Architecture</h3><p>For years, the standard React convention was “type-based” routing. Developers grouped files by their technical role: all components in src/components, all hooks in src/hooks, and all API calls in src/api.</p><p>While this works for a weekend project, it is a nightmare for scale. If you want to update the “User Profile” feature, you have to open src/components/UserProfile.jsx, src/hooks/useProfile.js, src/api/profileApi.js, and src/store/profileSlice.js. You are jumping across the entire codebase just to change one feature.</p><p><strong>The 2026 Paradigm is Feature-Sliced Design (FSD) or Feature-Driven Architecture.</strong></p><p>Instead of grouping by technical type, we group by <strong>domain or feature</strong>. A feature should be a self-contained module. If you delete the “Auth” feature folder, the rest of the application should not break.</p><h3>Principles of Scalability:</h3><ul><li><strong>Colocation:</strong> Files that change together should live together. If a helper function is only used by the PaymentForm component, it belongs in the PaymentForm directory, not in a global src/utils folder.</li><li><strong>Strict Boundaries:</strong> Features can import global UI components, but global UI components should never import feature-specific logic.</li><li><strong>Separation of Concerns:</strong> Keep your UI dumb and your data layers smart.</li></ul><h3>2. The Ultimate 2026 Folder Structure</h3><p>Let us look at the blueprint. This structure is framework-agnostic but assumes a modern SPA built with Vite (though it adapts perfectly to Next.js or Remix with slight routing modifications).</p><pre>src/<br>├── assets/              # Static files: images, fonts, global CSS<br>├── components/          # GLOBAL shared components (buttons, inputs, modals)<br>│   ├── ui/              # Shadcn/ui or primitive components<br>│   └── layout/          # App shells, sidebars, headers<br>├── config/              # Global app config, environment variables<br>├── features/            # THE CORE: Domain-specific modules<br>│   ├── authentication/<br>│   ├── dashboard/<br>│   └── products/<br>├── hooks/               # GLOBAL custom hooks (e.g., useTheme, useWindowSize)<br>├── lib/                 # Pre-configured 3rd party libraries (axios, sentry)<br>├── pages/               # Route configurations (brings features together)<br>├── providers/           # Global React Context providers (Theme, AuthProvider)<br>├── routes/              # React Router setup<br>├── store/               # Global state (Zustand/Redux) - Keep this minimal!<br>├── types/               # Global TypeScript interfaces<br>└── utils/               # Global pure functions (formatters, regex)</pre><p>Let us break down the most critical directories and why they are structured this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhufN71u-sfXEyP-CQeZrA.png" /></figure><h3>3. Deep Dive: The features/ Directory</h3><p>The features folder is where 80% of your application&#39;s logic will live. Every major domain of your app gets its own folder. Think of them as mini-applications inside your main app.</p><p>Let us peek inside src/features/authentication:</p><pre>features/authentication/<br>├── api/                 # API requests specific to auth (login, register)<br>├── components/          # Components ONLY used in auth (LoginForm, PasswordReset)<br>├── hooks/               # Hooks specific to auth (useAuthValidation)<br>├── store/               # Local state slice for auth <br>├── types/               # TS interfaces for auth (User, LoginCredentials)<br>└── index.ts             # The Public API of this feature</pre><h3>The Magic of the index.ts Barrel File</h3><p>Notice the index.ts file at the root of the feature. This acts as the <strong>Public API</strong> for the feature module.</p><p><strong>Rule:</strong> Other parts of your application are ONLY allowed to import from the feature’s index.ts file. They cannot dig deep into the feature&#39;s internal folders.</p><pre>export { LoginForm } from &#39;./components/LoginForm&#39;;<br>export { useAuth } from &#39;./hooks/useAuth&#39;;<br>export type { User } from &#39;./types&#39;;</pre><p>If the Dashboard feature needs the User type, it imports it like this: import { User } from &#39;@/features/authentication&#39;;</p><p>This strict boundary prevents tightly coupled code and ensures that you can refactor the internals of the Authentication feature without breaking the Dashboard.</p><h3>4. The Global components/ Directory</h3><p>If most logic lives in features/, what goes into the global src/components/ folder?</p><p>Only <strong>pure, generic, domain-agnostic UI components</strong>.</p><p>If a component knows about your business logic (e.g., it fetches “User” data or dispatches a “Buy Product” action), it belongs in a feature. If it is just a dumb visual wrapper, it goes here.</p><p>In 2026, component libraries like Material-UI are being replaced by headless UI and copy-paste libraries like <strong>shadcn/ui</strong>. Your components folder should look like this:</p><pre>components/<br>├── ui/                # Base primitives (shadcn/ui)<br>│   ├── Button.tsx<br>│   ├── Input.tsx<br>│   └── Dialog.tsx<br>├── form/              # Form wrappers (React Hook Form integrations)<br>└── feedback/          # Global loaders, toast notifications</pre><p>A good test for a global component: <em>Could I copy and paste this component into a completely different project and have it work immediately?</em> If yes, it is a global UI component.</p><h3>5. State Management and Data Fetching in 2026</h3><p>If you are still putting all your API responses into a global Redux store, you are living in the past.</p><p>In modern React architecture, we distinguish between <strong>Server State</strong> (data that lives on your database) and <strong>Client State</strong> (UI state, like dark mode or a toggled dropdown).</p><h3>Server State: React Query (TanStack Query)</h3><p>Data fetching should be handled by robust server-state libraries like React Query or SWR. They handle caching, background refetching, pagination, and loading states automatically. You do not need to write isLoading or data states manually anymore.</p><p>These queries should be colocated inside your features.</p><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;<br>import { axiosInstance } from &#39;@/lib/axios&#39;;<br><br>export const useGetProducts = () =&gt; {<br>  return useQuery({<br>    queryKey: [&#39;products&#39;],<br>    queryFn: async () =&gt; {<br>      const { data } = await axiosInstance.get(&#39;/products&#39;);<br>      return data;<br>    },<br>  });<br>};</pre><h3>Client State: Zustand</h3><p>For global client state (like user preferences, themes, or multi-step form data), heavy boilerplate like Redux is rarely necessary. <strong>Zustand</strong> has become the industry standard for lightweight, unopinionated state management.</p><pre>import { create } from &#39;zustand&#39;;<br><br>interface ThemeState {<br>  theme: &#39;light&#39; | &#39;dark&#39;;<br>  toggleTheme: () =&gt; void;<br>}<br><br>export const useThemeStore = create&lt;ThemeState&gt;((set) =&gt; ({<br>  theme: &#39;light&#39;,<br>  toggleTheme: () =&gt; set((state) =&gt; ({ theme: state.theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39; })),<br>}));</pre><p>Keep your global src/store/ as empty as possible. Push state down the tree. If a state is only needed in the Products feature, create a Zustand store inside src/features/products/store/.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QY6cNR72_ElRVF0pkJAKmA.png" /></figure><h3>6. The lib/ and utils/ Directories</h3><p>It is easy to confuse lib/ and utils/. Here is the modern distinction:</p><ul><li><strong>src/lib/</strong>: This is for <strong>configuring third-party libraries</strong>. If you are setting up an Axios instance with interceptors, initializing Sentry for error tracking, or configuring Firebase, it goes here.<br><em>Example:</em> lib/axios.ts, lib/sentry.ts</li><li><strong>src/utils/</strong>: This is for <strong>pure JavaScript/TypeScript functions</strong> that you wrote yourself. These should have zero dependencies on React (no JSX, no hooks). They take an input and return an output.<br><em>Example:</em> utils/formatDate.ts, utils/calculateDiscount.ts</li></ul><p>By keeping these separate, your codebase remains highly testable. Pure utility functions can be unit-tested in isolation instantly.</p><h3>7. Routing and the pages/ Directory</h3><p>How do we tie all these isolated features together? That is the job of the src/pages/ (or src/views/) directory.</p><p>A “Page” component should contain almost no logic. Its only responsibility is to map a URL route to the appropriate Features and provide the layout.</p><pre>import { DashboardLayout } from &#39;@/components/layout&#39;;<br>import { UserStats } from &#39;@/features/dashboard&#39;;<br>import { RecentActivity } from &#39;@/features/activity&#39;;<br><br>export const DashboardPage = () =&gt; {<br>  return (<br>    &lt;DashboardLayout&gt;<br>      &lt;div className=&quot;grid-layout&quot;&gt;<br>        &lt;UserStats /&gt;<br>        &lt;RecentActivity /&gt;<br>      &lt;/div&gt;<br>    &lt;/DashboardLayout&gt;<br>  );<br>};</pre><p>By keeping pages thin, you ensure that your business logic remains reusable. If you suddenly need to display the RecentActivity widget on the User Profile page as well as the Dashboard, you simply import the feature.</p><h3>8. Styling Strategy</h3><p>In 2026, the debate over CSS is largely settled in favor of utility-first CSS, specifically <strong>Tailwind CSS</strong>.</p><p>When using a feature-sliced architecture, traditional CSS (BEM) or even CSS modules can become tedious to maintain across deeply nested folders. Tailwind allows you to colocate your styling directly with your JSX, reducing context switching and eliminating dead CSS code.</p><p>If you must write custom CSS, use CSS Modules (Component.module.css) and colocate the CSS file directly next to the .tsx file it styles. Never use a global src/styles/ folder for anything other than absolute base resets and CSS variables.</p><h3>Conclusion: Discipline is the Ultimate Architecture</h3><p>No matter how beautiful your folder structure is on day one, an architecture is only as good as the discipline of the team maintaining it.</p><p>Implementing a Feature-Driven architecture requires a mental shift. Developers must stop asking <em>“What type of file is this?”</em> and start asking <em>“What domain does this logic belong to?”</em></p><p>When you colocate your files, respect feature boundaries, leverage server-state libraries like React Query, and keep your global folders aggressively clean, you build an application that can scale indefinitely. You eliminate the fear of refactoring. You accelerate onboarding for new developers.</p><p>Stop building software that fights against you as it grows. Adopt these modern architectural practices, structure your React project with intention, and build a codebase that your future self — and your team — will thank you for.</p><p><em>Happy coding! If you found this architecture guide helpful, share it with your team or drop a comment below on how you handle scaling in your own React projects.</em></p><h3>References &amp; Further Reading</h3><blockquote><strong>Feature-Sliced Design (FSD):</strong> An architectural methodology for frontend projects. The concepts of domain-driven folder structures are heavily inspired by this paradigm.<br><a href="https://feature-sliced.design/">Official FSD Documentation</a></blockquote><blockquote><strong>Bulletproof React:</strong> A comprehensive guide and repository demonstrating enterprise-grade React architecture, colocation, and feature-driven development.<br><a href="https://github.com/alan2207/bulletproof-react">Bulletproof React on GitHub</a></blockquote><blockquote><strong>Managing Server State with React Query:<br></strong><a href="https://tanstack.com/query/latest">TanStack Query Official Docs</a></blockquote><blockquote><strong>Lightweight Client State Management:<br></strong><a href="https://github.com/pmndrs/zustand">Zustand Documentation</a></blockquote><blockquote><strong>Modern UI Components:<br></strong><a href="https://ui.shadcn.com/">shadcn/ui — Beautifully designed components that you can copy and paste into your apps.</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d533298dff24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Performance Optimization: The Ultimate Guide]]></title>
            <link>https://medium.com/@kasunnadeera100/mastering-react-performance-optimization-the-ultimate-guide-60d6c48dbef8?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/60d6c48dbef8</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Sun, 03 May 2026 11:52:28 GMT</pubDate>
            <atom:updated>2026-05-03T11:52:28.061Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Stop letting unnecessary re-renders slow down your application. Learn the advanced techniques for memoization, code splitting, and state management to build lightning-fast React apps.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddzAqYEPg1gxLzgM1Jl3JA.png" /></figure><p>React is fast out of the box. Its Virtual DOM architecture was revolutionary when it first launched, allowing developers to build interactive UIs without worrying about the heavy cost of direct DOM manipulation. However, as applications scale and teams grow, React’s default behavior can easily become a bottleneck.</p><p>We have all experienced it: typing into an input field feels slightly delayed, navigating between tabs stutters, and the laptop fan spins up just from clicking a dropdown menu. This is the “death by a thousand cuts” in React applications. It is rarely one massive function causing the lag; rather, it is hundreds of tiny, unnecessary re-renders compounding over time.</p><p>In this comprehensive guide, we will dive deep into the mechanics of React’s rendering lifecycle and explore advanced techniques to optimize your applications, including strategic memoization, code splitting, list virtualization, and managing complex UI state cleanly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2bksubTbpsopgL-uno9kA.png" /></figure><h3>1. You Cannot Optimize What You Cannot Measure</h3><p>Before throwing useMemo at every variable in your codebase, you must understand how to measure performance. Blind optimization leads to unreadable code and, ironically, worse performance due to the overhead of the optimization itself.</p><p>Your primary weapon is the <strong>React Developer Tools Profiler</strong>. When you record a session using the Profiler, React provides a flame graph of your component tree. It tells you exactly which components rendered, how long they took, and most importantly, <em>why</em> they rendered (e.g., “Hook 1 changed” or “Props changed”).</p><p><strong>The Golden Rule of Optimization:</strong> Only optimize code that the Profiler proves is slow. Premature optimization is the root of all evil in frontend development.</p><h3>2. Understanding the Render Lifecycle</h3><p>To optimize React, you must understand what “rendering” actually means. A render in React does not necessarily mean a DOM update.</p><p>There are two phases:</p><ol><li><strong>The Render Phase:</strong> React calls your component function, calculates the new Virtual DOM tree, and compares it to the previous Virtual DOM tree (Diffing).</li><li><strong>The Commit Phase:</strong> If React finds differences between the two Virtual DOM trees, it applies those exact changes to the actual browser DOM.</li></ol><p>The Commit phase is expensive, but React is highly optimized to minimize it. The problem usually lies in the Render phase. If a parent component re-renders, <strong>all of its children re-render by default</strong>, even if their props have not changed. Running thousands of component functions just to realize “nothing changed” wastes precious CPU cycles.</p><h3>3. The Art of Memoization (React.memo, useMemo, useCallback)</h3><p>Memoization is the process of caching the result of an expensive operation so that it does not need to be recalculated unless its inputs change.</p><h3>React.memo: Shielding Your Components</h3><p>React.memo is a higher-order component that prevents a component from re-rendering if its props have not changed.</p><pre>import React from &#39;react&#39;;<br><br>const HeavyChart = React.memo(({ data, title }) =&gt; {<br>  return &lt;div&gt;{title} Chart&lt;/div&gt;;<br>});</pre><p>If the parent component re-renders because a user typed into a completely unrelated search bar, HeavyChart will intercept the render, compare the new data and title props with the old ones, and skip its own render if they are strictly equal (===).</p><h3>The Referential Equality Trap and useCallback</h3><p>There is a massive catch to React.memo. In JavaScript, two objects or functions are only equal if they share the exact same memory address.</p><pre>{} === {} // false<br>(() =&gt; {}) === (() =&gt; {}) // false</pre><p>Look at this common mistake:</p><pre>const Dashboard = () =&gt; {<br>  const [query, setQuery] = useState(&quot;&quot;);<br><br>  const handleChartClick = () =&gt; {<br>    console.log(&quot;Chart clicked!&quot;);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input value={query} onChange={(e) =&gt; setQuery(e.target.value)} /&gt;<br>      &lt;HeavyChart data={chartData} onClick={handleChartClick} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Every time the user types in the input, Dashboard re-renders. handleChartClick gets a new memory address. HeavyChart sees a &quot;new&quot; prop and re-renders anyway.</p><p><strong>The Solution:</strong> Use useCallback to cache the function&#39;s memory address.</p><pre>const handleChartClick = useCallback(() =&gt; {<br>  console.log(&quot;Chart clicked!&quot;);<br>}, []); </pre><h3>useMemo: Caching Expensive Calculations</h3><p>While useCallback caches functions, useMemo caches values. It is ideal for computationally heavy operations, like filtering massive arrays.</p><pre>const Dashboard = ({ users, filterString }) =&gt; {<br>  const filteredUsers = useMemo(() =&gt; {<br>    console.log(&quot;Running expensive filter...&quot;);<br>    return users.filter(user =&gt; user.name.includes(filterString));<br>  }, [users, filterString]); <br><br>  return &lt;UserList users={filteredUsers} /&gt;;<br>};</pre><p><strong>Warning:</strong> Do not use useMemo for simple operations like adding two numbers or mapping over an array of 5 items. The memory overhead of useMemo itself is heavier than the calculation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5p3Ga_s_g-pJJZ-Ni2KtUA.png" /></figure><h3>4. Code Splitting and Lazy Loading</h3><p>If you use Create React App or standard Vite configurations, your entire application is bundled into one massive JavaScript file (e.g., main.bundle.js). If a user visits your &quot;Login&quot; page, they are also downloading the JavaScript for the &quot;Admin Dashboard&quot;, &quot;Billing Settings&quot;, and &quot;Heavy Charting Library&quot;.</p><p>This crushes your Initial Load Time and Time to Interactive (TTI) metrics.</p><h3>Enter React.lazy and Suspense</h3><p>Code splitting allows you to split your bundle into smaller chunks that are only loaded when needed. The most effective way to do this is <strong>Route-Based Code Splitting</strong>.</p><p>Instead of importing all pages at the top of your router:</p><pre>import LoginPage from &#39;./pages/Login&#39;;<br>import AdminDashboard from &#39;./pages/AdminDashboard&#39;;</pre><p>Use dynamic imports with React.lazy:</p><pre>import React, { Suspense, lazy } from &#39;react&#39;;<br><br>const LoginPage = lazy(() =&gt; import(&#39;./pages/Login&#39;));<br>const AdminDashboard = lazy(() =&gt; import(&#39;./pages/AdminDashboard&#39;));<br><br>const App = () =&gt; (<br>  &lt;Suspense fallback={&lt;LoadingSpinner /&gt;}&gt;<br>    &lt;Routes&gt;<br>      &lt;Route path=&quot;/&quot; element={&lt;LoginPage /&gt;} /&gt;<br>      &lt;Route path=&quot;/admin&quot; element={&lt;AdminDashboard /&gt;} /&gt;<br>    &lt;/Routes&gt;<br>  &lt;/Suspense&gt;<br>);</pre><p>Now, the JavaScript for the Admin Dashboard will only be fetched over the network when the user actually navigates to /admin.</p><h3>5. Managing Complex UI State Cleanly</h3><p>Poor state management is the number one cause of performance issues in React.</p><h3>The React Context API Trap</h3><p>The Context API is fantastic for dependency injection (like Themes or user auth status), but it is terrible for rapidly changing state.</p><p>If you put a rapidly changing value (like a mouse position or an active text input) into a global Context provider, <strong>every single component that consumes that context will re-render</strong> on every keystroke, even if they only care about a different value in that context.</p><p><strong>How to fix it:</strong></p><ol><li><strong>Split your Contexts:</strong> Do not have one massive GlobalAppContext. Split it into AuthContext, ThemeContext, and FormContext.</li><li><strong>Use Atomic State Libraries:</strong> If you have highly dynamic UI state, abandon Context and use libraries like <strong>Zustand</strong> or <strong>Jotai</strong>. Zustand allows components to subscribe to a specific slice of the global state, meaning they only re-render when that specific slice changes.</li></ol><pre>import { create } from &#39;zustand&#39;;<br><br>const useStore = create((set) =&gt; ({<br>  bearCount: 0,<br>  nutCount: 0,<br>  increaseBears: () =&gt; set((state) =&gt; ({ bearCount: state.bearCount + 1 })),<br>}));<br><br>const BearCounter = () =&gt; {<br>  const bears = useStore((state) =&gt; state.bearCount); <br>  return &lt;h1&gt;{bears} around here ...&lt;/h1&gt;;<br>};</pre><h3>State Colocation (Move State Down)</h3><p>Before reaching for global state, ask yourself: <em>Does this state need to be global?</em></p><p>If you have a modal window that opens and closes, do not put isModalOpen in Redux or Zustand. Keep it inside the specific component where the modal lives. This is called <strong>State Colocation</strong>. By moving state as low down the component tree as possible, you drastically reduce the number of components affected by state changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suQPQ-ZQv0ddw9DZvAExLQ.png" /></figure><h3>6. List Virtualization (Windowing)</h3><p>Rendering a list of 50 items is fine. Rendering a list of 10,000 items (like a giant data table or an endless social media feed) will crash the browser tab. The browser simply cannot handle that many DOM nodes simultaneously.</p><p><strong>Virtualization</strong> is the technique of rendering only the items that are currently visible on the screen. If you have 10,000 rows, but the user’s screen can only fit 20, virtualization tools ensure that only 20 &lt;div&gt; elements exist in the DOM. As the user scrolls, the data inside those 20 &lt;div&gt; elements is dynamically swapped out.</p><p>Use industry-standard libraries like react-window or react-virtuoso for this.</p><pre>import { FixedSizeList as List } from &#39;react-window&#39;;<br><br>const GiantList = ({ items }) =&gt; (<br>  &lt;List<br>    height={500} // The height of the scrolling container<br>    itemCount={items.length} // 10,000<br>    itemSize={35} // Height of a single row<br>    width={300}<br>  &gt;<br>    {({ index, style }) =&gt; (<br>      &lt;div style={style}&gt;<br>        Row {index}: {items[index].name}<br>      &lt;/div&gt;<br>    )}<br>  &lt;/List&gt;<br>);</pre><p>This single change can take a page from being completely frozen to buttery-smooth 60fps scrolling.</p><h3>7. Non-Blocking UIs with Concurrent React (React 18+)</h3><p>Modern React introduced Concurrent Mode features, specifically useTransition and useDeferredValue, which allow you to tell React: <em>&quot;This state update is not urgent. Keep the UI responsive, and do this heavy calculation in the background.&quot;</em></p><p>Imagine an autocomplete search bar filtering a massive list. As the user types “A… p… p… l… e”, you want the input field to update instantly so it doesn’t feel laggy, but the filtering of the list can happen a split-second later.</p><pre>import { useState, useTransition } from &#39;react&#39;;<br><br>const SearchComponent = ({ data }) =&gt; {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const [filteredData, setFilteredData] = useState(data);<br>  const [isPending, startTransition] = useTransition();<br><br>  const handleChange = (e) =&gt; {<br>    const value = e.target.value;<br>    <br>    setQuery(value); <br><br>    startTransition(() =&gt; {<br>      const results = data.filter(item =&gt; item.includes(value));<br>      setFilteredData(results);<br>    });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input value={query} onChange={handleChange} /&gt;<br>      {isPending ? &lt;p&gt;Loading results...&lt;/p&gt; : &lt;List items={filteredData} /&gt;}<br>    &lt;/div&gt;<br>  );<br>};</pre><p>By wrapping the heavy state update in startTransition, React yields control back to the browser so it can process the user&#39;s typing animation without freezing.</p><h3>Conclusion</h3><p>React performance optimization is not about applying every single trick to every component. It is a targeted, surgical process.</p><ol><li>Use the <strong>React Profiler</strong> to find the actual bottlenecks.</li><li>Use <strong>Code Splitting (</strong><strong>React.lazy)</strong> to reduce initial load times.</li><li>Implement <strong>State Colocation</strong> and atomic state management (Zustand) to prevent widespread re-renders.</li><li>Use React.memo, useCallback, and useMemo defensively to protect heavy components from unwanted renders.</li><li>Use <strong>Virtualization</strong> for massive lists.</li></ol><p>By mastering these techniques, you elevate yourself from a developer who simply makes React applications <em>work</em>, to a software engineer who builds enterprise-grade applications that perform flawlessly at scale.</p><p><em>If you found this guide valuable, save it for your next performance auditing session and share it with your frontend team!</em></p><h3><strong>References &amp; Further Reading:</strong></h3><blockquote><strong><em>React Official Documentation: Optimizing Performance:</em></strong><em> The ultimate source of truth for understanding React’s rendering behavior and the Profiler API.<br></em><a href="https://react.dev/reference/react/Profiler"><em>React Docs: Profiler</em></a></blockquote><blockquote><strong><em>Understanding </em></strong><strong><em>useMemo and </em></strong><strong><em>useCallback:<br></em></strong><a href="https://react.dev/reference/react/useCallback"><em>React Docs: useCallback</em></a></blockquote><blockquote><strong><em>List Virtualization:</em></strong><em> Render massive datasets efficiently without freezing the DOM.<br></em><a href="https://github.com/bvaughn/react-window"><em>react-window Official GitHub</em></a></blockquote><blockquote><strong><em>Atomic State Management:</em></strong><em> Move away from React Context for rapidly changing state.<br></em><a href="https://github.com/pmndrs/zustand"><em>Zustand Documentation</em></a></blockquote><blockquote><strong><em>Concurrent React (</em></strong><strong><em>useTransition):<br></em></strong><a href="https://react.dev/reference/react/useTransition"><em>React Docs: useTransition</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60d6c48dbef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An In-Depth Guide to Machine Learning: From Fundamental Concepts to Your First Model]]></title>
            <link>https://medium.com/@kasunnadeera100/an-in-depth-guide-to-machine-learning-from-fundamental-concepts-to-your-first-model-53db7d1dccb6?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/53db7d1dccb6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Sat, 02 May 2026 17:52:32 GMT</pubDate>
            <atom:updated>2026-05-02T17:52:32.504Z</atom:updated>
            <content:encoded><![CDATA[<p>Demystifying the algorithms, exploring real-world applications, and writing your very first machine learning model from scratch using modern Python frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMe8d9o1UOFnLBFK108-9g.png" /></figure><p>For decades, the standard paradigm of software engineering was strictly rule-based. Developers wrote explicit instructions — if/else statements, loops, and logic gates — that took input data and produced an output. You provided the rules and the data, and the computer gave you the answers.</p><p>Machine Learning (ML) completely flips this paradigm. Instead of providing the rules, you provide the computer with the data and the answers, and the computer figures out the rules.</p><p>Today, Machine Learning is no longer a niche academic discipline; it is the underlying engine powering the modern web, enterprise software, and our daily digital experiences. From the recommendation algorithms on YouTube and Netflix to autonomous driving systems and advanced medical diagnostics, ML is everywhere.</p><p>Whether you are a traditional software engineer looking to pivot into Data Science, or a tech enthusiast wanting to understand the magic behind Artificial Intelligence, this comprehensive guide will demystify the core concepts of Machine Learning, explore its applications, and walk you through building your very first predictive model from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noGfeaoNTPU10tJH16oo-w.png" /></figure><h3>Part 1: The Core Paradigms of Machine Learning</h3><p>Machine Learning is a broad field, but almost all algorithms can be categorized into three primary learning paradigms based on how they interact with data.</p><h3>1. Supervised Learning</h3><p>Supervised learning is the most common and widely implemented form of machine learning. In this approach, the algorithm is trained on a <strong>labeled dataset</strong>. This means that every piece of training data comes with the correct answer (the label). The model’s goal is to learn the mapping function from the input to the output so it can predict the labels for new, unseen data.</p><p>Supervised learning is further divided into two types:</p><ul><li><strong>Classification:</strong> The output variable is a category or a discrete class. For example, an algorithm trained on thousands of emails labeled as “Spam” or “Not Spam.” When a new email arrives, the model classifies it into one of these two buckets. Other examples include image recognition (identifying if a picture is a cat or a dog) or medical diagnosis (malignant vs. benign tumors).</li><li><em>Common Algorithms:</em> Logistic Regression, Support Vector Machines (SVM), Decision Trees, Random Forests.</li><li><strong>Regression:</strong> The output variable is a continuous numerical value. For example, predicting the price of a house based on its square footage, number of bedrooms, and location. Because the price can be any real number, it is a regression problem.</li><li><em>Common Algorithms:</em> Linear Regression, Ridge/Lasso Regression, Gradient Boosting.</li></ul><h3>2. Unsupervised Learning</h3><p>In unsupervised learning, the algorithm is fed <strong>unlabeled data</strong>. The system is not told what the “right answer” is. Instead, its job is to explore the data and find hidden patterns, structures, or relationships on its own.</p><ul><li><strong>Clustering:</strong> The algorithm groups similar data points together based on their inherent characteristics. A classic example is customer segmentation in e-commerce. You feed the model raw purchasing data, and it groups customers into distinct clusters (e.g., “bargain hunters,” “frequent buyers,” “seasonal shoppers”) without you ever defining those categories beforehand.</li><li><em>Common Algorithms:</em> K-Means Clustering, Hierarchical Clustering, DBSCAN.</li><li><strong>Dimensionality Reduction:</strong> This technique reduces the number of random variables under consideration by obtaining a set of principal variables. It is crucial for visualizing high-dimensional data and compressing data while retaining its core mathematical meaning.</li><li><em>Common Algorithms:</em> Principal Component Analysis (PCA), t-SNE.</li></ul><h3>3. Reinforcement Learning</h3><p>Reinforcement learning operates on a system of rewards and punishments. You have an <strong>Agent</strong> that takes actions within an <strong>Environment</strong> to achieve a specific goal. Every action yields a state change and a <strong>Reward</strong> (positive or negative). Over millions of iterations, the agent learns to maximize its cumulative reward.</p><p>This is how computers learned to beat human world champions at chess and Go (AlphaGo), and it is heavily used in robotics and autonomous vehicle navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gKZXe60N58ut0-A9mTfPA.png" /></figure><h3>Part 2: Real-World Applications Powering the Modern Era</h3><p>To truly appreciate Machine Learning, we must look at how it solves complex, real-world problems that traditional programming simply cannot handle.</p><ul><li><strong>Financial Fraud Detection:</strong> Billions of credit card transactions occur daily. Writing if/else rules to catch fraud is impossible. Instead, ML models analyze transaction patterns in real-time. If you suddenly buy a $5,000 watch in another country while your phone&#39;s GPS shows you are at home, a classification model flags the transaction as an anomaly and blocks it instantly.</li><li><strong>Healthcare and Diagnostics:</strong> Deep Learning models (a specialized subset of ML using neural networks) are now outperforming human radiologists at detecting early-stage tumors in X-rays and MRI scans. By analyzing pixel patterns across millions of medical images, these models identify microscopic abnormalities invisible to the human eye.</li><li><strong>Natural Language Processing (NLP):</strong> From basic sentiment analysis on Twitter to advanced Large Language Models (LLMs) like ChatGPT, ML enables computers to understand, interpret, and generate human language, revolutionizing customer support and content creation.</li><li><strong>Predictive Maintenance:</strong> In manufacturing, ML models analyze sensor data (temperature, vibration, acoustic signals) from factory machines to predict exactly when a machine is likely to fail, allowing for maintenance <em>before</em> a costly breakdown occurs.</li></ul><h3>Part 3: The Machine Learning Lifecycle (The Pipeline)</h3><p>A common misconception among junior developers is that Machine Learning is mostly about writing the algorithm. In reality, writing the model code is often the shortest part of the process. The standard ML lifecycle consists of several crucial steps:</p><ol><li><strong>Data Collection:</strong> Gathering raw data from databases, APIs, or scraping the web. Data is the fuel; poor data yields poor models (“Garbage In, Garbage Out”).</li><li><strong>Data Preprocessing &amp; Cleaning:</strong> This is where data scientists spend 70% of their time. It involves handling missing values, removing duplicates, and scaling numerical features (so a feature measured in thousands doesn’t mathematically overpower a feature measured in decimals).</li><li><strong>Feature Engineering:</strong> Transforming raw data into meaningful inputs. For example, extracting the “Day of the Week” from a raw datetime timestamp because consumer behavior changes on weekends.</li><li><strong>Model Selection &amp; Training:</strong> Choosing the right algorithm based on the problem type and training it using historical data.</li><li><strong>Evaluation:</strong> Testing the model against data it has never seen before to ensure it hasn’t just memorized the training data (a problem known as <em>overfitting</em>).</li><li><strong>Deployment &amp; Monitoring:</strong> Wrapping the model in an API (using Flask, FastAPI, or Spring Boot) and deploying it to the cloud so frontend applications can consume its predictions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qn5zOkXmPWswSevhPmfehg.png" /></figure><h3>Part 4: Building Your First Model from Scratch</h3><p>Enough theory. Let us build a real Machine Learning model.</p><p>We will solve a classic <strong>Supervised Learning Classification</strong> problem: Predicting whether a patient has breast cancer (Malignant or Benign) based on the physical measurements of cell nuclei from digitized images.</p><p>We will use <strong>Python</strong>, the undisputed king of ML languages, alongside <strong>Scikit-Learn</strong>, the industry-standard library for traditional machine learning.</p><p><em>(Prerequisites: Ensure you have Python installed, and run </em><em>pip install pandas scikit-learn in your terminal).</em></p><h3>Step 1: Loading the Data</h3><p>Scikit-Learn comes with several built-in datasets for practice. We will load the Breast Cancer dataset.</p><pre>import pandas as pd<br>from sklearn.datasets import load_breast_cancer<br><br># Load the dataset<br>data = load_breast_cancer()<br><br># Convert it to a Pandas DataFrame for easier manipulation<br>df = pd.DataFrame(data.data, columns=data.feature_names)<br><br># Add the target label (0 = malignant, 1 = benign)<br>df[&#39;target&#39;] = data.target<br><br>print(df.head())</pre><h3>Step 2: Splitting the Data</h3><p>We cannot train our model on all our data and then test it on that same data. That would be like giving a student the exam paper to study from the night before the test; they would get a 100%, but they haven’t actually learned the subject.</p><p>We must split our data into a <strong>Training Set</strong> (to teach the model) and a <strong>Testing Set</strong> (to evaluate it).</p><pre>from sklearn.model_selection import train_test_split<br><br># X contains our features (the cell measurements)<br>X = df.drop(&#39;target&#39;, axis=1)<br><br># y contains our labels (the answers)<br>y = df[&#39;target&#39;]<br><br># Split 80% for training, 20% for testing<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br>print(f&quot;Training data size: {X_train.shape}&quot;)<br>print(f&quot;Testing data size: {X_test.shape}&quot;)</pre><h3>Step 3: Selecting and Training the Model</h3><p>For this classification task, we will use a <strong>Random Forest Classifier</strong>. An individual “Decision Tree” algorithm makes decisions by asking a series of yes/no questions about the data. A “Random Forest” builds hundreds of these trees and averages their predictions, making it incredibly accurate and resistant to overfitting.</p><pre>from sklearn.ensemble import RandomForestClassifier<br><br># Initialize the model<br># random_state ensures reproducibility (we get the same results every time)<br>model = RandomForestClassifier(n_estimators=100, random_state=42)<br><br># Train the model! This is where the machine &quot;learns&quot; the patterns.<br>model.fit(X_train, y_train)<br><br>print(&quot;Model training complete.&quot;)</pre><h3>Step 4: Making Predictions</h3><p>Now that our model understands the mathematical relationship between cell measurements and cancer diagnoses, let us ask it to predict the outcomes for our hidden Testing Set.</p><pre># Pass the hidden test features into the model<br>predictions = model.predict(X_test)</pre><h3>Step 5: Evaluating the Model</h3><p>How well did it do? We will calculate its accuracy and generate a classification report.</p><pre>from sklearn.metrics import accuracy_score, classification_report<br><br># Compare the model&#39;s predictions against the actual hidden answers<br>accuracy = accuracy_score(y_test, predictions)<br><br>print(f&quot;Model Accuracy: {accuracy * 100:.2f}%\n&quot;)<br>print(&quot;Detailed Classification Report:&quot;)<br>print(classification_report(y_test, predictions, target_names=data.target_names))</pre><p><strong>The Output:</strong> When you run this code, you will likely see an accuracy of around <strong>96%</strong>.</p><p>Think about what you just achieved. With fewer than 20 lines of code, you built a system capable of looking at raw numerical data regarding human cells and accurately predicting whether those cells represent a malignant tumor with 96% accuracy. No explicit medical rules were programmed; the machine learned the rules entirely from historical data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QuctbYC7YjyYp8Wq27TqQ.png" /></figure><h3>Part 5: The Modern ML Landscape and Frameworks</h3><p>While Scikit-Learn is fantastic for foundational machine learning, the industry has expanded massively into Deep Learning and Neural Networks. As you continue your journey, you will encounter these heavyweights:</p><ol><li><strong>TensorFlow / Keras:</strong> Developed by Google, this is an end-to-end open-source platform for building deep learning models, particularly neural networks used for image recognition and complex numerical predictions.</li><li><strong>PyTorch:</strong> Developed by Meta (Facebook), PyTorch has become the absolute favorite among researchers and modern data scientists due to its dynamic computational graph, making it incredibly “Pythonic” and easy to debug.</li><li><strong>Hugging Face:</strong> If you are interested in NLP (Natural Language Processing) and LLMs, Hugging Face is the modern Github for AI. It provides access to thousands of pre-trained state-of-the-art models (like Llama, BERT, and GPT variants) that you can download and integrate into your applications with three lines of code.</li></ol><h3>Conclusion</h3><p>Machine Learning can initially feel like an overwhelming mountain of complex mathematics, statistics, and foreign terminology. However, as we have seen in this guide, the foundational concepts are highly logical, and modern frameworks abstract away the heaviest mathematical lifting.</p><p>The true art of Machine Learning does not lie in memorizing algorithms. It lies in understanding your data, formulating the right questions, and knowing which tools to apply to extract actionable intelligence.</p><p>As software engineers, adding Machine Learning to your toolkit transitions you from building applications that simply store and retrieve data, to building applications that <em>understand</em> and <em>predict</em>.</p><p>Start small. Copy the code above, run it in a Jupyter Notebook, tweak the parameters, and watch the accuracy change. The best way to learn Machine Learning is to get your hands dirty with the data.</p><p><em>Welcome to the future of software engineering.</em></p><h3>References &amp; Further Reading</h3><blockquote><strong>Scikit-Learn Official Documentation:</strong> The definitive guide to the machine learning library used in this tutorial, featuring excellent explanations of underlying algorithms.<br><a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">Scikit-Learn Docs: Random Forest Classifier</a></blockquote><blockquote><strong>“Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow” by Aurélien Géron:</strong> Widely considered the best practical book for developers transitioning into Machine Learning.<br><a href="https://www.oreilly.com/library/view/hands-on-machine-learning/9781098125967/">O’Reilly Book Link</a></blockquote><blockquote><strong>Introduction to Machine Learning Paradigms:</strong> A deeper dive into the mathematics and theory behind Supervised, Unsupervised, and Reinforcement Learning.<br><a href="https://www.coursera.org/specializations/machine-learning-introduction">Coursera: Machine Learning Specialization by Andrew Ng</a></blockquote><blockquote><strong>Modern Deep Learning Frameworks:<br></strong><a href="https://pytorch.org/tutorials/">PyTorch Official Tutorials</a><br><a href="https://www.tensorflow.org/tutorials">TensorFlow Crash Course</a></blockquote><blockquote><strong>Hugging Face:</strong> The modern hub for open-source AI models and Natural Language Processing.<br><a href="https://huggingface.co/models">Hugging Face Models</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53db7d1dccb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication Done Right: Common Mistakes and Best Practices]]></title>
            <link>https://medium.com/@kasunnadeera100/jwt-authentication-done-right-common-mistakes-and-best-practices-9d1e01a6485a?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d1e01a6485a</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 09:30:43 GMT</pubDate>
            <atom:updated>2026-04-22T09:30:43.188Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A definitive guide to securing modern web applications, understanding token mechanics, and building enterprise-grade authentication architectures.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8AsF875DJJBVGU3FmdxFnw.png" /></figure><p>In the landscape of modern web development, particularly when building Single Page Applications (SPAs) and robust microservices, <strong>JSON Web Tokens (JWT)</strong> have become the de facto standard for handling user authentication. They are lightweight, highly scalable, and fundamentally stateless, making them an incredibly attractive option for developers.</p><p>However, despite their ubiquitous adoption, JWTs are frequently misunderstood and notoriously poorly implemented. From junior developers building their first application to senior engineers architecting large-scale enterprise systems, the fundamental security principles surrounding JWTs are often compromised for the sake of convenience.</p><p>When implemented incorrectly, a JWT-based authentication system is practically an open door for malicious actors. In this comprehensive guide, we will demystify JWTs. We will dive deep into the most common — and catastrophic — security mistakes developers make, explore the theoretical attack vectors these flaws open up, and finally, outline a robust, enterprise-grade blueprint for getting JWT authentication right.</p><h3>Part 1: Demystifying the JSON Web Token</h3><p>Before we can secure a system, we must understand how it operates under the hood. A common misconception is that a JWT is a highly encrypted, impenetrable black box. In reality, a standard JWT is not encrypted at all; it is merely encoded.</p><p>Defined by RFC 7519, a JWT is a compact, URL-safe means of representing claims to be transferred between two parties. It consists of three distinct parts separated by dots (.):</p><ol><li><strong>The Header:</strong> This section typically consists of two parts: the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 (HS256) or RSA (RS256).</li><li><strong>The Payload:</strong> This is the heart of the token, containing the “claims.” Claims are statements about an entity (typically, the user) and additional metadata (like expiration time and user roles).</li><li><strong>The Signature:</strong> To create the signature, the issuing server takes the encoded header, the encoded payload, a secret key, and the algorithm specified in the header, and signs them together.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vRckB7wOQl3bn6zB8O9Sw.png" /></figure><p>The resulting string looks like xxxxx.yyyyy.zzzzz. Because the Header and Payload are merely Base64Url encoded, anyone who intercepts the token can easily decode and read the contents. The security of a JWT relies entirely on the <strong>Signature</strong>. If a malicious actor alters the payload, the signature will no longer match, and the server will reject the token—provided the server is verifying it correctly.</p><h3>Part 2: The Fatal Flaws — Common Mistakes in JWT Implementation</h3><p>The inherent design of JWTs makes them secure against tampering, but the way we store, transport, and validate them is where vulnerabilities arise. Let us examine the most common mistakes that plague modern web applications.</p><h3>Mistake 1: Storing Tokens in localStorage or sessionStorage</h3><p>This is arguably the most prevalent mistake in frontend development today. When a user successfully logs in, the backend sends back a JWT, and the frontend developer promptly saves it using localStorage.setItem(&#39;token&#39;, jwt).</p><p><strong>The Security Flaw: Cross-Site Scripting (XSS)</strong> localStorage and sessionStorage are directly accessible via JavaScript. If your application suffers from a Cross-Site Scripting (XSS) vulnerability—which can happen if you render user-generated content without sanitizing it, or if a third-party NPM package is compromised—an attacker can easily extract the token. Once the attacker has the token, they can completely impersonate the user until it expires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbfW1LlS_bgSrLIvae4HBw.png" /></figure><h3>Mistake 2: Issuing Immortal or Long-Lived Access Tokens</h3><p>To avoid the friction of forcing users to log in repeatedly, developers sometimes set the exp (expiration) claim of an Access Token to a dangerously long duration (e.g., expiresIn: &#39;365d&#39;).</p><p><strong>The Security Flaw: The Stateless Trap</strong> The primary benefit of a JWT is that it is stateless. The server does not need to query a database to verify the token; it simply checks the signature and the expiration date. If you issue an access token that is valid for 30 days, an attacker who steals that token has a 30-day window to wreak havoc on your system.</p><h3>Mistake 3: Leaking Sensitive Data in the Payload</h3><p>Because JWTs are Base64Url encoded and not encrypted, anyone can paste a JWT into a site like jwt.io and read the payload. If you store personally identifiable information (PII) such as home addresses or plain-text passwords in the JWT payload, you are publicly exposing sensitive data.</p><h3>Part 3: The Enterprise-Grade Blueprint — Best Practices</h3><p>Now that we understand the pitfalls, let us construct a highly secure, scalable authentication architecture. Implementing these best practices will elevate your application from a vulnerable target to a robust, enterprise-grade system.</p><h3>Practice 1: The HttpOnly Cookie Vault</h3><p>To completely mitigate the risk of XSS attacks stealing your JWTs, you must abandon localStorage. Instead, instruct your backend to send the JWT to the client via an <strong>HttpOnly Cookie</strong>.</p><p>When a cookie is marked with the HttpOnly flag, the browser prevents client-side JavaScript from accessing it. Even if your site suffers a severe XSS injection, the attacker&#39;s script cannot read the token. Furthermore, secure the cookie with SameSite=Strict to prevent Cross-Site Request Forgery (CSRF) and set the Secure flag to true to enforce HTTPS.</p><h3>Practice 2: Dual Token Architecture (Short-Lived Access + Refresh Tokens)</h3><p>To solve the “Immortal Token” problem while maintaining an excellent User Experience (UX), implement a Dual Token Architecture.</p><ol><li><strong>The Access Token:</strong> Sent with every API request. Its lifespan must be extremely short — typically between 10 to 15 minutes.</li><li><strong>The Refresh Token:</strong> Used solely to obtain a new Access Token from a dedicated /api/refresh endpoint. It has a longer lifespan (e.g., 7 days).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrvaVSrf4FGPQM-XYOzP8g.png" /></figure><h3>Practice 3: Refresh Token Rotation</h3><p>If a Refresh Token is stolen, the attacker can generate endless Access Tokens. To mitigate this, implement <strong>Refresh Token Rotation</strong>. Every time a user uses a Refresh Token to get a new Access Token, the server must invalidate the old Refresh Token and issue a brand new one. If the server detects the reuse of an old Refresh Token, it should immediately revoke all tokens for that user.</p><h3>Practice 4: Token Revocation Using a Redis Blacklist</h3><p>Because JWTs are stateless, forcing a user to log out is challenging. The most efficient way to handle immediate token revocation is to introduce an in-memory database like <strong>Redis</strong>. When a user logs out, you extract the token’s unique identifier (jti claim) and store it in a Redis &quot;blacklist.&quot; On every protected API request, an authorization middleware checks if the token&#39;s jti exists in the Redis blacklist.</p><h3>Practice 5: Transition to Asymmetric Encryption (RS256)</h3><p>If you are building a microservices architecture, using a symmetric algorithm like HS256 (where the same secret key signs and verifies the token) becomes a security liability.</p><p>Instead, utilize <strong>RS256</strong>, an asymmetric algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N923mwRU2O3Bu67nlzNmqQ.png" /></figure><p>The Authentication Service uses a highly secure Private Key to sign the tokens. It then exposes a Public Key to all other microservices. The microservices can use this Public Key to verify the token’s signature, but they cannot generate new tokens.</p><h3>Part 4: Practical Implementation in the Modern Stack</h3><p>To ground these concepts in reality, let us look at how this looks in a MERN stack environment utilizing Node.js (Express) and React.</p><h3>The Backend: Setting the HttpOnly Cookies (Node.js/Express)</h3><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br><br>exports.login = async (req, res) =&gt; {<br>    const user = await authenticateUser(req.body.email, req.body.password);<br><br>    const accessToken = jwt.sign({ userId: user._id, role: user.role }, process.env.ACCESS_SECRET, { expiresIn: &#39;15m&#39; });<br>    const refreshToken = jwt.sign({ userId: user._id }, process.env.REFRESH_SECRET, { expiresIn: &#39;7d&#39; });<br><br>    res.cookie(&#39;accessToken&#39;, accessToken, {<br>        httpOnly: true,<br>        secure: process.env.NODE_ENV === &#39;production&#39;,<br>        sameSite: &#39;Strict&#39;,<br>        maxAge: 15 * 60 * 1000 // 15 minutes<br>    });<br><br>    res.cookie(&#39;refreshToken&#39;, refreshToken, {<br>        httpOnly: true,<br>        secure: process.env.NODE_ENV === &#39;production&#39;,<br>        sameSite: &#39;Strict&#39;,<br>        path: &#39;/api/auth/refresh&#39;, // ONLY sent to the refresh endpoint<br>        maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days<br>    });<br><br>    res.status(200).json({ success: true, message: &#39;Authentication successful&#39; });<br>};</pre><h3>The Frontend: Silent Refresh with Interceptors (React/Axios)</h3><p>Using Axios interceptors is the standard approach to gracefully handle expired Access Tokens without disrupting the UI.</p><pre>import axios from &#39;axios&#39;;<br><br>const api = axios.create({<br>    baseURL: &#39;https://api.yourdomain.com&#39;,<br>    withCredentials: true <br>});<br><br>api.interceptors.response.use(<br>    (response) =&gt; response,<br>    async (error) =&gt; {<br>        const originalRequest = error.config;<br><br>        if (error.response.status === 401 &amp;&amp; !originalRequest._retry) {<br>            originalRequest._retry = true;<br><br>            try {<br>                await axios.post(&#39;https://api.yourdomain.com/api/auth/refresh&#39;, {}, { withCredentials: true });<br>                <br>                return api(originalRequest);<br>            } catch (refreshError) {<br>                window.location.href = &#39;/login&#39;;<br>                return Promise.reject(refreshError);<br>            }<br>        }<br>        return Promise.reject(error);<br>    }<br>);<br><br>export default api;</pre><h3>Conclusion</h3><p>Authentication is the fortress wall of your application; it is not the place to cut corners. While JSON Web Tokens offer a beautifully scalable, stateless solution for distributed systems, they require a deep understanding of security mechanics to implement safely.</p><p>By abandoning localStorage in favor of HttpOnly cookies, implementing a robust dual-token architecture with refresh rotation, enforcing strict signature validation with RS256, and utilizing tools like Redis for token blacklisting, you transform a potentially vulnerable implementation into an enterprise-grade security protocol.</p><p>Review your current codebase today, apply these best practices, and build systems that are secure by design.</p><h3>References &amp; Further Reading</h3><blockquote><strong>RFC 7519: JSON Web Token (JWT):</strong> The official IETF specification defining the JWT standard. <a href="https://datatracker.ietf.org/doc/html/rfc7519">Read Specification</a></blockquote><blockquote><strong>OWASP JSON Web Token Security Cheat Sheet:</strong> A comprehensive guide by the Open Worldwide Application Security Project on mitigating JWT vulnerabilities. <a href="https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html">Read Guide</a></blockquote><blockquote><strong>Auth0 Documentation: Token Storage Best Practices:</strong> Industry-standard guidelines on securely storing tokens in Single Page Applications.</blockquote><blockquote><strong>MDN Web Docs: Using HTTP Cookies:</strong> Official documentation on implementing HttpOnly, Secure, and SameSite attributes. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies">Read Docs</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d1e01a6485a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Cognitive Architecture of AI: Why Multi-Agent Systems are Redefining Software Engineering]]></title>
            <link>https://medium.com/@kasunnadeera100/the-cognitive-architecture-of-ai-why-multi-agent-systems-are-redefining-software-engineering-deefa53f5a9e?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/deefa53f5a9e</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 20:46:38 GMT</pubDate>
            <atom:updated>2026-04-02T03:06:35.673Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Moving beyond simple ReAct loops. Exploring the state space of autonomous agents, multi-agent orchestration, and the transition from conversational AI to systemic execution.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JgfLV7wFDgIIoxSAGfLvA.jpeg" /></figure><h3><strong>The Paradigm Shift: From Stateless APIs to Stateful Actors</strong></h3><p>For years, our interaction with Large Language Models (LLMs) was fundamentally stateless and passive. We provided a prompt; the model predicted the next token. If the task required traversing a complex logic tree or interacting with a dynamic environment, the human operator had to act as the orchestrator.</p><p>Today, the frontier of Machine Learning has decisively shifted toward <strong>Agentic Workflows</strong> and <strong>Cognitive Architectures</strong>. We are no longer simply scaling parameter counts; we are wrapping foundational models in robust architectures that provide them with long-term memory, recursive planning capabilities, and unrestricted tool execution.</p><h3><strong>The Anatomy of an Advanced Agentic System</strong></h3><p>To understand why modern agents are so capable, we must look past the LLM itself and examine the control loop. An advanced autonomous agent is not just a model; it is an orchestrator of its own cognitive state.</p><h4>1. Advanced Planning and Reasoning Loops</h4><p>Early agents relied on simple Chain-of-Thought (CoT) or zero-shot tool use. Modern systems utilize frameworks like <strong>ReAct (Reasoning and Acting)</strong>, but scale them up using tree-based search algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bqj4M133Ep2nRA_Hv60lIw.jpeg" /><figcaption>Formal equation and its conceptual flow for an agent operating on a rainy Thursday in Matale, Sri Lanka.</figcaption></figure><p>Advanced agents now use <strong>Tree of Thoughts (ToT)</strong> or even <strong>Monte Carlo Tree Search (MCTS)</strong> to explore multiple reasoning paths simultaneously, simulating the outcome of different tool calls before committing to an action. This significantly reduces the hallucination rate in complex software tasks.</p><h4>2. State Management and Memory Horizons</h4><p>An agent without memory is just a reactive function. Modern architectures segment memory into three tiers:</p><ul><li><strong>Working Memory (Context Window):</strong> Utilizing advanced attention mechanisms to process millions of tokens efficiently, allowing the agent to hold an entire codebase in its immediate context.</li><li><strong>Episodic Memory (Vector RAG):</strong> Storing past executions, successful code snippets, and error logs as high-dimensional vector embeddings in databases like Pinecone or Milvus.</li><li><strong>Semantic Memory (Knowledge Graphs):</strong> Maintaining a structured understanding of the project architecture, API endpoints, and database schemas, preventing the agent from making contradictory changes across a full-stack application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfQDtLbysQ2l7BslIkMtgA.png" /></figure><h3>Multi-Agent Orchestration: The Software Team of the Future</h3><p>The most significant leap forward has been the transition from single, monolithic agents to <strong>Multi-Agent Systems (MAS)</strong>. Frameworks like LangGraph and Microsoft’s AutoGen allow developers to instantiate entire teams of specialized agents.</p><p>Imagine a modern full-stack development workflow — perhaps building a scalable MERN stack application with a Spring Boot microservice backend. A single agent will struggle to maintain the context of the React frontend, the Node/Express middleware, the Java backend, and the database schema simultaneously.</p><p>Instead, a Multi-Agent System deploys a topology of experts:</p><ol><li><strong>The Lead Architect Agent:</strong> Breaks down the user requirement into Jira-style tickets.</li><li><strong>The Frontend Specialist Agent:</strong> Writes the React components and handles UI state.</li><li><strong>The Backend/DevOps Agent:</strong> Writes the Spring Boot controllers, provisions the MongoDB schemas, and writes the Dockerfiles and GitHub Actions YAML for the CI/CD pipeline.</li><li><strong>The QA Agent:</strong> Unrelentingly writes unit tests and attempts to break the code written by the others.</li></ol><p>These agents converse with one another, debate architectural decisions, and pass state back and forth through a shared state graph until the application compiles and passes all tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAh2G1E4QL6HSbfhQoEDbw.jpeg" /></figure><h3>The Hard Problems: What Still Breaks?</h3><p>Despite the rapid acceleration, deploying autonomous agents in production environments carries severe, unresolved challenges:</p><ul><li><strong>Cascading Failures in Long-Horizon Tasks:</strong> Error compounding is the enemy of autonomy. If a DevOps agent makes a subtle error in a Kubernetes configuration file at step 3, and the workflow requires 50 steps, the error will often cascade invisibly until the final deployment crashes.</li><li><strong>Security and Sandboxing:</strong> Giving an LLM access to a terminal to execute shell commands is inherently dangerous. Prompt injection attacks can hijack an agent, turning a helpful coding assistant into a vector for remote code execution (RCE).</li><li><strong>Deterministic Output:</strong> LLMs are probabilistic. Continuous Integration (CI) systems demand deterministic reliability. Forcing agents to strictly adhere to rigid JSON schemas for tool calling remains computationally expensive and brittle.</li></ul><h3>Conclusion</h3><p>We have moved past the era of writing code <em>with</em> AI. We are entering the era of delegating systems <em>to</em> AI. By combining robust multi-agent orchestration, recursive planning algorithms, and advanced state management, we are laying the groundwork for software that writes, deploys, and heals itself. For developers and engineers, the skill is no longer just writing the syntax; it is architecting the agents that write the syntax.</p><h3>References</h3><blockquote><strong>Yao, S., et al. (2022).</strong> <em>Tree of Thoughts: Deliberate Problem Solving with Large Language Models.</em> arXiv preprint. <a href="https://arxiv.org/abs/2305.10601">https://arxiv.org/abs/2305.10601</a></blockquote><blockquote><strong>Yao, S., et al. (2023).</strong> <em>ReAct: Synergizing Reasoning and Acting in Language Models.</em> ICLR. <a href="https://arxiv.org/abs/2210.03629">https://arxiv.org/abs/2210.03629</a></blockquote><blockquote><strong>Wu, Q., et al. (2023).</strong> <em>AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation.</em> arXiv preprint. <a href="https://arxiv.org/abs/2308.08155">https://arxiv.org/abs/2308.08155</a></blockquote><blockquote><strong>LangChain. (2024).</strong> <em>LangGraph: Multi-Actor Stateful Applications with LLMs.</em> LangChain Blog. <a href="https://blog.langchain.dev/langgraph/">https://blog.langchain.dev/langgraph/</a></blockquote><blockquote><strong>Cognition AI. (2024).</strong> <em>Introducing Devin, the first AI software engineer.</em> Cognition Blog. <a href="https://www.cognition.ai/blog/introducing-devin">https://www.cognition.ai/blog/introducing-devin</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deefa53f5a9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Innovation at the Edge: A Retrospective on URSIE 2025]]></title>
            <link>https://medium.com/@kasunnadeera100/innovation-at-the-edge-a-retrospective-on-ursie-2025-21ad20ebe423?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/21ad20ebe423</guid>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 07:45:34 GMT</pubDate>
            <atom:updated>2025-12-27T07:45:34.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWLKUmi07S6lMjbtOxVj4Q.png" /></figure><p>Walking through the corridors of the Faculty of Science at the University of Kelaniya on October 10th, the atmosphere was electric. The Undergraduate Research Symposium &amp; Innovation Exhibition (URSIE 2025) wasn’t just a display of posters; it was a glimpse into how the next generation of scientists plans to tackle Sri Lanka’s most pressing problems.</p><p>While the sheer volume of research presented was overwhelming, a few standout projects caught my attention — ideas that moved beyond textbook theory into the realm of practical, life-saving application. From mathematical ecology to AI-driven wildlife protection and renewable energy, here are the highlights that defined the event for me.</p><h3>1. Mathematics as a Tool for Survival</h3><p>One of the most intriguing intersections of disciplines was found in <strong>Paper ID 07</strong>, titled <em>“Optimal Control for Maximizing Total Population in a Predator-Prey System.”</em></p><p>We often think of mathematics as abstract, but authors <strong>Arachchi C.N.D. and Hasasemeenu W.P.T.</strong> demonstrated how differential equations can effectively manage the delicate balance of our ecosystems.</p><p>The core of their research addressed a critical flaw in traditional ecological models: they often ignore human intervention. By introducing “optimal control theory” — a method usually reserved for engineering — the team modeled how specific interventions (like controlled harvesting or conservation efforts) could maximize a total population over a fixed time.</p><p>Using MATLAB simulations, they provided visual proof (via phase portraits) that a controlled system significantly outperforms a natural, unmonitored one. It was a powerful reminder that math isn’t just about solving for x; it’s about solving for survival.</p><h3>2. Saving Giants on the Railway</h3><p>Perhaps the most heart-wrenching issue addressed at the symposium was the human-elephant conflict, specifically the tragedy of train collisions. A team from the <strong>Department of Physics and Electronics</strong> (Keethipala S.D., Dilshan J.K., et al.) presented a high-tech solution that felt long overdue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1zsAyfniuWeIX992clr_w.png" /></figure><p>Their project, <em>“Elephant Early Warning System in Railway Transport,”</em> proposes a sophisticated, four-stage defense mechanism designed to eliminate the “false alarms” that plague current systems.</p><ul><li><strong>The Trigger:</strong> A Laser-LDR grid set at specific heights to detect the massive scale of an elephant.</li><li><strong>The Eye:</strong> Once triggered, a solar-powered camera activates <strong>YOLOv8 AI</strong>, a computer vision algorithm capable of verifying the animal in milliseconds, even in pitch darkness.</li><li><strong>The Precision:</strong> A radar module then measures the distance to ensure the elephant is actually on the track, not just near it.</li><li><strong>The Alert:</strong> Finally, the system warns the driver and the nearest station automatically.</li></ul><p>It is a perfect example of how hardware and AI can converge to solve a uniquely Sri Lankan tragedy.</p><h3>3. Stabilizing the Sun: The Hybrid Energy Future</h3><p>Finally, as we look toward a greener future, energy reliability remains a hurdle. Solar power is clean, but it is also “intermittent” — clouds pass, and the sun sets. <strong>Paper ID 16</strong>, presented by <strong>Amaraweera T.R. and team</strong>, tackled this head-on with their <em>“Supercapacitor Battery Hybrid PV System.”</em></p><p>The brilliance of their approach lies in acknowledging that no single storage method is perfect. Lithium-ion batteries provide great long-term storage but degrade quickly if forced to handle sudden power spikes. Supercapacitors, on the other hand, handle spikes effortlessly but hold very little energy.</p><p>The team’s prototype merged these two technologies. By using supercapacitors to absorb the initial shock of power fluctuations (transients) and batteries for the steady load, they created a system that is more efficient and longer-lasting than standard off-grid setups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJWLithe8u9JuQJ6fn2oMA.png" /></figure><h3>Conclusion</h3><p>Leaving the B1 building, I realized that URSIE 2025 was more than an academic requirement. Whether it was using control theory to save ecosystems, AI to protect elephants, or hybrid physics to stabilize our power grid, the message was clear: the students of Kelaniya aren’t just observing the world — they are engineering the tools to fix it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21ad20ebe423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First Step into Operating System Development]]></title>
            <link>https://medium.com/@kasunnadeera100/first-step-into-operating-system-development-3657df87d610?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/3657df87d610</guid>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 16:37:58 GMT</pubDate>
            <atom:updated>2025-12-27T06:41:53.132Z</atom:updated>
            <content:encoded><![CDATA[<p>Repository Link: <a href="https://github.com/nadeera-se22018/kasunOS"><strong>https://github.com/nadeera-se22018/kasunOS</strong></a></p><p>Hi! I’m Kasun, a first-year Software Engineering student with a big interest in low-level programming. As a personal project, I wanted to create a very simple operating system using <strong>Assembly language</strong> and test it on <strong>QEMU</strong>.</p><p>This project helped me understand how computers actually boot, how memory works, and how the CPU communicates with hardware. In this article, I’ll briefly share my journey of building this project.</p><h3>Why Assembly?</h3><p>When learning about operating systems, I realized you can either use <strong>C/C++</strong> (with some extra setup) or directly use <strong>Assembly</strong>. I wanted to experience how the system works at the lowest possible level, so I chose Assembly.</p><p>Even though Assembly looks complex, once you understand the structure, it becomes a powerful tool to directly control the hardware.</p><h3>Tools I Used</h3><p>Since I always use <strong>Linux</strong> for development, I installed two important tools:</p><pre>sudo apt install nasm qemu   # (Ubuntu/Debian)<br># or<br>sudo dnf install nasm qemu   # (Fedora/RHEL)</pre><ul><li><strong>NASM</strong> → Assembler to compile Assembly code</li><li><strong>QEMU</strong> → Virtual machine to run and test the OS</li></ul><h3>Bootloader</h3><p>The very first step was writing a <strong>bootloader</strong>. A bootloader is a small piece of code that the BIOS loads into memory right after starting the computer. Its main task is to load the <strong>kernel</strong> into RAM so the OS can start running.</p><p>I studied some examples like <strong>MikeOS</strong> to understand how bootloaders work before writing my own version.</p><h3>Kernel</h3><p>Once the bootloader is done, the kernel is the heart of the OS. My kernel is responsible for:</p><ul><li>Reading hardware information (CPU vendor, CPU brand, memory size, video mode, etc.)</li><li>Displaying information on the screen</li><li>Providing simple commands</li></ul><p>It shows details like:</p><ul><li>CPU vendor &amp; brand</li><li>Video mode</li><li>Conventional and extended memory</li></ul><h3>Automating the Build</h3><p>At first, I had to manually compile and run the OS every time, which was slow. So I wrote two small shell scripts:</p><ul><li><strong>build.sh</strong> → Compiles the Assembly code</li><li><strong>run.sh</strong> → Runs the OS inside QEMU</li></ul><p>Now I can simply run:</p><pre>./build.sh &amp;&amp; ./run.sh</pre><p>And the OS will compile and start instantly .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*Jcsw0BjiHoybWy73lGk1yg.jpeg" /></figure><h3>Commands in My OS</h3><p>Currently, my OS supports only a few basic commands:</p><ul><li>info → Show hardware information</li><li>clear → Clear the screen</li><li>help → Display help menu</li></ul><p>It’s not much compared to modern OS, but for a beginner project, it’s a big step!</p><h3>What I Learned</h3><p>Building this OS taught me:</p><ul><li>How a computer boots from BIOS</li><li>Basics of memory (conventional vs extended)</li><li>Writing low-level Assembly code</li><li>Using QEMU for system testing</li></ul><p>This project gave me a strong foundation to continue exploring OS development and maybe expand KasunOS into something bigger in the future.</p><h3>Final Thoughts</h3><p>This project was challenging but very rewarding. If you are interested in operating systems, I highly recommend starting small with Assembly. You’ll learn a lot about how computers actually work.</p><p>I will continue to improve <strong>KasunOS</strong> and maybe even add features like file handling, keyboard input, and a simple shell.</p><p>✨ Thanks for reading! If you’re curious about low-level programming, give it a try. It’s fun to see your own OS booting on QEMU!</p><blockquote>References</blockquote><blockquote><em>https://medium.com/dev-genius/from-boot-to-kernel-building-a-simple-os-bootloader-with-asm-abb7c1cb3675</em></blockquote><blockquote><em>https://medium.com/@hathibel/how-to-create-an-operating-system-5cec37ecd568</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3657df87d610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the CIA Triad]]></title>
            <link>https://medium.com/@kasunnadeera100/understanding-the-cia-triad-f7c2634fbc1d?source=rss-5b92357c2c14------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7c2634fbc1d</guid>
            <dc:creator><![CDATA[Kasun Nadeera]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 09:55:56 GMT</pubDate>
            <atom:updated>2024-07-17T09:55:56.267Z</atom:updated>
            <content:encoded><![CDATA[<p>The CIA Triad is a fundamental concept in cybersecurity that serves as the cornerstone for protecting sensitive information. In this article, we’ll explore <strong>what the CIA Triad is, why it’s crucial, when to apply it, and some real world scenarios where it makes a difference.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvB9OuGmnuH7he48pQFdDw.png" /></figure><p>The CIA Triad consists of <strong>three core principles</strong>.</p><ol><li>Confidentiality - Ensuring that information is kept secret from unauthorized parties.</li><li>Integrity - Maintaining the accuracy and consistency of data throughout its lifecycle.</li><li>Availability - Guaranteeing that authorized users can access information when needed.</li></ol><p>These principles work together to form a comprehensive approach to information security.</p><p><strong><em>Why Should You Use the CIA Triad?</em></strong></p><p>The CIA Triad provides a simple yet powerful framework for,</p><ol><li>Assessing security risks</li><li>Developing security policies</li><li>Designing secure systems</li><li>Evaluating existing security measures</li></ol><p>By focusing on these three key areas, organizations can create a robust security posture that addresses the most critical aspects of information protection.</p><p><strong><em>When Should You Use the CIA Triad?</em></strong></p><p>The CIA Triad should be applied,</p><ol><li>During the planning and design phase of new systems or applications</li><li>When conducting security audits</li><li>While developing incident response plans</li><li>Throughout the lifecycle of data and systems</li></ol><p>Essentially, the CIA Triad should be a constant consideration in all aspects of information security.</p><p><strong><em>Example Scenarios</em></strong></p><p>Let’s explore how the CIA Triad applies in real-world situations:</p><p>1. Healthcare Records</p><ul><li>Confidentiality - Encrypting patient data and limiting access to authorized personnel only.</li><li>Integrity - Using digital signatures to ensure medical records haven’t been tampered with.</li><li>Availability - Implementing redundant systems to ensure healthcare providers can access critical information 24*7.</li></ul><p>2. E-commerce Platforms</p><ul><li>Confidentiality - Securing customer payment information using encryption and tokenization.</li><li>Integrity - Employing checksums to verify that product information and prices hadn’t been altered.</li><li>Availability - Using load balancers and content delivery networks to maintain site accessibility during high traffic periods.</li></ul><p>3. Government Intelligence Agencies</p><ul><li>Confidentiality - Implementing strict access controls and multi factor authentication for classified information.</li><li>Integrity - Using blockchain technology to create tamper evident logs of data access and modifications.</li><li>Availability - Creating geographically distributed backup sites to ensure continuity of operations.</li></ul><p><strong><em>Beyond the Basics</em></strong></p><p>While the CIA Triad forms the foundation of information security, modern cybersecurity practices often expand on this concept. Some additional principles to consider include,</p><ol><li>Non repudiation - Ensuring that a user cannot deny having performed an action.</li><li>Privacy -Protecting personal information and complying with data protection regulations.</li><li>Authentication -Verifying the identity of users or systems.</li></ol><p>The CIA Triad gives a solid foundation for building robust information security practices. By focusing on confidentiality, integrity and availability, organizations can protect their critical assets, maintain trust with customers and partners, and comply with regulatory requirements. Information security is an ongoing process. Regularly review your security measures through the lens of the CIA Triad to ensure your organization stays protected in an ever changing digital landscape.</p><h4><strong>References</strong></h4><blockquote>Principles of Information Security Fourth Edition<br>Fourth Edition<br>Michael E. Whitman, Ph.D., CISM, CISSP Herbert J. Mattord, CISM, CISSP Kennesaw State University<br><a href="https://almuhammadi.com/sultan/sec_books/Whitman.pdf">https://almuhammadi.com/sultan/sec_books/Whitman.pdf</a></blockquote><blockquote>NIST Special Publication 800–12 Rev. 1 (2017). “An Introduction to Information Security.” National Institute of Standards and Technology. <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-12r1.pdf">https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-12r1.pdf</a></blockquote><blockquote>Information Security Policies, Procedures, and Standards,<br>Guidelines for Effective Information Security Management,<br><em>By</em>Thomas R. Peltier<a href="https://www.taylorfrancis.com/books/edit/10.1201/9780849390326/information-security-policies-procedures-standards-thomas-peltier">https://www.taylorfrancis.com/books/edit/10.1201/9780849390326/information-security-policies-procedures-standards-thomas-peltier</a></blockquote><blockquote>Principles of Information Security, 4th edition<br>November 2014 Edition: 4th <br>Publisher: Cengage Learning<br>Authors:<br><a href="https://www.researchgate.net/profile/Michael-Whitman-3">Michael E. Whitman</a><br><a href="https://www.researchgate.net/institution/Kennesaw_State_University?_tp=eyJjb250ZXh0Ijp7ImZpcnN0UGFnZSI6InB1YmxpY2F0aW9uIiwicGFnZSI6InB1YmxpY2F0aW9uIn19">Kennesaw State University</a><a href="https://www.researchgate.net/publication/311574679_Principles_of_Information_Security_4th_edition">https://www.researchgate.net/publication/311574679_Principles_of_Information_Security_4th_edition</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7c2634fbc1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>