<?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"><channel><title><![CDATA[Taksh's Dev Blogs]]></title><description><![CDATA[Taksh's Dev Blogs]]></description><link>https://takshpatel02.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1593680282896/kNC7E8IR4.png</url><title>Taksh&apos;s Dev Blogs</title><link>https://takshpatel02.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 07 Oct 2026 09:46:13 GMT</lastBuildDate><atom:link href="https://takshpatel02.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Defending Your Node.js App: Understanding and Mitigating DDoS Attacks]]></title><description><![CDATA[Welcome to Part 4, the final installment of our series on Defending Your Node.js App. In our previous article on CSRF, we learned how to protect users from forged requests. Today, we will zoom out fro]]></description><link>https://takshpatel02.hashnode.dev/defending-your-node-js-app-understanding-and-mitigating-ddos-attacks</link><guid isPermaLink="true">https://takshpatel02.hashnode.dev/defending-your-node-js-app-understanding-and-mitigating-ddos-attacks</guid><dc:creator><![CDATA[Patel Taksh]]></dc:creator><pubDate>Thu, 25 Jun 2026 05:46:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a204787823cf7a978c06c48/65aceaf0-0c2e-45c8-be1f-7ecc1d173d90.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to Part 4, the final installment of our series on <strong>Defending Your Node.js App</strong>. In our <a href="https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-cross-site-request-forgery-csrf-prevention">previous article on CSRF</a>, we learned how to protect users from forged requests. Today, we will zoom out from the application code and focus on understanding and mitigating <strong>DDoS (Distributed Denial of Service)</strong> attacks.</p>
<hr />
<h2>What is DDoS?</h2>
<p>A DDoS (Distributed Denial of Service) attack is a cyberattack where attackers overwhelm a server, website, or API with an extremely large number of requests. The goal is to consume so much of the target's resources that it becomes slow, unavailable, or completely crashes.</p>
<p>Because too many fake requests are sent to a server simultaneously, real, legitimate users are blocked from accessing the application or website.</p>
<h3>How It Works</h3>
<p>During a DDoS attack, the basic flow is: <strong>Millions of fake requests</strong> ➔ <strong>Server Overload</strong> ➔ <strong>Crash / Slowdown</strong></p>
<p>To generate this massive volume of traffic, attackers usually use:</p>
<ul>
<li><p><strong>Bot networks (Botnets)</strong></p>
</li>
<li><p><strong>Compromised computers</strong></p>
</li>
<li><p><strong>Malware-infected devices (IoT)</strong></p>
</li>
<li><p><strong>Automated scripts</strong></p>
</li>
</ul>
<h3>The Impact</h3>
<p>A successful DDoS attack can lead to severe consequences for a business:</p>
<ul>
<li><p><strong>Website downtime</strong></p>
</li>
<li><p><strong>Loss of revenue</strong></p>
</li>
<li><p><strong>Damage to reputation</strong></p>
</li>
<li><p><strong>Loss of customer trust</strong></p>
</li>
</ul>
<hr />
<h2>How to Prevent DDoS Attacks</h2>
<p>Unlike XSS or NoSQL Injection, defending against massive DDoS attacks cannot be fully handled within the application code itself. However, there is one crucial first step you <em>can</em> implement in Node.js before relying on infrastructure.</p>
<p>Here are the key strategies to mitigate DDoS attacks:</p>
<h3>1. Rate Limiting in Node.js</h3>
<p>Limit the number of requests a single user or IP address can make within a specific time frame. This prevents automated scripts from flooding your server. You can implement this directly in your Express app using <code>express-rate-limit</code>.</p>
<pre><code class="language-bash">npm install express-rate-limit
</code></pre>
<pre><code class="language-javascript">import express from 'express';
import rateLimit from 'express-rate-limit';

const app = express();

// Set up the global rate limiter
const globalLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes window
    max: 100, // Limit each IP to 100 requests per `windowMs`
    message: "Too many requests from this IP, please try again after 15 minutes." // Message sent back to the user
});

// Apply the rate limiter globally to all requests
app.use(globalLimiter);

// You can also apply stricter limits to specific routes (like login)
const loginLimiter = rateLimit({
    windowMs: 60 * 1000, // 1 minute window
    max: 5, // Limit each IP to 5 login attempts per minute
    message: "Too many login attempts, please try again after a minute."
});

app.post('/login', loginLimiter, (req, res) =&gt; {
    // Login logic here
    res.send("Login successful");
});
</code></pre>
<p><em>This is the one DDoS mitigation strategy you can implement directly in your Node.js app. Everything else happens at the infrastructure level.</em></p>
<h3>2. Load Balancing</h3>
<p>Distribute incoming traffic across multiple servers. This ensures that no single server is overwhelmed, improving overall resilience.</p>
<h3>3. Firewall Rules (WAF)</h3>
<p>Configure Web Application Firewalls (WAF) to inspect incoming traffic and block requests from known malicious IP addresses or unexpected geographic regions.</p>
<h3>4. CDN &amp; Caching</h3>
<p>Content Delivery Networks (CDNs) absorb traffic at the edge (closer to the user) and serve cached content. This dramatically reduces the direct load on your origin server during an attack.</p>
<h3>5. Intrusion Detection Systems (IDS)</h3>
<p>Monitor network traffic for unusual patterns, sudden spikes, or anomalies that may indicate an impending DDoS attack.</p>
<h3>6. Anti-DDoS Services</h3>
<p>Use specialized services (like Cloudflare, AWS Shield, or Akamai) that provide infrastructure designed to detect and absorb massive DDoS attacks in real-time before they even reach your servers.</p>
<hr />
<h2>Conclusion</h2>
<p>Using these strategies can help protect your website or application from DDoS attacks and ensure that legitimate users can access your services without interruption.</p>
<p>However, it is important to remember that no system is completely immune to DDoS attacks. Continuous monitoring, regular updates, and a proactive security approach are essential to minimize the risk and impact of such attacks.</p>
<p><em>Note: Load balancing, CDNs, and caching go beyond just Node.js and touch upon system architecture. We will discuss these topics in further detail in our upcoming</em> <em><strong>System Design</strong></em> <em>series!</em></p>
]]></content:encoded></item><item><title><![CDATA[Defending Your Node.js App: A Deep Dive into Cross-Site Request Forgery (CSRF) Prevention]]></title><description><![CDATA[Welcome to Part 3 of our series on Defending Your Node.js App. In our previous article on XSS, we explored how to stop attackers from injecting malicious scripts. Today, we will focus on understanding]]></description><link>https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-cross-site-request-forgery-csrf-prevention</link><guid isPermaLink="true">https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-cross-site-request-forgery-csrf-prevention</guid><dc:creator><![CDATA[Patel Taksh]]></dc:creator><pubDate>Thu, 25 Jun 2026 05:43:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a204787823cf7a978c06c48/798200c2-619e-4fbe-8300-ab7672c802d5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to Part 3 of our series on <strong>Defending Your Node.js App</strong>. In our <a href="https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-cross-site-scripting-xss-prevention">previous article on XSS</a>, we explored how to stop attackers from injecting malicious scripts. Today, we will focus on understanding and preventing <strong>Cross-Site Request Forgery (CSRF) attacks</strong> in a Node.js environment.</p>
<hr />
<h2>What is CSRF?</h2>
<p>CSRF (Cross-Site Request Forgery) is a type of attack where an attacker tricks a logged-in user into performing unwanted actions on a website without their knowledge.</p>
<p>For Node.js developers, understanding CSRF is critical because Express and other frameworks don't provide built-in CSRF protection by default, making applications vulnerable without proper implementation.</p>
<p>Common targets for CSRF attacks include:</p>
<ul>
<li><p>Changing a password</p>
</li>
<li><p>Transferring money</p>
</li>
<li><p>Updating an email address</p>
</li>
<li><p>Deleting an account</p>
</li>
<li><p>Modifying profile information</p>
</li>
</ul>
<h3>A Real-Life Example</h3>
<p>Imagine a user is already logged into a banking website, let's call it <code>bank.com</code>. Their browser already has an active login session (a cookie stored).</p>
<p>Now, an attacker creates a malicious website containing the following code:</p>
<pre><code class="language-html">&lt;form action="https://bank.com/transfer" method="POST"&gt;
  &lt;input type="hidden" name="amount" value="50000"&gt;
  &lt;input type="hidden" name="to_account" value="attacker_account"&gt;
