<?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 Rohit Raj on Medium]]></title>
        <description><![CDATA[Stories by Rohit Raj on Medium]]></description>
        <link>https://medium.com/@rohitraj1912000?source=rss-13fb7706ee99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a0YMGTvohkhjNxWyS3N7Xg.jpeg</url>
            <title>Stories by Rohit Raj on Medium</title>
            <link>https://medium.com/@rohitraj1912000?source=rss-13fb7706ee99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:15:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohitraj1912000/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[Silent Performance Wins: Practical Lessons from Optimizing a Real-World Node.js + React System]]></title>
            <link>https://medium.com/@rohitraj1912000/silent-performance-wins-practical-lessons-from-optimizing-a-real-world-node-js-react-system-d3e376065f87?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3e376065f87</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 18:34:00 GMT</pubDate>
            <atom:updated>2025-10-07T18:34:00.700Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last few months, I’ve been working with one of my client’s projects to quietly — but significantly — improve system performance.</p><p>The goal wasn’t to do a complete rewrite or add fancy infrastructure. Instead, the focus was on identifying the small, often-overlooked optimizations that collectively make the system faster, lighter, and more reliable.</p><p>Here are some of the techniques that made a noticeable difference — both on the backend (Node.js) and the frontend (React.js).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*adGfncOiWTBYSW-v" /><figcaption>written by Rohit Raj</figcaption></figure><h3>1. Parallelizing Independent Calls</h3><p>A surprising amount of time in most APIs is lost waiting for independent operations to finish one after another.</p><p>If two or more downstream calls don’t depend on each other, running them in parallel can drastically reduce latency.</p><pre>// Before<br>const user = await getUser(id);<br>const orders = await getOrders(user.id);</pre><pre>// After<br>const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);</pre><p>This simple change helped reduce end-to-end API response times by 30–40% in a few places.</p><h3>2. Smart Caching at the Upstream Layer</h3><p>We started caching static and semi-static data at the upstream service layer to reduce unnecessary downstream calls.</p><p>The key was to set appropriate <strong>TTL (Time To Live)</strong> and handle <strong>cache invalidation</strong> properly — since stale data can be worse than no data.</p><p>Example with Node.js memory cache:</p><pre>import NodeCache from &#39;node-cache&#39;;<br>const cache = new NodeCache({ stdTTL: 300 }); // cache for 5 mins<br><br>async function getConfig() {<br>  const cached = cache.get(&#39;config&#39;);<br>  if (cached) return cached;<br>  const config = await fetchConfigFromDB();<br>  cache.set(&#39;config&#39;, config);<br>  return config;<br>}</pre><p>Caching reduced load on our downstream systems by nearly 50% in some endpoints.</p><h3>3. Eliminating Redundant Calls (Deduplication)</h3><p>When multiple parts of an API make the same downstream request, it results in wasted effort and latency.</p><p>We implemented a simple deduplication layer that detects identical in-flight requests and reuses their responses instead of triggering new ones.</p><p>This was especially helpful in microservices that aggregate data from multiple sources.</p><h3>4. Diagnosing Bottlenecks with Traces and Timing Logs</h3><p>To make performance improvements meaningful, we needed visibility.</p><p>I relied heavily on:</p><ul><li><strong>Waterfall traces</strong> (to visualize internal call timings per API)</li><li>console.time() / console.timeEnd() for precise measurement</li></ul><p>Example:</p><pre>console.time(&#39;fetch-user&#39;);<br>const user = await getUser(id);<br>console.timeEnd(&#39;fetch-user&#39;);</pre><p>This made it clear which internal steps dominated our response time.</p><h3>5. Compressing and Optimizing Payloads</h3><p>Reducing payload size is one of the most effective (and easiest) wins.</p><p>We enabled compression in Node.js using the compression library:</p><pre>import compression from &#39;compression&#39;;<br>app.use(compression());</pre><p>We also revisited response payloads to ensure the backend wasn’t sending unnecessary or verbose data structures. Returning only what’s actually needed helped both network speed and frontend parsing time.</p><h3>6. Database-Level Optimizations</h3><p>In downstream repositories, I spent time checking:</p><ul><li>Whether queries were <strong>indexed</strong> properly</li><li>Avoiding full table <strong>scans</strong></li><li>Ensuring <strong>connection pooling</strong> was configured correctly</li><li>Applying <strong>pagination</strong> for heavy data fetches</li></ul><p>A well-indexed query or a properly pooled connection can easily outperform most code-level optimizations.</p><h3>7. Frontend Performance: React and Beyond</h3><p>On the React side, we targeted metrics like <strong>LCP (Largest Contentful Paint)</strong> and <strong>FCP (First Contentful Paint)</strong> — the key indicators of how fast the user perceives the page to load.</p><h3>a. Bundle Size Reduction</h3><p>We audited the build output and trimmed unnecessary dependencies. Even small libraries add up quickly.</p><h3>b. Lazy Loading via Dynamic Imports</h3><p>Instead of loading everything upfront, we dynamically import routes and modules:</p><pre>const UserProfile = React.lazy(() =&gt; import(&#39;./UserProfile&#39;));</pre><p>This defers loading until needed and improves initial load times significantly.</p><h3>c. Monitoring User Experience</h3><p>We integrated <strong>Lighthouse</strong> audits during development and used <strong>Sentry</strong> + <strong>AWS RUM (Real User Monitoring)</strong> to track actual performance metrics and user sessions in production.</p><p>These insights helped us identify slow pages, assets, or API calls that users really felt.</p><h3>8. The “Silent” Wins</h3><p>None of these changes required new frameworks or expensive hardware.<br> They were simply thoughtful adjustments — parallelization, caching, compression, query tuning, and better monitoring.</p><p>Each improvement was small on its own, but together they created a much faster, more efficient system — without any visible disruption.</p><h3>Closing Thoughts</h3><p>Performance optimization isn’t always about adding new tech.<br> It’s about <strong>removing friction</strong> — in code, data flow, and delivery.</p><p>The key is to observe, measure, and optimize silently.</p><p>If your app feels slow, start by tracing, measuring, and questioning every call.<br> Chances are, your next big win will come from something small.</p><p>Written By:<br>Rohit Raj<br>Software Engineer</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3e376065f87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Why My Brain is an API: Thoughts from a Fullstack Developer]]></title>
            <link>https://medium.com/@rohitraj1912000/why-my-brain-is-an-api-thoughts-from-a-fullstack-developer-a7f959f6b2ee?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7f959f6b2ee</guid>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[funny]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 15:52:29 GMT</pubDate>
            <atom:updated>2025-07-07T15:52:29.119Z</atom:updated>
            <content:encoded><![CDATA[<p>“I’m a fullstack developer — which means I understand enough frontend to know I want to be a backend developer.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HI4mx7w5kaBoC1qt" /><figcaption>Written by Rohit Raj</figcaption></figure><p>As someone who primarily lives and breathes backend (Node.js, Java Spring Boot) but frequently ventures into the pixel-pushing chaos of frontend (yes, I’m looking at you, React), I’ve come to one inevitable realization:</p><p><strong>My brain thinks in APIs. But React doesn’t care.</strong></p><p>This article is a heartfelt, humorous look into the identity crisis I go through every time I shift from clean backend logic to the wild jungle of the frontend UI.</p><h4>🧩 Thinking in Controllers, but Rendering in Components</h4><p>When I’m writing backend code, everything feels logical — almost poetic.</p><pre>// Node.js<br>router.post(&#39;/tasks&#39;, authenticate, validateBody, createTask);</pre><p>It’s structured. I know the flow. I can debug it with my eyes closed.Now, switch to the frontend:</p><pre>const [clicked, setClicked] = useState(false);<br><br>return (<br>  &lt;div className={`btn ${clicked ? &#39;active&#39; : &#39;&#39;}`} onClick={() =&gt; setClicked(!clicked)}&gt;<br>    Click Me<br>  &lt;/div&gt;<br>)</pre><p>And suddenly I’m asking:<br> <strong>“Wait, why is this class not applying?”</strong><br> <strong>“What is hydration error?”</strong><br> <strong>“Why do I need <em>another</em> custom hook to manage a dropdown?”</strong></p><p>The backend is like chess. Frontend is like trying to solve a Rubik’s cube that’s on fire… in reverse.</p><h4>🪓 When Props Drilling Drills Your Soul</h4><p>In backend, I pass data from service to controller. Done.</p><p>In React:</p><ul><li>Parent needs to pass userData to a child → which passes it to another → which passes it to another…</li><li>Somewhere deep down the tree, a component just needs a single username.</li></ul><p>But instead of just calling a function, I’m doing a <strong>prop relay race</strong></p><pre>&lt;Parent&gt;<br>  &lt;Child&gt;<br>    &lt;Grandchild username={username} /&gt;<br>  &lt;/Child&gt;<br>&lt;/Parent&gt;</pre><p>Why, oh why, does my simple API response have to suffer such a tragic journey?</p><p>I used to think REST APIs were hard. Then I discovered context API, Redux, and Zustand.<br> Now I long for the sweet simplicity of just throwing everything into res.locals.</p><h3>😩 The Emotionally Unstable State of State</h3><p>Backend data flows like this:</p><ul><li>Request → Validate → Process → Respond</li><li>You know what changed, where, and why.</li></ul><p>Frontend state?</p><ul><li>useState, useRef, useContext, useReducer, useQuery, useStore, useMutation, useCache, useTheForce</li></ul><p>Half the time, I’m updating state, and the UI doesn’t reflect it. Other times, the UI updates… but nothing actually changed.</p><p>And don’t even get me started on <strong>React re-renders</strong></p><h3>🕹️ Debugging Tools vs Design Tools</h3><p>As a backend dev:</p><ul><li>I love Postman. Logs. Stack traces.</li><li>I can explain a 500 error in 10 seconds.</li></ul><p>As a frontend dev:</p><ul><li>I open DevTools, see a red error.</li><li>It says “Cannot read property ‘map’ of undefined.”</li><li>I spend 30 minutes figuring out I forgot to handle the loading state.</li></ul><p>Or worse:</p><ul><li>“It works in incognito.”</li><li>“It only breaks on iOS Safari 15.3.”</li></ul><h3>❤️ Backend Will Always Be Home</h3><p>Yes, I’m a fullstack dev. But when I deploy my Java Spring Boot microservice, and the logs say:</p><pre>Successfully connected to the database<br>Server running on port 8080</pre><p>It feels like a warm hug.</p><p>Frontend teaches me patience. Backend rewards my logic. Together, they make me a better engineer — but only one of them makes me <strong>feel sane</strong>.</p><p>So to all the fellow backend-first fullstack devs out there…</p><p><strong>It’s okay to cry over CSS. Your API still loves you.</strong></p><h3>🙌 Found this relatable?</h3><p>If you’ve ever screamed at your screen because useEffect didn’t behave, or smiled when your API returned a clean 200 OK — <strong>you’re not alone</strong>.</p><p>👨‍💻 I’m Rohit — a backend-first fullstack developer sharing tech struggles, learnings, and developer humor.</p><p>🔁 <strong>Follow me for more stories, code tips, and the occasional vent about CSS.</strong></p><p>Let’s survive this stack — together. 💻❤️🎨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7f959f6b2ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Was Tired of JSON.parse() Crashing My App — So I Built a Safer Alternative]]></title>
            <link>https://medium.com/@rohitraj1912000/i-was-tired-of-json-parse-crashing-my-app-so-i-built-a-safer-alternative-a9a84366ff8e?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9a84366ff8e</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[parser]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 13:39:48 GMT</pubDate>
            <atom:updated>2025-06-23T13:39:48.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Was Tired of JSON.parse() Crashing My App — So I Built a Safer Alternative</h3><p><em>By: Rohit Raj , Senior Software Developer</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0VveltQWu1uimYbl" /><figcaption>Rohit Raj</figcaption></figure><h3>A few weeks ago, I ran into a frustrating problem — again.</h3><p>I was parsing a JSON string from an API using JavaScript’s built-in JSON.parse(), and once again, one bad input caused my entire application to crash. No fallback. No grace.</p><p>I thought: “Why is there no safer way to parse JSON?”<br>So I built one — and published it on npm.</p><h3>The Problem: JSON.parse() Throws on Invalid JSON<br>If you’ve used JSON.parse() enough, you already know this:</h3><pre>const malformed = &#39;{name: &quot;rohit&quot;}&#39;; // missing quotes<br><br>const parsed = JSON.parse(malformed); // Throws SyntaxError</pre><p>Even if one character is off, it throws a SyntaxError. You need to manually wrap every parse in a try-catch:</p><pre>let data;<br>try {<br> data = JSON.parse(malformed);<br>} catch (e) {<br> data = {}; // fallback<br>}</pre><p>I got tired of repeating that.</p><h3>The Idea: A Safer Wrapper</h3><h4>I wanted a simple helper function:</h4><p><em>That doesn’t throw</em></p><p><em>That returns a fallback if parsing fails</em></p><p><em>That gives me both: parsed data and the error (if any)</em></p><h3>The Solution: @rohit_raj_1901/safe-json-parser<br>I created a tiny npm package that solves this:</h3><pre>npm install @rohit_raj_1901/safe-json-parser</pre><pre>const { safeParse } = require(&#39;@rohit_raj_1901/safe-json-parser&#39;);<br>const badJson = &#39;{name: &quot;rohit&quot;}&#39;;<br>const goodJson = &#39;{&quot;name&quot;: &quot;rohit&quot;}&#39;;<br>console.log(safeParse(goodJson));<br>// ➜ { data: { name: &#39;rohit&#39; }, error: null }<br>console.log(safeParse(badJson, { name: &#39;default&#39; }));<br>// ➜ { data: { name: &#39;default&#39; }, error: [SyntaxError: Unexpected token n…] }</pre><p>You don’t need try/catch anymore. Just use safeParse() and handle both outcomes cleanly.</p><h4>How It Works Internally<br>The logic is dead simple:</h4><pre>function safeParse(str, fallback = null) {<br> try {<br> return { data: JSON.parse(str), error: null };<br> } catch (err) {<br> return { data: fallback, error: err };<br> }<br>}</pre><p>You can check out the full code on GitHub:</p><p><a href="https://github.com/rohit-raj-1901/safe-json-parser">https://github.com/rohit-raj-1901/safe-json-parser</a></p><h3>Why I Published It</h3><p>At first, I just needed it for my own projects. But then I thought: “Others must be running into this too.”<br>So I wrapped it into a clean utility, gave it a name, wrote a README, and published it to npm.</p><p>📦 <a href="http://twitter.com/rohit_raj_1901/safe-json-parser">@rohit_raj_1901/safe-json-parser</a> on npm</p><h3>What’s Next?</h3><p>I plan to:</p><p>Add TypeScript support</p><p>Add an optional strictMode flag</p><p>Accept feedback &amp; contributions</p><p><em>If you find this helpful, feel free to ⭐️ the GitHub repo or suggest improvements!</em></p><h3>Final Thoughts</h3><p>Sometimes the best open-source tools are born out of developer frustration.<br>This was mine. If JSON.parse() has ever annoyed you — give safeParse a shot.</p><p>Let me know what you think or how you’d use it in your own apps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9a84366ff8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Payment Gateway Integration with Node.js — A Practical Guide for Developers]]></title>
            <link>https://medium.com/@rohitraj1912000/deep-dive-into-payment-gateway-integration-with-node-js-a-practical-guide-for-developers-73a7c6346ac7?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/73a7c6346ac7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 10:41:36 GMT</pubDate>
            <atom:updated>2025-06-23T10:41:36.415Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Dive into Payment Gateway Integration with Node.js — A Practical Guide for Developers</h3><p>By Rohit Raj , Senior Software Engineer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-kBfdrekUdJSjwil" /><figcaption>Rohit Raj</figcaption></figure><p>In today’s digital world, online payments are at the heart of most web and mobile applications. Whether you’re building an e-commerce store, a SaaS product, or a simple donation page, integrating a <strong>payment gateway</strong> is a critical skill for developers.</p><p>In this article, we’ll explore how payment gateways work, what you need to know as a developer, and how to approach building a basic integration using <strong>Node.js</strong> — all from a beginner’s perspective.</p><h3>What is a Payment Gateway?</h3><p>A <strong>Payment Gateway</strong> is a technology that enables merchants (businesses) to accept debit/credit card or UPI payments from customers. It acts as a <strong>middleman</strong> between the application and the payment processing networks (like banks, card networks, UPI providers).</p><h4>How it works (simplified flow):</h4><ol><li>User initiates a payment (enters card/UPI details)</li><li>Details are securely passed to the payment gateway</li><li>Gateway verifies and processes the transaction</li><li>The merchant gets confirmation of success or failure</li></ol><h4>Popular payment gateways:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2GsLqHoxZWSv0KhI" /><figcaption>Rohit Raj</figcaption></figure><ul><li><strong>Razorpay</strong> (India-centric, great for INR/UPI)</li><li><strong>Stripe</strong> (global, supports multi-currency)</li><li><strong>PayPal</strong></li><li><strong>Cashfree</strong>, <strong>Paytm</strong>, <strong>Instamojo</strong></li></ul><h4>Why Learn Payment Gateway Integration?</h4><p>If you’re a student or junior developer, working with payment gateways helps you understand:</p><ul><li><strong>Frontend &amp; backend collaboration</strong> (UI to API flow)</li><li><strong>Security practices</strong> (handling sensitive data)</li><li><strong>Real-world APIs</strong> and asynchronous workflows</li><li><strong>Error handling</strong>, currency conversion, and localization</li><li>Practical use of <strong>Node.js</strong> with services like Stripe or Razorpay</li></ul><p>To integrate a basic payment gateway using <strong>Node.js</strong>, here’s what your system generally includes:</p><h3>1. Frontend UI</h3><ul><li>Input fields for amount and currency</li><li>A <strong>“Pay Now”</strong> button</li><li>A modal or redirect flow for entering card/UPI details</li><li>Display of success/failure messages</li></ul><h3>2. Backend Server (Node.js)</h3><ul><li>Handles secure API calls to the payment gateway</li><li>Generates payment intents or orders</li><li>Optionally stores transaction data in a database (like MongoDB)</li></ul><h3>3. Payment Gateway Dashboard</h3><ul><li>A free test/sandbox account</li><li>API keys for authentication</li><li>Logs to monitor all transactions</li></ul><h3>Technical Concepts You Should Know Before Integrating</h3><p>Before jumping in, get comfortable with these:</p><p>1. <strong>Client and Server Roles</strong><br>The client (frontend) collects payment details and triggers the transaction.</p><p>The server (backend) securely communicates with the payment gateway using secret keys and verifies the outcome.</p><p>2. <strong>Tokenization</strong><br>Raw card or bank details are never sent directly. They’re tokenized (converted into a secure one-time token) before being used in requests.</p><p><strong>3. Payment Intent / Order</strong><br>Most gateways require you to create a payment intent (Stripe) or order object (Razorpay) before initiating the payment.</p><p><strong>4. Webhook Events</strong><br>Gateways like Stripe use webhooks to notify your server when events happen (e.g., payment success, failure, refunds).</p><h3>Security &amp; Compliance Considerations:</h3><p><em>Never expose secret keys on frontend</em></p><p><em>Validate all amounts and currencies on the server side</em></p><p><em>Use HTTPS for real deployments</em></p><p><em>Implement webhook signature verification</em></p><p><em>Avoid storing sensitive card data unless you’re PCI-DSS compliant</em></p><h3>Final Thoughts<br>Integrating a payment gateway isn’t just about accepting money — it teaches you about:</h3><p><strong>Security</strong></p><p><strong>API design</strong></p><p><strong>Client-server coordination</strong></p><p><strong>Real-world data workflows</strong></p><p>Start simple. Test with Stripe or Razorpay sandbox. Once you’re confident, try building a complete app with authentication + payments.</p><p>GITHUB LINK :</p><p><a href="https://github.com/rohit-raj-1901/stripe-payment-nodejs">https://github.com/rohit-raj-1901/stripe-payment-nodejs</a></p><p><strong>Building this skill adds a strong edge to your resume and helps you build monetized apps with confidence.</strong></p><p><strong>💬 Have you built a payment integration recently? Planning to use Stripe, Razorpay, or PayPal?</strong></p><p><strong>Let me know your thoughts or questions in the comments 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73a7c6346ac7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ What Could the System Design of GTA 6 Look Like ?]]></title>
            <link>https://medium.com/@rohitraj1912000/what-could-the-system-design-of-gta-6-look-like-8eeabbff98e1?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eeabbff98e1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gta-6]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 18:10:54 GMT</pubDate>
            <atom:updated>2025-06-06T18:10:54.378Z</atom:updated>
            <content:encoded><![CDATA[<p>A Curious Breakdown of Game Architecture for One of the Most Anticipated Titles Ever</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TX3aSrATloFjEcHO" /><figcaption>Written by Rohit Raj</figcaption></figure><p>GTA 6 is one of the most talked-about games in the world right now. With Rockstar Games pushing the boundaries of open-world realism, fans and developers alike are wondering — what kind of tech powers a game like this?</p><p>As someone passionate about backend systems and large-scale architecture, I couldn&#39;t help but imagine the possible system design behind such a massive and immersive game.</p><p>Of course, this is a speculative exploration. The actual architecture used by Rockstar may differ significantly, and likely includes proprietary optimizations. But if we were to build something inspired by GTA 6 today, here’s how it might look.</p><p><strong>Functional Requirements (What GTA 6 Needs to Do)</strong></p><p>1. Massive open world with real-time rendering and interactions</p><p>2. Multiplayer gameplay supporting thousands of concurrent users</p><p>3. Realistic AI behavior (NPCs, police, traffic, pedestrians)</p><p>4. Live events, updates, and patches without downtime</p><p>5. Player progression and inventory saved across devices</p><p>6. Real-time chat and voice communication</p><p>7. Cross-platform support (consoles + PC)</p><p><strong>Non-Functional Requirements</strong></p><p>High availability</p><p>Near-zero latency in real-time interactions</p><p>Scalability across millions of players</p><p>Fault tolerance</p><p>Security (no cheating, no data leaks)</p><p>🏗️ High-Level System Design Overview</p><pre>+--------------------+<br>                     |   Game Clients     |   ← PC, PlayStation, Xbox<br>                     +--------+-----------+<br>                              |<br>                   +----------v-----------+<br>                   |  Matchmaking Gateway |   ← Load Balancer/API Gateway<br>                   +----------+-----------+<br>                              |<br>         +--------------------+--------------------+<br>         |                                         |<br>+--------v--------+                       +--------v--------+<br>|   Game Server   |                       |   Game Server   |   ← Sharded regions or lobbies<br>| (Region: Vice)  |                       | (Region: Leonida) |<br>+--------+--------+                       +--------+--------+<br>         |                                         |<br> +-------v------+                           +------v--------+<br> | Physics + AI |                           |  World Engine |<br> +------------+-+                           +---------------+<br>              |<br>    +---------v-----------+<br>    | Real-Time Database  |   ← Player state, inventory, world state<br>    +---------------------+<br><br>    +------------------------+<br>    | Chat &amp; Voice Services  |<br>    +------------------------+<br><br>    +------------------------+<br>    | Analytics &amp; Anti-Cheat |<br>    +------------------------+</pre><p>🧩 Architecture Patterns That Might Be Used</p><p>1. Microservices Architecture</p><p>Each feature (chat, inventory, matchmaking, anti-cheat) can be developed and deployed independently.</p><p>2. Event-Driven Architecture</p><p>For real-time actions like shooting, car crashes, or police chase triggers — an event bus (like Kafka or RabbitMQ) could relay events instantly across services.</p><p>3. Sharded Game Servers</p><p>The open world could be broken into zones, with each zone handled by a dedicated server or shard to distribute load.</p><p>4. Edge Computing + CDN</p><p>To reduce latency, edge servers can serve assets (textures, scripts) and even handle partial physics computations closer to the players.</p><p>🛠️<strong> Tools &amp; Technologies (Hypothetical Stack)</strong></p><p>Component	Possible Tools/Tech</p><p>Game Engine	Rockstar Advanced Game Engine (RAGE)<br>Matchmaking/API Gateway	NGINX, Envoy, AWS API Gateway<br>Real-Time Networking	WebSockets, gRPC, UDP-based custom protocols<br>Player State Storage	Redis, DynamoDB, CockroachDB<br>Persistent Storage	PostgreSQL, S3 (for replays, assets, etc.)<br>Voice/Chat	Agora, Vivox, WebRTC<br>Analytics	Apache Kafka + Flink + BigQuery<br>Anti-Cheat System	In-house + behavioral modeling + AI detection<br>CI/CD	Jenkins, Docker, Kubernetes, ArgoCD<br>DevOps/Monitoring	Prometheus, Grafana, ELK Stack, Sentry<br>Asset Delivery	Akamai, Cloudflare CDN, AWS CloudFront<br>Cloud Providers	AWS, Azure, or even private bare-metal servers for control and speed</p><p><strong>Bonus Thoughts: AI in GTA 6</strong></p><p>NPC behavior is expected to be next level in GTA 6. For that, Rockstar might be using:</p><p>Behavior Trees for rule-based decision making</p><p>Reinforcement Learning models for dynamic responses</p><p>Procedural Generation for dialogues, movement, or events</p><p>Voice synthesis models for unique NPC voice interactions</p><p>🧨 Conclusion</p><p>Building a game like GTA 6 is not just about great graphics, but about engineering an extremely scalable, low-latency, and intelligent system that runs seamlessly across platforms.</p><p>While we don’t know exactly what Rockstar is using under the hood, this architecture gives us a glimpse into the kind of backend and infrastructure thinking that powers such legendary open-world games.</p><p>If you liked this breakdown, follow me for more deep dives into tech, gaming, and system design! 🎮💻</p><p>Written by:</p><p>Rohit Raj</p><p>Software Development Engineer 🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eeabbff98e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Curious Dive into Java Multithreading and Streams — Explained Simply with Code]]></title>
            <link>https://medium.com/@rohitraj1912000/my-curious-dive-into-java-multithreading-and-streams-explained-simply-with-code-a7127085cbc1?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7127085cbc1</guid>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 16:55:19 GMT</pubDate>
            <atom:updated>2025-06-06T16:55:19.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="My favourite coffeebar. Missing it a lot during the Corona outbreak!" src="https://cdn-images-1.medium.com/max/1024/0*QCCDdVua5kiTl246" /><figcaption>Rohit Raj</figcaption></figure><p>How I Landed into the World of Java Threads and Streams</p><p>I’ve been working with both Java and Node.js for backend development, and I’ve realized that Java has a few important concepts every developer should know—especially when it comes to multithreading and streams.</p><p>Out of curiosity (and a little FOMO 😅), I decided to explore these topics from scratch — and wow, they opened a whole new world of Java programming to me.</p><p>Here’s a beginner-friendly breakdown of what I learned, with code snippets that I hope will help you if you&#39;re on the same journey.</p><p><strong>Understanding</strong> <strong>Threads in Java</strong></p><p><strong>What is a Thread?</strong></p><p>In simple terms, a thread is a lightweight subprocess — the smallest unit of execution. Java programs start with a main thread by default, but we can create multiple threads to run tasks in parallel.</p><p><strong>Why Use Threads?</strong></p><p>For faster performance (e.g., downloading multiple files simultaneously)</p><p>For responsive UIs (in desktop or mobile apps)</p><p>For parallel processing in backend systems</p><p><strong>Basic Example of Creating a Thread:</strong></p><pre>class MyThread extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Thread is running: &quot; + Thread.currentThread().getName());<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        MyThread t1 = new MyThread();<br>        t1.start(); // Starts a new thread<br>    }<br>}</pre><p>Or using <strong>Runnable interface:</strong></p><pre>class MyRunnable implements Runnable {<br>    public void run() {<br>        System.out.println(&quot;Runnable thread: &quot; + Thread.currentThread().getName());<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Thread t = new Thread(new MyRunnable());<br>        t.start();<br>    }<br>}</pre><p><strong>Bonus: Using ExecutorService for Thread Management</strong></p><pre>import java.util.concurrent.*;<br><br>public class ExecutorExample {<br>    public static void main(String[] args) {<br>        ExecutorService service = Executors.newFixedThreadPool(2);<br><br>        service.submit(() -&gt; System.out.println(&quot;Task 1 by &quot; + Thread.currentThread().getName()));<br>        service.submit(() -&gt; System.out.println(&quot;Task 2 by &quot; + Thread.currentThread().getName()));<br><br>        service.shutdown();<br>    }<br>}</pre><p>ExecutorService handles thread pooling efficiently so you don’t have to manage threads manually.</p><p><strong>Exploring Java Streams</strong></p><p>While learning about multithreading, I also stumbled upon Java Streams, which are a powerful feature to process collections in a functional and declarative way.</p><p><strong>Example: Using Streams to Filter and Map</strong></p><pre>import java.util.*;<br>import java.util.stream.*;<br><br>public class StreamExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = Arrays.asList(&quot;Rohit&quot;, &quot;Rahul&quot;, &quot;Raj&quot;, &quot;Riya&quot;);<br><br>        List&lt;String&gt; filtered = names.stream()<br>            .filter(name -&gt; name.startsWith(&quot;R&quot;))<br>            .map(String::toUpperCase)<br>            .collect(Collectors.toList());<br><br>        System.out.println(filtered); // [ROHIT, RAHUL, RAJ, RIYA]<br>    }<br>}</pre><p>🔍 Stream Methods I Found Useful</p><p>filter() – filters based on a condition</p><p>map() – transforms each element</p><p>collect() – converts stream back to a list</p><p>forEach() – performs an action on each element</p><p>sorted() – sorts the elements</p><p><strong>Final Thoughts</strong></p><p>Learning about multithreading and streams in Java helped me appreciate the power of parallelism and functional programming. It’s amazing how Java lets you manage tasks and process data in such elegant ways.</p><p>If you found this article helpful, follow me for more developer insights, learnings, and hands-on breakdowns from my tech journey !!!</p><p>Written by :</p><p>Rohit Raj,</p><p>Software Development Engineer 🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7127085cbc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“RCB Finally Wins IPL — I Built a Tribute Website Overnight Using JavaScript!”]]></title>
            <link>https://medium.com/@rohitraj1912000/rcb-finally-wins-ipl-i-built-a-tribute-website-overnight-using-javascript-73b7c5f08075?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b7c5f08075</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[virat-kohli]]></category>
            <category><![CDATA[rcb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 05:54:37 GMT</pubDate>
            <atom:updated>2025-06-04T05:54:37.132Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>“RCB Finally Wins IPL — I Built a Tribute Website Overnight Using JavaScript!”</em></h3><p>Because when you’re a die-hard fan and a developer, you express love with code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*7xeCrjKv3PdbVxzOQm2l2A.jpeg" /></figure><p>As a long-time <strong>Royal Challengers Bangalore (RCB)</strong> fan, I’ve witnessed it all — <strong>heartbreaks, memes, and chants of “Ee Sala Cup Namde.”</strong> After <strong>18 long years</strong>, RCB finally lifted the <strong>IPL trophy in 2025</strong>, and I just couldn’t contain my emotions.</p><p>So, I decided to do what I do best — <strong>build something with code</strong>.</p><p>In one night, I built a fun little project to <strong>celebrate RCB’s journey</strong> from 2008 to 2025 using <strong>Node.js, Express, and EJS</strong>. It’s a simple timeline site showing every year’s performance and a special /champions route to honor the historic 2025 win.</p><p>Let me show you how I did it.</p><h3>What I Used</h3><ul><li><strong>Node.js + Express.js</strong> (Backend)</li><li><strong>EJS</strong> (Template engine)</li><li><strong>CSS</strong> (Basic styling + animations)</li><li><strong>Hosted on Render</strong></li></ul><h3>Project Structure</h3><pre>rcb-tribute/<br>├── data/<br>│   └── journey.json<br>├── public/<br>│   └── styles.css<br>├── views/<br>│   ├── index.ejs<br>│   └── champions.ejs<br>├── server.js<br>├── package.json</pre><h3>Sample Code Snippets</h3><h4>journey.json</h4><pre>[<br>  { &quot;year&quot;: 2008, &quot;highlight&quot;: &quot;League Stage. Rahul Dravid led the way.&quot; },<br>  ...<br>  { &quot;year&quot;: 2025, &quot;highlight&quot;: &quot;🔥 Finally, RCB wins their first IPL title!&quot; }<br>]</pre><h4>Express Routes</h4><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  const journey = require(&#39;./data/journey.json&#39;);<br>  res.render(&#39;index&#39;, { journey });<br>});<br><br>app.get(&#39;/champions&#39;, (req, res) =&gt; {<br>  res.render(&#39;champions&#39;);<br>});</pre><h4>Special Styling for 2025</h4><pre>.card.champion-2025 {<br>  background-color: #ffd700;<br>  border-left-color: #ff6f00;<br>  font-weight: bold;<br>  animation: pulse 1.5s infinite;<br>}</pre><h3>🔗 Links</h3><ul><li>🔍 <strong>GitHub Repo</strong>: <a href="https://github.com/rohit-raj-1901/rcb-tribute-site">github.com/rohit-raj-1901/rcb-tribute-site</a></li><li>🚀 <strong>Live Demo on Render</strong>:<a href="https://rcb-tribute-site.onrender.com/"> rcb-tribute.onrender.com</a></li></ul><h3>What You’ll Learn</h3><ul><li>How to create a simple <strong>timeline UI</strong> using HTML + CSS + EJS</li><li>How to build lightweight <strong>Express.js apps</strong></li><li>Deploy Node.js sites for <strong>free using Render</strong></li><li>Most importantly, how to <strong>express love for your favorite team using code</strong> ❤️</li></ul><h3>🧡 Final Thoughts</h3><p>Whether you’re an RCB fan or a budding JavaScript developer, I hope this project inspires you to <strong>code what you love</strong>.</p><p>If you enjoyed this and want to see more such fun, beginner-friendly JavaScript + backend projects…<br> Let’s build something cool together! 💻🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b7c5f08075" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Email Automation with Node.js: Overcoming Gmail Hurdles and Unlocking Ethereal for Seamless Testing]]></title>
            <link>https://medium.com/@rohitraj1912000/email-automation-with-node-js-overcoming-gmail-hurdles-and-unlocking-ethereal-for-seamless-testing-bbb28ce81461?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb28ce81461</guid>
            <category><![CDATA[email]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nodemailer]]></category>
            <category><![CDATA[ethereal]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 17:32:31 GMT</pubDate>
            <atom:updated>2025-04-18T17:32:31.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aGcxew9nJBAtNC5w" /></figure><p>Today I decided to learn how to send emails using Node.js. I’ve heard of <strong>Nodemailer</strong> quite a bit and thought, “Hey, let’s try this out.” What started as a simple task turned into a deep dive into SMTP configurations, Gmail’s security policies, and the beauty of Ethereal for local testing. Here’s what I learned (and struggled with!) along the way.</p><h3>My Goal</h3><p>I wanted to build a simple Node.js server that could send an email every minute using a cron job. Eventually, I also wanted to add support for attachments.</p><h3>My First Attempt: Using Gmail Credentials</h3><p>Here’s the code I initially wrote:</p><pre>const nodemailer = require(&quot;nodemailer&quot;);<br>const cron = require(&quot;node-cron&quot;);<br>const express = require(&quot;express&quot;);<br>const app = express();<br><br>cron.schedule(&quot;*/1 * * * *&quot;, function () {<br>  sendMail();<br>});<br><br>function sendMail() {<br>  const transporter = nodemailer.createTransport({<br>    service: &quot;gmail&quot;,<br>    auth: {<br>      user: &quot;myemail@gmail.com&quot;,<br>      pass: &quot;mypassword&quot;<br>    }<br>  });<br><br>  const mailOptions = {<br>    from: &quot;myemail@gmail.com&quot;,<br>    to: &quot;receiver@gmail.com&quot;,<br>    subject: &quot;Cron Job Email&quot;,<br>    text: &quot;This is a test email from a cron job.&quot;<br>  };<br><br>  transporter.sendMail(mailOptions, function (err, info) {<br>    if (err) {<br>      console.log(&quot;Error sending email:&quot;, err);<br>    } else {<br>      console.log(&quot;Email sent:&quot;, info.response);<br>    }<br>  });<br>}<br><br>app.listen(3000, () =&gt; console.log(&quot;Server running on http://localhost:3000&quot;));</pre><h3>The Problems I Faced</h3><ol><li><strong>self-signed certificate in certificate chain</strong></li></ol><p>This happened because Gmail’s SMTP rejected the TLS handshake</p><p><strong>2. Invalid login: 535–5.7.8 Username and Password not accepted</strong></p><ul><li>This was a frustrating one. I had entered my Gmail and password correctly.</li><li>Turns out, Google blocks this kind of access unless:</li><li>You enable <strong>2-Step Verification</strong> on your Google account.</li><li>Then you generate an <strong>App Password</strong> to use in your code.</li></ul><p><strong>3. No App Password option available?</strong></p><ul><li>If you don’t have 2-Step Verification enabled, you won’t see the App Password option.</li><li>And without it, using your Gmail password just won’t work.</li></ul><p>So I thought, “There’s gotta be a better way to test this locally…”</p><h3>The Better Way: Ethereal Email for Local Testing</h3><p>That’s when I discovered <strong>Ethereal</strong>, a fake SMTP service that’s perfect for development.</p><p>Here’s how I set it up:</p><pre>const nodemailer = require(&quot;nodemailer&quot;);<br>const express = require(&quot;express&quot;);<br>const app = express();<br><br>app.get(&quot;/send-mail&quot;, async (req, res) =&gt; {<br>  try {<br>    const testAccount = await nodemailer.createTestAccount();<br><br>    const transporter = nodemailer.createTransport({<br>      host: testAccount.smtp.host,<br>      port: testAccount.smtp.port,<br>      secure: testAccount.smtp.secure,<br>      auth: {<br>        user: testAccount.user,<br>        pass: testAccount.pass,<br>      },<br>      tls: {<br>        rejectUnauthorized: false, // this fixes self-signed cert issue<br>      },<br>    });<br><br>    const mailOptions = {<br>      from: &#39;&quot;Rohit Raj&quot; &lt;no-reply@example.com&gt;&#39;,<br>      to: &quot;receiver@example.com&quot;,<br>      subject: &quot;Testing with Ethereal&quot;,<br>      text: &quot;This email is for testing purposes.&quot;,<br>      attachments: [<br>        {<br>          filename: &quot;hello.txt&quot;,<br>          path: &quot;./files/hello.txt&quot;<br>        }<br>      ]<br>    };<br><br>    const info = await transporter.sendMail(mailOptions);<br><br>    console.log(&quot; Email sent:&quot;, info.messageId);<br>    console.log(&quot; Preview URL:&quot;, nodemailer.getTestMessageUrl(info));<br>    res.send(&quot;Mail sent successfully!&quot;);<br>  } catch (error) {<br>    console.log(&quot;Error sending email:&quot;, error);<br>    res.status(500).send(&quot;Email failed&quot;);<br>  }<br>});<br><br>app.listen(3000, () =&gt; console.log(&quot;Server running on http://localhost:3000&quot;));</pre><figure><img alt="Sample screenshot of the test email for local tesing" src="https://cdn-images-1.medium.com/max/1024/1*7ik2rHYngArSTKIXNNYQwQ.png" /></figure><h3>Why Ethereal is Awesome</h3><ul><li>It gives you dummy credentials to use</li><li>Emails are not actually sent, but you get a <strong>preview link</strong> to see what it would look like.</li><li>No App Password or Gmail setup issues.</li><li>Perfect for local dev &amp; testing attachments.</li></ul><h3>What I Learned</h3><ul><li>Avoid using real Gmail credentials for local testing. It’s a headache unless you set up App Passwords.</li><li>Use <strong>Ethereal</strong> when you’re testing functionality.</li><li>When you go to production, switch to a proper email provider (like SendGrid, Mailgun, or Gmail with App Password).</li></ul><p>Today, I didn’t just learn how to send emails with Node.js — I learned a whole lot about SMTP, TLS, and security quirks. Definitely one of those small side quests that turned out to be really insightful.</p><p>If you’re trying this out too, hope this helps you skip the frustrating part!</p><h3>Github repo:</h3><p><a href="https://github.com/rohit-raj-1901/nodemailer-testing">https://github.com/rohit-raj-1901/nodemailer-testing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb28ce81461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Node.js Best Practices I Wish I Knew Earlier]]></title>
            <link>https://medium.com/@rohitraj1912000/10-node-js-best-practices-i-wish-i-knew-earlier-89ece9cfca95?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ece9cfca95</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 07:23:58 GMT</pubDate>
            <atom:updated>2025-04-18T07:23:58.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*jzuxBjlxp1XueJaNa6i3Ng.jpeg" /></figure><p>When I first started working with Node.js, I dove in headfirst — writing APIs, playing with Express, and shipping features at lightning speed. But like many developers, I eventually hit walls: unmanageable codebases, weird memory issues, performance slowdowns, and security concerns I hadn’t even thought of.</p><p>Over time, and after working on multiple real-world Node.js applications — some powering thousands of users — I’ve picked up a few lessons the hard way. In this post, I’m going to walk you through the top 10 Node.js best practices I swear by today, and more importantly, the <em>problems</em> they help solve.</p><h3>1. Structure Your Project with a Scalable Folder Architecture</h3><p><strong>Problem:</strong> As your project grows, it becomes harder to find files, understand code relationships, or onboard new developers.</p><p><strong>Solution:</strong> Organize your code into clear folders: routes, controllers, services, middlewares, utils, and config. This separation of concerns makes your codebase modular, readable, and easier to maintain or scale.</p><pre>project/<br>├── controllers/<br>├── routes/<br>├── services/<br>├── middlewares/<br>├── utils/<br>├── config/<br>└── app.js</pre><h3>2. Use Environment Variables for Configuration</h3><p><strong>Problem:</strong> Hardcoding sensitive data (like API keys or DB credentials) in your code is a major security risk and makes your app environment-dependent.</p><p><strong>Solution:</strong> Use the dotenv package and manage all configuration through environment variables.</p><pre># .env<br>PORT=3000<br>DB_URI=mongodb://localhost:27017/myapp</pre><pre>// config/db.js<br>require(&#39;dotenv&#39;).config();<br>const mongoose = require(&#39;mongoose&#39;);</pre><pre>mongoose.connect(process.env.DB_URI);</pre><h3>3. Always Use Asynchronous Code (Avoid Blocking the Event Loop)</h3><p><strong>Problem:</strong> Node.js runs on a single thread. Blocking it — even for a second — can freeze your entire app for all users.</p><p><strong>Solution:</strong> Use async/await or Promises instead of synchronous functions.</p><pre>// Bad: Blocking code<br>const fs = require(&#39;fs&#39;);<br>const data = fs.readFileSync(&#39;/file.txt&#39;);</pre><pre>// Good: Non-blocking<br>const fs = require(&#39;fs&#39;).promises;<br>const data = await fs.readFile(&#39;/file.txt&#39;);</pre><h3>4. Implement Proper Error Handling (Try/Catch + Global Handlers)</h3><p><strong>Problem:</strong> A single uncaught error can crash your entire app or expose internal server details to users.</p><p><strong>Solution:</strong> Wrap async code in try/catch and use centralized error-handling middleware.</p><pre>// Middleware<br>app.use((err, req, res, next) =&gt; {<br>  console.error(err.stack);<br>  res.status(500).json({ message: &#39;Something went wrong!&#39; });<br>});</pre><pre>// Example route<br>app.get(&#39;/data&#39;, async (req, res, next) =&gt; {<br>  try {<br>    const data = await fetchData();<br>    res.json(data);<br>  } catch (err) {<br>    next(err);<br>  }<br>});</pre><h3>5. Validate All Inputs (Especially from Users)</h3><p><strong>Problem:</strong> Unvalidated inputs can lead to SQL injections, XSS, crashes, and more.</p><p><strong>Solution:</strong> Use libraries like Joi or express-validator.</p><pre>const { body, validationResult } = require(&#39;express-validator&#39;);</pre><pre>app.post(&#39;/user&#39;, <br>  body(&#39;email&#39;).isEmail(),<br>  (req, res) =&gt; {<br>    const errors = validationResult(req);<br>    if (!errors.isEmpty()) {<br>      return res.status(400).json({ errors: errors.array() });<br>    }<br>    // Process request<br>  }<br>);</pre><h3>6. Secure Your App with Helmet &amp; Rate Limiting</h3><p><strong>Problem:</strong> APIs exposed to the internet are vulnerable to a variety of attacks.</p><p><strong>Solution:</strong> Use helmet and express-rate-limit.</p><pre>const helmet = require(&#39;helmet&#39;);<br>const rateLimit = require(&#39;express-rate-limit&#39;);</pre><pre>app.use(helmet());</pre><pre>const limiter = rateLimit({<br>  windowMs: 15 * 60 * 1000,<br>  max: 100,<br>});<br>app.use(limiter);</pre><h3>7. Log Properly Using a Logger (Don’t Use console.log in Production)</h3><p><strong>Problem:</strong> console.log is fine in dev, but in production, you need structured logs.</p><p><strong>Solution:</strong> Use a logger like winston.</p><pre>const winston = require(&#39;winston&#39;);</pre><pre>const logger = winston.createLogger({<br>  level: &#39;info&#39;,<br>  format: winston.format.json(),<br>  transports: [<br>    new winston.transports.Console(),<br>    new winston.transports.File({ filename: &#39;combined.log&#39; }),<br>  ],<br>});</pre><pre>logger.info(&#39;Server started&#39;);</pre><h3>8. Write Unit and Integration Tests</h3><p><strong>Problem:</strong> Without tests, every change becomes a gamble.</p><p><strong>Solution:</strong> Use Jest or Mocha with Supertest.</p><pre>// Example with Jest and Supertest<br>const request = require(&#39;supertest&#39;);<br>const app = require(&#39;../app&#39;);</pre><pre>describe(&#39;GET /health&#39;, () =&gt; {<br>  it(&#39;should return 200 OK&#39;, async () =&gt; {<br>    const res = await request(app).get(&#39;/health&#39;);<br>    expect(res.statusCode).toEqual(200);<br>  });<br>});</pre><h3>9. Keep Dependencies Up to Date and Avoid Untrusted Packages</h3><p><strong>Problem:</strong> Outdated packages can have vulnerabilities.</p><p><strong>Solution:</strong> Use npm audit and npm-check. Stick to trusted packages.</p><pre>npm audit fix<br>npm-check -u</pre><p>Check the weekly downloads, GitHub activity, and read some source code if it’s a smaller package.</p><h3>10. Use a Process Manager for Production (Like PM2)</h3><p><strong>Problem:</strong> If your app crashes and there’s no restart mechanism, it stays down.</p><p><strong>Solution:</strong> Use pm2.</p><pre>npm install pm2 -g<br>pm2 start app.js<br>pm2 startup<br>pm2 save</pre><p>This ensures zero-downtime restarts, monitoring, and log retention.</p><h3>Final Thoughts</h3><p>Node.js is powerful, but it demands discipline. These best practices aren’t just arbitrary rules — they’re guardrails that have saved me (and my team) from countless bugs, outages, and late-night production issues. Whether you’re just starting out or already knee-deep in code, I hope this list helps you write more robust, secure, and maintainable Node.js apps.</p><p>If you found this helpful or have your own favorite practices, drop a comment — I’d love to learn from your experience too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ece9cfca95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Authentication and Authorization in Backend Systems]]></title>
            <link>https://medium.com/@rohitraj1912000/demystifying-authentication-and-authorization-in-backend-systems-52489c3fae8c?source=rss-13fb7706ee99------2</link>
            <guid isPermaLink="false">https://medium.com/p/52489c3fae8c</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Rohit Raj]]></dc:creator>
            <pubDate>Fri, 10 May 2024 04:22:16 GMT</pubDate>
            <atom:updated>2024-05-10T04:23:51.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RD9S_LHR4sX-wHFo" /></figure><p><strong>Introduction</strong></p><p>Authentication and authorization are fundamental aspects of backend development, playing crucial roles in ensuring the security and integrity of applications.</p><p>Authentication serves as the gatekeeper, verifying the identity of users attempting to access a system. It confirms whether the user is who they claim to be, typically through the submission of credentials such as usernames and passwords.</p><p>Authorization, on the other hand, determines what actions authenticated users are allowed to perform within the application. It sets permissions and access levels, dictating which resources a user can interact with and what operations they can carry out.</p><p>In summary, while authentication verifies a user’s identity, authorization controls their access rights. Together, they form the backbone of backend security, ensuring that only authenticated and authorized users can interact with an application’s resources and functionalities.</p><h3>Authentication Methods</h3><h3><strong>1. Basic Authentication</strong></h3><p>Basic Authentication is a simple method for authenticating users in web applications. Here’s how it works:</p><p><em>How it Works:</em></p><p>1. <strong>Client Request</strong>: When a client (such as a web browser) attempts to access a protected resource, the server responds with a 401 Unauthorized status code.<br> <br>2. <strong>Credential Submission</strong>: The client then prompts the user to enter their username and password.<br> <br>3. <strong>Authorization Header</strong>: Upon receiving the credentials, the client encodes them using Base64 and includes them in the `Authorization` header of subsequent requests.<br><br> <br>4. <strong>Server Validation</strong>: The server extracts the username and password from the Authorization header, decodes the Base64 encoding, and validates the credentials against its user database.<br> <br>5. <strong>Access Granted or Denied</strong>: If the credentials are valid, the server allows access to the requested resource. Otherwise, it returns a 401 Unauthorized status code.</p><h3><strong>2. Token-based Authentication</strong></h3><p>Token-based authentication involves issuing tokens to users upon successful login, which they then present to access protected resources. There are two main types of tokens: session tokens and JSON Web Tokens (JWT).</p><p><strong>Session Tokens</strong>: These are generated by the server upon successful authentication and stored in the server’s memory or a database. The token is then associated with the user’s session, typically via a session ID stored in a cookie.</p><p><strong>JSON Web Tokens (JWT)</strong>: JWT is a compact, self-contained token format that securely encodes user information in JSON format. Unlike session tokens, JWTs are stateless, meaning all necessary information is contained within the token itself. They consist of three parts: <strong>a header, a payload, and a signature</strong>, which are base64url-encoded and concatenated with periods. JWTs are commonly used in modern web applications and APIs due to their flexibility, scalability, and ease of implementation.</p><p>In summary, token-based authentication involves issuing tokens to users upon login, with JWTs being a popular choice for modern web applications due to their stateless nature and flexibility.</p><h3>3. JWT (JSON Web Tokens)</h3><p>JWT, or JSON Web Tokens, is a compact, URL-safe means of representing claims to be transferred between two parties. Let’s explore its structure and advantages:</p><p><strong>Structure</strong>:<br>1. <strong>Header</strong>: The header typically consists of two parts: the type of token (JWT) and the signing algorithm used, such as HMAC SHA256 or RSA. This part is base64url-encoded.<br>2. <strong>Payload</strong>: The payload contains the claims or statements about the entity (user) and additional metadata. Claims are typically user information, such as user ID, username, role, etc. The payload is also base64url-encoded.<br>3. <strong>Signature</strong>: The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way. It’s created by combining the encoded header, encoded payload, a secret key (for HMAC algorithms), and signing it with the specified algorithm.</p><p>In summary, JWTs provide a secure and efficient way to transmit user information between parties. Their statelessness, scalability, interoperability, and performance make them a popular choice for authentication and authorization in modern web applications and APIs.</p><h3>4. OAuth (Open Authorization)</h3><p>OAuth is an open standard for access delegation commonly used for delegated authorization. Let’s delve into its framework and various components:</p><p><strong>Introduction:</strong> OAuth enables third-party services to access resources on behalf of a resource owner (user) without sharing credentials. It’s widely used in scenarios where users want to grant access to their data to third-party applications, such as social media login integrations or accessing APIs.</p><p><strong>Roles</strong>:<br>1. <strong>Resource Owner</strong>: The entity that owns the resource and grants access to it. Typically, this is the end-user.<br>2. <strong>Client</strong>: The application requesting access to the protected resource on behalf of the resource owner. This could be a web or mobile application.<br>3. <strong>Authorization Server</strong>: The server responsible for authenticating the resource owner and issuing access tokens after obtaining authorization.<br>4. <strong>Resource Server</strong>: The server hosting the protected resources that the client wants to access. It verifies the access token and grants access if valid.</p><p>OAuth’s versatility and flexibility make it a popular choice for managing delegated access to resources in various scenarios. However, it’s crucial to choose the appropriate OAuth flow based on the specific requirements and security considerations of your application.</p><h3><strong>Implementing Authentication and Authorization</strong></h3><h4>1. Using JWT for Authentication</h4><p>Here’s a basic example of JWT-based authentication in a Node.js backend using libraries like jsonwebtoken and express:</p><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br>const express = require(&#39;express&#39;);<br>const app = express();<br><br>// Secret key for signing JWT tokens<br>const secretKey = &#39;your_secret_key&#39;;<br><br>// Middleware to authenticate requests<br>const authenticateToken = (req, res, next) =&gt; {<br>    // Extract token from Authorization header<br>    const authHeader = req.headers[&#39;authorization&#39;];<br>    const token = authHeader &amp;&amp; authHeader.split(&#39; &#39;)[1];<br>    <br>    // If token is null, return 401 Unauthorized<br>    if (!token) return res.sendStatus(401);<br><br>    // Verify token<br>    jwt.verify(token, secretKey, (err, user) =&gt; {<br>        if (err) return res.sendStatus(403); // Forbidden<br>        req.user = user; // Attach user information to request object<br>        next(); // Proceed to next middleware<br>    });<br>};<br><br>// Example route requiring authentication<br>app.get(&#39;/protected&#39;, authenticateToken, (req, res) =&gt; {<br>    res.json({ message: &#39;Protected resource accessed successfully&#39;, user: req.user });<br>});<br><br>// Example route for generating JWT token upon login<br>app.post(&#39;/login&#39;, (req, res) =&gt; {<br>    // Verify user credentials...<br>    <br>    // If credentials are valid, generate JWT token<br>    const token = jwt.sign({ username: &#39;example_user&#39; }, secretKey, { expiresIn: &#39;30m&#39; });<br>    res.json({ token });<br>});<br><br>app.listen(3000, () =&gt; {<br>    console.log(&#39;Server started on port 3000&#39;);<br>});</pre><p>In this example, the /login route generates a JWT token upon successful login, and the /protected route requires authentication using the authenticateToken middleware. The token is verified using the jsonwebtoken library, and the user information is attached to the request object for further processing in subsequent middleware or route handlers.</p><p>This is a basic implementation; you can enhance it by adding error handling, user roles/permissions, token blacklisting, and other security features based on your application’s requirements.</p><h3>2. OAuth Integration</h3><p>Integrating OAuth into your backend system enables third-party authentication and authorization, allowing users to sign in using their existing accounts with providers like Google, Facebook, or GitHub. Here’s how you can implement OAuth integration:</p><p>1. <strong>Register Your Application</strong>:<br> — Sign up for developer accounts with the OAuth providers you want to integrate (e.g., Google Developer Console, Facebook for Developers, GitHub Developer Settings).<br> — Register your application and obtain client credentials (client ID and client secret) provided by the OAuth provider.</p><p>2. <strong>Implement OAuth Flow</strong>:<br> — Choose the appropriate OAuth flow based on your application’s requirements and security considerations (e.g., Authorization Code Flow for server-side applications, Implicit Flow for client-side applications).<br> — Implement the OAuth flow in your backend system using OAuth libraries or SDKs provided by the OAuth provider or third-party libraries (e.g., Passport.js for Node.js).</p><p>3. <strong>Exchange Authorization Code for Access Token</strong>:<br> — Exchange the authorization code received from the OAuth provider for an access token using the OAuth provider’s token endpoint.<br> — This step typically involves sending a POST request to the token endpoint with the authorization code, client ID, client secret, and other required parameters.</p><p>4. <strong>Access User Information</strong>:<br> — Use the access token obtained from the OAuth provider to access the user’s profile information or other resources available through the OAuth provider’s API.</p><p>5. <strong>Authenticate and Authorize Users</strong>:<br> — Upon receiving the user information from the OAuth provider, authenticate the user in your backend system based on their OAuth provider’s ID or other unique identifier.<br> — Authorize the user’s access to resources or functionalities in your application based on their OAuth provider’s identity, roles, or permissions.</p><p>6. <strong>Handle OAuth Provider Callbacks</strong>:<br> — Implement callback endpoints in your backend system to handle OAuth provider callbacks after successful authentication and authorization.<br> — Parse the authorization code or access token received from the OAuth provider callback and complete the OAuth flow.</p><p>7<strong>. Example Integration with Popular OAuth Providers</strong>:<br> — Provide examples of OAuth integration with popular providers like Google, Facebook, or GitHub, demonstrating how to obtain client credentials, implement the OAuth flow, and access user information using their APIs.</p><p>Here’s an example of OAuth integration with Google using Node.js and Passport.js:</p><pre>const passport = require(&#39;passport&#39;);<br>const GoogleStrategy = require(&#39;passport-google-oauth20&#39;).Strategy;<br><br>// Configure Google OAuth 2.0 strategy<br>passport.use(new GoogleStrategy({<br>    clientID: GOOGLE_CLIENT_ID,<br>    clientSecret: GOOGLE_CLIENT_SECRET,<br>    callbackURL: &#39;http://localhost:3000/auth/google/callback&#39;<br>  },<br>  (accessToken, refreshToken, profile, done) =&gt; {<br>    // Handle user authentication and authorization<br>    // Access user profile information from &#39;profile&#39; object<br>    return done(null, profile);<br>  }<br>));<br><br>// Example route for initiating Google OAuth authentication<br>app.get(&#39;/auth/google&#39;,<br>  passport.authenticate(&#39;google&#39;, { scope: [&#39;profile&#39;, &#39;email&#39;] }));<br><br>// Example route for handling Google OAuth callback<br>app.get(&#39;/auth/google/callback&#39;,<br>  passport.authenticate(&#39;google&#39;, { failureRedirect: &#39;/login&#39; }),<br>  (req, res) =&gt; {<br>    // Successful authentication, redirect to home page or perform other actions<br>    res.redirect(&#39;/&#39;);<br>  });</pre><p>In this example, the `/auth/google` route initiates the Google OAuth authentication flow, and the `/auth/google/callback` route handles the callback from Google after successful authentication. The user’s profile information is accessible in the callback function, allowing you to authenticate and authorize the user in your backend system.</p><p>This is a basic implementation; you can customize it based on your application’s requirements and integrate OAuth with other providers like Facebook or GitHub using similar principles.</p><h3>Conclusion</h3><p>In this blog post, we explored various aspects of authentication and authorization in backend systems, covering different methods and their implementation. Here’s a summary of the key points discussed:</p><p>-<strong>Authentication </strong>verifies users’ identities, while <strong>authorization</strong> controls their access rights within an application.<br>- Methods such as <strong>Basic Authentication </strong>involve sending credentials with each request, while <strong>Token-based Authentication</strong> like <strong>JWT </strong>provides stateless, scalable, and secure alternatives.<br>- <strong>OAuth</strong> is a framework for delegated authorization, allowing third-party services to access resources on behalf of users without sharing credentials.<br>- Integration with OAuth providers like Google, Facebook, or GitHub enables third-party authentication and authorization in your backend applications.</p><p>I encourage readers to prioritize security in their backend development efforts, leverage modern authentication and authorization methods, and continuously update and improve their security practices to stay ahead of evolving threats.</p><p>Remember, safeguarding user data and ensuring trust in your application are essential responsibilities that should be central to every backend developer’s mindset and workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52489c3fae8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>