<?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 Abhirup Basu on Medium]]></title>
        <description><![CDATA[Stories by Abhirup Basu on Medium]]></description>
        <link>https://medium.com/@basu.abhirup27?source=rss-4e0b491aba16------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U0dvUYREZBOlRBAInXUQyQ.jpeg</url>
            <title>Stories by Abhirup Basu on Medium</title>
            <link>https://medium.com/@basu.abhirup27?source=rss-4e0b491aba16------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:19:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@basu.abhirup27/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[I Spent Years Opposing BJP. So Why Wasn’t I Angry When They Won Bengal?]]></title>
            <link>https://medium.com/@basu.abhirup27/i-spent-years-opposing-bjp-so-why-wasnt-i-angry-when-they-won-bengal-f366a6a35a75?source=rss-4e0b491aba16------2</link>
            <guid isPermaLink="false">https://medium.com/p/f366a6a35a75</guid>
            <category><![CDATA[west-bengal-politics]]></category>
            <category><![CDATA[tmc-vs-bjp-2026]]></category>
            <category><![CDATA[mamata-banerjee]]></category>
            <category><![CDATA[anti-incumbency]]></category>
            <category><![CDATA[assembly-elections]]></category>
            <dc:creator><![CDATA[Abhirup Basu]]></dc:creator>
            <pubDate>Tue, 05 May 2026 23:38:29 GMT</pubDate>
            <atom:updated>2026-05-05T23:38:29.722Z</atom:updated>
            <content:encoded><![CDATA[<h4>What the BJP’s landslide victory in West Bengal taught me about democracy, emotion, and growing up politically</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a7OkvcPQ6zyhmWwh" /><figcaption>Photo by <a href="https://unsplash.com/@amaanabidhussain?utm_source=medium&amp;utm_medium=referral">Amaan Abid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Yesterday were the West Bengal Assembly Election results… and BJP pulled off a landslide victory. 207 out of 294 seats?? Unbelievable!! So we’re officially a part of the cow belt now. What else is there to say.</p><p>For those outside Bengal: Mamata Banerjee’s Trinamool Congress had governed this state for over a decade. What began as a genuine alternative to Left Front stagnation had, over time, hardened into the exact same kind of establishment— a machinery of patronage, intimidation, and unchecked incumbency that made daily civic life feel like a negotiation with power at every turn. By 2026, opposing TMC wasn’t really an ideological position anymore. For most people, it was just exhaustion.</p><p>I genuinely wasn’t expecting a result like this. But here’s the strange part: my initial reaction wasn’t anger, disbelief, or shock. Not even close. TMC had to be defeated at any cost; the “lesser evil” logic of 2021 simply didn’t hold up this time. So the real question became: <em>what am I even supposed to feel right now? </em>I wasn’t remotely prepared to feel anything. And to my own surprise, I found myself quietly justifying BJP’s win—reassuring people around me that it won’t be <em>that</em> harmful for Bengal this time. Or at least, that was the excuse I kept repeating to everyone, including myself.</p><p>The conversations that followed were long and winding. Friends called, group chats exploded, and somewhere across all of it I kept noticing myself subtly defending the result, cushioning the blow, softening the edges. The proximity effect is extraordinarily real in politics. When your immediate social circle shrinks or shifts over time, your political standpoint quietly drifts toward something more individualistic — often without you fully noticing it. And when TMC’s sheer arrogance had become completely insufferable for years on end, some part of you starts feeling that their monopoly simply <em>had</em> to be broken, by any means necessary.</p><h3>What 2024 Actually Taught Us</h3><p>I&#39;d seen the Hindutva wave up close. I was living in Noida during the Ram Mandir consecration on 22nd January 2024 — and the energy that day was unlike anything I&#39;d witnessed before. It was an unofficial holiday across Uttar Pradesh. My office declared one too. Neighbours were inviting each other for Ramayana Path, distributing sweets, chanting “Jay Shree Ram&quot; at every possible moment. And I want to be clear — these weren&#39;t unkind people. They were warm, generous, genuinely friendly neighbours with whom I had no friction whatsoever. But the fervour was total and unignorable. Standing inside it, I became quietly convinced that BJP would cross 400 seats in the parliamentary election. That no opposition could meaningfully fight this back. The opposition alliance (I.N.D.I.A) felt almost beside the point.</p><p>But to my surprise, BJP lost Ayodhya — the very constituency cradling the Ram Mandir — to a Samajwadi Party candidate!! Because the people living in the shadow of that temple had watched their homes get demolished, their livelihoods erased, all in service of a grand construction they were never really included in. So no matter how deeply they were hardcore Hindus at heart, when the moment came, they didn’t vote their faith. They voted their fury. And their fury was specific, local, and entirely legitimate.</p><p>And it wasn’t just Ayodhya. The party that had been confidently talking about 400+ seats couldn’t even cross 272 — the bare majority mark — on its own. The same BJP that had consecrated a temple to near-universal fanfare just months before the election was suddenly dependent on coalition partners to form a government. The mandate that had felt inevitable from inside that Noida neighbourhood turned out to be far more fragile than anyone standing within the fervour could have imagined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aDjlc21Y61T-caZ9" /><figcaption>Photo by <a href="https://unsplash.com/@chiragsinghvi01?utm_source=medium&amp;utm_medium=referral">Chirag Singhvi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the most important lessons I took away from the 2024 Lok Sabha elections is this: it is absolutely not okay to dismiss common citizens as politically ignorant.</p><p>There’s a subtle elitism built into many educated, progressive circles — the casual writing-off of northerners, the reflexive mockery of social conservatism in states like UP and Bihar, the complete absence of curiosity about why people’s lives and communities look the way they do. I’ve been guilty of it myself. And somewhere between 2024 and now, I stopped finding it defensible.</p><h3>People Are Not as Unaware as We Like to Believe</h3><p>This is the part that tends to make ideologically rigid people deeply uncomfortable: in a free and fair election, ordinary people almost always deliver a clear and coherent mandate. They may not use the language of political theory. They may not cite policy frameworks or historical precedents. But they know when they’ve been taken for granted, and they act on it.</p><p>I know BJP lacks a strong opposition across Bengal this time around. But that’s almost beside the point. Governments reveal themselves through power, not through promises — and Bengal has just handed them an unambiguous mandate to do exactly that. Whatever happens next, at least it will be legible. At least people will see clearly, and then decide accordingly. This country’s voters have a long memory and a surprisingly accurate aim when they feel betrayed. That much, I’ve come to trust.</p><p>And perhaps that’s the real shift in me — not which party I support or oppose, but that I’ve stopped needing politics to feel like a moral emergency at all times. The NOTA-advocating, fully-certain younger version of me feels distant today. But I hold that distance lightly. Political consciousness is never a fixed destination — it shifts, it contracts, it quietly surprises you when you’re not looking. <em>Change is the one and only unchangeable thing in this ever-changing world.</em> That applies to governments. It applies to voters. And if I’m being honest, it applies most of all to me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6iganRRV26RjI4kn" /><figcaption>Photo by <a href="https://unsplash.com/@anirbaansarkar?utm_source=medium&amp;utm_medium=referral">Anirbaan Sarkar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Conversation That Made Me Introspect</h3><p>I got into a minor but meaningful argument with a friend who has been deeply immersed in ideas of rebellion and disbelief in electoral democracy. My more balanced take came across as threatening to her — even faintly Hindutva-adjacent — and honestly, for entirely legitimate reasons from her vantage point. I don’t blame her at all.</p><p>I’ve stood exactly where she’s standing right now, at a certain point in time. The rage feels clarifying. The refusal to compromise feels like integrity. The suspicion of “balance” feels like the only honest response to a system that keeps failing people. I genuinely understand all of it.</p><p>But after some introspection, I also recognized something uncomfortable about myself: I play it very safe these days. I’m not remotely the political rebel I once was. I’ve grown more measured, more selfish, even, in ways I broadly think are justified. Debating someone still at that earlier, more emotionally charged stage of political thinking was, strangely, grounding. It reminded me how far my own views have traveled—and whether that distance is growth or drift, I honestly cannot say with certainty.</p><p>What I do know is this: it takes real courage to hold onto a communist worldview in a society that incentivizes capitalism at every turn and in every dimension of life. That conviction deserves genuine respect, not disdain. I’ve simply found myself inhabiting a different political space right now—though I hold no illusions about that being permanent. Political consciousness is never a fixed address. You move in, you move out, and sometimes you return. I have no interest in pretending I know exactly where I’ll land ten years from now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PohFxMbn6qKgyu1w" /><figcaption>Photo by <a href="https://unsplash.com/@amaanabidhussain?utm_source=medium&amp;utm_medium=referral">Amaan Abid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Street vs. The Bubble</h3><p>Out on the streets of Kolkata the day after results, people of all ages were engaged in animated political conversations — and most of them seemed genuinely relieved, even happy, about BJP’s victory. Their reasoning was simple and direct: TMC deserved this. Not because BJP is great, but because TMC had become intolerable.</p><p>This is the fault line that urban, campus-insulated political discourse consistently misses. People who remain within protected ideological environments — whether on the left or the liberal centre — tend to see only one villain clearly. But people navigating everyday life on the ground assign their anger based on whoever has wronged them most <em>recently</em> and most <em>personally</em>. Right now, in Bengal, that was TMC.</p><p>Political reality looks radically different depending on where you’re standing. And neither vantage point has a monopoly on truth.</p><p>Expecting people to care about ‘civilisational consequences’ while they struggle with daily corruption is absurd. You can’t demand a macro-level perspective from people fighting micro-level battles. Taking a bird’s-eye view of systemic risks is a luxury most voters simply don’t have. But this is precisely why political leadership matters so enormously: if the right kind of communicative, honest, and effective leaders emerge who can make people meaningfully more politically conscious — who can help shift priorities from short-term fixes toward longer-term solutions — that would be genuinely transformative. For society. For democracy. For everyone caught in between.</p><h3>A Mandate Is Not Always an Endorsement</h3><p>But here’s the distinction I think gets lost most often in the noise of election analysis: a mandate is not always an endorsement.</p><p>Yes, there are Bengali voters who have genuinely absorbed the Hindutva narrative that BJP and RSS have been patiently, methodically building in this state over the last ten to twelve years. That influence is real and it would be naive to dismiss it. But 207 seats cannot be explained by ideological conversion alone. For the majority of people who voted BJP this time, it was not a <em>yes</em> to Hindutva. It was an exhausted, unflinching <em>no</em> to TMC — to the anarchy, the patronage networks, the culture of impunity that had made ordinary life in Bengal feel like a daily negotiation with someone’s arbitrary power.</p><p>People voted with what was immediately in front of them. Not a civilisational vision, not a long-term ideological alignment — just the lived, accumulated frustration of years of incumbent misrule and the very human desire to make it stop. That’s not ignorance. That’s not even cynicism. That’s democracy functioning more or less as intended — imperfectly, noisily, but functioning.</p><p>And that, strangely, is where my hope comes from. Not from any illusion about what BJP will or won’t do with this mandate. But from the belief that the same restless, pragmatic, quietly rational voter who said <em>enough</em> to TMC today will say it again — to whoever next forgets that power in a democracy is borrowed, not owned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tFfjRhmjDoFYpEMS" /><figcaption>Photo by <a href="https://unsplash.com/@dibakar16roy?utm_source=medium&amp;utm_medium=referral">Dibakar Roy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Reality of Post-Poll Violence</h3><p>But hope, right now, has to share the page with something harder to look at.</p><p>Within hours of the results, reports started coming in — properties vandalised, intimidation in localities, the occasional eruption of hardline Hindutva muscle-flexing that felt less like political celebration and more like a demonstration of who owns the street now. I won’t sensationalise it. But I also won’t pretend it isn’t happening.</p><p>The truth is, post-poll violence is not a BJP problem or a TMC problem. It is a Bengal problem — written so deep into the political culture of this state that it almost feels structural. Parties have stood on public stages and issued barely-veiled threats into open microphones for decades. We’ve watched it happen so many times that we’ve built a strange immunity to it — nodding along, filing it under <em>that’s just how it is here</em>, and moving on. The Election Commission comes, the Central Paramilitary forces deploy, assurances are issued — and still, when the results land, the cycle finds a way to continue. People get so viscerally attached during election season that the aftermath almost always carries a settling of scores that no external force has ever quite managed to prevent.</p><p>That’s the part that unsettles me most — not who won, but what winning has always meant on the ground in this state. And that, regardless of which flag is flying, remains unchanged.</p><h3>Looking Forward</h3><p>Somewhere underneath the unsettledness there’s something that feels almost like clarity — the kind that only comes after you stop demanding that politics give you clean answers.</p><p>Democracy in India is battered, frequently infuriating, and deeply imperfect. It is also, somehow, still working — still throwing up surprises, still humbling the overconfident, still giving ordinary people a legitimate way to say <em>enough</em>. That’s not nothing. In fact, on most days, that feels like everything.</p><p>What I want most for Bengal is simple and perhaps naive: that whatever changes around us — whoever holds power, whatever culture dominates the public space — the instinct toward tolerance that has always lived in these streets, in these people, survives it all. Not as a slogan. Just as a quiet, stubborn habit of living alongside each other.</p><p><em>Ashay banche chasha</em>. Hope sustains the farmer through the long season of waiting — not because the harvest is guaranteed, but because giving up on it guarantees nothing grows at all. That feels like enough to hold onto, for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IfNzVyEuYO5mX0L0" /><figcaption>Photo by <a href="https://unsplash.com/@subhajit2021?utm_source=medium&amp;utm_medium=referral">Subhajit Jana</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>These are personal reflections written in the immediate aftermath of the 2026 West Bengal Assembly Election results. The views expressed are the author’s own, evolving, and offered in good faith.<br> — Kolkata, West Bengal | May 5, 2026</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f366a6a35a75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API to WebSocket: I Upgraded My iOS (Internal Operating System) to Have Emotional Real-Time Sync…]]></title>
            <link>https://medium.com/@basu.abhirup27/api-to-websocket-i-upgraded-my-ios-internal-operating-system-to-have-emotional-real-time-sync-af794548f56f?source=rss-4e0b491aba16------2</link>
            <guid isPermaLink="false">https://medium.com/p/af794548f56f</guid>
            <category><![CDATA[self-awareness]]></category>
            <category><![CDATA[healing]]></category>
            <category><![CDATA[emotional-intelligence]]></category>
            <category><![CDATA[philosophy-of-mind]]></category>
            <category><![CDATA[self-validation]]></category>
            <dc:creator><![CDATA[Abhirup Basu]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 22:47:08 GMT</pubDate>
            <atom:updated>2025-10-16T22:47:08.879Z</atom:updated>
            <content:encoded><![CDATA[<h3>REST API to WebSocket: I Upgraded My iOS (Internal Operating System) to Have Emotional Real-Time Sync with My Inner Child</h3><p>What if emotional healing worked like upgrading from REST API to WebSocket? Here’s how I rebuilt my internal operating system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnMS7gzSIsmkvFpD3u8dmQ.jpeg" /><figcaption>Sunset at Odayam Beach, Varkala, Kerala</figcaption></figure><p>For most of my life, my communication between my <strong>inner child</strong> and <strong>outer adult</strong> worked like traditional REST API calls. My adult self would “call” the API whenever something went wrong like heartbreak, failure, or confusion and my inner child would respond with stored emotions, unmet needs, and memories - sometimes with anger, sometimes with pain, and sometimes with silence.</p><p>It was a <em>request-response</em> model of self-communication - reactive, functional, but far from alive.</p><p>But recently, something shifted.</p><p>Through months of solitude, introspection, and journaling, I’ve built what I can only describe as a <strong>WebSocket connection - </strong>a continuous, real-time, two-way sync between my inner child and adult self.</p><p><em>(If you’re not from a tech background, think of REST API as one-way communication between two parties where only one party can initiate the call, whereas a WebSocket allows a real-time two-way dialogue between them)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGHk5VOGfIwFSe72_tutLw.png" /><figcaption>REST API vs Websocket (<em>Generated using Google Gemini 2.5 Flash</em>)</figcaption></figure><p>Now, my inner child doesn’t need to wait for the adult to “call.” He can initiate. He can express. He can demand affection, play, or rest - without needing a crisis to justify it.</p><p>And honestly, this might be one of the most profound upgrades of my life: upgrading my <strong>internal operating system (iOS) </strong>from request-response to <strong>real-time emotional sync.</strong></p><h3>The Missing Update: Internal Validation</h3><p>Ideally, I would have loved external validation. Who doesn’t? As social creatures, being seen and understood is how we confirm that we exist.</p><p>But what happens when life doesn’t offer that validation when you crave it most? What if circumstances simply don’t permit it? Do you just give up?</p><p>Absolutely no.</p><p>As Robi Thakur (Rabindranath Tagore) said it long ago:</p><blockquote><em>“</em>Jodi tor daak shune keu na aase, tobe ekla cholo re.<em>”<br> </em>(If no one responds to your call, walk alone.)</blockquote><p>That became my guiding line.</p><p>So I began the journey inward - not to reject the world, but to find my own mirror.</p><p>And there, I discovered the power of <strong>internal validation</strong>. I’ve come to trust my own intelligence and kindness more deeply than ever before.</p><p>My healing journey stands as evidence. I’ve witnessed myself fall apart, rebuild, love, and forgive - not for an audience, but for my own integrity.</p><p>The way I continued my internal monologues, the way I always found light at the end of every thought loop, and the way I treated my inner child with such consistent kindness - all of it proves one thing: I am enough.</p><p>Not perfect. Not flawless. But enough.</p><h3>Protecting My Internal Ecosystem</h3><p>Right now, I’m not chasing approval, love, or reassurance. What I’ve built inside is something far more sustainable: an <strong>ecosystem</strong>.</p><p>My inner child and outer adult have created a relationship that’s mutually dependent, gentle, and powerful. This live real-time socket connection is the <strong>core infrastructure</strong> of my emotional system. It powers my creativity, my calmness, and my ability to stay soft in a hard world.</p><p>I’ve realized I was mostly afraid of myself all these years - my thoughts, my emotions, my own intensity, my moods, my overthinking. But all that fear was essentially just <strong>self-avoidance. </strong>The only thing I was missing all along was <em>my own internal validation.</em></p><p>The real slavery wasn’t heartbreak or rejection. It was my hunger <strong>to be understood</strong>.</p><p>Now, I’m giving enough time and energy to <strong>understanding myself </strong>so deeply that I’ve freed myself from the need for anyone else to do it for me. I’ve built a feedback loop inside that’s kind, consistent, and surprisingly reliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccXCHVXIEtPS01RRv2IMhA.png" /><figcaption>The inner child and adult self finally in real-time sync (<em>Generated using Google Gemini 2.5 Flash</em>)</figcaption></figure><h3>The Paradox of Being Selfish to Be Selfless</h3><p>Does this mean I’ll stay socially aloof forever? Absolutely not.</p><p>I still crave laughter, connection, and moments of unfiltered chaos. I’ll go out, make new friends, flirt, travel, dance - all of it. But this time, without the hidden expectation of being fully understood.</p><p>Earlier, I used to meet people with an invisible checklist - emotional depth, wavelength match, shared worldview.</p><p>Now I realize that not every connection needs to be deep. Some can be fleeting and still beautiful - like strangers singing together on a random backpackers hostel or laughing over street food.</p><p>The key is to <strong>show up without emotional hunger</strong>.</p><p>When our emotional needs are fulfilled internally, every external bond becomes lighter, freer, and more genuine.</p><p>It’s funny, but true: We have to be <em>selfish enough</em> to meet our own needs before we can be <em>selfless enough</em> to love without expectation.</p><h3>My Emotional Container</h3><p>I’m not claiming my emotional container is full to the brim. There’s still enough space left - space to grow, to receive, to stay curious.</p><p>But I have enough emotional capital now to look outward again. To build connections from abundance, not absence.</p><p>Earlier, I couldn’t socialize easily because I was secretly waiting for people who could match my emotional frequency, who could “vibe” at the same depth.</p><p>Now, I’ve realized that’s not in my control. Even mindless, shallow connections - over drinks, music, or laughter - are valuable in their own right. Not every bond needs to be profound, as long as I remain mindful of protecting and nurturing my own depth.</p><p>Depth is beautiful. But lightness is also sacred.</p><h3>Epilogue — The Real-Time Sync</h3><p>So yes, I’ve upgraded my <strong>iOS - </strong>my <em>internal operating system.</em></p><p>My emotional system now runs on <strong>real-time sync</strong>, where both the inner child and the adult self coexist in dialogue, not hierarchy. They talk, they joke, they cry, they repair.</p><p>No more one-way REST API calls.<br>No more waiting for external servers to respond.</p><p>Just a live connection - a websocket of self-understanding, acceptance, and trust.</p><p>And maybe that’s what growing up truly means - keeping the channel open between who we were and who we’re becoming.</p><p>If you’ve ever felt like you only talk to yourself when something’s wrong, try opening that channel a little wider. Let your inner child speak before crisis hits, and you might be surprised by how fluent that dialogue can become.</p><p>Sometimes the best technology we build is the one that lets us listen inward.</p><p><em>[Oct 16th 2025, Varkala, Kerala]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af794548f56f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NPM vs YARN vs PNPM: Choosing the Right Package Manager for Your JavaScript Projects]]></title>
            <link>https://medium.com/@basu.abhirup27/npm-vs-yarn-vs-pnpm-choosing-the-right-package-manager-for-your-javascript-projects-f0cfce779545?source=rss-4e0b491aba16------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0cfce779545</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[pnpm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abhirup Basu]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 06:57:03 GMT</pubDate>
            <atom:updated>2024-09-18T06:57:03.493Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Deep Dive into JavaScript Dependency Management Tools for Modern Projects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JWTH_4Orsu8aqAcO" /><figcaption>Photo by <a href="https://unsplash.com/@rahuulmiishra?utm_source=medium&amp;utm_medium=referral">Rahul Mishra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the ever-evolving landscape of JavaScript development, choosing the right package manager can significantly impact your project’s efficiency and performance. As an experienced JavaScript developer, I’ve worked with various tools and witnessed the evolution of dependency management in our ecosystem. In this article, I’ll dig deep into the three heavyweight contenders in the package management arena — NPM, YARN, and PNPM.</p><h3>NPM: The Pioneer</h3><p><a href="https://www.npmjs.com/">NPM</a>, introduced in 2010, is the default package manager for <a href="https://nodejs.org/en">Node.js</a>. It revolutionized JavaScript development by providing a centralized repository for sharing and reusing code.</p><p><strong>Pros:</strong></p><ul><li>Largest package ecosystem</li><li>Integrated with Node.js</li><li>Familiar to most developers</li></ul><p><strong>Cons:</strong></p><ul><li>Slower performance compared to alternatives</li><li>Less efficient disk space usage</li><li>Potential security vulnerabilities in older versions</li></ul><h3>YARN: The Contender</h3><p><a href="https://yarnpkg.com/">YARN</a>, developed by Facebook in 2016, aimed to address some of NPM’s shortcomings, particularly in terms of performance and consistency.</p><p><strong>Pros:</strong></p><ul><li>Faster installation times than NPM</li><li>Yarn.lock file for consistent installations</li><li>Offline mode for improved reliability</li></ul><p><strong>Cons:</strong></p><ul><li>Still uses a flat node_modules structure</li><li>Can be slower than PNPM in some scenarios</li></ul><h3>PNPM: The Game Changer</h3><p><a href="https://pnpm.io/">PNPM</a>, short for “Performant NPM,” is the newest contender, gaining rapid adoption due to its innovative approach to package management.</p><p><strong>Pros:</strong></p><ul><li>Highly efficient disk space usage</li><li>Fastest installation times in most scenarios</li><li>Improved security through stricter dependency isolation</li></ul><p><strong>Cons:</strong></p><ul><li>Smaller community compared to NPM and YARN</li><li>Potential compatibility issues with some packages</li></ul><h3>Performance Comparison</h3><p>When it comes to speed, PNPM often outperforms both NPM and YARN. According to benchmarks:</p><ul><li>PNPM is typically 2–3 times faster than NPM and YARN for fresh installs</li><li>For subsequent installs from the cache, PNPM maintains its lead, though the gap narrows</li></ul><h3>Disk Space Efficiency</h3><p>PNPM truly shines in disk space efficiency:</p><ul><li>Uses a <a href="https://pnpm.io/motivation">content-addressable storage system</a></li><li>Shares package versions across projects</li><li>Can save gigabytes of disk space in large monorepo setups</li></ul><p>NPM and YARN, with their flat node_modules structure, often lead to duplication and wasted space.</p><h3>Security Considerations</h3><p>All three package managers have made strides in security, but PNPM offers some unique advantages:</p><ul><li>Stricter dependency isolation prevents unauthorized access to packages</li><li>Like YARN, PNPM uses checksums to verify package integrity</li></ul><p>NPM has improved its security features over time, but older versions may have vulnerabilities.</p><h3>Ease of Migration</h3><p>Migrating between package managers is relatively straightforward:</p><ul><li>PNPM is designed as a drop-in replacement for NPM</li><li>Most NPM and YARN commands have direct PNPM equivalents</li><li>YARN to PNPM migration is usually smooth due to similar philosophies</li></ul><h3>Advanced Features</h3><p>PNPM offers several advanced features that set it apart:</p><ol><li><strong>Workspaces:</strong> Excellent support for monorepo setups</li><li><strong>Offline Mode:</strong> Efficient caching for offline development</li><li><strong>NodeLinker Mode:</strong> Flexible linking strategies</li><li><strong>Hooks and User Scripts:</strong> Customizable lifecycle scripts</li></ol><p>While NPM and YARN offer some similar features, PNPM’s implementation is often more efficient and flexible.</p><h3>Conclusion</h3><p>As experienced JavaScript developers know, the choice of package manager can significantly impact project workflow, performance, and maintenance. Each of the package managers we’ve discussed — NPM, YARN, and PNPM — has its strengths and use cases.</p><p>For beginners or small projects, NPM’s familiarity and extensive ecosystem make it a safe choice. It’s also the easiest to get started with, as it comes bundled with Node.js.</p><p>In modern, large-scale JavaScript projects, we’re seeing an increasing adoption of both YARN and PNPM. Yarn is often chosen for its balance of performance improvements and widespread adoption. PNPM, with its unique approach to dependency management, is gaining traction, especially in projects where disk space efficiency and strict dependency isolation are crucial.</p><p>As experienced developers, your choice will likely depend on specific project requirements:</p><ol><li>For projects requiring maximum package compatibility and where onboarding new developers quickly is a priority, NPM might still be the go-to choice.</li><li>If you need improved performance and consistency over NPM, without straying too far from familiar workflows, YARN could be the ideal option.</li><li>For large-scale projects, monorepos, or scenarios where disk space and dependency isolation are critical, PNPM’s innovative approach might provide significant benefits.</li></ol><p>It’s worth noting that migrating between these package managers is relatively straightforward, so you’re not locked into one choice permanently. Many teams find value in experimenting with different package managers on new projects to find the best fit for their workflows and requirements.</p><p>Ultimately, the “best” package manager depends on your specific needs, team expertise, and project constraints. As the JavaScript ecosystem continues to evolve, staying informed about these tools and their developments will help you make optimal decisions for your projects and teams.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0cfce779545" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering TypeScript in React: Benefits, Challenges, and Migration Strategies]]></title>
            <link>https://medium.com/@basu.abhirup27/mastering-typescript-in-react-benefits-challenges-and-migration-strategies-2ddf3d03da20?source=rss-4e0b491aba16------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ddf3d03da20</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Abhirup Basu]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 07:19:44 GMT</pubDate>
            <atom:updated>2024-09-16T07:19:44.379Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore the advantages and challenges of using TypeScript in React applications and strategies for migrating existing projects to TypeScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRVfTk0eeeQnxtZZDaY9Bg.jpeg" /><figcaption>Mastering TypeScript in React (Generated using “Adobe Firefly”)</figcaption></figure><p>React has been a dominant force in front-end development for years, and TypeScript has been gaining significant traction in the JavaScript ecosystem. Combining these technologies can lead to more robust and maintainable React applications. This article explores the advantages and challenges of using TypeScript in React projects and strategies for migrating existing React applications to TypeScript.</p><h3>Pros of Using TypeScript in React Projects</h3><h4>1. Static Type Checking</h4><p>TypeScript’s static typing can catch many common errors at compile-time, reducing runtime errors in React components and their props. This is particularly beneficial for larger React applications with complex component hierarchies.</p><p>Example of type checking in a React component:</p><pre>interface UserProps {<br>  name: string;<br>  age: number;<br>  email: string;<br>}<br><br>const UserProfile: React.FC&lt;UserProps&gt; = ({ name, age, email }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{name}&lt;/h2&gt;<br>      &lt;p&gt;Age: {age}&lt;/p&gt;<br>      &lt;p&gt;Email: {email}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>// Usage<br>const App: React.FC = () =&gt; {<br>  return (<br>    &lt;UserProfile<br>      name=&quot;John Doe&quot;<br>      age={30}<br>      email=&quot;john@example.com&quot;<br>    /&gt;<br>  );<br>};</pre><p>In this example, TypeScript will catch errors if you try to pass incorrect types or miss required props when using the `UserProfile` component.</p><h4>2. Enhanced Code Maintainability</h4><p>With TypeScript, you can define interfaces for component props and state, making it easier to understand and maintain component APIs. This is especially useful when working in teams or on long-term projects.</p><h4>3. Improved Developer Productivity</h4><p>TypeScript provides better autocompletion and IntelliSense in modern IDEs, which can significantly speed up development and reduce errors when working with React components and libraries.</p><h4>4. Better Refactoring Support</h4><p>TypeScript’s static typing makes it easier to refactor React components and their usage throughout an application. The compiler will catch many issues that might arise during refactoring.</p><h4>5. Enhanced Documentation</h4><p>TypeScript interfaces serve as inline documentation for your React components, making it easier for developers to understand how to use components without having to dive into the implementation details.</p><h3>Cons of Using TypeScript in React Projects</h3><h4>1. Learning Curve</h4><p>Developers who are new to TypeScript may face a learning curve, especially when dealing with more advanced type concepts in React contexts (e.g., generic components, conditional types).</p><h4>2. Initial Setup Complexity</h4><p>Setting up a new React project with TypeScript requires additional configuration, which can be intimidating for beginners or time-consuming for quick prototypes.</p><h4>3. Increased Boilerplate</h4><p>TypeScript often requires more code upfront to define types and interfaces, which can make simple React components more verbose.</p><h4>4. Potential Over-typing</h4><p>There’s a risk of spending too much time on creating elaborate type structures, which might not always provide proportional benefits in smaller projects.</p><h4>5. Third-party Library Compatibility</h4><p>While improving, not all React libraries have good TypeScript support, which can lead to challenges when integrating certain packages.</p><h3>Migration Strategies</h3><p>Let’s go through a step-by-step process of migrating an existing React project from JavaScript to TypeScript.</p><h4>1. Install TypeScript and Type Definitions</h4><p>First, install TypeScript and the necessary type definitions:</p><pre>npm install --save-dev typescript @types/react @types/react-dom @types/node</pre><h4>2. Create a TypeScript Configuration File</h4><p>Create a tsconfig.json file in your project root:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],<br>    &quot;allowJs&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;allowSyntheticDefaultImports&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;noFallthroughCasesInSwitch&quot;: true,<br>    &quot;module&quot;: &quot;esnext&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;noEmit&quot;: true,<br>    &quot;jsx&quot;: &quot;react-jsx&quot;<br>  },<br>  &quot;include&quot;: [&quot;src&quot;]<br>}</pre><h4>3. Rename Files</h4><p>Rename your .js or .jsx files to .ts or .tsx respectively. For example:</p><pre>mv src/App.js src/App.tsx<br>mv src/index.js src/index.tsx</pre><h4>4. Gradual Migration of Components</h4><p>Start with a simple component and add types gradually. Here’s an example of migrating a functional component:</p><pre>// Before (App.js)<br><br>const App = ({ message }) =&gt; {<br>  return &lt;div&gt;{message}&lt;/div&gt;;<br>};<br><br>export default App;<br><br>// After (App.tsx)<br><br>interface AppProps {<br>  message: string;<br>}<br><br>const App: React.FC&lt;AppProps&gt; = ({ message }) =&gt; {<br>  return &lt;div&gt;{message}&lt;/div&gt;;<br>};<br><br>export default App;</pre><h4>5. Handling State with TypeScript</h4><p>When using hooks, you can specify types for state:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>interface User {<br>  name: string;<br>  age: number;<br>}<br><br>const UserProfile: React.FC = () =&gt; {<br>  const [user, setUser] = useState&lt;User | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    // Simulating an API call<br>    const fetchUser = async () =&gt; {<br>      const response = await fetch(&#39;/api/user&#39;);<br>      const userData: User = await response.json();<br>      setUser(userData);<br>    };<br><br>    fetchUser();<br>  }, []);<br><br>  if (!user) return &lt;div&gt;Loading...&lt;/div&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{user.name}&lt;/h2&gt;<br>      &lt;p&gt;Age: {user.age}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UserProfile;</pre><h4>6. Migrating Class Components</h4><p>For class components, you can use TypeScript to define prop and state types:</p><pre><br>interface CounterProps {<br>  initialCount: number;<br>}<br><br>interface CounterState {<br>  count: number;<br>}<br><br>class Counter extends React.Component&lt;CounterProps, CounterState&gt; {<br>  constructor(props: CounterProps) {<br>    super(props);<br>    this.state = {<br>      count: props.initialCount,<br>    };<br>  }<br><br>  increment = () =&gt; {<br>    this.setState((prevState) =&gt; ({ count: prevState.count + 1 }));<br>  };<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;p&gt;Count: {this.state.count}&lt;/p&gt;<br>        &lt;button onClick={this.increment}&gt;Increment&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>export default Counter;</pre><h4>7. Use TypeScript with React Hooks</h4><p>TypeScript works well with React Hooks. Here’s an example using useReducer:</p><pre>import { useReducer } from &#39;react&#39;;<br><br>interface State {<br>  count: number;<br>}<br><br>type Action = { type: &#39;increment&#39; } | { type: &#39;decrement&#39; };<br><br>const reducer = (state: State, action: Action): State =&gt; {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return { count: state.count + 1 };<br>    case &#39;decrement&#39;:<br>      return { count: state.count - 1 };<br>    default:<br>      return state;<br>  }<br>};<br><br>const Counter: React.FC = () =&gt; {<br>  const [state, dispatch] = useReducer(reducer, { count: 0 });<br><br>  return (<br>    &lt;div&gt;<br>      Count: {state.count}<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;increment&#39; })}&gt;+&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;decrement&#39; })}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Counter;</pre><h3>Conclusion</h3><p>Integrating TypeScript into React projects offers significant advantages in terms of code quality, maintainability, and developer experience. However, it does come with some challenges, particularly in terms of initial setup and learning curve. By adopting a gradual migration strategy and focusing on the most impactful areas first, teams can successfully leverage TypeScript in their React projects while minimizing disruption.</p><p>As the React ecosystem continues to embrace TypeScript, the benefits of using it in React projects are likely to increase, making it a valuable skill for React developers to acquire and utilize.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ddf3d03da20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10-Minute Guide to Building a REST API with Node.js & MongoDB]]></title>
            <link>https://medium.com/@basu.abhirup27/build-your-first-rest-api-in-10-minutes-using-node-js-and-mongodb-2c15ac29e413?source=rss-4e0b491aba16------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c15ac29e413</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[mongodb-tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abhirup Basu]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 12:27:30 GMT</pubDate>
            <atom:updated>2024-09-16T07:11:07.129Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>Create your first REST API in 10 minutes using Node.js, Express.js, and MongoDB.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnCkLHTj1qtrsrWD-dLzjg.jpeg" /></figure><p>In this guide, I’ll walk you through creating your first REST API using Node.js, Express.js, and MongoDB. If you’re completely new to Node.js and MongoDB, don’t worry—I&#39;ll break down everything into easy-to-follow steps.</p><p>By the end, you’ll have a basic API that allows you to Create, Read, Update, and Delete (CRUD) articles in a database.</p><h3>What is a REST API?</h3><p>REST, or <strong>Representational State Transfer</strong>, is a widely used architectural style for building APIs (Application Programming Interfaces). It allows communication between client and server via standard HTTP methods (also known as “verbs”) to perform actions on resources (like data). REST is stateless, meaning each request from the client contains all the necessary information for the server to understand and process it — there’s no need to store session information on the server.</p><p>Let’s break down REST using a common example of interacting with <strong>articles</strong> in a blog, covering the HTTP verbs and route naming conventions.</p><h3>REST HTTP Verbs Explained</h3><p>REST APIs primarily use these HTTP methods:</p><ol><li><strong>GET</strong> — Retrieve data (read-only)</li><li><strong>POST</strong> — Create a new resource (like adding data)</li><li><strong>PUT</strong> — Replace an existing resource entirely (update)</li><li><strong>PATCH</strong> — Update a specific part of an existing resource (partial update)</li><li><strong>DELETE</strong> — Remove a resource</li></ol><p>These methods allow the client (like a browser or app) to interact with resources (like articles, users, or products) stored on a server.</p><h3>Conventions for Route Naming in REST APIs</h3><p>RESTful APIs follow specific conventions for <strong>route naming</strong>. These conventions make it easier to understand the purpose of each route just by looking at the URL.</p><ol><li><strong>Resources should be nouns</strong>: RESTful routes typically represent resources like articles, users, or products. Instead of verbs, we use nouns in the URL.<br>Example: /articles, /users, /products</li><li><strong>Use plural nouns for collections</strong>: When referring to a collection of resources (like all articles), use the plural form.<br>Example: <strong>GET /articles</strong>: Retrieves all articles.</li><li><strong>Use IDs to reference specific resources</strong>: When working with a specific resource, use its unique ID in the route.<br>Example: <strong>GET /articles/1</strong>: Retrieves the article with ID 1.</li><li><strong>Nest resources for relationships</strong>: If a resource is related to another resource, you can nest routes.<br>Example:<strong> GET /users/1/articles</strong>: Retrieves all articles written by the user with ID</li><li><strong>Use HTTP methods for actions</strong>: Instead of including actions in the URL (like /createArticle), use HTTP methods to specify the action.<br>Example:<strong> POST /articles</strong> (instead of /createArticle): Creates a new article.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*-i1iSrs8SkPci5xmUGtVaw.png" /><figcaption>Summary of REST Conventions</figcaption></figure><p>By adhering to these conventions, your API will be clean, easy to use, and maintainable.</p><p>In this example, we’ll build a REST API for managing articles in a database.</p><h3>Step-by-Step Guide</h3><h4>1. Install Node.js</h4><p>First, you’ll need to install Node.js on your computer. <a href="https://nodejs.org/">Download it here</a> and follow the installation instructions. Node.js will allow you to run JavaScript on your computer.</p><p>To verify if Node.js is installed, run this command in your terminal:</p><pre>node -v</pre><h4>2. Install MongoDB</h4><p>MongoDB is a NoSQL database, meaning it stores data in a flexible, document-like format (instead of tables and rows like SQL databases). <a href="https://www.mongodb.com/try/download/community">Download MongoDB here</a> and follow the setup instructions for your operating system.</p><p>To check if MongoDB is installed, you can run:</p><pre>mongod --version</pre><h4>3. Create a New Project Folder</h4><p>Create a folder for your project. Open your terminal and run:</p><pre>mkdir MyFirstRestAPI<br>cd MyFirstRestAPI</pre><h4>4. Initialize Node.js in the Project</h4><p>In your project folder, you need to initialize npm (Node Package Manager), which helps you manage your project’s dependencies (libraries).</p><pre>npm init -y</pre><p>This will generate a package.json file where the project&#39;s settings and dependencies will be listed.</p><h4>5. Install the Required Packages</h4><p>We’ll need four packages:</p><ul><li>express: A web framework to help you handle routing (URLs).</li><li>body-parser: To process data sent in requests (like forms).</li><li>mongoose: To connect and interact with MongoDB.</li><li>nodemon (optional): Automatically restarts the server when files change.</li></ul><p>Run this command to install these packages:</p><pre>npm install express body-parser mongoose</pre><p>To install nodemon, use this command:</p><pre>npm install -g nodemon</pre><h4>6. Set Up MongoDB</h4><p>Start your MongoDB server in a separate terminal window:Copy code</p><pre>mongod</pre><p>Then, open a new terminal tab or window and start the MongoDB shell by running:</p><pre>mongosh</pre><p>Once inside the shell, create a new database:</p><pre>use WikiDB</pre><p>Now create a collection (similar to a table) for storing articles:</p><pre>db.articles.insertMany([<br>  { title: &quot;Article 1&quot;, content: &quot;Content for article 1&quot; },<br>  { title: &quot;Article 2&quot;, content: &quot;Content for article 2&quot; }<br>])</pre><h4>7. Set Up the Express Server</h4><p>Now, let’s create our server.</p><ol><li>Create a file named app.js in your project folder:</li></ol><pre>touch app.js</pre><ol><li>Open app.js and add the following code to set up a basic Express server:</li></ol><pre>const express = require(&quot;express&quot;);<br>const bodyParser = require(&quot;body-parser&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br><br>const app = express();<br>app.use(bodyParser.urlencoded({ extended: true }));<br><br>// Connect to the MongoDB database<br>mongoose.connect(&quot;mongodb://localhost:27017/wikiDB&quot;, { useNewUrlParser: true });<br><br>// Create a schema for the articles<br>const articleSchema = new mongoose.Schema({<br>  title: String,<br>  content: String,<br>});<br><br>// Create a model for the articles<br>const Article = mongoose.model(&quot;Article&quot;, articleSchema);<br><br>// Start the server on port 3000<br>app.listen(3000, () =&gt; {<br>  console.log(&quot;Server started on port 3000&quot;);<br>});</pre><p>Let’s break this down:</p><ul><li>We import express, body-parser, and mongoose.</li><li>We initialize an Express app and configure it to parse URL-encoded data (data from forms).</li><li>We connect to a MongoDB database called wikiDB.</li><li>We define a schema and a model for our articles.</li><li>We start the server on port 3000.</li></ul><h4>8. Define the REST API Routes</h4><p>Now let’s create the routes (or URL paths) for our API. We’ll break each route handler into separate functions for clarity.</p><p>1. <strong>Handle GET Requests (Retrieve Articles)</strong></p><p>We want to allow the user to retrieve a list of all articles.</p><pre>// Handle GET requests to /articles<br>app.get(&quot;/articles&quot;, (req, res) =&gt; {<br>  Article.find({}, (err, foundArticles) =&gt; {<br>    if (!err) {<br>      res.send(foundArticles);<br>    } else {<br>      res.send(err);<br>    }<br>  });<br>});</pre><p>This route listens for GET requests at /articles. When a request is made, it retrieves all articles from the database using the find method.</p><p>2. <strong>Handle POST Requests (Create New Articles)</strong></p><p>We need a way to allow users to add new articles.</p><pre>// Handle POST requests to /articles<br>app.post(&quot;/articles&quot;, (req, res) =&gt; {<br>  const newArticle = new Article({<br>    title: req.body.title,<br>    content: req.body.content,<br>  });<br><br>  newArticle.save((err) =&gt; {<br>    if (!err) {<br>      res.send(&quot;Successfully added a new article.&quot;);<br>    } else {<br>      res.send(err);<br>    }<br>  });<br>});</pre><p>Here, when a POST request is made to /articles, the server creates a new article with the data from the request body and saves it to the database.</p><p>3. <strong>Handle Specific Routes (GET, PUT, PATCH, DELETE for Specific Articles)</strong></p><p>Now, let’s handle requests to a specific article by its title.</p><pre>app.route(&quot;/articles/:articleTitle&quot;)<br>  .get((req, res) =&gt; {<br>    Article.findOne({ title: req.params.articleTitle }, (err, foundArticle) =&gt; {<br>      if (foundArticle) {<br>        res.send(foundArticle);<br>      } else {<br>        res.send(&quot;No article matching that title was found.&quot;);<br>      }<br>    });<br>  })<br>  .put((req, res) =&gt; {<br>    Article.updateOne(<br>      { title: req.params.articleTitle },<br>      { title: req.body.title, content: req.body.content },<br>      (err) =&gt; {<br>        if (!err) {<br>          res.send(&quot;Successfully updated article.&quot;);<br>        } else {<br>          res.send(err);<br>        }<br>      }<br>    );<br>  })<br>  .patch((req, res) =&gt; {<br>    Article.updateOne(<br>      { title: req.params.articleTitle },<br>      { $set: req.body },<br>      (err) =&gt; {<br>        if (!err) {<br>          res.send(&quot;Successfully updated article.&quot;);<br>        } else {<br>          res.send(err);<br>        }<br>      }<br>    );<br>  })<br>  .delete((req, res) =&gt; {<br>    Article.deleteOne({ title: req.params.articleTitle }, (err) =&gt; {<br>      if (!err) {<br>        res.send(&quot;Successfully deleted the article.&quot;);<br>      } else {<br>        res.send(err);<br>      }<br>    });<br>  });</pre><p>This block of code handles the GET, PUT, PATCH, and DELETE requests for a specific article by its title.</p><ul><li>GET retrieves an article by its title.</li><li>PUT replaces the entire article with a new one.</li><li>PATCH updates specific fields of an article.</li><li>DELETE removes a specific article.</li></ul><h4>9. Run the Server</h4><p>Now that your API is ready, start the server using:</p><pre>nodemon app.js</pre><p>If everything is set up correctly, you’ll see:</p><pre>Server started on port 3000</pre><h3>Testing Your REST API with Postman</h3><p>Once your REST API is running, Postman can help you test each route easily.</p><h4>Steps to Test API with Postman:</h4><ol><li><strong>Install Postman</strong>: <a href="https://www.postman.com/downloads/">Download Postman and install it</a>.</li><li><strong>Set up requests</strong>:</li></ol><p><strong>GET Request</strong>:</p><ul><li>Open Postman, select GET, and enter <a href="http://localhost:3000/articles.">http://localhost:3000/articles.</a></li><li>Click “Send” to retrieve all articles.</li></ul><p><strong>POST Request</strong>:</p><ul><li>Select POST, and enter <a href="http://localhost:3000/articles.">http://localhost:3000/articles.</a></li><li>Under the <strong>Body</strong> tab, select <strong>x-www-form-urlencoded</strong> and add:</li><li>title: &quot;New Article&quot;</li><li>content: &quot;This is the content&quot;</li><li>Click “Send” to create a new article.</li></ul><p><strong>PUT Request</strong>:</p><ul><li>Select PUT, enter <a href="http://localhost:3000/articles/ArticleTitle.">http://localhost:3000/articles/:articleTitle</a></li><li>Replace :articleTitle in the URL path with the exact title of the article you want to update.</li><li>Provide new title and content in the <strong>Body</strong>.</li><li>Click “Send” to replace the article.</li></ul><p><strong>PATCH Request</strong>:</p><ul><li>Select PATCH, enter <a href="http://localhost:3000/articles/ArticleTitle.">http://localhost:3000/articles/:articleTitle</a></li><li>Replace :articleTitle in the URL path with the exact title of the article you want to update.</li><li>Provide only the field to update, like title in the <strong>Body</strong>.</li><li>Click “Send” to update part of the article.</li></ul><p><strong>DELETE Request</strong>:</p><ul><li>Select DELETE, enter <a href="http://localhost:3000/articles/ArticleTitle.">http://localhost:3000/articles/:articleTitle</a></li><li>Replace :articleTitle in the URL path with the exact title of the article you want to delete.</li><li>Click “Send” to delete the article.</li></ul><h3>Conclusion</h3><p>Congratulations! You’ve successfully built and tested your first REST API using Node.js, Express, and MongoDB. By using Postman, you were able to verify the functionality of each route — testing GET, POST, PUT, PATCH, and DELETE requests with ease.</p><p>Through this guide, you’ve learned to:</p><ul><li>Set up a Node.js server with Express</li><li>Connect and interact with a MongoDB database</li><li>Implement RESTful routes to handle CRUD operations</li><li>Test API routes using Postman</li></ul><p>With these skills, you’re well-equipped to expand your API, integrate it with front-end applications, or build more advanced APIs in the future.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c15ac29e413" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>