&lt;/form&gt;

&lt;script&gt;
  document.forms[0].submit();
&lt;/script&gt;
</code></pre>
<p>If the browser automatically sends the bank's session cookie along with the request to the logged-in banking website, the bank will process the request as if it came from the legitimate user, transferring money to the attacker's account without the user's consent.</p>
<hr />
<h2>The CSRF Attack Architecture</h2>
<p>Here is a step-by-step breakdown of how a CSRF attack happens:</p>
<ol>
<li><p>The user logs into a website and receives a session cookie.</p>
</li>
<li><p>The session cookie is stored in the browser.</p>
</li>
<li><p>The user visits a malicious website while still logged into the original website.</p>
</li>
<li><p>The malicious website contains a hidden form that submits a request to the original website (e.g., transfer money, change password).</p>
</li>
<li><p>The browser automatically includes the session cookie in the request to the original website.</p>
</li>
<li><p>The server trusts the request because it appears to come from the authenticated user, and processes the action.</p>
</li>
<li><p>The action is performed without the user's knowledge or consent.</p>
</li>
</ol>
<hr />
<h2>How to Prevent CSRF Attacks</h2>
<p>Here are three effective strategies to protect your application from CSRF attacks:</p>
<h3>Method 1: Use CSRF Tokens with <code>csrf-csrf</code></h3>
<p>The most robust way to prevent CSRF is by using Anti-CSRF tokens.</p>
<ul>
<li><p>Generate a unique token for each user session.</p>
</li>
<li><p>Include the token in forms and AJAX requests.</p>
</li>
<li><p>Validate the token on the server side before processing the request.</p>
</li>
</ul>
<p>First, install the recommended <code>csrf-csrf</code> package (since <code>csurf</code> is deprecated):</p>
<pre><code class="language-bash">npm install csrf-csrf
</code></pre>
<p>Then, configure it in your Express app:</p>
<pre><code class="language-javascript">import express from 'express';
import { doubleCsrf } from 'csrf-csrf';
import cookieParser from 'cookie-parser';

const app = express();
app.use(cookieParser("super-secret"));
app.use(express.json());

const { doubleCsrfProtection, generateToken } = doubleCsrf({
  getSecret: () =&gt; "super-secret", // A secret to generate the token
  cookieName: "x-csrf-token", // Name of the cookie to store the secret
  cookieOptions: {
    sameSite: "lax", // Recommended sameSite policy
    secure: true,    // Send only over HTTPS
  },
  size: 64,
  ignoredMethods: ["GET", "HEAD", "OPTIONS"],
});

// Protect all routes
app.use(doubleCsrfProtection);
</code></pre>
<p>Provide the token to your frontend:</p>
<pre><code class="language-javascript">app.get("/csrf-token", (req, res) =&gt; {
    res.json({ 
        csrfToken: generateToken(req, res)
    });
});
</code></pre>
<p>On the frontend, include the CSRF token in your forms or AJAX requests:</p>
<pre><code class="language-javascript">fetch("/submit", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "x-csrf-token": csrfToken // Include the CSRF token in the request header
    },
});
</code></pre>
<p>The server will validate the token automatically. If it doesn't match or is missing, it will reject the request.</p>
<p><strong>A Note on Single Page Applications (SPAs):</strong> If your frontend is a Single Page Application (SPA) that uses JSON Web Tokens (JWT) stored in memory and sent via the <code>Authorization: Bearer &lt;token&gt;</code> header (instead of using cookies), your app is naturally CSRF-resistant. CSRF relies on the browser automatically attaching cookies to cross-origin requests. Since headers must be added manually in JavaScript, an attacker cannot force the victim's browser to send the JWT.</p>
<h3>Method 2: Use Same-Site Cookies</h3>
<p>Set the <code>SameSite</code> attribute of your cookies to <code>Strict</code> or <code>Lax</code> to prevent them from being sent with cross-site requests.</p>
<pre><code class="language-javascript">res.cookie("session_id", token_value, {
    sameSite: "Strict"
});
</code></pre>
<p>By doing this, the browser will not send the cookie along with requests initiated by third-party websites, thus preventing CSRF attacks.</p>
<h3>Method 3: Use HttpOnly Cookies</h3>
<p>Set the <code>httpOnly</code> attribute of cookies to prevent client-side scripts from accessing them.</p>
<pre><code class="language-javascript">res.cookie("session_id", token_value, {
    httpOnly: true
});
</code></pre>
<p><strong>Important Distinction:</strong> Using <code>httpOnly</code> does <em>not</em> directly prevent CSRF attacks. Instead, it prevents XSS (Cross-Site Scripting) attacks from easily stealing your session cookie via <code>document.cookie</code>. However, because CSRF and XSS are often chained together, securing your cookies with <code>httpOnly</code> is a crucial part of your overall defense-in-depth strategy.</p>
<hr />
<h2>Summary</h2>
<p>Preventing CSRF is a vital part of web application security. By implementing modern Anti-CSRF tokens with <code>csrf-csrf</code>, leveraging SameSite cookie attributes, and understanding how SPA architecture impacts your risk, you can ensure that your users' actions are truly their own.</p>
<p><strong>Stay tuned!</strong> In Part 4 of our series, we will focus on <strong>DDoS (Distributed Denial of Service)</strong> attacks and how to mitigate them.</p>
]]></content:encoded></item><item><title><![CDATA[Defending Your Node.js App: A Deep Dive into Cross-Site Scripting (XSS) Prevention]]></title><description><![CDATA[Welcome to Part 2 of our series on Defending Your Node.js App. In Part 1, we covered how to secure your database against NoSQL Injection. Today, we will shift our focus to the frontend-backend boundar]]></description><link>https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-cross-site-scripting-xss-prevention</link><guid isPermaLink="true">https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-cross-site-scripting-xss-prevention</guid><dc:creator><![CDATA[Patel Taksh]]></dc:creator><pubDate>Thu, 25 Jun 2026 05:42:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a204787823cf7a978c06c48/835e6523-f15d-49a1-84af-5390c7ed9aab.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to Part 2 of our series on <strong>Defending Your Node.js App</strong>. In <a href="https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-nosql-injection-prevention">Part 1</a>, we covered how to secure your database against NoSQL Injection. Today, we will shift our focus to the frontend-backend boundary, exploring how to understand and prevent <strong>Cross-Site Scripting (XSS) attacks</strong> in a Node.js environment.</p>
<hr />
<h2>What is XSS?</h2>
<p>XSS (Cross-Site Scripting) is a security vulnerability where an attacker injects malicious JavaScript code into a website, which then executes in another user's browser.</p>
<p>XSS is critical because JavaScript runs on both the server and client side, making proper input handling essential. If an attacker can execute code in a victim's browser, they can steal session cookies, hijack accounts, or deface the web page.</p>
<h3>Types of XSS</h3>
<p>There are two main types of XSS vulnerabilities you need to worry about:</p>
<ol>
<li><p><strong>Stored XSS</strong>: The malicious script is saved permanently in the database and affects all users who access the affected page. Common targets include comment sections, chat messages, and profile bios.</p>
<p>Example vulnerability:</p>
<pre><code class="language-javascript">// Saving an un-sanitized comment to the database
app.post('/comments', async (req, res) =&gt; {
    const { text } = req.body; 
    // If text is &lt;script&gt;alert('hacked')&lt;/script&gt;, it gets saved directly!
    await Comment.create({ text });
    res.send("Comment saved!");
});
</code></pre>
<p>When other users visit the comments page, the malicious script is loaded from the database and executed in their browser without their knowledge.</p>
</li>
<li><p><strong>Reflected XSS</strong>: The malicious script comes through URL parameters or request data and executes immediately in the user's browser.</p>
<p>Example URL: <code>https://example.com/search?q=&lt;script&gt;alert('hacked')&lt;/script&gt;</code></p>
</li>
</ol>
<hr />
<h2>How the Attack Works: A Practical Example</h2>
<p>Let's look at a vulnerable implementation. Imagine we have a simple search endpoint in an Express application that returns the search query back to the user.</p>
<h3>The Vulnerable Search Endpoint</h3>
<pre><code class="language-javascript">import express from "express";
const app = express();

