<?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 Edberthalim on Medium]]></title>
        <description><![CDATA[Stories by Edberthalim on Medium]]></description>
        <link>https://medium.com/@edberthalim29?source=rss-b9dd4adb03e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*st6s6XiJTyvNC676</url>
            <title>Stories by Edberthalim on Medium</title>
            <link>https://medium.com/@edberthalim29?source=rss-b9dd4adb03e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:03:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edberthalim29/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[Why I Embraced BDD After TDD — and How It Changed the Way I Test My APIs]]></title>
            <link>https://medium.com/@edberthalim29/why-i-embraced-bdd-after-tdd-and-how-it-changed-the-way-i-test-my-apis-77d1fbb3675b?source=rss-b9dd4adb03e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/77d1fbb3675b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[bdd-testing]]></category>
            <category><![CDATA[bdd-development]]></category>
            <dc:creator><![CDATA[Edberthalim]]></dc:creator>
            <pubDate>Tue, 20 May 2025 03:39:27 GMT</pubDate>
            <atom:updated>2025-05-20T03:39:27.511Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I Embraced BDD After TDD — and How It Changed the Way I Test My APIs</h3><p>As developers, we spend a significant portion of our time writing tests. First, to verify functionality. Then, to prevent regressions. And later, to communicate how our system is supposed to behave. At some point, the act of writing tests becomes more than just a technical ritual — it becomes a conversation between us and the system we’re building.</p><p>For a while, I relied heavily on Test-Driven Development (TDD) to guide my design and implementation. It worked. It made me confident about my codebase and pushed me toward modular, testable functions. But something still felt off.</p><p>I realized that while TDD helped me write code that was functionally correct, it didn’t always help me write code that reflected <em>how the user expected it to behave</em>. That’s when I started experimenting with Behavior-Driven Development (BDD).</p><h3>The Limitations of Traditional TDD</h3><p>Don’t get me wrong — TDD is invaluable. It teaches discipline. It encourages small, focused design. It ensures that code exists because there’s a test that requires it.</p><p>But here’s where I started feeling its limitations:</p><ul><li>TDD made me think like a developer, not like a user.</li><li>I was writing tests around the mechanics — function outputs, service responses, edge cases.</li><li>My tests were becoming harder for non-developers (like PMs or QA engineers) to interpret or validate.</li></ul><p>I wanted a way to align technical tests with business expectations. I wanted my test suite to not just <em>verify</em> the system, but to <em>document</em> it in language everyone could understand.</p><p>That’s where BDD came in.</p><h3>What Is BDD and Why I Started Using It</h3><p>Behavior-Driven Development flips the traditional testing mindset. Instead of focusing on units of code, BDD starts with user behavior.</p><p>It asks questions like:</p><ul><li>“What should happen when a user checks the status of an invoice?”</li><li>“What if the invoice doesn’t belong to them?”</li><li>“What response do we expect if no credentials are provided?”</li></ul><p>It’s a shift from internal logic to external expectations.</p><p>The syntax of BDD reinforces this shift. Using Gherkin (Given, When, Then), we describe features in a way that mimics how a user might actually interact with the system.</p><p>And when I started applying this mindset to one of my existing endpoints — the GET /api/invoices/status/:id/ endpoint—I realized just how powerful it could be.</p><h3>The Feature: Fetching Invoice Status</h3><p>The feature was straightforward: a partner should be able to check the status of their invoice to see if it’s been processed.</p><p>In TDD, I would have approached this by unit testing the controller, stubbing the service, and asserting responses. Which I still did. But now, I started with this:</p><pre>Feature: Get Invoice Status<br>  As a partner<br>  I want to check the status of my invoice<br>  So that I can know whether it has been processed successfully</pre><p>This gave me clarity. It grounded the technical implementation in user value.</p><h3>From User Stories to Scenarios</h3><p>Rather than just writing test cases, I began writing <em>scenarios</em>. Each scenario reflected a different real-world context in which a partner might use the endpoint.</p><p>Some examples:</p><h3>Scenario 1: The Happy Path</h3><p>A partner checks the status of a valid invoice they submitted, and it has been successfully analyzed.</p><h3>Scenario 2: Invoice Still Processing</h3><p>The invoice hasn’t finished processing yet, and the system should reflect that honestly.</p><h3>Scenario 3: Invoice Failed</h3><p>The analysis failed — how do we surface this to the user?</p><h3>Scenario 4: Invoice Doesn’t Exist</h3><p>What if the partner sends an invalid ID? Should we just return a 500? Or a meaningful 404?</p><h3>Scenario 5: Invoice Belongs to Someone Else</h3><p>Security is critical. If a partner tries to access an invoice they didn’t submit, we return a 403.</p><h3>Scenario 6: No Authentication</h3><p>If a request comes in without credentials, it shouldn’t proceed at all. That’s an immediate 401.</p><p>Writing these scenarios made me think about my endpoint not just as a function to test — but as a product to deliver.</p><h3>The Tech Stack I Used</h3><p>To bring these BDD tests to life, I integrated the following tools:</p><ul><li><strong>@cucumber/cucumber</strong> for defining features and step definitions</li><li><strong>supertest</strong> for sending HTTP requests and simulating user behavior</li><li><strong>sinon</strong> for mocking external services like authentication and invoice status fetching</li><li><strong>express</strong> for setting up a real test server</li></ul><p>One of the biggest strengths of this setup was the <strong>level of isolation</strong> I could achieve. For each scenario, I stubbed the invoice service and authentication logic. This way, I wasn’t dependent on actual database state or external APIs, which kept the tests fast and deterministic.</p><p>Here’s an excerpt from my setup:</p><pre>Before({ tags: &quot;@getInvoiceStatus&quot; }, function() {<br>  sinon.restore();<br>  <br>  this.invoiceServiceStub = {<br>    getInvoiceStatus: sinon.stub(),<br>    getPartnerId: sinon.stub(),<br>    uploadInvoice: sinon.stub() // still required by controller<br>  }; <br> <br>  this.controller = new InvoiceController({<br>      invoiceService: this.invoiceServiceStub<br>    });<br><br>  sinon.stub(authService, &#39;authenticate&#39;).callsFake(async (req) =&gt; {<br>      return {<br>        uuid: &#39;partner-123&#39;,<br>        client_id: req.headers.client_id,<br>        client_secret: req.headers.client_secret<br>      };<br>    });<br>  });<br>  </pre><p>This setup gave me complete control over the behavior I wanted to test — allowing me to simulate both success and error paths with precision.</p><h3>Writing Tests That Communicate, Not Just Validate</h3><p>One of the unexpected benefits of BDD was how it changed the way I <em>communicated</em> about the code.</p><p>Instead of walking someone through controller logic, I could show them the Gherkin:</p><pre>Scenario: Attempt to get the status without authentication<br>  Given an unauthenticated user for invoice status<br>  When the user requests status for invoice &quot;inv-123&quot;<br>  Then the response status for invoice should be 401<br>  And the response message for invoice should be &quot;Unauthorized: Missing credentials&quot;</pre><p>This wasn’t just a test. It was documentation. A living, testable spec that told everyone — developers, PMs, QA — how the system was expected to behave.</p><h3>The Payoff: Confidence and Clarity</h3><p>So what did I gain by layering BDD on top of my TDD practice?</p><ul><li><strong>Greater confidence in my API</strong> — because I was testing not just code, but expectations.</li><li><strong>Cleaner test architecture</strong> — because scenarios forced me to decouple setup logic from implementation.</li><li><strong>Better team communication</strong> — because Gherkin made tests readable even for non-engineers.</li><li><strong>Reduced ambiguity</strong> — because behaviors were defined up front, not discovered mid-implementation.</li></ul><p>Most importantly, it changed my relationship with testing. It wasn’t something I had to do. It became part of how I designed.</p><h3>Final Thoughts</h3><p>Embracing BDD didn’t mean abandoning TDD. I still write unit tests for utility functions, and still use assertions to validate edge cases. But for critical user-facing features — especially API endpoints where behavior and access control matter — BDD adds another layer of clarity.</p><p>If you’re already practicing TDD and feel like your tests are too focused on the internals, try writing just one feature in Gherkin. You might be surprised by how much it reveals — not just about your code, but about your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77d1fbb3675b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Test Isolation: Mocking and Stubbing for Scalable, High-Quality Testing]]></title>
            <link>https://medium.com/@edberthalim29/mastering-test-isolation-mocking-and-stubbing-for-scalable-high-quality-testing-dbd7aa07fe67?source=rss-b9dd4adb03e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd7aa07fe67</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Edberthalim]]></dc:creator>
            <pubDate>Sun, 18 May 2025 07:05:11 GMT</pubDate>
            <atom:updated>2025-05-18T07:14:31.918Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern backend systems rarely operate in isolation. They interact with a multitude of services — databases, external APIs, cloud storage, monitoring tools, and more.</p><p>But when it comes to testing, these integrations often become bottlenecks.</p><p>Testing with real services introduces latency, unpredictability, potential side effects, and unnecessary complexity. This is why <strong>test isolation</strong> is critical — and it starts with <strong>mocking</strong> and <strong>stubbing</strong>.</p><p>This article explores how to apply these techniques in real-world projects involving external dependencies such as <strong>AWS S3</strong> and <strong>Azure OCR</strong>, and why mastering them significantly improves software quality and developer efficiency.</p><h3>What Are Mock Objects and Stubs?</h3><p>Mock objects and stubs are tools used in software testing to replace real parts of a system with controllable, predictable versions. A <strong>stub</strong> is like a simple stand-in that always returns the same result, regardless of how it’s used. For instance, if you’re testing a weather app, instead of calling a real weather API, a stub might always return “25°C.” It helps you focus on testing your own logic without relying on the actual response from an external service.</p><p>A <strong>mock</strong>, on the other hand, does more than just return a value — it also tracks how it was used. You can verify if a function was called, how many times, and with what arguments. While their purposes slightly differ, both mocks and stubs help you isolate the code under test, making your tests faster, more reliable, and easier to maintain — especially when dealing with complex systems that rely on APIs, databases, or cloud platforms.</p><h3>The Need for Isolation in Complex Systems</h3><p>In large-scale applications, services may rely on:</p><ul><li>Database repositories</li><li>File storage like AWS S3</li><li>External APIs such as Azure Document Analyzer</li><li>Formatters for content rendering</li></ul><p>Directly invoking these services in unit tests creates problems:</p><ul><li>Tests become slower due to network calls</li><li>Results may be inconsistent</li><li>Real data may be exposed unintentionally</li><li>Test outcomes may be affected by third-party service availability</li></ul><p>To ensure fast, reliable, and safe testing, we mock or stub these dependencies.</p><h3>How We Implemented Test Isolation</h3><p>We used <strong>Jest</strong> as the testing framework and applied mocking and stubbing across all external and internal services.</p><h3>1. Mocking Repository Dependencies</h3><p>Instead of querying real databases, repository methods are mocked:</p><pre>jest.mock(&#39;../../repositories/customerRepository&#39;);<br>customerRepository.findById.mockResolvedValue(mockCustomer);</pre><p>This provides full control over the returned data and eliminates reliance on real datasets.</p><h3>2. Mocking External APIs (Azure OCR, AWS S3)</h3><p>External APIs like Azure Document Analyzer or AWS S3 introduce latency and cost.</p><p><strong>Azure OCR Mock Example</strong>:</p><pre>jest.mock(&#39;../../utils/azureAnalyzer&#39;);<br>azureAnalyzer.analyzeDocument.mockResolvedValue(mockOcrData);</pre><p><strong>AWS S3 Mock Example</strong>:</p><pre>jest.mock(&#39;aws-sdk&#39;, () =&gt; ({<br>  S3: jest.fn(() =&gt; ({<br>    getObject: jest.fn().mockReturnValue({<br>      promise: () =&gt; Promise.resolve(mockFileData)<br>    })<br>  }))<br>}));</pre><p>This ensures tests are independent of external environments, fast, and consistent.</p><h3>3. Stubbing Sentry for Error Reporting</h3><p>Monitoring tools like Sentry should not receive test exceptions. We stub these to suppress real error reporting:</p><pre>jest.spyOn(Sentry, &#39;captureException&#39;).mockImplementation(() =&gt; {});</pre><p>This keeps test runs clean and avoids polluting production logs.</p><h3>4. Maintaining a Clean Test State</h3><p>Using beforeEach and afterEach, we reset mocks and avoid state contamination:</p><pre>beforeEach(() =&gt; {<br>  jest.clearAllMocks();<br>});</pre><p>This guarantees that every test runs in isolation with a clean environment.</p><h3>Benefits of Mocking and Stubbing in Testing</h3><p>Mocking and stubbing aren’t just about convenience. They are fundamental to writing <strong>effective</strong>, <strong>scalable</strong>, and <strong>maintainable</strong> tests.</p><h3>1. Faster Test Execution</h3><p>Without real API calls or database queries, unit tests execute in milliseconds. This accelerates the feedback loop and supports rapid development.</p><h3>2. Deterministic Results</h3><p>Mocked dependencies behave consistently. The same test will yield the same result every time, regardless of external factors such as network latency or service downtime.</p><h3>3. Better Test Coverage of Edge Cases</h3><p>Mocks allow simulation of rare or difficult-to-reproduce conditions, such as:</p><ul><li>Corrupted API responses</li><li>Database unavailability</li><li>OCR misclassifications</li><li>Uncommon file formats</li></ul><p>This leads to more robust and resilient code.</p><h3>4. Safe Integration with External Services</h3><p>Mocking prevents real data from being sent to cloud services and avoids incurring costs from repeated test calls to paid APIs.</p><h3>5. Cleaner Code and Architecture</h3><p>To mock a component, it needs to be modular and decoupled. This encourages better design practices:</p><ul><li>Clear separation of concerns</li><li>Reusable interfaces</li><li>Simplified dependencies</li></ul><p>Well-isolated code is not only easier to test — it’s easier to maintain and extend.</p><h3>Conclusion</h3><p>Mocking and stubbing are indispensable for building test suites that are:</p><ul><li>Fast</li><li>Predictable</li><li>Isolated</li><li>Scalable</li></ul><p>When working with external services like <strong>AWS S3</strong> or <strong>Azure OCR</strong>, test isolation ensures that:</p><ul><li>Your tests are not dependent on the cloud</li><li>You can simulate rare and critical scenarios</li><li>Your test data stays safe</li><li>Your code becomes more modular and robust</li></ul><p>Mocking isn’t just a testing technique — it’s a gateway to better software design and higher development velocity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd7aa07fe67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Test-Driven Development (TDD) Fortified My Express Endpoint]]></title>
            <link>https://medium.com/@edberthalim29/how-test-driven-development-tdd-fortified-my-express-endpoint-ee9d8799dd23?source=rss-b9dd4adb03e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee9d8799dd23</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Edberthalim]]></dc:creator>
            <pubDate>Sun, 18 May 2025 06:33:05 GMT</pubDate>
            <atom:updated>2025-05-18T06:33:05.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*ipMEr-eTYBZlFRmJl0WnGg.png" /></figure><p>In my <a href="https://medium.com/@edberthalim29/securing-modern-web-applications-with-middleware-in-express-js-857f1209d61e">previous article</a>, I explored how Express.js middleware plays a crucial role in securing web applications.</p><p>But middleware is just the bouncer at the door.</p><p>What happens inside your app — when a user requests sensitive data like invoices — demands an even higher level of control. That’s where <strong>Test-Driven Development (TDD)</strong> made all the difference in my latest work on the getInvoiceById endpoint.</p><p>This post explores how TDD not only improved my code, but also helped me grow as a developer — sharpening my thinking, increasing confidence, and reducing stress.</p><h3>🧠 What Is Test-Driven Development (TDD)?</h3><p><strong>TDD</strong> is a development methodology that flips the usual workflow. Instead of writing code first and testing later, you:</p><ol><li><strong>Write a failing test</strong> that describes the desired behavior.</li><li><strong>Write the minimal code</strong> to make that test pass.</li><li><strong>Refactor the code</strong> for clarity, performance, or maintainability — while keeping tests green.</li></ol><p>This <strong>Red → Green → Refactor</strong> cycle makes testing part of the design process, not a separate task.</p><h3>💡 Why TDD Matters in Backend APIs</h3><p>Here’s what makes TDD especially valuable for backend developers:</p><ul><li>🔐 <strong>Security First</strong>: You define who should access what data before implementing logic.</li><li>🔍 <strong>Better Error Handling</strong>: TDD forces you to handle edge cases proactively.</li><li>📉 <strong>Fewer Bugs</strong>: With test coverage from the start, regression bugs become rare.</li><li>📚 <strong>Living Documentation</strong>: Tests describe what the code does, serving as real-time documentation.</li></ul><p>But it’s not just about the code. It’s also about how <strong>you grow as a software engineer</strong>.</p><h3>🧑‍💻 How TDD Helps You As a Software Engineer</h3><h3>1. ✅ You Think Clearly Before You Code</h3><p>Writing a test forces you to ask: <em>What exactly should this function do?</em><br> This avoids vague or over-complicated implementations.</p><blockquote><em>💡 TDD makes you a </em><strong><em>decision-maker</em></strong><em>, not just a coder.</em></blockquote><h3>2. 🔄 You Gain Confidence in Refactoring</h3><p>Worried that a small change might break everything? Not with TDD.</p><p>With your test suite acting as a safety net, you can confidently:</p><ul><li>Rename variables</li><li>Split large functions</li><li>Improve performance</li></ul><blockquote><em>🧪 </em><strong><em>Fearless refactoring</em></strong><em> becomes your new superpower.</em></blockquote><h3>3. 📦 You Deliver Reliable Features Faster</h3><p>It sounds counterintuitive, but TDD often saves time in the long run.</p><ul><li>No “test later” backlogs.</li><li>Fewer bug reports after deployment.</li><li>Clear definition of done.</li></ul><blockquote><em>🕒 TDD turns debugging hours into proactive planning minutes.</em></blockquote><h3>4. 🧩 You Design Modular, Maintainable Code</h3><p>You can’t test a 200-line function easily. TDD encourages smaller, reusable pieces that:</p><ul><li>Do one thing well</li><li>Are easier to debug</li><li>Work independently</li></ul><blockquote><em>🧱 TDD helps build code that’s scalable and clean — by default.</em></blockquote><h3>5. 💼 You Build Trust With Teams and Stakeholders</h3><p>When every feature is covered by tests, teammates trust your changes won’t break theirs.</p><blockquote><em>🤝 TDD makes you a more dependable engineer in team environments.</em></blockquote><h3>🛠 The Real Use Case: getInvoiceById Authorization</h3><h3>What I Needed to Build:</h3><p>An endpoint that:</p><ul><li>Returns an invoice only if it belongs to the authenticated user</li><li>Handles invalid inputs gracefully</li><li>Catches system errors without exposing internal issues</li></ul><h3>Step 1: Write the Positive Case Test</h3><pre>test(&quot;Should return an invoice when given a valid ID&quot;, async () =&gt; {<br>  req.user = { uuid: &quot;dummy-uuid&quot; };<br>  req.params = { id: 1 };<br>  const mockInvoice = { id: 1, partner_id: &quot;dummy-uuid&quot;, ... };<br>  invoiceService.getInvoiceById.mockResolvedValue(mockInvoice);<br>  await getInvoiceById(req, res);<br>  expect(res.status).toHaveBeenCalledWith(200);<br>  expect(res.json).toHaveBeenCalledWith(mockInvoice);<br>});</pre><p>This test defines the <strong>ideal behavior</strong> before implementation starts.</p><h3>Step 2: Write Negative Case Tests</h3><p><strong>Unauthorized:</strong></p><pre>test(&quot;Should return 401 if req.user is not defined&quot;, ...);</pre><p><strong>Forbidden:</strong></p><pre>test(&quot;Should return 403 if invoice doesn&#39;t belong to that user&quot;, ...);</pre><p><strong>Not Found:</strong></p><pre>test(&quot;Should return 404 when invoice is not found&quot;, ...);</pre><p><strong>Server Error:</strong></p><pre>test(&quot;Should return 500 when internal server error occurs&quot;, ...);</pre><p><strong>Corner Cases:</strong></p><pre>test(&quot;Should return 400 if ID is a string / null / negative&quot;, ...);</pre><h3>Step 3: Write the Minimal Implementation</h3><p>Once all tests are in place, the implementation becomes straightforward:</p><pre>if (!id || isNaN(id) || parseInt(id) &lt;= 0) {<br>  return res.status(400).json({ message: &quot;Invalid invoice ID&quot; });<br>}<br>if (!req.user) {<br>  return res.status(401).json({ message: &quot;Unauthorized&quot; });<br>}<br>const invoice = await invoiceService.getInvoiceById(parseInt(id));<br>if (!invoice) {<br>  return res.status(404).json({ message: &quot;Invoice not found&quot; });<br>}<br>if (invoice.partner_id !== req.user.uuid) {<br>  return res.status(403).json({ message: &quot;Forbidden: You do not have access to this invoice&quot; });<br>}<br>return res.status(200).json(invoice);</pre><p>Notice how each code path <strong>mirrors a test</strong>. The implementation is shaped by behavior, not assumptions.</p><h3>🧠 What I Gained From TDD (Beyond Passing Tests)</h3><ul><li>I understood <strong>user roles and risks</strong> better by thinking through edge cases.</li><li>I wrote <strong>defensive code</strong> from the start, not after a bug report.</li><li>I delivered a <strong>more secure and robust feature</strong> with less back-and-forth.</li></ul><p>But most importantly:</p><blockquote><em>I became a more deliberate, thoughtful engineer — not just someone who makes it work, but someone who makes it </em>right<em>.</em></blockquote><h3>✍️ Final Thoughts</h3><p>Test-Driven Development isn’t just for unit tests. It’s a mindset that enhances:</p><ul><li>Your <strong>code</strong></li><li>Your <strong>workflow</strong></li><li>And your <strong>growth</strong> as an engineer</li></ul><p>In a world where security, reliability, and speed all matter — <strong>TDD is the tool that gives you all three.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee9d8799dd23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Modern Web Applications with Middleware in Express.js]]></title>
            <link>https://medium.com/@edberthalim29/securing-modern-web-applications-with-middleware-in-express-js-857f1209d61e?source=rss-b9dd4adb03e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/857f1209d61e</guid>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[middleware]]></category>
            <dc:creator><![CDATA[Edberthalim]]></dc:creator>
            <pubDate>Thu, 15 May 2025 04:08:16 GMT</pubDate>
            <atom:updated>2025-05-15T04:08:16.827Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How Middleware Acts as a Strategic Shield in Node.js Backend Security</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKTEcFTskJbgQCOk7TZH5g.png" /></figure><p>Modern web applications are constantly exposed to threats — from brute-force attacks and abusive bots to insecure file uploads and unauthorized access. As developers, our responsibility is to not only deliver functionality but also to ensure our systems are secure, scalable, and resistant to common vulnerabilities.</p><p>In the Node.js ecosystem, <strong>Express.js middleware</strong> offers a powerful mechanism to intercept, inspect, and control requests before they reach your core application logic. In this article, we’ll walk through how to strategically use middleware to strengthen application security — focusing on <strong>authentication</strong>, <strong>rate limiting</strong>, and <strong>safe file uploads</strong>.</p><h3>🧱 What Middleware Really Does</h3><p>Middleware in Express.js is like a <strong>checkpoint</strong> between the client request and your server’s business logic. Every incoming request must pass through this series of functions, where it can be:</p><ul><li>Authenticated and authorized</li><li>Sanitized and validated</li><li>Logged, throttled, or even rejected</li></ul><p>Think of it like a security guard posted at every entrance to your application — verifying credentials and determining access <strong>before</strong> anyone reaches your valuable resources.</p><h3>🔐 Implementing Authentication Middleware</h3><p>Authentication is your app’s first layer of protection. Before users can access restricted content or perform actions, you need to ensure they’re who they claim to be.</p><p>Here’s a simple example of token-based authentication middleware:</p><pre>function authenticate(req, res, next) {<br>  const token = req.headers[&#39;authorization&#39;];<br>  if (token) {<br>    // Normally, you&#39;d verify using JWT or another token service<br>    next();<br>  } else {<br>    res.status(401).send(&#39;Unauthorized&#39;);<br>  }<br>}</pre><p>With this middleware in place, any route you protect using authenticate will deny access to unauthenticated users. This pattern is the foundation for securing APIs and private endpoints.</p><p>You can apply it selectively:</p><pre>app.get(&#39;/dashboard&#39;, authenticate, (req, res) =&gt; {<br>  res.send(&#39;Welcome to your dashboard&#39;);<br>});</pre><p>Or globally:</p><pre>app.use(authenticate); </pre><h3>🚦 Preventing Abuse with Rate Limiting Middleware (Your First Line of Defense)</h3><p>If there’s one middleware every production-grade app should have, it’s <strong>rate limiting</strong>.</p><p>APIs are prime targets for abuse. Attackers can:</p><ul><li>Repeatedly hit your login endpoint to guess passwords (brute-force attacks)</li><li>Flood your server with requests, draining bandwidth and compute</li><li>Exploit open APIs for scraping or abuse</li></ul><p>To defend against this, we use express-rate-limit, a powerful middleware for controlling how many requests a client can make in a given time window.</p><h3>Setting Up Rate Limiting</h3><pre>const rateLimit = require(&#39;express-rate-limit&#39;);<br><br>const limiter = rateLimit({<br>  windowMs: 15 * 60 * 1000, // 15-minute window<br>  max: 100, // Max 100 requests per IP<br>  message: &#39;Too many requests, please try again later.&#39;,<br>});<br><br>app.use(limiter); // Apply to all routes</pre><p>This configuration allows a maximum of <strong>100 requests per IP every 15 minutes</strong>. If a client exceeds this, they’ll receive a 429 Too Many Requests response with the provided message.</p><p>This lightweight measure instantly provides protection against:</p><ul><li>Abusive bots</li><li>Denial-of-service attempts</li><li>Excessive usage by misconfigured clients</li></ul><h3>Skipping Rate Limiting for Trusted IPs</h3><p>In certain cases, like development environments or internal monitoring systems, you might want to <strong>exclude specific IP addresses</strong> from the limiter. This can be done by adding a skip condition:</p><pre>const WHITELISTED_IPS = [&#39;127.0.0.1&#39;, &#39;192.168.1.100&#39;];<br><br>const limiter = rateLimit({<br>  windowMs: 15 * 60 * 1000,<br>  max: 100,<br>  message: &#39;Too many requests, please try again later.&#39;,<br>  skip: (req) =&gt; WHITELISTED_IPS.includes(req.ip),<br>});</pre><p>This ensures your own tools and teammates aren’t inadvertently rate-limited during testing, while still enforcing strict limits on external clients.</p><h3>🗂 Securing File Uploads</h3><p>File uploads often go overlooked during security audits, but they pose real threats — especially when users can upload content directly to your server.</p><p>Poorly handled uploads can lead to:</p><ul><li>Remote code execution (if files are executable)</li><li>Directory traversal</li><li>Disk space exhaustion</li><li>Malware being stored on your server</li></ul><h3>Safe Uploads with Multer</h3><p>To handle uploads securely, we use the multer middleware:</p><pre>const multer = require(&#39;multer&#39;);<br>const upload = multer({<br>  dest: &#39;uploads/&#39;,<br>  limits: { fileSize: 1024 * 1024 * 5 }, // 5MB max<br>  fileFilter: (req, file, cb) =&gt; {<br>    const isValid = file.mimetype === &#39;image/jpeg&#39; || file.mimetype === &#39;image/png&#39;;<br>    cb(isValid ? null : new Error(&#39;Invalid file type&#39;), isValid);<br>  },<br>});</pre><p>This configuration restricts uploads to JPEG and PNG images under 5MB in size. It also validates MIME types, which helps prevent users from disguising dangerous files as images.</p><h3>Additional File Upload Best Practices</h3><ul><li><strong>Validate file types</strong> using both MIME type and extension.</li><li><strong>Sanitize filenames</strong> to remove risky characters or path traversal sequences.</li><li><strong>Store uploads outside public directories</strong> and serve them through authenticated routes.</li><li><strong>Integrate antivirus scanning tools</strong> like ClamAV in production to detect malware.</li></ul><h3>🔄 Why Middleware Beats Controller-Level Logic</h3><p>You might wonder: <em>Can’t we just handle security checks inside controllers?</em></p><p>Technically, yes. But as your app grows, <strong>this leads to duplication, human error, and performance issues</strong>.</p><p>Here’s a quick comparison:</p><h3>Controller-based JWT Check</h3><pre>app.get(&#39;/profile&#39;, async (req, res) =&gt; {<br>  const token = req.headers[&#39;authorization&#39;];<br>  if (!token) return res.status(401).send(&#39;Unauthorized&#39;);<br>  // Verify token...<br>  res.send(&#39;User profile&#39;);<br>});</pre><p>Now imagine repeating that in 30 different controllers. That’s:</p><ul><li>Hard to maintain</li><li>Easy to forget on a new route</li><li>Complicated to update later</li></ul><h3>Middleware-based Approach</h3><pre>app.use(authenticate); // Apply once</pre><p>You write the authentication logic <strong>once</strong>, and it guards every protected route automatically. This keeps your controllers clean, your logic centralized, and your app easier to maintain.</p><h3>✅ Conclusion: Middleware as a Security Strategy</h3><p>Middleware in Express.js is more than just a convenience — it’s a strategic design decision that allows you to:</p><ul><li><strong>Enforce consistent security policies</strong></li><li><strong>Protect against attacks automatically</strong></li><li><strong>Avoid code duplication and human error</strong></li><li><strong>Scale your backend safely and efficiently</strong></li></ul><p>To recap, here’s what we covered:</p><ul><li>✅ <strong>Authentication</strong>: Verifies identity before processing.</li><li>🚦 <strong>Rate Limiting</strong>: Controls request volume, protects against abuse.</li><li>🗂 <strong>File Upload Security</strong>: Prevents dangerous content from reaching your server.</li></ul><p>By implementing middleware early and thoughtfully, you’re not just shipping features — you’re building <strong>secure, sustainable infrastructure</strong> that can scale and evolve with your app.</p><blockquote><em>The time you spend now writing middleware will save you hours of debugging, performance bottlenecks, and incident response down the road.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=857f1209d61e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Team Collaboration with Git, CI/CD, and Scrum Board]]></title>
            <link>https://medium.com/@edberthalim29/tdd-3b837b7fcf22?source=rss-b9dd4adb03e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b837b7fcf22</guid>
            <dc:creator><![CDATA[Edberthalim]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 16:19:01 GMT</pubDate>
            <atom:updated>2025-02-27T04:02:57.254Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Study on Optimizing Software Development Workflow by a 6th semester computer science student</em></p><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*k1G61CIwOHOtopG9hjJtuA.png" /><figcaption>team collaboration</figcaption></figure><p>Team collaboration is very critical in software development. Managing contributions, ensuring code quality, and deploying seamlessly require structured workflows. Our new team recently worked on an <strong>invoice upload feature</strong>, where we encountered challenges such as <strong>code collaboration, automated testing, task management, and deployment consistency</strong>. To overcome this issue, we must implement a structured Git workflow, CI/CD pipelines, and scrum board task management.</p><h3>Enhancing Productivity with Scrum Board</h3><p>Effective task management is a crucial component of <strong>Agile development</strong>. Our team adopted a <strong>Scrum board</strong> to streamline our workflow.</p><p>We divided our <strong>invoice upload feature</strong> into smaller, manageable tasks. By <strong>actively updating task progress</strong>, we ensured transparency, <strong>minimized duplicate work</strong>, and enabled <strong>clear communication</strong> between developers.</p><p>Using the Scrum board allowed us to <strong>track development status in real-time, set priorities, and ensure smooth coordination</strong> within the team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWs_uV9HwPAvZK802nx6gQ.png" /><figcaption>Example of utilizing scrum board</figcaption></figure><h3>Optimizing Git Workflow with Branches</h3><p>One of the most critical aspects of our workflow was <strong>managing branches effectively using Git</strong>. We established a structured <strong>branching strategy</strong> to keep our codebase organized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*WhmedG7yQcTIEe4Qi0vLpA.png" /></figure><ul><li>PBI-1-unggah-invoice: A feature branch containing all updates related to the invoice upload functionality.</li><li>PBI-1/edbert-dev: A developer-specific branch where isolated changes were made before merging into the feature branch.</li></ul><p>To ensure clarity and maintainability, we <strong>followed a structured TDD commit tagging convention</strong>:</p><p>✅ [RED] → Adding a test (expected to fail initially)<br>✅ [GREEN] → Implementing a feature that passes the test<br>✅ [Refactor] → Improving code structure without changing functionality</p><p>Each <strong>merge request (MR)</strong> followed a strict validation process. <strong>Before merging a feature branch, we ensured that it:</strong></p><ul><li>Passed all <strong>CI/CD pipelines</strong>, including automated tests.</li><li>Underwent a <strong>code review</strong> to maintain code quality.</li><li>Had <strong>descriptive commit messages</strong> to document changes effectively.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoTYrWeXYu6ozrvGVzLObw.png" /></figure><p>For example, one of my merge requests was titled:<br><em>“Membuat test dan code backbone (routes, controllers, services) untuk fitur upload invoice”</em>,<br>which clearly communicated the changes introduced.</p><p>By enforcing a <strong>disciplined Git workflow</strong>, we significantly improved <strong>collaboration, code quality, and traceability</strong> in our development process.</p><h3>Implementing CI/CD Across All Branches: Automated Testing, Code Coverage, and SonarCloud</h3><p>To prevent merging <strong>faulty or incomplete code</strong>, we implemented <strong>CI/CD pipelines</strong> that run on <strong>every branch</strong>, ensuring that each change is automatically validated before integration. This approach significantly <strong>reduces the risk of breaking the application</strong>, improves <strong>code quality</strong>, and enhances <strong>team collaboration</strong> by enforcing consistent development practices.</p><h3>Key Features of Our CI/CD Pipeline</h3><p>Our <strong>CI/CD pipeline</strong> is structured to <strong>automate validation steps</strong> before merging any feature, bug fix, or enhancement. The pipeline includes:</p><ul><li><strong>Automated Unit Testing</strong>: Every commit and merge request triggers unit tests to verify that all core functionalities work as expected.</li><li><strong>Code Coverage Analysis</strong>: We track <strong>code coverage</strong> to ensure that new code is properly tested and does not introduce untested functionality.</li><li><strong>SonarCloud </strong>: Integrated <strong>SonarCloud</strong> to detect <strong>code smells, security vulnerabilities, and technical debt</strong>, improving code maintainability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDAo8K509B66mwKZ4O9OOw.png" /><figcaption>Example of CI/CD automation</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b837b7fcf22" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>