// VULNERABILITY: Directly rendering user input into the HTML response
app.get('/search', (req, res) =&gt; {
    const query = req.query.q;
    res.send(`&lt;h1&gt;Search Results for: ${query}&lt;/h1&gt;`);
});
</code></pre>
<h4>Executing the XSS Attack</h4>
<p>If a legitimate user searches for "node", they visit <code>https://example.com/search?q=node</code>, and the server responds with:</p>
<pre><code class="language-html">&lt;h1&gt;Search Results for: node&lt;/h1&gt;
</code></pre>
<p>However, if an attacker crafts a malicious link and tricks a user into clicking it: <code>https://example.com/search?q=&lt;script&gt;alert('hacked')&lt;/script&gt;</code></p>
<p>The server will respond with:</p>
<pre><code class="language-html">&lt;h1&gt;Search Results for: &lt;script&gt;alert('hacked')&lt;/script&gt;&lt;/h1&gt;
</code></pre>
<p>The script will execute directly in the victim's browser, demonstrating a classic Reflected XSS attack.</p>
<hr />
<h2>How to Prevent XSS</h2>
<p>Fortunately, preventing these attacks is straightforward. Here are the most effective methods to secure your application:</p>
<h3>Method 1: Input Sanitization using <code>sanitize-html</code></h3>
<p>The first line of defense is ensuring the input is cleaned of any malicious scripts before it's saved to the database or rendered. We can use the robust <code>sanitize-html</code> package.</p>
<pre><code class="language-bash">npm install sanitize-html
</code></pre>
<p>You can use it in your Express routes to clean specific fields:</p>
<pre><code class="language-javascript">import express from "express";
import sanitizeHtml from "sanitize-html";

const app = express();
app.use(express.json());

app.post('/comments', (req, res) =&gt; {
    const dirtyComment = req.body.text;
    
    // Sanitize the input to strip out any dangerous HTML tags or scripts
    const cleanComment = sanitizeHtml(dirtyComment, {
        allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],
        allowedAttributes: {
            'a': [ 'href' ]
        }
    });

    // Save cleanComment to the database...
    res.send({ success: true, comment: cleanComment });
});
</code></pre>
<p>This ensures that even if an attacker sends a <code>&lt;script&gt;</code> tag, it gets stripped out completely before hitting your database.</p>
<h3>Method 2: Manual Output Encoding</h3>
<p>If you are rendering HTML manually on the server (though modern frameworks like React or Vue handle this for you automatically), you must encode user input before putting it into the HTML document.</p>
<p>This means replacing special characters with their safe HTML entity equivalents:</p>
<ul>
<li><p><code>&lt;</code> becomes <code>&amp;lt;</code></p>
</li>
<li><p><code>&gt;</code> becomes <code>&amp;gt;</code></p>
</li>
<li><p><code>&amp;</code> becomes <code>&amp;amp;</code></p>
</li>
<li><p><code>"</code> becomes <code>&amp;quot;</code></p>
</li>
</ul>
<p>This ensures the browser treats the input as pure text, not executable code.</p>
<h3>Method 3: Set Security Headers with <code>helmet</code></h3>
<p>Another crucial layer of defense is setting proper HTTP security headers. The <code>helmet</code> library helps secure your Express apps by setting various HTTP headers, including the Content Security Policy (CSP).</p>
<pre><code class="language-bash">npm install helmet
</code></pre>
<pre><code class="language-javascript">import express from "express";
import helmet from "helmet";

const app = express();

// Configure Helmet with a basic Content Security Policy
app.use(helmet.contentSecurityPolicy({
    directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "https://trusted-cdn.com"],
        objectSrc: ["'none'"],
        upgradeInsecureRequests: [],
    }
}));
</code></pre>
<p>While full CSP configuration is a complex topic that varies greatly depending on your application's architecture, setting a basic policy restricts the domains from which scripts can be loaded, significantly mitigating the impact of XSS attacks.</p>
<hr />
<h2>Summary</h2>
<p>Preventing XSS is critical for maintaining the trust and safety of your users. By properly sanitizing inputs with <code>sanitize-html</code>, employing output encoding, and setting strict CSP headers via Helmet, you can effectively neutralize malicious script injections.</p>
<p><strong>Stay tuned!</strong> In our next blog post, we will dive into <strong>CSRF (Cross-Site Request Forgery)</strong> attacks and how to defend against them in Node.js.</p>
]]></content:encoded></item><item><title><![CDATA[Defending Your Node.js App: A Deep Dive into NoSQL Injection Prevention
]]></title><description><![CDATA[Welcome to Part 1 of our series on Defending Your Node.js App. Security in Node.js is paramount. It means proactively protecting your backend architecture, APIs, databases, and most importantly, your ]]></description><link>https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-nosql-injection-prevention</link><guid isPermaLink="true">https://takshpatel02.hashnode.dev/defending-your-node-js-app-a-deep-dive-into-nosql-injection-prevention</guid><dc:creator><![CDATA[Patel Taksh]]></dc:creator><pubDate>Thu, 25 Jun 2026 05:37:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a204787823cf7a978c06c48/14b3e3f1-c09e-425e-8504-76e08ee5cdce.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to Part 1 of our series on <strong>Defending Your Node.js App</strong>. Security in Node.js is paramount. It means proactively protecting your backend architecture, APIs, databases, and most importantly, your users' data from malicious attackers.</p>
<p>When building web applications, developers frequently face several <strong>common security threats</strong>:</p>
<ul>
<li><p><strong>SQL/NoSQL Injection</strong></p>
</li>
<li><p><strong>XSS</strong> (Cross-Site Scripting)</p>
</li>
<li><p><strong>CSRF</strong> (Cross-Site Request Forgery)</p>
</li>
<li><p><strong>DDoS</strong> (Distributed Denial of Service)</p>
</li>
</ul>
<p>In this first article, we will focus specifically on how to understand and prevent <strong>NoSQL Injection attacks</strong> in a Node.js and MongoDB environment.</p>
<hr />
<h2>What is NoSQL Injection?</h2>
<p>NoSQL injection occurs when an attacker manipulates user input to alter the intended behavior of a database query (such as a MongoDB query). When successful, this can lead to devastating consequences, including:</p>
<ul>
<li><p>Unauthorized data access</p>
</li>
<li><p>Authentication bypass (e.g., logging in without a password)</p>
</li>
<li><p>Sensitive data leakage</p>
</li>
</ul>
<h3>The Golden Rule: Never Trust User Input</h3>
<p>As a backend developer, you should treat all incoming data as potentially dangerous. Never implicitly trust data coming from:</p>
<ul>
<li><p><code>req.body</code></p>
</li>
<li><p><code>req.params</code></p>
</li>
<li><p><code>req.query</code></p>
</li>
</ul>
<p>Attackers can easily modify incoming payloads using tools like Postman, browser developer tools, automated scripts, or custom API testing tools.</p>
<hr />
<h2>How the Attack Works: A Practical Example</h2>
<p>Let's look at a vulnerable implementation. Imagine we have a simple sign-up and login flow. We take a <code>username</code>, <code>email</code>, and <code>password</code> from the user and store them in the database.</p>
<h3>The User Model</h3>
<p>Here is the Mongoose schema we use for storing our user data:</p>
<pre><code class="language-javascript">const { Schema, model } = require("mongoose");

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

const User = model("User", userSchema);
</code></pre>
<h3>The Vulnerable Login Function</h3>
<p>Now, let's create a simple login function. It checks if the email exists and, if so, returns a success message (Note: In a real-world scenario, you would compare password hashes and issue a JWT, but we've simplified this for the example).</p>
<pre><code class="language-javascript">const login = async (req, res) =&gt; {
  try {
    const { email } = req.body;

    // VULNERABILITY: Directly passing user input into the query
    const user = await User.find({ email });

    if (!user || user.length === 0) {
      return res.status(404).json({
        success: false,
        message: "User not found",
      });
    }

    return res.status(200).json({
      success: true,
      message: "User logged in successfully",
      user: user,
    });
  } catch (err) {
    console.error(err);
    return res.status(500).json({
      success: false,
      message: "Internal Server Error",
    });
  }
};
</code></pre>
<h4>A Normal Login Request</h4>
<p>A legitimate user might send the following request body:</p>
<pre><code class="language-json">{
  "email": "user4@gmail.com"
}
</code></pre>
<p>And receive a successful response containing their user details: <em>(Note: Passwords should always be securely hashed like in the example below, never stored in plain text.)</em></p>
<pre><code class="language-json">{
  "success": true,
  "message": "User logged in successfully",
  "user": [
    {
      "_id": "6a3bd70f5630095b96f0c5bd",
      "username": "user4",
      "email": "user4@gmail.com",
      "password": "\(2b\)10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjIQqiRQYq",
      "createdAt": "2026-06-24T13:09:35.461Z",
      "updatedAt": "2026-06-24T13:09:35.461Z",
      "__v": 0
    }
  ]
}
</code></pre>
<hr />
<h2>Executing the NoSQL Injection Attack</h2>
<p>Because our <code>login</code> function directly passes <code>req.body.email</code> into <code>User.find()</code>, an attacker can send a MongoDB query operator instead of a standard string.</p>
<p>Let's inject a <code>$ne</code> (not equal) operator into the login request to bypass authentication and fetch user data without knowing a valid email.</p>
<h4>The Malicious Payload</h4>
<pre><code class="language-json">{
  "email": { "$ne": null }
}
</code></pre>
<h4>The Result</h4>
<p>Because the query translates to <code>User.find({ email: { $ne: null } })</code>, MongoDB will return <strong>every single user</strong> in the database whose email is not null!</p>
<pre><code class="language-json">{
  "success": true,
  "message": "User logged in successfully",
  "user": [
    {
      "_id": "6a3bd6f55630095b96f0c5ba",
      "username": "user1",
      "email": "user1@gmail.com",
      "password": "\(2b\)10$hackedhash1..."
    },
    {
      "_id": "6a3bd7045630095b96f0c5bb",
      "username": "user2",
      "email": "user2@gmail.com",
      "password": "\(2b\)10$hackedhash2..."
    }
    // ... all other users are exposed!
  ]
}
</code></pre>
<p>The same vulnerability applies to password fields. An attacker could send:</p>
<pre><code class="language-json">{
  "email": { "$ne": null },
  "password": { "$ne": null }
}
</code></pre>
<p>And successfully log into the first account returned by the database.</p>
<hr />
<h2>How to Prevent NoSQL Injection</h2>
<p>Fortunately, preventing these attacks is straightforward. Here are three effective methods:</p>
<h3>Method 1: Input Validation using <code>validator</code></h3>
<p>The first line of defense is ensuring the input is exactly what you expect. We can use the popular <code>validator</code> package.</p>
<pre><code class="language-bash">npm install validator
</code></pre>
<p>Update the login function to enforce email validation:</p>
<pre><code class="language-javascript">import validator from "validator";

const login = async (req, res) =&gt; {
  try {
    const { email } = req.body;

    // 1. Validate the input
    if (!email || !validator.isEmail(email)) {
      return res.status(400).json({
        success: false,
        message: "Invalid email format",
      });
    }

    // 2. Use findOne instead of find
    // Using find() returns an array, meaning if an attacker forces a query to match multiple documents, 
    // it will return all of them, exposing massive amounts of data and making it harder to properly check if a specific user exists.
    // findOne() ensures only a single object is ever returned.
    const user = await User.findOne({ email });

    if (!user) {
      return res.status(404).json({
        success: false,
        message: "User not found",
      });
    }

    return res.status(200).json({
      success: true,
      message: "User logged in successfully",
      user: user,
    });
  } catch (err) {
    console.error(err);
    return res.status(500).json({
      success: false,
      message: "Internal Server Error",
    });
  }
};
</code></pre>
<p>If an attacker tries to send <code>{"email": { "$ne": null }}</code>, <code>validator.isEmail()</code> will fail, and the request will be rejected immediately.</p>
<p>Additionally, you can secure fields like passwords directly at the Mongoose Schema level using Regex and length constraints:</p>
<pre><code class="language-javascript">password: {
  type: String,
  required: true,
  match: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, // Enforce strong passwords
  minlength: 8,
  maxlength: 20,
}
</code></pre>
<h3>Method 2: Type Casting</h3>
<p>Another simple fix is to force the input into the expected data type. By converting the input to a String, any injected MongoDB operators (which are objects) are neutralized.</p>
<pre><code class="language-javascript">const { email } = req.body;

// Force the input to be a string
const user = await User.findOne({ email: String(email) });
</code></pre>
<p><em>Note: While helpful, type casting alone is not considered the best practice, as attackers might still exploit string-based vulnerabilities. It is best used in combination with other methods.</em></p>
<h3>Method 3: Use <code>express-mongo-sanitize</code> (Recommended)</h3>
<p>The most robust and efficient way to prevent NoSQL injection is to strip out any keys that start with <code>$</code> or <code>.</code> from user input. The <code>express-mongo-sanitize</code> middleware does this automatically for your entire application.</p>
<pre><code class="language-bash">npm install express-mongo-sanitize
</code></pre>
<p>Add it to your Express server configuration:</p>
<pre><code class="language-javascript">import express from "express";
import mongoSanitize from "express-mongo-sanitize";

const app = express();

// Middleware to parse JSON bodies
app.use(express.json());

// Sanitize user-supplied data to prevent MongoDB Operator Injection
app.use(mongoSanitize());
</code></pre>
<p>With this middleware in place, if a user sends:</p>
<pre><code class="language-json">{
  "email": { "$ne": null }
}
</code></pre>
<p>The middleware will silently sanitize the payload to:</p>
<pre><code class="language-json">{
  "email": {}
}
</code></pre>
<p>This ensures that the MongoDB query remains safe and the attacker is completely blocked from bypassing authentication.</p>
<hr />
<h2>Summary</h2>
<p>Preventing NoSQL injection is critical, but it's just one piece of the puzzle. By leveraging input validation, type casting, and query sanitization, you can ensure your MongoDB queries execute exactly as intended.</p>
<p><strong>Stay tuned!</strong> In our next blog post, we will dive into <strong>XSS (Cross-Site Scripting)</strong> attacks and how to defend against them in Node.js.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Client-Server Architecture: The Backbone of the Modern Web]]></title><description><![CDATA[From scrolling through Instagram and streaming on Netflix to ordering on Amazon and messaging on WhatsApp, almost every modern application relies on a single, fundamental paradigm: the Client-Server A]]></description><link>https://takshpatel02.hashnode.dev/understanding-client-server-architecture-the-backbone-of-the-modern-web</link><guid isPermaLink="true">https://takshpatel02.hashnode.dev/understanding-client-server-architecture-the-backbone-of-the-modern-web</guid><dc:creator><![CDATA[Patel Taksh]]></dc:creator><pubDate>Mon, 22 Jun 2026 13:50:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a204787823cf7a978c06c48/a84b0e6b-4773-4ffb-81db-780734ff409e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>From scrolling through Instagram and streaming on Netflix to ordering on Amazon and messaging on WhatsApp, almost every modern application relies on a single, fundamental paradigm: the <strong>Client-Server Architecture</strong>.</p>
<p>Whether you are a beginner taking your first steps in web development or a system design enthusiast, understanding how clients and servers talk to each other is crucial.</p>
<p>In this post, we'll break down what client-server architecture is, explore its key components, trace a complete request-response cycle, and compare the different architectural tiers (from 2-tier to multi-tier architectures).</p>
<hr />
<h2>What is Client-Server Architecture?</h2>
<p>At its core, <strong>Client-Server Architecture</strong> is a distributed application structure that partitions tasks or workloads between the providers of a resource or service (servers) and service requesters (clients).</p>
<ul>
<li><p><strong>The Client:</strong> Requests services or data.</p>
</li>
<li><p><strong>The Server:</strong> Processes the request, performs the necessary actions, and sends back a response.</p>
</li>
</ul>
<h3>The Restaurant Analogy</h3>
<p>To understand this concept simply, think of it as dining at a restaurant:</p>
<table>
<thead>
<tr>
<th>Component</th>
<th>Real-World Analog</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Client</strong></td>
<td>Customer</td>
<td>Requesters who want something (e.g., food) but do not prepare it themselves.</td>
</tr>
<tr>
<td><strong>Server</strong></td>
<td>Kitchen</td>
<td>The backend engine that processes orders and prepares the request.</td>
</tr>
<tr>
<td><strong>Request</strong></td>
<td>Food Order</td>
<td>The message sent from the customer containing what they want.</td>
</tr>
<tr>
<td><strong>Response</strong></td>
<td>Prepared Food</td>
<td>The final result delivered back to the customer's table.</td>
</tr>
</tbody></table>
<p>Just like a customer doesn't walk into the kitchen to cook their own food, and the kitchen staff doesn't eat the meal, the client and server have a clear <strong>separation of concerns</strong>.</p>
<hr />
<h2>The Basic Client-Server Model</h2>
<p>At its simplest, the interaction between a client and server flows like this:</p>
<p><strong>[ Client ]</strong> ➔ <em>Sends HTTP Request</em> ➔ <strong>[ Server ]</strong> ➔ <em>Sends HTTP Response</em> ➔ <strong>[ Client ]</strong></p>
<h3>An Everyday Example: Instagram</h3>
<p>When you open the Instagram app or website:</p>
<ol>
<li><p><strong>Client</strong> (your mobile app or web browser at <code>instagram.com</code>) initiates a request.</p>
</li>
<li><p><strong>Request:</strong> <code>GET /feed</code></p>
</li>
<li><p><strong>Server</strong> receives the request, processes it, and queries the database to fetch the latest posts.</p>
</li>
<li><p><strong>Response:</strong> A JSON payload containing posts, image URLs, and user details is sent back.</p>
</li>
<li><p><strong>Client</strong> renders that JSON data into the beautiful UI scrollable feed on your screen.</p>
</li>
</ol>
<hr />
<h2>Core Components of the Architecture</h2>
<p>A functioning client-server system relies on four main pillars:</p>
<h3>1. The Client</h3>
<p>A client is any device or software application that requests resources or services.</p>
<ul>
<li><p><strong>Examples:</strong> Google Chrome, React single-page applications, iOS/Android mobile apps, or desktop applications.</p>
</li>
<li><p><strong>Key Responsibilities:</strong></p>
<ul>
<li><p>Initiating requests to the server.</p>
</li>
<li><p>Managing and displaying the User Interface (UI).</p>
</li>
<li><p>Handling user interactions (clicks, keyboard inputs, touches).</p>
</li>
<li><p>Parsing and rendering data received from the server.</p>
</li>
</ul>
</li>
</ul>
<p><em>Code Example (Client-side JavaScript fetch request):</em></p>
<pre><code class="language-javascript">// Requesting user data from a backend API
fetch('/api/users')
  .then(response =&gt; response.json())
  .then(data =&gt; console.log(data));
</code></pre>
<h3>2. The Server</h3>
<p>A server is a high-performance machine or software application that hosts, manages, and provides resources or services to clients.</p>
<ul>
<li><p><strong>Examples:</strong> Node.js/Express, Django, Spring Boot, or Ruby on Rails backends.</p>
</li>
<li><p><strong>Key Responsibilities:</strong></p>
<ul>
<li><p>Listening for incoming client requests.</p>
</li>
<li><p>Processing business and application logic.</p>
</li>
<li><p>Communicating with databases and external services.</p>
</li>
<li><p>Returning appropriate response codes and payloads (HTML, JSON, XML, files).</p>
</li>
</ul>
</li>
</ul>
<p><em>Code Example (Server-side Node.js/Express route):</em></p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

app.get('/api/users', (req, res) =&gt; {
  // Logic to fetch users from database...
  res.json(users);
});
</code></pre>
<h3>3. The Network</h3>
<p>The communication medium that links the client and the server.</p>
<ul>
<li><p><strong>Examples:</strong> The Internet, Wi-Fi, Local Area Networks (LAN), or Cellular networks (4G/5G).</p>
</li>
<li><p><em>Without a network connection, the client and server cannot communicate.</em></p>
</li>
</ul>
<h3>4. Protocols</h3>
<p>Protocols are standard sets of rules and formats that govern how data is transmitted and interpreted between the client and server.</p>
<table>
<thead>
<tr>
<th>Protocol</th>
<th>Full Name</th>
<th>Common Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><strong>HTTP</strong></td>
<td>Hypertext Transfer Protocol</td>
<td>General web communication (stateless request-response).</td>
</tr>
<tr>
<td><strong>HTTPS</strong></td>
<td>HTTP Secure</td>
<td>Encrypted and secure web communication.</td>
</tr>
<tr>
<td><strong>WebSocket</strong></td>
<td>WebSocket Protocol</td>
<td>Persistent, bi-directional, real-time communication.</td>
</tr>
<tr>
<td><strong>FTP</strong></td>
<td>File Transfer Protocol</td>
<td>Transferring files between client and server.</td>
</tr>
<tr>
<td><strong>SMTP</strong></td>
<td>Simple Mail Transfer Protocol</td>
<td>Sending email communications.</td>
</tr>
</tbody></table>
<hr />
<h2>The Request-Response Cycle: A Step-by-Step Breakdown</h2>
<p>Let's trace exactly what happens behind the scenes when a user logs into a website. The data flows logically from the user's device, across the internet, into the backend, and back again:</p>
<ol>
<li><p><strong>Step 1:</strong> The user enters credentials and clicks the <strong>Login</strong> button.</p>
</li>
<li><p><strong>Step 2:</strong> The client app packages the credentials and sends an HTTP POST request to the server: <code>POST /login</code>.</p>
</li>
<li><p><strong>Step 3:</strong> The request travels through the network (routers, switches, DNS servers, and the internet) to reach the server's endpoint.</p>
</li>
<li><p><strong>Step 4:</strong> The server receives the request, parses the payload, and performs security checks.</p>
</li>
<li><p><strong>Step 5:</strong> The server queries the database to verify if the email and hashed password exist:</p>
<pre><code class="language-sql">SELECT * FROM users WHERE email = 'user@example.com';
</code></pre>
</li>
<li><p><strong>Step 6:</strong> The database finds the record and returns the user data to the server.</p>
</li>
<li><p><strong>Step 7:</strong> The server compares passwords and generates a response payload:</p>
<ul>
<li><p><strong>If credentials match:</strong></p>
<pre><code class="language-json">{
  "status": "success",
  "message": "Login successful"
}
</code></pre>
</li>
<li><p><strong>If credentials fail:</strong></p>
<pre><code class="language-json">{
  "status": "error",
  "message": "Invalid credentials"
}
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Step 8:</strong> The server wraps this payload in an HTTP response (with an appropriate status code like <code>200 OK</code> or <code>401 Unauthorized</code>).</p>
</li>
<li><p><strong>Step 9:</strong> The response travels back across the network to the client's device.</p>
</li>
<li><p><strong>Step 10:</strong> The client receives the response and updates the UI:</p>
<ul>
<li><p><strong>On Success:</strong> Redirects the user to the dashboard.</p>
</li>
<li><p><strong>On Failure:</strong> Displays an error message alert.</p>
</li>
</ul>
</li>
</ol>
<hr />
<h2>Types of Clients</h2>
<p>Clients are broadly categorized by how much computational workload they handle locally:</p>
<h3>1. Thin Clients</h3>
<p>A client that relies heavily on the server to perform the bulk of its data processing. The client itself is lightweight and primarily acts as a display terminal.</p>
<ul>
<li><p><strong>Examples:</strong> Traditional server-side rendered websites (built with PHP, Jinja, or JSP), banking portals, and terminal displays.</p>
</li>
<li><p><strong>Characteristics:</strong></p>
<ul>
<li><p>Minimal local business logic.</p>
</li>
<li><p>Server does the heavy lifting; client simply displays the HTML/CSS payload.</p>
</li>
</ul>
</li>
</ul>
<h3>2. Thick (Rich) Clients</h3>
<p>A client that performs a significant amount of data processing and business logic locally before requesting or displaying data.</p>
<ul>
<li><p><strong>Examples:</strong> Modern Single Page Applications (React, Vue, Angular), mobile apps (iOS/Android), and standalone gaming clients.</p>
</li>
<li><p><strong>Characteristics:</strong></p>
<ul>
<li><p>Handles UI rendering, state management, and input validation on the client.</p>
</li>
<li><p>The server is primarily used as an API endpoint to fetch and save raw data.</p>
</li>
</ul>
</li>
</ul>
<blockquote>
<p>[!NOTE] Modern applications often use a hybrid approach (e.g., Server-Side Rendering with Client-Side Hydration) to get the best of both thin and thick client models.</p>
</blockquote>
<hr />
<h2>Types of Servers</h2>
<p>In production systems, responsibilities are split across different types of specialized servers:</p>
<ol>
<li><p><strong>Web Servers:</strong> Responsible for serving static assets (HTML, CSS, JavaScript, images) and handling HTTP routing.</p>
<ul>
<li><em>Examples:</em> Nginx, Apache HTTP Server.</li>
</ul>
</li>
<li><p><strong>Application Servers:</strong> Host the business logic, API routes, and execute code to process requests.</p>
<ul>
<li><em>Examples:</em> Node.js/Express, Django (Python), Spring Boot (Java).</li>
</ul>
</li>
<li><p><strong>Database Servers:</strong> Dedicated servers designed to store, manage, query, and secure application data.</p>
<ul>
<li><em>Examples:</em> PostgreSQL, MySQL, MongoDB.</li>
</ul>
</li>
</ol>
<hr />
<h2>Evolution of Architectures: Tiers</h2>
<p>System architectures are categorized into "tiers" based on how physical components are separated.</p>
<h3>1. Two-Tier Architecture</h3>
<p>The client connects directly to the database. There is no middle application layer.</p>
<p><strong>[ Client App ] ↔ [ Database Server ]</strong></p>
<ul>
<li><p><strong>Use Case:</strong> Small, internal desktop tools.</p>
</li>
<li><p><strong>Limitations:</strong></p>
<ul>
<li><p><strong>Security Risk:</strong> The database credentials and connection details are stored on the client side, exposing them to users.</p>
</li>
<li><p><strong>Scalability Bottleneck:</strong> Direct database connections do not scale well when thousands of clients try to connect concurrently.</p>
</li>
</ul>
</li>
</ul>
<h3>2. Three-Tier Architecture</h3>
<p>The standard setup for modern web applications. An intermediate application server is added between the client and the database.</p>
<p><strong>[ Presentation Tier ] ➔ [ Application Tier ] ➔ [ Data Tier ]</strong></p>
<ul>
<li><p><strong>Example:</strong> React Frontend ➔ Node.js Backend ➔ MongoDB Database.</p>
</li>
<li><p><strong>Key Benefits:</strong></p>
<ul>
<li><p><strong>Separation of Concerns:</strong> Each tier is independent, making the codebase easier to maintain.</p>
</li>
<li><p><strong>Enhanced Security:</strong> The client never directly queries the database. The app server acts as a gatekeeper.</p>
</li>
<li><p><strong>Independent Scaling:</strong> You can spin up more app servers to handle traffic without overloading the database.</p>
</li>
</ul>
</li>
</ul>
<h3>3. Multi-Tier (N-Tier) Architecture</h3>
<p>Enterprise applications scale three-tier setups by splitting them into many specialized microservices and layers.</p>
<p><strong>[ Client App ] ➔ [ Load Balancer ] ➔ [ API Gateway ] ➔ [ Microservices ] ↔ [ Cache &amp; Databases ]</strong></p>
<ul>
<li><p><strong>Example:</strong> Instagram, Netflix, Amazon.</p>
</li>
<li><p><strong>Benefits:</strong></p>
<ul>
<li><p>High fault tolerance and granular scalability.</p>
</li>
<li><p>Optimized data retrieval via caching (Redis/Memcached).</p>
</li>
<li><p>Specialized microservices manage different domains (e.g., auth, payments, notifications).</p>
</li>
</ul>
</li>
</ul>
<hr />
<h2>Advantages &amp; Disadvantages of Client-Server Architecture</h2>
<h3>Advantages</h3>
<ul>
<li><p><strong>Centralized Management:</strong> All data, security policies, and business logic are centralized on the server, making updates and backups simple.</p>
</li>
<li><p><strong>Robust Security:</strong> Access controls, encryption, and firewalls are easier to enforce on centralized servers rather than thousands of user devices.</p>
</li>
<li><p><strong>Granular Scalability:</strong> Different parts of the infrastructure can scale independently based on demand (e.g., adding more app servers during sales).</p>
</li>
<li><p><strong>Resource Sharing:</strong> Multiple clients can easily share access to centralized resources (like databases, APIs, and file systems).</p>
</li>
</ul>
<h3>Disadvantages</h3>
<ul>
<li><p><strong>Single Point of Failure (SPOF):</strong> If the primary backend server or database goes down, the entire application becomes unavailable to all clients.</p>
</li>
<li><p><strong>Network Latency:</strong> Every user action that requires data must travel across a network, which introduces delay.</p>
</li>
<li><p><strong>Server Overload:</strong> Sudden traffic spikes (e.g., flash sales) can overwhelm servers, causing slowdowns or crashes.</p>
</li>
</ul>
<hr />
<h2>Client-Server Architecture in a Modern Stack (MERN)</h2>
<p>To put this in perspective, here is how a MERN stack maps to this model:</p>
<p><strong>[ React App ] ➔ [ Node.js + Express ] ➔ [ MongoDB ]</strong></p>
<ul>
<li><p><strong>Client (React):</strong> UI rendering, state management, HTTP requests.</p>
</li>
<li><p><strong>Server (Node/Express):</strong> API routes, authentication, logic, validation.</p>
</li>
<li><p><strong>Database (MongoDB):</strong> JSON-like documents, collections, indexes.</p>
</li>
</ul>
<hr />
<blockquote>
<p>[!TIP] <strong>What's Next?</strong> Now that you understand how clients and servers interact, the next step is designing effective APIs. In the next section, we'll dive deep into <strong>REST API Design: The Right Way</strong> (covering versioning, pagination, idempotency, error handling, status codes, and more). Keep reading!</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[How the Internet Works: IP, DNS, TCP/UDP, and HTTP/HTTPS]]></title><description><![CDATA[System Design Series — Blog 2

Before you can design systems that scale, you need to understand the ground they run on. Every request your app handles — a user loading a page, submitting a form, watch]]></description><link>https://takshpatel02.hashnode.dev/how-the-internet-works-ip-dns-tcp-udp-and-http-https</link><guid isPermaLink="true">https://takshpatel02.hashnode.dev/how-the-internet-works-ip-dns-tcp-udp-and-http-https</guid><dc:creator><![CDATA[Patel Taksh]]></dc:creator><pubDate>Tue, 16 Jun 2026 08:29:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a204787823cf7a978c06c48/c3046ce5-a752-4523-91af-4508313f31a0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>System Design Series — Blog 2</em></p>
<hr />
<p>Before you can design systems that scale, you need to understand the ground they run on. Every request your app handles — a user loading a page, submitting a form, watching a video — travels through a stack of protocols working together invisibly. This blog breaks down that stack: IP, TCP, UDP, HTTP/HTTPS, and DNS.</p>
<hr />
<h2>IP — Internet Protocol: Every Device Needs an Address</h2>
<p>When you connect to the internet — whether at home via Wi-Fi or on your phone — your Internet Service Provider (ISP) assigns your device an IP address. Think of it as a postal address for your device on the internet. It looks like this:</p>
<ul>
<li><p><strong>IPv4:</strong> <code>192.168.1.5</code> — four numbers separated by dots. Only ~4.3 billion addresses possible, and we've nearly run out.</p>
</li>
<li><p><strong>IPv6:</strong> A much longer format, offering essentially unlimited addresses. The new standard going forward.</p>
</li>
</ul>
<p>Your ISP-assigned IP is <strong>not permanent</strong> — it changes every time you reconnect. Servers like Google, however, have reserved, fixed public IPs so the internet can consistently reach them.</p>
<h3>What IP actually does</h3>
<p>IP's job is purely <strong>addressing and routing</strong>. It breaks data into small packets, attaches the destination IP address, and sends them off. That's it.</p>
<blockquote>
<p>IP does <strong>not</strong> guarantee delivery, order, or error correction. Those responsibilities belong to the layer above it.</p>
</blockquote>
<h3>Key concepts</h3>
<table>
<thead>
<tr>
<th>Term</th>
<th>What it means</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Public IP</strong></td>
<td>Visible to the internet — assigned by your ISP</td>
</tr>
<tr>
<td><strong>Private IP</strong></td>
<td>Internal to your network — assigned by your router</td>
</tr>
<tr>
<td><strong>Packet</strong></td>
<td>A small chunk of data, labeled with source and destination IP</td>
</tr>
<tr>
<td><strong>Routing</strong></td>
<td>Routers read the destination IP and forward packets toward the target</td>
</tr>
</tbody></table>
<p><strong>Flow:</strong></p>
<pre><code class="language-plaintext">Your device (192.168.1.5) → Your router → Internet → Google (142.250.77.46)
</code></pre>
<hr />
<h2>TCP — Transmission Control Protocol: Reliable Delivery</h2>
<p>TCP sits on top of IP. While IP routes packets, TCP makes sure they all arrive at the destination in the correct order, without corruption.</p>
<h3>The 3-way handshake</h3>
<p>Before any data is sent, TCP establishes a connection:</p>
<pre><code class="language-plaintext">Client    server
SYN  →  (Can we start?)
     ←  SYN-ACK  (Yes, confirmed)
ACK  →  (Starting transmission)
</code></pre>
<p>After the handshake, data flows. For every packet received, the receiver sends an acknowledgement (ACK). If the sender doesn't receive an ACK within a timeout window, it automatically retransmits that specific packet.</p>
<p><strong>Real example:</strong> When you load a webpage, your browser connects to the server via TCP. If a packet carrying part of the HTML is lost, TCP requests it again automatically — you'll never see a half-loaded page with missing chunks.</p>
<h3>The cost of reliability</h3>
<p>TCP's back-and-forth makes it <strong>slower than UDP</strong>. This is perfectly fine for webpages and file downloads. But for live video calls, a delay from retransmitting one outdated packet is worse than simply skipping it — which is exactly where UDP comes in.</p>
<hr />
<h2>UDP — User Datagram Protocol: Speed Over Guarantees</h2>
<p>UDP is the lightweight, speed-focused protocol. No handshake, no acknowledgements, no retransmissions. You send packets and they go — no questions asked.</p>
<p>This sounds risky, but for certain use cases it's exactly the right choice:</p>
<ul>
<li><p><strong>Online gaming:</strong> Your position updates 60–120 times per second. If one update packet drops, the next one corrects your position anyway. TCP would stall the entire game waiting to retransmit a position that's already outdated.</p>
</li>
<li><p><strong>Video calls:</strong> A brief audio blip from a dropped packet is far less disruptive than a frozen call waiting for retransmission.</p>
</li>
<li><p><strong>DNS lookups:</strong> A quick request deserves a quick response — there's no point running a handshake for a 50ms operation.</p>
</li>
<li><p><strong>Video streaming (YouTube, Netflix):</strong> Interestingly, they use both — UDP-based protocols for speed, with their own error-correction logic built in at a higher level.</p>
</li>
</ul>
<h3>Key concepts</h3>
<table>
<thead>
<tr>
<th>Property</th>
<th>UDP behaviour</th>
</tr>
</thead>
<tbody><tr>
<td>Handshake</td>
<td>None — just start sending</td>
</tr>
<tr>
<td>Delivery guarantee</td>
<td>No — packets may be lost, duplicated, or arrive out of order</td>
</tr>
<tr>
<td>Latency</td>
<td>Very low — no waiting for ACKs</td>
</tr>
<tr>
<td>Best for</td>
<td>Live streams, gaming, DNS, video calls</td>
</tr>
</tbody></table>
<hr />
<h2>HTTP — HyperText Transfer Protocol: The Language of the Web</h2>
<p>HTTP is the set of rules for how clients (browsers, apps) request data and how servers respond. It runs on top of TCP — so by the time HTTP is talking, the TCP handshake is already done.</p>
<h3>HTTP Methods</h3>
<table>
<thead>
<tr>
<th>Method</th>
<th>What you're asking</th>
</tr>
</thead>
<tbody><tr>
<td><code>GET</code></td>
<td>Give me this resource (loading a page, fetching an image)</td>
</tr>
<tr>
<td><code>POST</code></td>
<td>Here's some data, do something with it (form submission, sign-up)</td>
</tr>
<tr>
<td><code>PUT / PATCH</code></td>
<td>Update this existing data</td>
</tr>
<tr>
<td><code>DELETE</code></td>
<td>Remove this</td>
</tr>
</tbody></table>
<h3>HTTP Status Codes</h3>
<table>
<thead>
<tr>
<th>Code</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><code>200 OK</code></td>
<td>Success — here's what you asked for</td>
</tr>
<tr>
<td><code>301 Moved Permanently</code></td>
<td>This URL has moved — go here instead</td>
</tr>
<tr>
<td><code>404 Not Found</code></td>
<td>Whatever you're looking for doesn't exist here</td>
</tr>
<tr>
<td><code>500 Internal Server Error</code></td>
<td>Something broke on the server's end</td>
</tr>
</tbody></table>
<h3>HTTP is stateless</h3>
<p>Each HTTP request is completely independent. The server has no memory of your previous request. This is why websites use <strong>cookies and sessions</strong> — to carry identity across requests and keep you logged in.</p>
<h3>Key concepts</h3>
<ul>
<li><p><strong>Request-response:</strong> The client always initiates; the server always responds. One cycle per resource.</p>
</li>
<li><p><strong>Headers:</strong> Both requests and responses carry metadata — content type, caching rules, cookies, and more.</p>
</li>
<li><p><strong>HTTP/2 and HTTP/3:</strong> Modern versions support multiple simultaneous requests over a single connection — significantly faster.</p>
</li>
</ul>
<p><strong>Flow:</strong></p>
<pre><code class="language-plaintext">Browser sends GET → over TCP (already open) → server processes → 200 OK + HTML returned
</code></pre>
<hr />
<h2>HTTPS — HTTP Secure: Encryption on Top</h2>
<p>HTTPS is HTTP + TLS (Transport Layer Security). Everything HTTP does, HTTPS does — but all data is encrypted, authenticated, and integrity-verified.</p>
<h3>How the TLS handshake works</h3>
<ol>
<li><p>Your browser connects to <code>https://sbi.co.in</code></p>
</li>
<li><p>SBI's server sends its <strong>SSL certificate</strong> — a digital ID card signed by a trusted Certificate Authority (CA)</p>
</li>
<li><p>Your browser checks: <em>Is this certificate legitimate? Is it actually for sbi.co.in and not a fake site?</em> If yes — trusted.</p>
</li>
<li><p>They exchange encryption keys and agree on a cipher. All communication from here is encrypted.</p>
</li>
</ol>
<h3>Why this matters</h3>
<p>On a public Wi-Fi (a café, airport, or mall) without HTTPS, anyone on the same network can intercept your requests using a <strong>man-in-the-middle attack</strong>. With HTTPS, they see only gibberish.</p>
<p>HTTPS guarantees three things:</p>
<table>
<thead>
<tr>
<th>Property</th>
<th>What it means</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Privacy</strong></td>
<td>Data is encrypted in transit</td>
</tr>
<tr>
<td><strong>Integrity</strong></td>
<td>Data wasn't altered on the way</td>
</tr>
<tr>
<td><strong>Authentication</strong></td>
<td>You're actually talking to the real server</td>
</tr>
</tbody></table>
<h3>Key concepts</h3>
<ul>
<li><p><strong>TLS vs SSL:</strong> TLS is the current encryption protocol. SSL is the older name — you'll still hear both used interchangeably.</p>
</li>
<li><p><strong>Certificate:</strong> Proves the server is who it claims to be. Issued by a Certificate Authority (CA).</p>
</li>
<li><p><strong>Ports:</strong> HTTP runs on port <code>80</code>, HTTPS on port <code>443</code> — the server listens on different doors.</p>
</li>
</ul>
<p><strong>Flow:</strong></p>
<pre><code class="language-plaintext">TCP handshake → TLS handshake → certificate verified → encrypted HTTP begins
</code></pre>
<hr />
<h2>DNS — Domain Name System: The Internet's Phone Book</h2>
<p>Humans remember names. Computers need numbers. DNS bridges this gap — converting human-readable domain names into IP addresses.</p>
<h3>The DNS resolution process</h3>
<p>What happens when you type <code>google.com</code> into your browser:</p>
<ol>
<li><p><strong>Browser cache</strong> — Have I looked this up recently? If yes, use the cached IP. Done.</p>
</li>
<li><p><strong>OS cache</strong> — Check the operating system's DNS cache.</p>
</li>
<li><p><strong>Recursive resolver</strong> — Your ISP takes over the lookup.</p>
</li>
<li><p><strong>Root nameserver</strong> — Who handles <code>.com</code> domains? Points to the <code>.com</code> TLD server.</p>
</li>
<li><p><strong>TLD nameserver</strong> — Who handles <code>google.com</code>? Points to Google's nameserver.</p>
</li>
<li><p><strong>Authoritative nameserver</strong> — Google's own DNS server responds: <code>142.250.77.46</code></p>
</li>
<li><p>The IP is returned to your browser. Now it can make an HTTP/HTTPS request to that IP.</p>
</li>
</ol>
<p>This sounds like many steps — but it happens in <strong>milliseconds</strong>. And results are cached, so it rarely goes all the way to step 6.</p>
<h3>DNS record types</h3>
<table>
<thead>
<tr>
<th>Record</th>
<th>What it does</th>
</tr>
</thead>
<tbody><tr>
<td><strong>A record</strong></td>
<td>Maps a domain to an IPv4 address — most common type</td>
</tr>
<tr>
<td><strong>AAAA record</strong></td>
<td>Maps a domain to an IPv6 address</td>
</tr>
<tr>
<td><strong>CNAME</strong></td>
<td>Alias — points one domain to another (e.g., <code>www.x.com → x.com</code>)</td>
</tr>
<tr>
<td><strong>TTL</strong></td>
<td>Time-to-live — how long the IP is cached before a fresh lookup is needed</td>
</tr>
</tbody></table>
<hr />
<h2>Putting It All Together</h2>
<p>Every time you visit a website, all of these protocols fire in sequence:</p>
<pre><code class="language-plaintext">1. DNS resolves the domain → gets the IP address
2. TCP handshake → establishes a reliable connection
3. TLS handshake → encrypts the connection (if HTTPS)
4. HTTP request → browser asks for the page
5. HTTP response → server sends back the HTML, CSS, JS
6. IP → routes every packet of that data to the right destination
</code></pre>
<p>Understanding this stack isn't just trivia — when you're designing systems, you're constantly making decisions that live at these layers. Should this service use WebSockets or HTTP polling? Should this data transfer use TCP or UDP? Is DNS caching a bottleneck? These questions only make sense once you understand what's happening underneath.</p>
<hr />
<p><em>This is part of my ongoing system design learning series. If you found this useful, follow along — the next post covers the core building blocks of scalable systems.</em></p>
]]></content:encoded></item><item><title><![CDATA[System Design — Blog 1: What is System Design? (HLD vs LLD)]]></title><description><![CDATA[What is System Design?
System design is the process of defining the elements of a system — the architecture, modules, components, and the data that flows through it.
In simple terms:

How do we struct]]></description><link>https://takshpatel02.hashnode.dev/system-design-blog-1-what-is-system-design-hld-vs-lld</link><guid isPermaLink="true">https://takshpatel02.hashnode.dev/system-design-blog-1-what-is-system-design-hld-vs-lld</guid><dc:creator><![CDATA[Patel Taksh]]></dc:creator><pubDate>Mon, 15 Jun 2026 16:51:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a204787823cf7a978c06c48/6052fd04-0b7e-4e4a-bbcc-a67e647da357.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h2>What is System Design?</h2>
<p>System design is the process of defining the elements of a system — the architecture, modules, components, and the data that flows through it.</p>
<p>In simple terms:</p>
<blockquote>
<p><strong>How do we structure software so it works at scale, stays maintainable, and different developers can build it together without chaos?</strong></p>
</blockquote>
<hr />
<h2>Two Types of System Design</h2>
<ol>
<li><p><strong>HLD — High Level Design</strong></p>
</li>
<li><p><strong>LLD — Low Level Design</strong></p>
</li>
</ol>
<blockquote>
<p>HLD is done first so the team agrees on the big picture before anyone writes a single line of code. LLD comes after, once the structure is locked.</p>
</blockquote>
<hr />
<h2>HLD (High Level Design)</h2>
<p>HLD describes the main components that would be developed for the system — the architecture, database design, services and processes, and the relationships between various modules and features.</p>
<p><strong>HLD answers the question:</strong></p>
<blockquote>
<p><em>What major parts exist in the system and how do they communicate with each other?</em></p>
</blockquote>
<h3>HLD focuses on:</h3>
<ul>
<li><p>Overall architecture</p>
</li>
<li><p>Services</p>
</li>
<li><p>Scalability</p>
</li>
<li><p>Databases</p>
</li>
<li><p>APIs</p>
</li>
<li><p>Traffic flow</p>
</li>
<li><p>Deployment</p>
</li>
<li><p>Distributed systems</p>
</li>
</ul>
<blockquote>
<p>In HLD, we do not think about code-level details.</p>
</blockquote>
<hr />
<h3>Example — Food Delivery App HLD</h3>
<p><strong>Components:</strong></p>
<ul>
<li><p>Client App</p>
</li>
<li><p>API Gateway</p>
</li>
<li><p>Auth Service</p>
</li>
<li><p>Restaurant Service</p>
</li>
<li><p>Order Service</p>
</li>
<li><p>Payment Service</p>
</li>
<li><p>Database</p>
</li>
<li><p>Cache</p>
</li>
<li><p>Notification Service</p>
</li>
</ul>
<p><strong>Flow:</strong></p>
<pre><code class="language-plaintext">User → API Gateway → Auth Service → Order Service → Payment Service → DB
                                                  ↓
                                       Notification Service
</code></pre>
<p>This is HLD.</p>
<hr />
<h3>HLD asks questions like:</h3>
<ul>
<li><p>Should we use monolith or microservices?</p>
</li>
<li><p>SQL or NoSQL?</p>
</li>
<li><p>Is Redis cache needed?</p>
</li>
<li><p>How do services talk to each other?</p>
</li>
<li><p>How do we scale?</p>
</li>
<li><p>How many servers?</p>
</li>
<li><p>Is a load balancer needed?</p>
</li>
<li><p>Is a queue system needed?</p>
</li>
</ul>
<p>HLD is purely about designing the system — which database to use, how services connect, how traffic flows. <strong>No code lives here.</strong></p>
<hr />
<h2>LLD (Low Level Design)</h2>
<p>LLD describes the internal design of each component mentioned in the HLD — the classes, interfaces, relationships between them, and the actual logic of each module.</p>
<p><strong>LLD answers the question:</strong></p>
<blockquote>
<p><em>How exactly will each component work internally?</em></p>
</blockquote>
<p>This is the <strong>code-level architecture</strong>.</p>
<h3>LLD focuses on:</h3>
<ul>
<li><p>Classes</p>
</li>
<li><p>Objects</p>
</li>
<li><p>Interfaces</p>
</li>
<li><p>Methods</p>
</li>
<li><p>Design patterns</p>
</li>
<li><p>Relationships between components</p>
</li>
<li><p>Business logic</p>
</li>
</ul>
<hr />
<h3>Example — Food Delivery App LLD</h3>
<p><strong>Inside the Order Service:</strong></p>
<p><strong>Classes:</strong></p>
<ul>
<li><p><code>Order</code></p>
</li>
<li><p><code>Cart</code></p>
</li>
<li><p><code>Payment</code></p>
</li>
<li><p><code>User</code></p>
</li>
<li><p><code>Restaurant</code></p>
</li>
</ul>
<p><strong>Methods:</strong></p>
<ul>
<li><p><code>createOrder()</code></p>
</li>
<li><p><code>cancelOrder()</code></p>
</li>
<li><p><code>calculateTotal()</code></p>
</li>
</ul>
<p><strong>Patterns used:</strong></p>
<ul>
<li><p>Factory Pattern</p>
</li>
<li><p>Singleton</p>
</li>
<li><p>Observer</p>
</li>
</ul>
<p>This is LLD.</p>
<hr />
<h2>HLD and LLD are Connected — Not Separate</h2>
<p>The most important thing to understand: <strong>HLD and LLD are not two separate worlds. One feeds the other.</strong></p>
<table>
<thead>
<tr>
<th>HLD says...</th>
<th>LLD says...</th>
</tr>
</thead>
<tbody><tr>
<td>We need an Authentication Service</td>
<td>Inside Auth Service: <code>JWTClass</code>, <code>TokenManager</code>, <code>Middleware</code>, <code>PasswordHasher</code></td>
</tr>
<tr>
<td>We need an Order Service</td>
<td>Inside Order Service: <code>Order</code>, <code>Cart</code>, <code>createOrder()</code>, Factory Pattern</td>
</tr>
<tr>
<td>We need a Notification Service</td>
<td>Inside Notification Service: <code>EmailNotifier</code>, <code>SMSNotifier</code>, Observer Pattern</td>
</tr>
</tbody></table>
<p>HLD gives you the map. LLD gives you what's inside each building on that map.</p>
<hr />
<p><em>This is Blog 1 of my System Design series. Next up: Scalability — Horizontal vs Vertical Scaling.</em></p>
]]></content:encoded></item></channel></rss>