<?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[Aditya Kumar Gupta]]></title><description><![CDATA[Discover the latest in tech with Aditya Kumar Gupta's insightful blog. From expert tutorials to breaking news, stay informed and inspired in the ever-evolving world of technology. Explore, learn, and]]></description><link>https://blog.adityaguptareal.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 12 Oct 2026 00:42:22 GMT</lastBuildDate><atom:link href="https://blog.adityaguptareal.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[JavaScript Part 2 : Scope & Execution ]]></title><description><![CDATA[JavaScript's execution model revolves around scope and execution context. Understanding how variables are accessed, how JavaScript resolves them, and how hoisting works is one of the most frequently t]]></description><link>https://blog.adityaguptareal.com/javascript-scope-execution</link><guid isPermaLink="true">https://blog.adityaguptareal.com/javascript-scope-execution</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Mon, 03 Aug 2026 06:13:00 GMT</pubDate><content:encoded><![CDATA[<p>JavaScript's execution model revolves around <strong>scope</strong> and <strong>execution context</strong>. Understanding how variables are accessed, how JavaScript resolves them, and how hoisting works is one of the most frequently tested topics in JavaScript interviews.</p>
<p>This guide provides a quick revision of the essential concepts.</p>
<h2>Topics Covered</h2>
<ul>
<li><p>Global Scope</p>
</li>
<li><p>Function Scope</p>
</li>
<li><p>Block Scope</p>
</li>
<li><p>Scope Chain</p>
</li>
<li><p>Lexical Scope</p>
</li>
<li><p>Dynamic Scope (Comparison)</p>
</li>
<li><p>Variable Shadowing</p>
</li>
<li><p>Hoisting</p>
</li>
<li><p>Temporal Dead Zone (TDZ)</p>
</li>
<li><p>Strict Mode</p>
</li>
</ul>
<h2>Global Scope</h2>
<p>Global Scope is the outermost scope in JavaScript. Variables declared outside any function or block belong to the global scope and can be accessed from anywhere in the program.</p>
<p>When JavaScript starts executing a file, it creates a global execution context. Any variable declared outside a function or block becomes part of the global scope.</p>
<h3>Example</h3>
<pre><code class="language-javascript">const company = "OpenAI";

function showCompany() {
    console.log(company);
}

showCompany();
</code></pre>
<p>Output</p>
<pre><code class="language-text">OpenAI
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Accessible throughout the program.</p>
</li>
<li><p>Created when JavaScript starts execution.</p>
</li>
<li><p>Avoid creating too many global variables as they can lead to naming conflicts.</p>
</li>
</ul>
<h2>Function Scope</h2>
<p>Variables declared inside a function can only be accessed within that function.</p>
<p>Every function creates its own scope. Variables inside a function are private to that function.</p>
<h3>Example</h3>
<pre><code class="language-javascript">function greet() {
    let message = "Hello";
    console.log(message);
}

greet();

// console.log(message);
</code></pre>
<p>Output</p>
<pre><code class="language-text">Hello
</code></pre>
<p>The last line throws a <code>ReferenceError</code> because <code>message</code> exists only inside the function.</p>
<h3>Important Points</h3>
<ul>
<li><p>Every function creates a new scope.</p>
</li>
<li><p>Variables inside a function are inaccessible from outside.</p>
</li>
<li><p><code>var</code> follows function scope.</p>
</li>
</ul>
<h2>Block Scope</h2>
<p>Variables declared using <code>let</code> and <code>const</code> are accessible only within the block (<code>{}</code>) where they are declared.</p>
<p>A block can be an <code>if</code> statement, <code>for</code> loop, <code>while</code> loop, or any pair of curly braces.</p>
<h3>Example</h3>
<pre><code class="language-javascript">if (true) {
    let age = 20;
    const city = "Delhi";
}

// console.log(age);
// console.log(city);
</code></pre>
<p>Both statements outside the block throw a <code>ReferenceError</code>.</p>
<h3>Important Points</h3>
<ul>
<li><p>Only <code>let</code> and <code>const</code> are block scoped.</p>
</li>
<li><p><code>var</code> ignores block scope.</p>
</li>
<li><p>Helps prevent accidental access to variables.</p>
</li>
</ul>
<h2>Scope Chain</h2>
<p>A Scope Chain is the process JavaScript uses to search for a variable when it is accessed.</p>
<p>JavaScript first looks in the current scope. If the variable is not found, it moves to the parent scope.</p>
<p>This continues until the global scope is reached. If the variable is still not found, a <code>ReferenceError</code> is thrown.</p>
<h3>Example</h3>
<pre><code class="language-javascript">const company = "OpenAI";

function outer() {
    const team = "AI";

    function inner() {
        console.log(company);
        console.log(team);
    }

    inner();
}

outer();
</code></pre>
<p>Output</p>
<pre><code class="language-text">OpenAI
AI
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Search starts from the current scope.</p>
</li>
<li><p>Moves outward toward the global scope.</p>
</li>
<li><p>Never searches child scopes.</p>
</li>
</ul>
<h2>Lexical Scope</h2>
<p>Lexical Scope means a function can access variables from the scope where it was defined.</p>
<p>The scope of a function is determined by its position in the source code, not by where it is called.</p>
<h3>Example</h3>
<pre><code class="language-javascript">const language = "JavaScript";

function outer() {
    function inner() {
        console.log(language);
    }

    inner();
}

outer();
</code></pre>
<p>Output</p>
<pre><code class="language-text">JavaScript
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Scope is decided when code is written.</p>
</li>
<li><p>JavaScript uses lexical scoping.</p>
</li>
<li><p>Closures are based on lexical scope.</p>
</li>
</ul>
<hr />
<h2>Dynamic Scope (Comparison)</h2>
<p>Dynamic Scope means a function accesses variables based on where it is called rather than where it is defined.</p>
<p>JavaScript <strong>does not support dynamic scoping</strong>. It always uses lexical scope.</p>
<h3>Example</h3>
<pre><code class="language-javascript">const name = "Global";

function greet() {
    console.log(name);
}

function execute() {
    const name = "Local";
    greet();
}

execute();
</code></pre>
<p>Output</p>
<pre><code class="language-text">Global
</code></pre>
<p>If JavaScript used dynamic scope, the output would have been <code>"Local"</code>.</p>
<h3>Important Points</h3>
<ul>
<li><p>JavaScript does not support dynamic scope.</p>
</li>
<li><p>Variable lookup is based on where the function is defined.</p>
</li>
</ul>
<h2>Variable Shadowing</h2>
<p>Variable Shadowing occurs when a variable declared in an inner scope has the same name as a variable in an outer scope.</p>
<p>The inner variable hides (or shadows) the outer variable within that scope.</p>
<h3>Example</h3>
<pre><code class="language-javascript">let name = "Global";

function greet() {
    let name = "Local";

    console.log(name);
}

greet();

console.log(name);
</code></pre>
<p>Output</p>
<pre><code class="language-text">Local
Global
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Inner variables take precedence.</p>
</li>
<li><p>Outer variable remains unchanged.</p>
</li>
<li><p>Commonly used inside functions and blocks.</p>
</li>
</ul>
<h2>Hoisting</h2>
<p>Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the creation phase of the execution context.</p>
<p>Only declarations are hoisted, not initializations.</p>
<ul>
<li><p><code>var</code> is hoisted and initialized with <code>undefined</code>.</p>
</li>
<li><p><code>let</code> and <code>const</code> are hoisted but remain uninitialized until their declaration executes.</p>
</li>
</ul>
<h3>Example</h3>
<pre><code class="language-javascript">console.log(age);

var age = 20;
</code></pre>
<p>Output</p>
<pre><code class="language-text">undefined
</code></pre>
<p>Internally, JavaScript treats it like:</p>
<pre><code class="language-javascript">var age;

console.log(age);

age = 20;
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Declarations are hoisted.</p>
</li>
<li><p>Initializations are not hoisted.</p>
</li>
<li><p>Function declarations are fully hoisted.</p>
</li>
</ul>
<h2>Temporal Dead Zone (TDZ)</h2>
<p>The Temporal Dead Zone (TDZ) is the period between entering a scope and initializing a <code>let</code> or <code>const</code> variable.</p>
<p>During this period:</p>
<ul>
<li><p>Memory has been allocated.</p>
</li>
<li><p>The variable exists.</p>
</li>
<li><p>The variable cannot be accessed.</p>
</li>
</ul>
<p>Trying to access it results in a <code>ReferenceError</code>.</p>
<h3>Example</h3>
<pre><code class="language-javascript">console.log(name);

let name = "Aditya";
</code></pre>
<p>Output</p>
<pre><code class="language-text">ReferenceError
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Applies only to <code>let</code> and <code>const</code>.</p>
</li>
<li><p>Starts when the scope is entered.</p>
</li>
<li><p>Ends when the variable is initialized.</p>
</li>
<li><p>Prevents accidental access before initialization.</p>
</li>
</ul>
<h2>Strict Mode</h2>
<p>Strict Mode is a special JavaScript mode that enables stricter parsing and error handling, helping developers write safer and more predictable code.</p>
<p>Strict Mode is enabled by adding <code>"use strict";</code> at the beginning of a script or function.</p>
<p>It prevents many common mistakes that JavaScript normally allows.</p>
<h3>Example</h3>
<pre><code class="language-javascript">"use strict";

age = 20;
</code></pre>
<p>Output</p>
<pre><code class="language-text">ReferenceError: age is not defined
</code></pre>
<p>Without Strict Mode, JavaScript would create a global variable automatically.</p>
<h3>Important Points</h3>
<ul>
<li><p>Enabled using <code>"use strict";</code></p>
</li>
<li><p>Prevents accidental global variables.</p>
</li>
<li><p>Disallows duplicate parameter names.</p>
</li>
<li><p>Makes silent errors throw exceptions.</p>
</li>
<li><p>Recommended for writing modern JavaScript.</p>
</li>
</ul>
<h2>Interview Questions</h2>
<ol>
<li><p>What is the difference between Global Scope, Function Scope, and Block Scope?</p>
</li>
<li><p>Explain the Scope Chain with an example.</p>
</li>
<li><p>What is Lexical Scope?</p>
</li>
<li><p>Does JavaScript support Dynamic Scope?</p>
</li>
<li><p>What is Variable Shadowing?</p>
</li>
<li><p>What is Hoisting? Are variables initialized during hoisting?</p>
</li>
<li><p>What is the Temporal Dead Zone?</p>
</li>
<li><p>Why does <code>var</code> not have a TDZ?</p>
</li>
<li><p>What is Strict Mode? Why is it used?</p>
</li>
<li><p>What is the difference between Hoisting and the Temporal Dead Zone?</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[JavaScript Revision Part 1 : Variables & Data Types]]></title><description><![CDATA[JavaScript variables and data types form the foundation of the language. Understanding how values are stored, copied, and identified is essential for writing efficient code and answering common interv]]></description><link>https://blog.adityaguptareal.com/javascript-revision-part-1-variables-data-types</link><guid isPermaLink="true">https://blog.adityaguptareal.com/javascript-revision-part-1-variables-data-types</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Mon, 27 Jul 2026 07:23:47 GMT</pubDate><content:encoded><![CDATA[<p>JavaScript variables and data types form the foundation of the language. Understanding how values are stored, copied, and identified is essential for writing efficient code and answering common interview questions.</p>
<p>This guide provides a quick revision of the most important concepts with concise explanations and practical examples.</p>
<h2>Topics Covered</h2>
<ul>
<li><p>Variables</p>
</li>
<li><p><code>var</code></p>
</li>
<li><p><code>let</code></p>
</li>
<li><p><code>const</code></p>
</li>
<li><p>Primitive Data Types</p>
</li>
<li><p>Non-Primitive Data Types</p>
</li>
<li><p>Pass by Value vs Pass by Reference</p>
</li>
<li><p><code>undefined</code> vs <code>null</code></p>
</li>
<li><p><code>undefined</code> vs <code>not defined</code></p>
</li>
<li><p><code>NaN</code></p>
</li>
<li><p><code>typeof</code> Operator</p>
</li>
</ul>
<hr />
<h2>Variables</h2>
<h3>Definition</h3>
<p>A variable is a named container used to store data in memory so it can be accessed, updated, and reused throughout a program.</p>
<h3>Explanation</h3>
<p>Instead of using hardcoded values multiple times, we store them in variables. JavaScript is a dynamically typed language, so a variable can hold any type of value.</p>
<h3>Example</h3>
<pre><code class="language-javascript">let name = "Aditya";
let age = 20;
let isStudent = true;
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Used to store data.</p>
</li>
<li><p>Can hold any data type.</p>
</li>
<li><p>Makes code reusable and maintainable.</p>
</li>
</ul>
<hr />
<h2>var</h2>
<h3>Definition</h3>
<p><code>var</code> is the original way of declaring variables in JavaScript. It is <strong>function-scoped</strong>, can be redeclared, and can be reassigned.</p>
<h3>Explanation</h3>
<p>Before ES6, developers used <code>var</code> for every variable. Since it ignores block scope and allows redeclaration, it can lead to unexpected behavior. For this reason, it is rarely used in modern JavaScript.</p>
<h3>Example</h3>
<pre><code class="language-javascript">var age = 20;

var age = 25;

age = 30;
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Function scoped</p>
</li>
<li><p>Can be redeclared</p>
</li>
<li><p>Can be reassigned</p>
</li>
<li><p>Hoisted and initialized with <code>undefined</code></p>
</li>
<li><p>Avoid using <code>var</code> in modern JavaScript</p>
</li>
</ul>
<hr />
<h2>let</h2>
<h3>Definition</h3>
<p><code>let</code> is a block-scoped variable introduced in ES6. It allows reassignment but does not allow redeclaration within the same scope.</p>
<h3>Explanation</h3>
<p>Unlike <code>var</code>, <code>let</code> respects block scope, making it safer to use inside loops, conditions, and functions.</p>
<h3>Example</h3>
<pre><code class="language-javascript">let age = 20;

age = 21;
</code></pre>
<pre><code class="language-javascript">let age = 20;
let age = 25; // SyntaxError
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Block scoped</p>
</li>
<li><p>Cannot be redeclared</p>
</li>
<li><p>Can be reassigned</p>
</li>
<li><p>Hoisted but remains in the Temporal Dead Zone until initialization</p>
</li>
</ul>
<hr />
<h2>const</h2>
<h3>Definition</h3>
<p><code>const</code> declares a block-scoped variable whose reference cannot be reassigned after initialization.</p>
<h3>Explanation</h3>
<p>Use <code>const</code> for values that should not be reassigned. For objects and arrays, only the reference is constant, not the contents.</p>
<h3>Example</h3>
<pre><code class="language-javascript">const user = {
  name: "Aditya",
};

user.name = "Rahul"; // Valid

user = {}; // Error
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Block scoped</p>
</li>
<li><p>Cannot be redeclared</p>
</li>
<li><p>Cannot be reassigned</p>
</li>
<li><p>Must be initialized during declaration</p>
</li>
<li><p>Object and array contents can still be modified</p>
</li>
</ul>
<hr />
<h2>var vs let vs const</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>var</th>
<th>let</th>
<th>const</th>
</tr>
</thead>
<tbody><tr>
<td>Scope</td>
<td>Function</td>
<td>Block</td>
<td>Block</td>
</tr>
<tr>
<td>Redeclare</td>
<td>Yes</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Reassign</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Hoisted</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Temporal Dead Zone</td>
<td>No</td>
<td>Yes</td>
<td>Yes</td>
</tr>
</tbody></table>
<hr />
<h2>Primitive Data Types</h2>
<h3>Definition</h3>
<p>Primitive data types are immutable values that store the actual value directly.</p>
<h3>Explanation</h3>
<p>Primitive values are copied when assigned to another variable. Modifying one variable does not affect the other because each variable stores its own copy.</p>
<p>JavaScript has <strong>7 primitive data types</strong>:</p>
<ul>
<li><p>String</p>
</li>
<li><p>Number</p>
</li>
<li><p>Boolean</p>
</li>
<li><p>Undefined</p>
</li>
<li><p>Null</p>
</li>
<li><p>Symbol</p>
</li>
<li><p>BigInt</p>
</li>
</ul>
<h3>Example</h3>
<pre><code class="language-javascript">let a = 10;
let b = a;

b = 20;

console.log(a);
</code></pre>
<p>Output</p>
<pre><code class="language-text">10
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Immutable</p>
</li>
<li><p>Stored by value</p>
</li>
<li><p>Compared by value</p>
</li>
<li><p>Independent copies are created during assignment</p>
</li>
</ul>
<hr />
<h2>Non-Primitive Data Types</h2>
<h3>Definition</h3>
<p>Non-primitive data types are objects that store a reference to the actual data instead of the data itself.</p>
<h3>Explanation</h3>
<p>When an object or array is assigned to another variable, JavaScript copies the reference, not the object. Both variables point to the same memory location.</p>
<p>Examples include:</p>
<ul>
<li><p>Object</p>
</li>
<li><p>Array</p>
</li>
<li><p>Function</p>
</li>
<li><p>Date</p>
</li>
<li><p>Map</p>
</li>
<li><p>Set</p>
</li>
</ul>
<h3>Example</h3>
<pre><code class="language-javascript">const user1 = {
  name: "Aditya",
};

const user2 = user1;

user2.name = "Rahul";

console.log(user1.name);
</code></pre>
<p>Output</p>
<pre><code class="language-text">Rahul
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Mutable</p>
</li>
<li><p>Stored by reference</p>
</li>
<li><p>Compared by reference</p>
</li>
<li><p>Multiple variables can reference the same object</p>
</li>
</ul>
<hr />
<h2>Pass by Value vs Pass by Reference</h2>
<h3>Pass by Value</h3>
<h4>Definition</h4>
<p>Pass by value means a copy of the original value is assigned or passed.</p>
<h4>Explanation</h4>
<p>Changing the copied value does not affect the original because both variables store separate copies.</p>
<h4>Example</h4>
<pre><code class="language-javascript">let a = 10;
let b = a;

b = 20;

console.log(a);
</code></pre>
<p>Output</p>
<pre><code class="language-text">10
</code></pre>
<hr />
<h3>Pass by Reference</h3>
<h4>Definition</h4>
<p>For objects, JavaScript copies the reference to the object instead of creating a new object.</p>
<h4>Explanation</h4>
<p>Both variables point to the same object. Any modification made through one variable is visible through the other.</p>
<h4>Example</h4>
<pre><code class="language-javascript">const obj1 = {
  name: "John",
};

const obj2 = obj1;

obj2.name = "Alex";

console.log(obj1.name);
</code></pre>
<p>Output</p>
<pre><code class="language-text">Alex
</code></pre>
<h3>Key Differences</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Pass by Value</th>
<th>Pass by Reference</th>
</tr>
</thead>
<tbody><tr>
<td>Applies To</td>
<td>Primitive Types</td>
<td>Objects</td>
</tr>
<tr>
<td>Copy Created</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Memory Shared</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Original Value Changes</td>
<td>No</td>
<td>Yes</td>
</tr>
</tbody></table>
<blockquote>
<p><strong>Interview Note:</strong> JavaScript is technically <strong>pass-by-value</strong>. For objects, the value being copied is the reference, which is why changes are reflected in all variables pointing to the same object.</p>
</blockquote>
<hr />
<h2>Undefined vs Null</h2>
<h3>Undefined</h3>
<h4>Definition</h4>
<p><code>undefined</code> is the default value assigned to a variable that has been declared but not initialized.</p>
<h4>Example</h4>
<pre><code class="language-javascript">let age;

console.log(age);
</code></pre>
<p>Output</p>
<pre><code class="language-text">undefined
</code></pre>
<h3>Null</h3>
<h4>Definition</h4>
<p><code>null</code> represents an intentional absence of value assigned by the developer.</p>
<h4>Example</h4>
<pre><code class="language-javascript">let user = null;
</code></pre>
<h3>Key Differences</h3>
<table>
<thead>
<tr>
<th>Undefined</th>
<th>Null</th>
</tr>
</thead>
<tbody><tr>
<td>Assigned by JavaScript</td>
<td>Assigned by Developer</td>
</tr>
<tr>
<td>Variable has no value yet</td>
<td>Variable intentionally has no value</td>
</tr>
<tr>
<td>Type is <code>undefined</code></td>
<td><code>typeof null</code> returns <code>"object"</code></td>
</tr>
</tbody></table>
<h2>Undefined vs Not Defined</h2>
<h3>Undefined</h3>
<p>A variable exists but has not been assigned a value.</p>
<pre><code class="language-javascript">let city;

console.log(city);
</code></pre>
<p>Output</p>
<pre><code class="language-text">undefined
</code></pre>
<hr />
<h3>Not Defined</h3>
<p>A variable has never been declared.</p>
<pre><code class="language-javascript">console.log(city);
</code></pre>
<p>Output</p>
<pre><code class="language-text">ReferenceError: city is not defined
</code></pre>
<h3>Key Differences</h3>
<table>
<thead>
<tr>
<th>Undefined</th>
<th>Not Defined</th>
</tr>
</thead>
<tbody><tr>
<td>Variable exists</td>
<td>Variable doesn't exist</td>
</tr>
<tr>
<td>Returns <code>undefined</code></td>
<td>Throws <code>ReferenceError</code></td>
</tr>
</tbody></table>
<h2>NaN</h2>
<h3>Definition</h3>
<p><code>NaN</code> stands for <strong>Not a Number</strong> and represents an invalid numeric result.</p>
<h3>Explanation</h3>
<p>It is returned when a mathematical operation cannot produce a valid number.</p>
<h3>Example</h3>
<pre><code class="language-javascript">console.log(Number("Hello"));
</code></pre>
<p>Output</p>
<pre><code class="language-text">NaN
</code></pre>
<p>Another common interview question:</p>
<pre><code class="language-javascript">console.log(NaN === NaN);
</code></pre>
<p>Output</p>
<pre><code class="language-text">false
</code></pre>
<p>Use <code>Number.isNaN()</code> to check whether a value is <code>NaN</code>.</p>
<h3>Important Points</h3>
<ul>
<li><p>Type of <code>NaN</code> is <code>number</code></p>
</li>
<li><p><code>NaN</code> is not equal to itself</p>
</li>
<li><p>Use <code>Number.isNaN()</code> instead of <code>==</code> or <code>===</code></p>
</li>
</ul>
<hr />
<h2>typeof Operator</h2>
<h3>Definition</h3>
<p>The <code>typeof</code> operator is used to determine the data type of a value.</p>
<h3>Explanation</h3>
<p>It returns a string representing the type of the operand. It is commonly used for type checking in JavaScript.</p>
<h3>Example</h3>
<pre><code class="language-javascript">typeof "Hello";      // "string"
typeof 10;           // "number"
typeof true;         // "boolean"
typeof undefined;    // "undefined"
typeof Symbol();     // "symbol"
typeof 10n;          // "bigint"
typeof {};           // "object"
typeof [];           // "object"
typeof function(){}; // "function"
typeof null;         // "object"
</code></pre>
<h3>Important Points</h3>
<ul>
<li><p>Returns the type as a string.</p>
</li>
<li><p>Arrays return <code>"object"</code>.</p>
</li>
<li><p>Functions return <code>"function"</code>.</p>
</li>
<li><p><code>typeof null</code> returns <code>"object"</code> due to a legacy JavaScript behavior.</p>
</li>
</ul>
<h2>Interview Questions</h2>
<ol>
<li><p>What is the difference between <code>var</code>, <code>let</code>, and <code>const</code>?</p>
</li>
<li><p>What is the difference between function scope and block scope?</p>
</li>
<li><p>Explain primitive and non-primitive data types.</p>
</li>
<li><p>What is the difference between pass by value and pass by reference?</p>
</li>
<li><p>What is the difference between <code>undefined</code> and <code>null</code>?</p>
</li>
<li><p>What is the difference between <code>undefined</code> and <code>not defined</code>?</p>
</li>
<li><p>What is <code>NaN</code>? Why is <code>NaN !== NaN</code>?</p>
</li>
<li><p>Why does <code>typeof null</code> return <code>"object"</code>?</p>
</li>
<li><p>Why does <code>typeof []</code> return <code>"object"</code>?</p>
</li>
<li><p>How does the <code>typeof</code> operator work?</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[
How Distribution Can 10x Your Luck, Career & Income]]></title><description><![CDATA[I recently watched one of Varun Mayya's talks on distribution, content, and personal branding, and it completely changed the way I think about building a career as a developer.
As engineers, we natura]]></description><link>https://blog.adityaguptareal.com/how-distribution-can-10x-your-luck-career-income</link><guid isPermaLink="true">https://blog.adityaguptareal.com/how-distribution-can-10x-your-luck-career-income</guid><category><![CDATA[distribution]]></category><category><![CDATA[luck]]></category><category><![CDATA[Founder]]></category><category><![CDATA[Freelancing]]></category><category><![CDATA[Founders]]></category><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Thu, 16 Jul 2026 15:21:29 GMT</pubDate><content:encoded><![CDATA[<p>I recently watched one of <strong>Varun Mayya's</strong> talks on <strong>distribution, content, and personal branding</strong>, and it completely changed the way I think about building a career as a developer.</p>
<p>As engineers, we naturally spend most of our time learning new technologies, building projects, and improving our technical skills. But this talk made me realize that technical skills alone are no longer enough.</p>
<p>The people who create the biggest impact aren't always the best engineers they're often the ones who know how to distribute their work.</p>
<p>These are the ideas that stayed with me and how I interpret them as a developer and aspiring founder.</p>
<h2>Distribution is More Valuable Than Product</h2>
<p>One of the strongest ideas from the talk was that <strong>distribution is often more valuable than the product itself</strong>.</p>
<p>At first, that sounds wrong. As developers, we're taught that if we build something great, users will naturally come.</p>
<p>Reality is different.</p>
<p>Distribution brings users. Users bring feedback. Feedback helps improve the product.</p>
<p>Better products attract better talent, investors, customers, and opportunities. Distribution creates a flywheel that makes everything else easier.</p>
<p>The product still matters, but without distribution, even great products can remain invisible.</p>
<h2>Content is a Long-Term Asset</h2>
<p>I used to think content was mainly for creators and influencers.</p>
<p>Now I see it differently.</p>
<p>Every article, project breakdown, technical tutorial, LinkedIn post, or YouTube video becomes a long-term asset that keeps working even when you're offline.</p>
<p>You're not creating content for today's likes.</p>
<p>You're creating opportunities that might appear months or even years later.</p>
<h2>Luck Can Be Engineered</h2>
<p>Another idea that really resonated with me was that success often looks like luck.</p>
<p>The difference is that some people deliberately increase their chances of getting lucky.</p>
<p>Every project you publish... Every article you write... Every conference you attend... Every developer you connect with... Every lesson you share...</p>
<p>...increases the number of opportunities that can find you.</p>
<p>You can't control when luck happens.</p>
<p>But you can increase the probability.</p>
<h2>Content is a Lightning Rod</h2>
<p>Varun compared content to a lightning rod.</p>
<p>Lightning is unpredictable.</p>
<p>But if you're visible enough, eventually some of that lightning hits you.</p>
<p>That could be:</p>
<ul>
<li><p>a recruiter discovering your profile,</p>
</li>
<li><p>a freelance client reaching out,</p>
</li>
<li><p>a founder inviting you to collaborate,</p>
</li>
<li><p>an investor noticing your startup,</p>
</li>
<li><p>or someone recommending your work.</p>
</li>
</ul>
<p>You don't know where the opportunity will come from.</p>
<p>That's exactly why visibility matters.</p>
<h2>Every Profession Needs Distribution</h2>
<p>One thing I hadn't thought about before was that distribution isn't only for startups or creators.</p>
<p>Doctors benefit from it.</p>
<p>Lawyers benefit from it.</p>
<p>Designers benefit from it.</p>
<p>Developers benefit from it.</p>
<p>Consultants benefit from it.</p>
<p>Freelancers benefit from it.</p>
<p>The internet rewards people who consistently share valuable work.</p>
<h2>Trust is Built Through Repetition</h2>
<p>People rarely trust someone after seeing them once.</p>
<p>Trust grows through repeated interactions.</p>
<p>Seeing your projects.</p>
<p>Reading your articles.</p>
<p>Watching your talks.</p>
<p>Following your progress.</p>
<p>Over time, people stop seeing you as a stranger and start seeing you as someone whose work they know.</p>
<p>That's when opportunities naturally begin to appear.</p>
<h2>Build Your Reputation Before You Need It</h2>
<p>One mistake many people make is trying to build a personal brand only when they need a job or clients.</p>
<p>By then, you're asking people to trust someone they've never seen before.</p>
<p>A much better approach is to build that trust continuously.</p>
<p>Share what you're learning.</p>
<p>Document your projects.</p>
<p>Explain your technical decisions.</p>
<p>Teach what you're discovering.</p>
<p>When opportunities arrive, people already know your work.</p>
<h2>Content is More Than Views</h2>
<p>Views are only a surface-level metric.</p>
<p>The real outcome of content is trust.</p>
<p>Someone might watch ten of your articles before reaching out.</p>
<p>A founder might silently follow your work for months before sending you a message.</p>
<p>You rarely know which piece of content influenced someone.</p>
<p>That's why consistency matters much more than individual performance.</p>
<h2>Give Value Before You Sell</h2>
<p>One idea I really liked was that the best creators don't constantly promote themselves.</p>
<p>They provide value first.</p>
<p>Teach.</p>
<p>Educate.</p>
<p>Entertain.</p>
<p>Solve problems.</p>
<p>Then occasionally talk about your product, service, or business.</p>
<p>People naturally trust those who consistently help them.</p>
<h2>Think in Years, Not Weeks</h2>
<p>Building distribution isn't a 30-day challenge.</p>
<p>It's a long-term investment.</p>
<p>The benefits compound slowly.</p>
<p>One article won't change your career.</p>
<p>Neither will one project.</p>
<p>But years of consistently sharing your work can completely transform the opportunities available to you.</p>
<h2>The 7-11-4 Principle</h2>
<p>One framework mentioned in the talk really stood out.</p>
<p>People usually don't trust a person or brand after seeing them once.</p>
<p>Trust often requires multiple interactions across different platforms over time.</p>
<p>That completely changed how I think about personal branding.</p>
<p>Instead of trying to create one viral post, it's probably more valuable to publish consistently for years.</p>
<h2>Developers Should Build in Public</h2>
<p>This was probably my biggest takeaway.</p>
<p>Instead of only uploading finished projects to GitHub, I want to share:</p>
<ul>
<li><p>why I built something,</p>
</li>
<li><p>what problems I solved,</p>
</li>
<li><p>what mistakes I made,</p>
</li>
<li><p>the architecture decisions,</p>
</li>
<li><p>performance improvements,</p>
</li>
<li><p>lessons learned,</p>
</li>
<li><p>and what I'd do differently next time.</p>
</li>
</ul>
<p>Clients and recruiters aren't only evaluating the final project.</p>
<p>They're evaluating how you think.</p>
<h2>My Biggest Reflection</h2>
<p>As developers, we spend years investing in technical skills.</p>
<p>Those skills will always be important.</p>
<p>But I'm starting to believe another skill deserves equal attention:</p>
<p><strong>The ability to communicate your work.</strong></p>
<p>Writing, teaching, documenting, and sharing ideas don't replace engineering—they amplify it.</p>
<p>This blog is my way of doing exactly that.</p>
<p>I'll continue documenting what I build, what I learn, and the ideas that shape how I think about software engineering, AI, startups, freelancing, and entrepreneurship.</p>
<p>If one article helps someone solve a problem, discover a new perspective, or simply think differently, then it's worth writing.</p>
]]></content:encoded></item><item><title><![CDATA[How JavaScript Works Internally Beginner-Friendly Guide ]]></title><description><![CDATA[If you've ever been asked questions like:

Why is JavaScript called single-threaded?

Why does setTimeout(..., 0) run later?

What is the Call Stack?

What are the Task Queue and Microtask Queue?

Wha]]></description><link>https://blog.adityaguptareal.com/how-javascript-works-internally-beginner-friendly-guide</link><guid isPermaLink="true">https://blog.adityaguptareal.com/how-javascript-works-internally-beginner-friendly-guide</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Mon, 13 Jul 2026 12:50:26 GMT</pubDate><content:encoded><![CDATA[<p>If you've ever been asked questions like:</p>
<ul>
<li><p>Why is JavaScript called <strong>single-threaded</strong>?</p>
</li>
<li><p>Why does <code>setTimeout(..., 0)</code> run later?</p>
</li>
<li><p>What is the <strong>Call Stack</strong>?</p>
</li>
<li><p>What are the <strong>Task Queue</strong> and <strong>Microtask Queue</strong>?</p>
</li>
<li><p>What does the <strong>Event Loop</strong> actually do?</p>
</li>
</ul>
<p>then you're in the right place.</p>
<p>These are some of the most common JavaScript interview questions, and they often confuse beginners because many tutorials explain them using complicated terms.</p>
<p>In this article, we'll understand <strong>how JavaScript executes code internally</strong> in the simplest way possible. By the end, you'll not only understand the concepts but also be able to explain them confidently in interviews.</p>
<p>Let's begin.</p>
<h2>What Happens When You Run JavaScript?</h2>
<p>Whether you run JavaScript in a browser or in Node.js, the execution process follows the same basic idea.</p>
<pre><code class="language-text">JavaScript Code
       ↓
JavaScript Engine
       ↓
Execution Context
       ↓
Call Stack
       ↓
Code Starts Executing
</code></pre>
<p>The JavaScript engine (like <strong>V8</strong> in Chrome and Node.js) reads your code, creates an execution environment, and starts executing it line by line.</p>
<p>Before we understand asynchronous JavaScript, we first need to understand how synchronous code works.</p>
<h2>What is an Execution Context?</h2>
<p>An <strong>Execution Context</strong> is simply the environment where JavaScript executes your code.</p>
<p>Whenever JavaScript starts running a file, it creates a <strong>Global Execution Context</strong>.</p>
<p>It has two phases:</p>
<table>
<thead>
<tr>
<th>Phase</th>
<th>What Happens</th>
</tr>
</thead>
<tbody><tr>
<td>Memory Creation Phase</td>
<td>Variables and functions are stored in memory.</td>
</tr>
<tr>
<td>Execution Phase</td>
<td>JavaScript executes the code line by line.</td>
</tr>
</tbody></table>
<p>Think of it like preparing a classroom before teaching begins.</p>
<ul>
<li><p>First, all the students enter the classroom (Memory Phase).</p>
</li>
<li><p>Then, the teacher starts teaching (Execution Phase).</p>
</li>
</ul>
<h2>The Call Stack</h2>
<p>The <strong>Call Stack</strong> is one of the most important concepts in JavaScript.</p>
<p>It is responsible for executing JavaScript code.</p>
<p>Whenever JavaScript wants to execute something, it pushes it into the Call Stack.</p>
<p>The Call Stack follows the <strong>LIFO (Last In, First Out)</strong> rule.</p>
<p><strong>For example:</strong></p>
<pre><code class="language-javascript">console.log("A");
console.log("B");
console.log("C");
</code></pre>
<p>Execution happens like this:</p>
<pre><code class="language-text">Push A
↓

Execute A
↓

Pop A
↓

Push B
↓

Execute B
↓

Pop B
↓

Push C
↓

Execute C
↓

Pop C
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-text">A
B
C
</code></pre>
<p>The Call Stack executes only <strong>one operation at a time</strong>.</p>
<h2>Why is JavaScript Single-Threaded?</h2>
<p>This is probably the most asked interview question.</p>
<p>JavaScript has <strong>one Call Stack</strong>, which means it executes <strong>one piece of JavaScript code at a time</strong>.</p>
<p>Imagine a restaurant with only one chef.</p>
<pre><code class="language-text">Customers
   │
   ▼
👨‍🍳 One Chef
</code></pre>
<p>The chef cannot cook five dishes at the same time.</p>
<p>He finishes one order before starting the next.</p>
<p>JavaScript works exactly the same way.</p>
<p>One Call Stack = One Thread = One JavaScript operation at a time.</p>
<p>This is why JavaScript is called <strong>single-threaded</strong>.</p>
<h2>Then How Does JavaScript Handle Asynchronous Code?</h2>
<p><strong>Consider this example:</strong></p>
<pre><code class="language-javascript">console.log("Start");

setTimeout(() =&gt; {
    console.log("Timeout");
}, 2000);

console.log("End");
</code></pre>
<p>Most beginners expect JavaScript to wait for two seconds.</p>
<p>But the output is:</p>
<pre><code class="language-text">Start
End
Timeout
</code></pre>
<p>Why?</p>
<p>Because <strong>JavaScript itself doesn't wait</strong>.</p>
<p>Instead, it delegates asynchronous work to the environment (Browser APIs or Node.js APIs).</p>
<p>The execution looks like this:</p>
<pre><code class="language-text">Call Stack
      │
      ▼
setTimeout()
      │
      ▼
Browser / Node API
      │
      ▼
Timer Starts
      │
      ▼
Call Stack Continues
</code></pre>
<p>While the timer is running, JavaScript continues executing the remaining code.</p>
<p>That's why <code>"End"</code> prints immediately.</p>
<h2>Is setTimeout Part of JavaScript?</h2>
<p>This is one of the biggest misconceptions.</p>
<p><strong>No.</strong></p>
<p><code>setTimeout()</code> is <strong>not part of the JavaScript language</strong>.</p>
<p>It is provided by the environment.</p>
<table>
<thead>
<tr>
<th>Environment</th>
<th>Provides</th>
</tr>
</thead>
<tbody><tr>
<td>Browser</td>
<td>Web APIs</td>
</tr>
<tr>
<td>Node.js</td>
<td>Node APIs</td>
</tr>
</tbody></table>
<p>When JavaScript sees <code>setTimeout()</code>, it asks the browser (or Node.js) to handle the timer.</p>
<p>JavaScript itself never manages timers.</p>
<h2>What Happens After the Timer Finishes?</h2>
<p>When the timer completes, the callback does <strong>not</strong> go directly into the Call Stack.</p>
<p>Instead, it goes into a queue called the <strong>Task Queue</strong>.</p>
<p>You might also hear different names for the same queue.</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td>Task Queue</td>
<td>Same</td>
</tr>
<tr>
<td>Callback Queue</td>
<td>Same</td>
</tr>
<tr>
<td>Macrotask Queue</td>
<td>Same</td>
</tr>
</tbody></table>
<p>All three names usually refer to the same queue.</p>
<p>So if an interviewer says <strong>Callback Queue</strong>, <strong>Task Queue</strong>, or <strong>Macrotask Queue</strong>, don't get confused.</p>
<p>They're talking about the same thing.</p>
<h2>Then What is the Event Loop?</h2>
<p>Now imagine the callback is waiting inside the Task Queue.</p>
<p>Who moves it back to the Call Stack?</p>
<p>The answer is the <strong>Event Loop</strong>.</p>
<p>The Event Loop continuously checks two things:</p>
<ol>
<li><p>Is the Call Stack empty?</p>
</li>
<li><p>Is there any callback waiting?</p>
</li>
</ol>
<p>If the Call Stack is empty, it moves the callback from the queue into the Call Stack.</p>
<p>A simple mental model looks like this:</p>
<pre><code class="language-text">while (true) {

    Is Call Stack Empty?

        Yes

          ↓

    Run Microtasks

          ↓

    Run One Task
}
</code></pre>
<p>This isn't the real implementation, but it's a great way to understand how the Event Loop behaves.</p>
<h2>Microtask Queue vs Task Queue</h2>
<p>JavaScript actually has two queues.</p>
<pre><code class="language-text">                Event Loop
                     │
         ┌───────────┴───────────┐
         │                       │
         ▼                       ▼
Microtask Queue           Task Queue
   (Higher Priority)     (Lower Priority)
</code></pre>
<p>The <strong>Microtask Queue</strong> has higher priority than the Task Queue.</p>
<h3>Microtask Queue</h3>
<p>Examples:</p>
<ul>
<li><p>Promise.then()</p>
</li>
<li><p>Promise.catch()</p>
</li>
<li><p>Promise.finally()</p>
</li>
<li><p>queueMicrotask()</p>
</li>
</ul>
<h3>Task Queue</h3>
<p>Examples:</p>
<ul>
<li><p>setTimeout()</p>
</li>
<li><p>setInterval()</p>
</li>
<li><p>DOM Events</p>
</li>
<li><p>MessageChannel</p>
</li>
</ul>
<p>This priority difference is very important for interviews.</p>
<h2>Let's Understand with an Example</h2>
<pre><code class="language-javascript">console.log("Start");

setTimeout(() =&gt; {
    console.log("Timeout");
}, 0);

Promise.resolve().then(() =&gt; {
    console.log("Promise");
});

console.log("End");
</code></pre>
<p>What do you think the output will be?</p>
<p>It is:</p>
<pre><code class="language-text">Start
End
Promise
Timeout
</code></pre>
<p>Let's understand why.</p>
<h3>Step 1</h3>
<p>JavaScript executes the synchronous code.</p>
<p>Output:</p>
<pre><code class="language-text">Start
End
</code></pre>
<h3>Step 2</h3>
<p>The Promise callback goes into the <strong>Microtask Queue</strong>.</p>
<p>The <code>setTimeout</code> callback goes into the <strong>Task Queue</strong>.</p>
<p>Current state:</p>
<pre><code class="language-text">Microtask Queue

Promise

Task Queue

Timeout
</code></pre>
<h3>Step 3</h3>
<p>The Event Loop checks the queues.</p>
<p>It always executes <strong>all Microtasks first</strong>.</p>
<p>So JavaScript executes:</p>
<pre><code class="language-text">Promise
</code></pre>
<h3>Step 4</h3>
<p>Now the Microtask Queue is empty.</p>
<p>The Event Loop takes one callback from the Task Queue.</p>
<pre><code class="language-text">Timeout
</code></pre>
<p>Final output:</p>
<pre><code class="language-text">Start
End
Promise
Timeout
</code></pre>
<p>This is why Promises always execute before <code>setTimeout()</code> callbacks, even when the timeout is <code>0</code>.</p>
<h2>Complete JavaScript Execution Flow</h2>
<p>Here's the complete picture.</p>
<pre><code class="language-text">JavaScript Code
        │
        ▼
Execution Context
        │
        ▼
Call Stack
        │
        ▼
Async Operation?
        │
   ┌────┴────┐
   │         │
 No         Yes
   │         │
Execute   Browser / Node API
             │
             ▼
      Operation Completes
             │
             ▼
      Queue (Microtask / Task)
             │
             ▼
         Event Loop
             │
             ▼
        Call Stack
             │
             ▼
          Output
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/33c9c9e1-97d3-4163-b87a-a9135f36901e.webp" alt="" style="display:block;margin:0 auto" />

<h2>Quick Interview Tips</h2>
<h3>1. Is JavaScript Single-Threaded?</h3>
<p>Yes.</p>
<p>JavaScript has only one Call Stack and executes one operation at a time.</p>
<h3>2. Does JavaScript Handle Timers?</h3>
<p>No.</p>
<p>Timers are handled by Browser APIs or Node.js APIs.</p>
<h3>3. Does <code>setTimeout(..., 0)</code> Run Immediately?</h3>
<p>No.</p>
<p>It first enters the Task Queue and waits until the Call Stack is empty.</p>
<h3>4. Which Queue Has Higher Priority?</h3>
<p>The <strong>Microtask Queue</strong>.</p>
<p>All pending microtasks execute before the Event Loop processes the next task from the Task Queue.</p>
<h3>5. Are Task Queue, Callback Queue, and Macrotask Queue Different?</h3>
<p>No.</p>
<p>Most of the time, these are simply different names for the same queue.</p>
<h2>JavaScript Execution Cheat Sheet</h2>
<table>
<thead>
<tr>
<th>Concept</th>
<th>Remember This</th>
</tr>
</thead>
<tbody><tr>
<td>JavaScript</td>
<td>Single-threaded language</td>
</tr>
<tr>
<td>Execution Context</td>
<td>Environment where code runs</td>
</tr>
<tr>
<td>Call Stack</td>
<td>Executes synchronous JavaScript code</td>
</tr>
<tr>
<td>Browser APIs / Node APIs</td>
<td>Handle asynchronous operations</td>
</tr>
<tr>
<td>Task Queue</td>
<td>Stores callbacks from <code>setTimeout</code>, <code>setInterval</code>, DOM events</td>
</tr>
<tr>
<td>Callback Queue</td>
<td>Another name for Task Queue</td>
</tr>
<tr>
<td>Macrotask Queue</td>
<td>Another name for Task Queue</td>
</tr>
<tr>
<td>Microtask Queue</td>
<td>Stores Promise callbacks and <code>queueMicrotask()</code></td>
</tr>
<tr>
<td>Event Loop</td>
<td>Moves callbacks into the Call Stack when it becomes empty</td>
</tr>
<tr>
<td>Execution Order</td>
<td>Synchronous Code → All Microtasks → One Task → Repeat</td>
</tr>
</tbody></table>
<h2>Conclusion</h2>
<p>Understanding JavaScript execution isn't about memorizing definitions—it's about understanding the flow.</p>
<p>Every JavaScript program follows the same lifecycle:</p>
<ol>
<li><p>JavaScript creates an Execution Context.</p>
</li>
<li><p>Code starts executing inside the Call Stack.</p>
</li>
<li><p>Asynchronous operations are delegated to the environment.</p>
</li>
<li><p>Completed callbacks are placed into either the Microtask Queue or the Task Queue.</p>
</li>
<li><p>The Event Loop waits for the Call Stack to become empty, executes all pending microtasks, then processes one task, and repeats the cycle.</p>
</li>
</ol>
<p>Once you understand this flow, concepts like <strong>Promises, async/await, the Event Loop,</strong> <code>setTimeout</code><strong>, and asynchronous programming</strong> become much easier to reason about.</p>
<p>If you're preparing for JavaScript interviews, mastering these concepts will help you answer some of the most frequently asked questions with confidence.</p>
]]></content:encoded></item><item><title><![CDATA[How to Build, Market, and Scale a Profitable Software Business description]]></title><description><![CDATA[Most developers believe that building a great product is enough.
It isn't.
Thousands of technically excellent products fail every year because nobody knows they exist. The biggest difference between a]]></description><link>https://blog.adityaguptareal.com/how-to-build-market-and-scale-a-profitable-software</link><guid isPermaLink="true">https://blog.adityaguptareal.com/how-to-build-market-and-scale-a-profitable-software</guid><category><![CDATA[product]]></category><category><![CDATA[Earning]]></category><category><![CDATA[marketing]]></category><category><![CDATA[distribution]]></category><category><![CDATA[money]]></category><category><![CDATA[startup]]></category><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sun, 12 Jul 2026 11:50:18 GMT</pubDate><content:encoded><![CDATA[<p>Most developers believe that building a great product is enough.</p>
<p>It isn't.</p>
<p>Thousands of technically excellent products fail every year because nobody knows they exist. The biggest difference between a successful SaaS founder and an unsuccessful one is rarely coding ability - it's distribution.</p>
<p>This guide summarizes proven insights from successful founders, startup communities, Reddit discussions, Indie Hackers, Y Combinator, SaaStr, and widely recommended startup books.</p>
<p>Think of it as a quick reference whenever you're validating an idea, launching a product, or trying to acquire your first paying customers.</p>
<h2>The Biggest Lesson</h2>
<blockquote>
<p><strong>Distribution comes before perfection.</strong></p>
</blockquote>
<p>The order should always be:</p>
<ol>
<li><p>Find a market that spends money.</p>
</li>
<li><p>Find a painful problem.</p>
</li>
<li><p>Talk to potential customers.</p>
</li>
<li><p>Validate demand.</p>
</li>
<li><p>Build the smallest useful solution.</p>
</li>
<li><p>Acquire customers.</p>
</li>
<li><p>Improve based on feedback.</p>
</li>
</ol>
<p>Never reverse this order.</p>
<h2>Best Countries to Sell SaaS</h2>
<p>Not every country has the same willingness to pay for software. If you're building globally, prioritize countries where businesses already subscribe to multiple software products.</p>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Country</th>
<th>Willingness to Pay</th>
<th>Best Customers</th>
</tr>
</thead>
<tbody><tr>
<td>🥇</td>
<td>United States</td>
<td>⭐⭐⭐⭐⭐</td>
<td>SMBs, Startups, Enterprises</td>
</tr>
<tr>
<td>🥈</td>
<td>United Kingdom</td>
<td>⭐⭐⭐⭐⭐</td>
<td>Agencies, Professional Services</td>
</tr>
<tr>
<td>🥉</td>
<td>Australia</td>
<td>⭐⭐⭐⭐⭐</td>
<td>SMBs, Healthcare, Trades</td>
</tr>
<tr>
<td>4</td>
<td>Canada</td>
<td>⭐⭐⭐⭐☆</td>
<td>Startups, SMBs</td>
</tr>
<tr>
<td>5</td>
<td>Germany</td>
<td>⭐⭐⭐⭐☆</td>
<td>Manufacturing, B2B</td>
</tr>
<tr>
<td>6</td>
<td>Netherlands</td>
<td>⭐⭐⭐⭐☆</td>
<td>Tech Companies</td>
</tr>
<tr>
<td>7</td>
<td>Sweden</td>
<td>⭐⭐⭐⭐☆</td>
<td>SaaS Businesses</td>
</tr>
<tr>
<td>8</td>
<td>Singapore</td>
<td>⭐⭐⭐⭐☆</td>
<td>SMEs, Startups</td>
</tr>
<tr>
<td>9</td>
<td>UAE</td>
<td>⭐⭐⭐⭐☆</td>
<td>Real Estate, Healthcare</td>
</tr>
<tr>
<td>10</td>
<td>New Zealand</td>
<td>⭐⭐⭐⭐☆</td>
<td>Small Businesses</td>
</tr>
</tbody></table>
<h3>Priority Markets</h3>
<p>If you're a solo founder, focus on:</p>
<ul>
<li><p>🇺🇸 United States</p>
</li>
<li><p>🇬🇧 United Kingdom</p>
</li>
<li><p>🇦🇺 Australia</p>
</li>
</ul>
<p>These three markets offer the best combination of purchasing power, English communication, and SaaS adoption.</p>
<h2>What Type of Software Sells Best?</h2>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Software Type</th>
<th>Demand</th>
</tr>
</thead>
<tbody><tr>
<td>🥇</td>
<td>AI Web Applications</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>🥈</td>
<td>Web SaaS Platforms</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>🥉</td>
<td>Chrome Extensions</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>4</td>
<td>Internal Business Tools</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>5</td>
<td>Mobile B2B Apps</td>
<td>⭐⭐⭐☆☆</td>
</tr>
<tr>
<td>6</td>
<td>Desktop Applications</td>
<td>⭐⭐⭐☆☆</td>
</tr>
</tbody></table>
<p>For most founders, <strong>web applications are the best starting point</strong> because they're easy to update, easy to sell through subscriptions, and don't rely on app store approval.</p>
<h2>Industries That Happily Pay for Software</h2>
<p>Businesses don't pay for software because it's innovative.</p>
<p>They pay because it saves time, increases revenue, or reduces operational costs.</p>
<table>
<thead>
<tr>
<th>Category</th>
<th>Demand</th>
</tr>
</thead>
<tbody><tr>
<td>AI Productivity Tools</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>CRM Software</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>Sales Automation</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>Marketing Automation</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>Internal Business Systems</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>Accounting &amp; Finance</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>Customer Support</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>Project Management</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>Scheduling &amp; Booking</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>Healthcare Practice Management</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>Construction Software</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>Real Estate CRM</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
</tbody></table>
<h2>Where Do Customers Discover New Software?</h2>
<p>Building software is only half the job. The other half is making sure the right people discover it.</p>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Acquisition Channel</th>
<th>Priority</th>
</tr>
</thead>
<tbody><tr>
<td>🥇</td>
<td>Google Search (SEO)</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>🥈</td>
<td>Google Search Ads</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>🥉</td>
<td>LinkedIn</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>4</td>
<td>Cold Email</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>5</td>
<td>Referrals</td>
<td>⭐⭐⭐⭐⭐</td>
</tr>
<tr>
<td>6</td>
<td>YouTube</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>7</td>
<td>Reddit</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>8</td>
<td>Product Hunt</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>9</td>
<td>G2</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>10</td>
<td>Capterra</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>11</td>
<td>Partnerships</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
<tr>
<td>12</td>
<td>Affiliate Programs</td>
<td>⭐⭐⭐⭐☆</td>
</tr>
</tbody></table>
<h2>Typical Customer Journey</h2>
<p>A buyer rarely discovers software randomly.</p>
<p>Their journey usually looks like this:</p>
<pre><code class="language-plaintext">Problem
      ↓
Google Search
      ↓
Blog Articles
      ↓
YouTube Videos
      ↓
Reddit Discussions
      ↓
Compare Alternatives
      ↓
Visit Website
      ↓
Free Trial
      ↓
Purchase
</code></pre>
<p>This means your marketing should exist across multiple touchpoints, not just your homepage.</p>
<h2>The Biggest Mistake New Founders Make</h2>
<p>Many developers spend six months building a product before speaking to a single customer.</p>
<p>Instead, spend those months talking to people who already experience the problem.</p>
<p>Ask questions like:</p>
<ul>
<li><p>How do you solve this today?</p>
</li>
<li><p>What's frustrating about your current solution?</p>
</li>
<li><p>What tools are you already paying for?</p>
</li>
<li><p>If you could change one thing, what would it be?</p>
</li>
</ul>
<p>Avoid asking:</p>
<blockquote>
<p>"Would you buy my product?"</p>
</blockquote>
<p>People often say "yes" to be polite. Their current behavior is a far more reliable indicator than hypothetical answers.</p>
<h2>The First 100 Customers</h2>
<p>The first customers almost never come from viral marketing.</p>
<p>They come from consistent manual effort.</p>
<p>Focus on:</p>
<ul>
<li><p>Cold emails</p>
</li>
<li><p>LinkedIn outreach</p>
</li>
<li><p>Reddit participation</p>
</li>
<li><p>Community engagement</p>
</li>
<li><p>Customer interviews</p>
</li>
<li><p>Founder networking</p>
</li>
</ul>
<p>Don't automate until you've learned what messaging actually resonates.</p>
<h2>Reddit Strategy</h2>
<p>Reddit is not a place to advertise.</p>
<p>It's a place to build credibility.</p>
<p>Instead of posting:</p>
<blockquote>
<p>"Here's my SaaS."</p>
</blockquote>
<p>Try:</p>
<ul>
<li><p>Solving someone's problem.</p>
</li>
<li><p>Writing detailed answers.</p>
</li>
<li><p>Sharing lessons learned.</p>
</li>
<li><p>Posting case studies.</p>
</li>
<li><p>Explaining mistakes.</p>
</li>
<li><p>Publishing tutorials.</p>
</li>
</ul>
<p>Trust first.</p>
<p>Promotion second.</p>
<h2>SEO Strategy</h2>
<p>Google is one of the most valuable long-term acquisition channels.</p>
<p>Create content around problems people actively search for.</p>
<p><strong>Examples:</strong></p>
<ul>
<li><p>How to manage interior design clients</p>
</li>
<li><p>Best CRM for dental clinics</p>
</li>
<li><p>Invoice templates for freelancers</p>
</li>
<li><p>AI tools for architects</p>
</li>
</ul>
<p>Your content should solve a real problem before introducing your product.</p>
<h2>LinkedIn Strategy</h2>
<p>LinkedIn is ideal for B2B software.</p>
<p>Post consistently about:</p>
<ul>
<li><p>Product updates</p>
</li>
<li><p>Customer stories</p>
</li>
<li><p>Industry insights</p>
</li>
<li><p>Lessons learned</p>
</li>
<li><p>Mistakes</p>
</li>
<li><p>Behind-the-scenes development</p>
</li>
<li><p>Educational content</p>
</li>
</ul>
<p>People buy from founders they trust.</p>
<h2>YouTube Strategy</h2>
<p>You don't need expensive production.</p>
<p>Simple tutorials outperform polished advertisements.</p>
<p>Examples:</p>
<ul>
<li><p>How to solve a common industry problem</p>
</li>
<li><p>Product walkthroughs</p>
</li>
<li><p>Customer case studies</p>
</li>
<li><p>Feature comparisons</p>
</li>
<li><p>Productivity tips</p>
</li>
</ul>
<p>Teach first.</p>
<p>Sell later.</p>
<h2>Cold Email Strategy</h2>
<p>Cold email remains one of the fastest ways to validate a SaaS idea.</p>
<p>Keep emails short.</p>
<p>Focus on the recipient's problem.</p>
<p>Never start by listing product features.</p>
<p>Instead:</p>
<ul>
<li><p>Identify the problem.</p>
</li>
<li><p>Explain the impact.</p>
</li>
<li><p>Offer a simple solution.</p>
</li>
<li><p>End with one clear call to action.</p>
</li>
</ul>
<h2>Recommended Growth Timeline</h2>
<h3>Stage 1 (0–10 Customers)</h3>
<p>Focus on conversations.</p>
<p>Primary channels:</p>
<ul>
<li><p>Cold Email</p>
</li>
<li><p>LinkedIn</p>
</li>
<li><p>Reddit</p>
</li>
<li><p>Customer interviews</p>
</li>
</ul>
<p>Goal:</p>
<p>Learn.</p>
<p>Not scale.</p>
<h3>Stage 2 (10–100 Customers)</h3>
<p>Focus on repeatable acquisition.</p>
<p>Add:</p>
<ul>
<li><p>SEO</p>
</li>
<li><p>Blog posts</p>
</li>
<li><p>LinkedIn content</p>
</li>
<li><p>YouTube</p>
</li>
<li><p>Customer testimonials</p>
</li>
</ul>
<h3>Stage 3 (100–1000 Customers)</h3>
<p>Focus on systems.</p>
<p>Invest in:</p>
<ul>
<li><p>Google Ads</p>
</li>
<li><p>Affiliate programs</p>
</li>
<li><p>Referral systems</p>
</li>
<li><p>Partnerships</p>
</li>
<li><p>G2</p>
</li>
<li><p>Capterra</p>
</li>
</ul>
<h2>Books Worth Reading</h2>
<table>
<thead>
<tr>
<th>Book</th>
<th>Why Read It</th>
</tr>
</thead>
<tbody><tr>
<td>Traction</td>
<td>Learn 19 customer acquisition channels.</td>
</tr>
<tr>
<td>The Mom Test</td>
<td>Learn how to interview customers properly.</td>
</tr>
<tr>
<td>Obviously Awesome</td>
<td>Master product positioning.</td>
</tr>
<tr>
<td>Lean Startup</td>
<td>Validate ideas before building.</td>
</tr>
<tr>
<td>Influence</td>
<td>Understand buying psychology.</td>
</tr>
<tr>
<td>Building a StoryBrand</td>
<td>Improve messaging and marketing.</td>
</tr>
<tr>
<td>$100M Leads</td>
<td>Learn practical lead generation strategies.</td>
</tr>
</tbody></table>
<h2>YouTube Channels Worth Following</h2>
<h2>Startups</h2>
<ul>
<li><p>Y Combinator</p>
</li>
<li><p>Startup School</p>
</li>
<li><p>MicroConf</p>
</li>
<li><p>SaaStr</p>
</li>
<li><p>Indie Hackers</p>
</li>
</ul>
<h2>Marketing</h2>
<ul>
<li><p>Ahrefs</p>
</li>
<li><p>Semrush</p>
</li>
<li><p>HubSpot</p>
</li>
<li><p>Exposure Ninja</p>
</li>
<li><p>Neil Patel</p>
</li>
</ul>
<h2>Copywriting &amp; Sales</h2>
<ul>
<li><p>Alex Hormozi</p>
</li>
<li><p>Marketing Against the Grain</p>
</li>
<li><p>CXL</p>
</li>
</ul>
<h2>Product Design</h2>
<ul>
<li><p>Design with Arash</p>
</li>
<li><p>Figma</p>
</li>
<li><p>Lenny's Podcast</p>
</li>
</ul>
<h2>The 80/20 Rule for SaaS Founders</h2>
<h3>Many developers spend:</h3>
<ul>
<li><p>80% Building</p>
</li>
<li><p>20% Marketing</p>
</li>
</ul>
<p>Successful founders usually reverse it after an MVP exists.</p>
<p>A healthier balance is:</p>
<ul>
<li><p>20% Building</p>
</li>
<li><p>40% Talking to Customers</p>
</li>
<li><p>20% Marketing</p>
</li>
<li><p>20% Content Creation</p>
</li>
</ul>
<p>Your product only grows when people know it exists.</p>
<h2>Final Checklist</h2>
<h3>Before building any SaaS, answer these questions:</h3>
<ul>
<li><p>Is this a painful problem?</p>
</li>
<li><p>Are businesses already spending money to solve it?</p>
</li>
<li><p>Which country will I target first?</p>
</li>
<li><p>Who is my ideal customer?</p>
</li>
<li><p>Where do they spend time online?</p>
</li>
<li><p>How will I acquire my first 10 users?</p>
</li>
<li><p>How will I acquire my first 100 users?</p>
</li>
<li><p>Can I explain my product in one sentence?</p>
</li>
<li><p>Do I have a distribution plan before writing code?</p>
</li>
</ul>
<p>If you cannot answer these questions, you're not ready to build yet.</p>
<h2>Key Takeaways</h2>
<ul>
<li><p>Build for markets that already pay for software.</p>
</li>
<li><p>Validate before you build.</p>
</li>
<li><p>Talk to customers early and often.</p>
</li>
<li><p>Master one acquisition channel before expanding.</p>
</li>
<li><p>SEO compounds over time.</p>
</li>
<li><p>LinkedIn is powerful for B2B.</p>
</li>
<li><p>Reddit is for trust, not promotion.</p>
</li>
<li><p>Cold outreach is still one of the fastest ways to get early customers.</p>
</li>
<li><p>Content is a long-term asset that attracts buyers continuously.</p>
</li>
<li><p>Distribution is just as important as product quality.</p>
</li>
</ul>
<p>The founders who succeed are rarely the ones with the most features—they're the ones who consistently solve real problems, reach the right audience, and keep improving based on customer feedback.</p>
]]></content:encoded></item><item><title><![CDATA[I Thought Building AI Meant Learning Python. I Was Wrong.]]></title><description><![CDATA[For the longest time, I believed one thing:

If I wanted to build AI applications, I'd eventually have to leave my TypeScript stack behind and learn Python.

As a Full Stack Developer, every AI roadma]]></description><link>https://blog.adityaguptareal.com/how-real-ai-products-are-built</link><guid isPermaLink="true">https://blog.adityaguptareal.com/how-real-ai-products-are-built</guid><category><![CDATA[AI]]></category><category><![CDATA[Developer]]></category><category><![CDATA[developer experience]]></category><category><![CDATA[product]]></category><category><![CDATA[product thinking]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sat, 11 Jul 2026 19:06:02 GMT</pubDate><content:encoded><![CDATA[<p>For the longest time, I believed one thing:</p>
<blockquote>
<p>If I wanted to build AI applications, I'd eventually have to leave my TypeScript stack behind and learn Python.</p>
</blockquote>
<p>As a Full Stack Developer, every AI roadmap I came across looked something like this:</p>
<blockquote>
<p>Python → NumPy → Pandas → PyTorch → TensorFlow → Deep Learning → Research Papers...</p>
</blockquote>
<p>Honestly, it felt overwhelming.</p>
<p>A few weeks ago, I started digging into how companies actually build computer vision products. Things like:</p>
<ul>
<li><p>Driver monitoring systems in cars</p>
</li>
<li><p>CCTV analytics</p>
</li>
<li><p>Smart parking</p>
</li>
<li><p>Retail theft detection</p>
</li>
<li><p>Factory safety systems</p>
</li>
<li><p>Attendance systems</p>
</li>
</ul>
<p>I expected to find hundreds of pages of machine learning magic.</p>
<p>Instead, I found something much more interesting.</p>
<h2>AI is just one small part of the system</h2>
<p>One thing finally clicked for me.</p>
<p>Most real-world AI products aren't just "an AI model."</p>
<p>They're software systems.</p>
<p>A very simplified architecture looks something like this:</p>
<pre><code class="language-text">Camera
    ↓
Video Stream
    ↓
AI Model
    ↓
Business Rules
    ↓
Database
    ↓
Notifications
    ↓
Dashboard
</code></pre>
<p>The AI model is only one component.</p>
<p>Everything else is just software engineering.</p>
<p>That realization completely changed how I think about AI.</p>
<h2>I also misunderstood what YOLO actually does</h2>
<p>Before this, I thought models like YOLO somehow understood what was happening inside a video.</p>
<p>They don't.</p>
<p>YOLO doesn't know if someone is cheating in an exam.</p>
<p>It doesn't know if someone is stealing from a store.</p>
<p>It doesn't know if a driver is sleepy.</p>
<p>It simply says things like:</p>
<ul>
<li><p>Person</p>
</li>
<li><p>Phone</p>
</li>
<li><p>Bottle</p>
</li>
<li><p>Car</p>
</li>
<li><p>Laptop</p>
</li>
</ul>
<p>That's it.</p>
<p>The interesting part comes afterwards.</p>
<p>Your application decides what those detections actually mean.</p>
<h2>The business logic is where products become useful</h2>
<p>Let's imagine an online exam.</p>
<p>YOLO detects:</p>
<ul>
<li><p>Person</p>
</li>
<li><p>Phone</p>
</li>
</ul>
<p>Your backend decides:</p>
<p>"If the exam has started and a phone is visible, create an alert."</p>
<p>Now imagine a retail store.</p>
<p>The exact same model detects:</p>
<ul>
<li><p>Person</p>
</li>
<li><p>Bottle</p>
</li>
</ul>
<p>Different product.</p>
<p>Different business rules.</p>
<p>Same AI model.</p>
<p>That was another big "aha!" moment for me.</p>
<h2>You don't always need to train AI models</h2>
<p>This was another misconception I had.</p>
<p>I assumed every company trained huge AI models from scratch.</p>
<p>Turns out, many products start with pretrained models.</p>
<p>The engineering effort goes into integrating them into a useful application.</p>
<p>Only after validating the product do teams usually think about collecting their own datasets and improving the model.</p>
<h2>The best part?</h2>
<p>I don't have to abandon the stack I already enjoy.</p>
<p>I can still build applications using:</p>
<ul>
<li><p>TypeScript</p>
</li>
<li><p>Node.js</p>
</li>
<li><p>Next.js</p>
</li>
<li><p>PostgreSQL</p>
</li>
</ul>
<p>while running pretrained AI models using technologies like ONNX Runtime.</p>
<p>That completely changed how approachable computer vision feels.</p>
<h2>I'm still learning</h2>
<p>I'm definitely not an expert in this space.</p>
<p>I'm just documenting what I'm learning because I know there are probably other JavaScript developers who think AI is only about ChatGPT or Python.</p>
<p>Over the next few weeks, I'm planning to explore topics like:</p>
<ul>
<li><p>How RTSP cameras actually work</p>
</li>
<li><p>How AI models process video streams</p>
</li>
<li><p>Why object tracking matters</p>
</li>
<li><p>What ONNX Runtime actually does</p>
</li>
<li><p>How production AI systems are designed</p>
</li>
<li><p>Building small computer vision projects using TypeScript</p>
</li>
</ul>
<p>If you're also exploring this space, I'd love to connect.</p>
<p>Learning in public has always been one of the best ways I've found to understand something deeply, and hopefully these notes help someone else who's just getting started.</p>
]]></content:encoded></item><item><title><![CDATA[How AI Agents Work: A Practical Guide for Developers]]></title><description><![CDATA[AI coding agents have become one of the biggest advancements in software development. Tools like Claude Code, OpenAI Codex, Cursor, and Pi are changing how developers write, debug, and maintain code.
]]></description><link>https://blog.adityaguptareal.com/how-ai-agents-works-complete-beginner-guide</link><guid isPermaLink="true">https://blog.adityaguptareal.com/how-ai-agents-works-complete-beginner-guide</guid><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[langchain]]></category><category><![CDATA[langgraph]]></category><category><![CDATA[aiagents]]></category><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Thu, 09 Jul 2026 07:21:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/ca4c0789-50a7-4161-be73-8ed6e0755dac.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>AI coding agents have become one of the biggest advancements in software development. Tools like Claude Code, OpenAI Codex, Cursor, and Pi are changing how developers write, debug, and maintain code.</p>
<p>Unlike traditional AI chatbots that simply answer questions, coding agents can explore your project, understand your codebase, modify files, execute terminal commands, and solve programming tasks with very little manual effort.</p>
<p>But before building an AI agent, it's important to understand the concepts that make these systems work.</p>
<p>In this article, we'll cover the foundation of AI agents, starting from Large Language Models (LLMs), how they generate responses, why tokens matter, and how system prompts influence their behavior.</p>
<p>By the end, you'll understand the building blocks used in almost every modern AI application.</p>
<h2>Why Learn These Concepts?</h2>
<p>Many developers jump directly into frameworks like LangChain or start building AI applications using APIs.</p>
<p>While that works, it often creates confusion when something doesn't behave as expected.</p>
<p>Understanding the basics helps you:</p>
<ul>
<li><p>Build your own AI agents from scratch.</p>
</li>
<li><p>Debug AI applications more effectively.</p>
</li>
<li><p>Write better prompts.</p>
</li>
<li><p>Understand how tools like Claude Code or Codex work internally.</p>
</li>
<li><p>Design AI-powered applications instead of only using existing ones.</p>
</li>
</ul>
<p>Think of these concepts as the operating system behind every AI application.</p>
<h2>What is a Large Language Model (LLM)?</h2>
<p>A <strong>Large Language Model (LLM)</strong> is an AI model trained on massive amounts of data to understand and generate human language.</p>
<p>Instead of storing answers like a database, an LLM learns patterns from billions of examples.</p>
<p>Whenever you ask it a question, it predicts the most likely next piece of text based on everything it learned during training.</p>
<h3>A Simple Example</h3>
<p>Suppose you type:</p>
<blockquote>
<p>The capital of India is</p>
</blockquote>
<p>Most people instantly think of <strong>Delhi</strong>.</p>
<p>An LLM does something similar.</p>
<p>It doesn't search the internet in real time. Instead, it predicts that <strong>Delhi</strong> is the most likely next answer based on patterns learned during training.</p>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/35a2a1bd-e312-4e89-90e0-42e79bb2d181.png" alt="" style="display:block;margin:0 auto" />

<h2>LLMs Don't Memorize Information</h2>
<p>A common misconception is that AI models work like search engines.</p>
<p>They don't.</p>
<p>Instead of remembering every sentence from the internet, they learn relationships between concepts.</p>
<p>For example, during training, the model learns patterns like these:</p>
<table>
<thead>
<tr>
<th>Concept</th>
<th>Relationship Learned</th>
</tr>
</thead>
<tbody><tr>
<td>Delhi</td>
<td>Capital of India</td>
</tr>
<tr>
<td>React</td>
<td>JavaScript library</td>
</tr>
<tr>
<td>Docker</td>
<td>Container platform</td>
</tr>
<tr>
<td>PostgreSQL</td>
<td>Relational database</td>
</tr>
</tbody></table>
<p>When you ask a question, the model predicts an answer using these learned relationships.</p>
<h2>Where Does an LLM Get Its Knowledge?</h2>
<p>Modern LLMs are trained using enormous datasets collected from publicly available sources.</p>
<p>These include:</p>
<ul>
<li><p>Books</p>
</li>
<li><p>Documentation</p>
</li>
<li><p>Research papers</p>
</li>
<li><p>Technical blogs</p>
</li>
<li><p>Programming tutorials</p>
</li>
<li><p>Public GitHub repositories</p>
</li>
<li><p>Forums</p>
</li>
<li><p>Educational websites</p>
</li>
</ul>
<p>The model studies this information during training to learn language, reasoning, and coding patterns.</p>
<p>It doesn't continuously learn from the internet after deployment unless it's retrained with newer data.</p>
<h2>Why Is Data Becoming a Problem?</h2>
<p>One interesting point discussed in the video is that AI companies have already consumed most of the publicly available internet data.</p>
<p>This creates a new challenge.</p>
<p>If every company is training on nearly the same public information, where will future training data come from?</p>
<p>To solve this problem, companies are now investing in:</p>
<table>
<thead>
<tr>
<th>Source</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>Synthetic Data</td>
<td>AI-generated training examples</td>
</tr>
<tr>
<td>Human Labeling</td>
<td>Creating high-quality datasets manually</td>
</tr>
<tr>
<td>Licensed Content</td>
<td>Access to premium data</td>
</tr>
<tr>
<td>Private Codebases</td>
<td>Better programming knowledge</td>
</tr>
</tbody></table>
<p>Some companies even pay developers for access to large, high-quality private codebases because they provide valuable training data.</p>
<h2>What Makes Modern AI So Powerful?</h2>
<p>Most modern language models are built using a neural network architecture called the <strong>Transformer</strong>.</p>
<p>Before Transformers, AI struggled to understand long conversations or complex documents.</p>
<p>The Transformer architecture introduced a concept called <strong>Attention</strong>, allowing models to understand how different words relate to each other.</p>
<p>For example:</p>
<blockquote>
<p>"The developer fixed the bug because <strong>he</strong> understood the code."</p>
</blockquote>
<p>The model learns that <strong>he</strong> refers to the developer.</p>
<p>This ability to understand context is one of the biggest reasons modern AI performs so well.</p>
<blockquote>
<p><strong>Note:</strong> You don't need to deeply understand Transformer mathematics before building AI applications. However, knowing that modern LLMs use the Transformer architecture gives you useful background knowledge.</p>
</blockquote>
<h2>What Are Tokens?</h2>
<p>Humans read complete words.</p>
<p>LLMs don't.</p>
<p>Instead, they break text into smaller pieces called <strong>tokens</strong>.</p>
<p>A token can be:</p>
<ul>
<li><p>A complete word</p>
</li>
<li><p>Part of a word</p>
</li>
<li><p>A punctuation mark</p>
</li>
<li><p>A number</p>
</li>
<li><p>Even a space in some tokenizers</p>
</li>
</ul>
<p>For example, the word:</p>
<pre><code class="language-plaintext">Programming
</code></pre>
<p>might be divided into:</p>
<pre><code class="language-plaintext">Program
ming
</code></pre>
<p>Similarly,</p>
<pre><code class="language-plaintext">Artificial Intelligence
</code></pre>
<p>might become several individual tokens depending on the tokenizer used.</p>
<h2>Why Are Tokens Important?</h2>
<p>Every interaction with an AI model is measured in tokens.</p>
<p>Tokens determine:</p>
<ul>
<li><p>How much text the model can remember</p>
</li>
<li><p>API usage costs</p>
</li>
<li><p>Maximum conversation length</p>
</li>
<li><p>Response size</p>
</li>
</ul>
<p>This is why you'll often hear terms like:</p>
<ul>
<li><p>Context Window</p>
</li>
<li><p>Input Tokens</p>
</li>
<li><p>Output Tokens</p>
</li>
</ul>
<p>These all refer to how many tokens the model is processing.</p>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/88810887-289a-4693-9549-19573e870039.png" alt="" style="display:block;margin:0 auto" />

<h2>How AI Generates Responses</h2>
<p>One of the most fascinating things about an LLM is that it never writes an entire paragraph at once.</p>
<p>Instead, it generates one token at a time.</p>
<p>For example, if you ask:</p>
<blockquote>
<p>Explain Docker.</p>
</blockquote>
<p>The model might internally generate something like:</p>
<pre><code class="language-plaintext">Docker
</code></pre>
<p>↓</p>
<pre><code class="language-plaintext">is
</code></pre>
<p>↓</p>
<pre><code class="language-plaintext">a
</code></pre>
<p>↓</p>
<pre><code class="language-plaintext">containerization
</code></pre>
<p>↓</p>
<pre><code class="language-plaintext">platform
</code></pre>
<p>Each new token is predicted using all the previous tokens that have already been generated.</p>
<p>This process continues until the model generates a special <strong>end token</strong>, indicating that the response is complete.</p>
<p>Although this happens token by token, it's so fast that it feels like the AI is writing naturally.</p>
<h2>What Is a System Prompt?</h2>
<p>Whenever you use an AI application like ChatGPT or Claude, there's usually an invisible instruction sent before your message.</p>
<p>This instruction is called the <strong>System Prompt</strong>.</p>
<p>Its purpose is to tell the AI how it should behave.</p>
<p>For example, a system prompt might instruct the model to:</p>
<ul>
<li><p>Answer politely</p>
</li>
<li><p>Keep responses short</p>
</li>
<li><p>Write code only</p>
</li>
<li><p>Avoid unsafe content</p>
</li>
<li><p>Explain concepts for beginners</p>
</li>
</ul>
<p>The user never sees this prompt, but it strongly influences the model's responses.</p>
<h3>Example</h3>
<p><strong>System Prompt</strong></p>
<pre><code class="language-plaintext">You are an expert programming tutor.

Always explain concepts in simple language.
</code></pre>
<p><strong>User Prompt</strong></p>
<pre><code class="language-plaintext">Explain React Hooks.
</code></pre>
<p>Because of the system prompt, the AI responds like a teacher rather than simply defining React Hooks.</p>
<h2>System Prompt vs User Prompt</h2>
<table>
<thead>
<tr>
<th>System Prompt</th>
<th>User Prompt</th>
</tr>
</thead>
<tbody><tr>
<td>Defines how the AI should behave</td>
<td>Contains the user's actual request</td>
</tr>
<tr>
<td>Usually written by the application</td>
<td>Written by the user</td>
</tr>
<tr>
<td>Applied before every conversation</td>
<td>Changes with each query</td>
</tr>
</tbody></table>
<p>Both are combined before being sent to the language model.</p>
<h2>Chat Applications vs APIs</h2>
<p>There are two common ways to interact with an LLM.</p>
<h3>Using a Chat Application</h3>
<p>Applications like ChatGPT or Claude provide:</p>
<ul>
<li><p>Predefined system prompts</p>
</li>
<li><p>Safety checks</p>
</li>
<li><p>Built-in conversation history</p>
</li>
<li><p>Extra features like web search or memory</p>
</li>
</ul>
<p>Everything is managed for you.</p>
<h3>Using an API</h3>
<p>When using an API, developers control everything.</p>
<p>They can decide:</p>
<ul>
<li><p>The system prompt</p>
</li>
<li><p>Which model to use</p>
</li>
<li><p>Conversation history</p>
</li>
<li><p>Temperature</p>
</li>
<li><p>Tool access</p>
</li>
<li><p>Response format</p>
</li>
</ul>
<p>This flexibility is what makes APIs ideal for building AI applications, assistants, and coding agents.</p>
<h2>Streaming vs One-Shot Responses</h2>
<p>When you ask ChatGPT a question, have you noticed that the response appears word by word instead of waiting until the entire answer is ready?</p>
<p>That's called <strong>streaming</strong>.</p>
<p>Instead of generating the complete response and sending it all at once, the AI sends small chunks as they are generated.</p>
<h3>One-Shot Response</h3>
<p>In a one-shot response:</p>
<ol>
<li><p>You send a request.</p>
</li>
<li><p>The model generates the complete answer.</p>
</li>
<li><p>The server sends everything back at once.</p>
</li>
</ol>
<p>The user has to wait until the response is fully generated.</p>
<h3>Streaming Response</h3>
<p>With streaming:</p>
<ol>
<li><p>You send a request.</p>
</li>
<li><p>The model starts generating tokens.</p>
</li>
<li><p>Each token is immediately sent back.</p>
</li>
<li><p>The UI updates continuously.</p>
</li>
</ol>
<p>This makes the application feel much faster, even though the total generation time is almost the same.</p>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/51a1622f-8182-42e5-bea9-87e0325033d5.png" alt="" style="display:block;margin:0 auto" />

<h2>Why Streaming Improves User Experience</h2>
<p>Imagine asking an AI to generate a 500-word explanation.</p>
<p>With a one-shot response, you might wait 10 seconds before seeing anything.</p>
<p>With streaming, you start reading within a second while the remaining content is still being generated.</p>
<p>This creates a much smoother and more interactive experience.</p>
<p>That's why almost every modern AI application uses streaming.</p>
<h2>How Does Streaming Actually Work?</h2>
<p>The AI model generates one token at a time.</p>
<p>Instead of collecting every token before sending the response, the backend forwards each token to the frontend as soon as it's available.</p>
<p>The flow looks like this:</p>
<ol>
<li><p>User sends a request.</p>
</li>
<li><p>Backend forwards the request to the AI model.</p>
</li>
<li><p>The model generates tokens one by one.</p>
</li>
<li><p>The backend streams those tokens to the frontend.</p>
</li>
<li><p>The frontend displays them immediately.</p>
</li>
</ol>
<p>The AI itself isn't aware that the response is being streamed.</p>
<p>Streaming is handled by the backend application.</p>
<h2>Image</h2>
<p><strong>AI Image Prompt</strong></p>
<blockquote>
<p>Create a flow diagram showing User → Backend Server → LLM. The LLM generates multiple tokens, and each token is streamed back through the backend to the frontend in real time. Show small text bubbles appearing one after another to represent streaming. Minimal flat design with modern developer aesthetics.</p>
</blockquote>
<h2>How Does the Frontend Receive Streaming Data?</h2>
<p>Since responses are continuously arriving, a normal HTTP request-response cycle isn't enough.</p>
<p>Instead, most AI providers use <strong>Server-Sent Events (SSE)</strong>.</p>
<p>SSE allows the server to keep a connection open and continuously send updates until the response is complete.</p>
<p>This is why AI applications can display responses in real time.</p>
<h2>Server-Sent Events (SSE)</h2>
<p>Server-Sent Events are a communication protocol built on top of HTTP.</p>
<p>Instead of sending a single response, the server keeps sending multiple events over the same connection.</p>
<p>For AI applications, those events usually contain newly generated tokens.</p>
<h3>Simple Flow</h3>
<pre><code class="language-plaintext">User
   ↓
Frontend
   ↓
Backend
   ↓
LLM

LLM → Token 1
LLM → Token 2
LLM → Token 3
LLM → Token 4

Backend streams every token back to the UI.
</code></pre>
<h2>Why Not Use WebSockets?</h2>
<p>Many developers assume WebSockets are required for AI streaming.</p>
<p>However, that's usually not the case.</p>
<p>The instructor explains that Server-Sent Events are a better fit because communication only needs to happen in one direction—from the server to the client.</p>
<h3>SSE vs WebSockets</h3>
<table>
<thead>
<tr>
<th>Server-Sent Events</th>
<th>WebSockets</th>
</tr>
</thead>
<tbody><tr>
<td>One-way communication</td>
<td>Two-way communication</td>
</tr>
<tr>
<td>Built on HTTP</td>
<td>Separate protocol</td>
</tr>
<tr>
<td>Easier to scale</td>
<td>More complex</td>
</tr>
<tr>
<td>Perfect for AI responses</td>
<td>Better for chat apps, games, collaborative editing</td>
</tr>
</tbody></table>
<p>Since the user isn't constantly sending data while the AI is responding, SSE is usually the simpler and more efficient solution.</p>
<h2>What Happens Behind the Scenes?</h2>
<p>When you click <strong>Send</strong> in ChatGPT or Claude, several things happen before the AI even starts generating a response.</p>
<p>The backend typically:</p>
<ul>
<li><p>Authenticates the user.</p>
</li>
<li><p>Applies safety checks.</p>
</li>
<li><p>Adds the system prompt.</p>
</li>
<li><p>Sends the request to the LLM.</p>
</li>
<li><p>Streams the generated tokens back to the UI.</p>
</li>
</ul>
<p>This entire process happens within seconds.</p>
<h2>What is an AI Agent?</h2>
<p>Now that we understand how AI communicates, let's answer an important question.</p>
<p><strong>What exactly is an AI agent?</strong></p>
<p>An AI agent is more than just a chatbot.</p>
<p>It's a software system that receives a goal and uses available tools to complete that goal.</p>
<p>Unlike a traditional LLM that only generates text, an AI agent can interact with the outside world.</p>
<p>For example, it can:</p>
<ul>
<li><p>Read files</p>
</li>
<li><p>Search code</p>
</li>
<li><p>Execute terminal commands</p>
</li>
<li><p>Call APIs</p>
</li>
<li><p>Browse the web</p>
</li>
<li><p>Update databases</p>
</li>
<li><p>Write new files</p>
</li>
</ul>
<p>The AI doesn't just answer questions—it performs actions.</p>
<h2>Assistant vs AI Agent</h2>
<p>These two terms are often used interchangeably, but they're not exactly the same.</p>
<h3>AI Assistant</h3>
<p>An assistant primarily focuses on conversation.</p>
<p>Examples include:</p>
<ul>
<li><p>ChatGPT</p>
</li>
<li><p>Claude</p>
</li>
<li><p>Gemini</p>
</li>
</ul>
<p>Their main job is to answer questions and provide information.</p>
<h3>AI Agent</h3>
<p>An agent receives a goal and actively works toward completing it.</p>
<p>Instead of simply explaining how to fix a bug, it can:</p>
<ul>
<li><p>Locate the relevant file</p>
</li>
<li><p>Edit the code</p>
</li>
<li><p>Run tests</p>
</li>
<li><p>Verify the fix</p>
</li>
</ul>
<p>This ability to perform actions is what makes an agent different.</p>
<h2>Comparison</h2>
<table>
<thead>
<tr>
<th>AI Assistant</th>
<th>AI Agent</th>
</tr>
</thead>
<tbody><tr>
<td>Answers questions</td>
<td>Completes tasks</td>
</tr>
<tr>
<td>Mostly conversational</td>
<td>Goal-oriented</td>
</tr>
<tr>
<td>Limited interaction with external systems</td>
<td>Uses tools and external services</td>
</tr>
<tr>
<td>Generates text</td>
<td>Generates text and performs actions</td>
</tr>
</tbody></table>
<h2>Is ChatGPT an AI Agent?</h2>
<p>The answer depends on how it's being used.</p>
<p>If ChatGPT is simply answering your questions, it's acting like an assistant.</p>
<p>However, if it's connected to tools such as:</p>
<ul>
<li><p>Web Search</p>
</li>
<li><p>File System</p>
</li>
<li><p>Calendar</p>
</li>
<li><p>Email</p>
</li>
<li><p>Database</p>
</li>
<li><p>APIs</p>
</li>
</ul>
<p>then it starts behaving much more like an AI agent.</p>
<p>The distinction isn't always black and white.</p>
<p>It's more of a spectrum.</p>
<h2>Coding Agents</h2>
<p>Coding agents are a specialized type of AI agent.</p>
<p>Instead of helping with general tasks, they're designed specifically for software development.</p>
<p>They can:</p>
<ul>
<li><p>Read project files</p>
</li>
<li><p>Understand repository structure</p>
</li>
<li><p>Search code</p>
</li>
<li><p>Modify existing code</p>
</li>
<li><p>Create new files</p>
</li>
<li><p>Run terminal commands</p>
</li>
<li><p>Execute tests</p>
</li>
<li><p>Fix bugs</p>
</li>
</ul>
<p>This makes them significantly more capable than a standard chatbot.</p>
<h2>Why Are Terminal-Based Coding Agents Becoming Popular?</h2>
<p>The transcript highlights an interesting trend.</p>
<p>Many developers are moving away from traditional AI chat interfaces and using terminal-based coding agents instead.</p>
<p>The reason is simple.</p>
<p>Developers already spend most of their time inside the terminal.</p>
<p>Instead of copying code between a browser and an editor, they can interact with AI directly from their development environment.</p>
<p>This creates a much smoother workflow.</p>
<h2>Why Do Simple Agents Sometimes Perform Better?</h2>
<p>One surprising point discussed in the video is that <strong>more complexity doesn't always lead to better performance</strong>.</p>
<p>Some AI coding agents use multiple sub-agents, memory systems, and complex orchestration pipelines.</p>
<p>Others, like <strong>Pi</strong>, follow a much simpler approach.</p>
<p>Despite having a lightweight architecture, they can still perform extremely well because modern language models have become much better at reasoning and exploring codebases on their own.</p>
<p>This is an important lesson for developers.</p>
<p>Instead of immediately building a complex multi-agent system, start with a simple agent that uses a capable model effectively.</p>
<p>In the previous part, we learned the difference between an AI assistant and an AI agent. We also saw how AI applications stream responses and why modern coding agents are becoming increasingly popular.</p>
<p>However, one question still remains:</p>
<p><strong>How can an AI model perform actions instead of just generating text?</strong></p>
<p>For example:</p>
<ul>
<li><p>How does ChatGPT search the web?</p>
</li>
<li><p>How does Claude check the weather?</p>
</li>
<li><p>How does Claude Code edit files on your computer?</p>
</li>
<li><p>How can an AI execute terminal commands?</p>
</li>
</ul>
<p>The answer lies in <strong>Tools</strong>, also known as <strong>Function Calling</strong>.</p>
<p>This is one of the most important concepts you'll learn if you want to build AI agents.</p>
<h2>Why LLMs Alone Are Limited</h2>
<p>A Large Language Model only knows what it learned during training.</p>
<p>It cannot:</p>
<ul>
<li><p>Browse the internet</p>
</li>
<li><p>Read your local files</p>
</li>
<li><p>Execute shell commands</p>
</li>
<li><p>Access databases</p>
</li>
<li><p>Send emails</p>
</li>
<li><p>Call APIs</p>
</li>
<li><p>Know today's weather</p>
</li>
<li><p>Know the latest stock prices</p>
</li>
</ul>
<p>It simply predicts text based on its training data.</p>
<p>For example, if an LLM was trained six months ago, it doesn't know what happened yesterday unless someone provides that information.</p>
<h3>A Simple Example</h3>
<p>Imagine asking:</p>
<blockquote>
<p><strong>"What's the weather in Delhi right now?"</strong></p>
</blockquote>
<p>Without internet access, the model can only guess.</p>
<p>It might respond with something like:</p>
<blockquote>
<p>"Delhi is generally warm during this season."</p>
</blockquote>
<p>Notice something?</p>
<p>That's not the <strong>current</strong> weather.</p>
<p>It's simply making an educated prediction.</p>
<h2>Why Do AI Applications Give Better Answers?</h2>
<p>When you ask ChatGPT or Claude the same question, they often return the <strong>live weather</strong>.</p>
<p>How?</p>
<p>Not because the model suddenly learned today's weather.</p>
<p>Instead, the application gives the model access to a <strong>Weather Tool</strong>.</p>
<p>The model requests the latest weather data, receives it, and then uses that information to generate its response.</p>
<h2>What Are Tools?</h2>
<p>A <strong>Tool</strong> is simply a function that allows an AI model to interact with something outside its own knowledge.</p>
<p>Think of tools as bridges between the AI and the real world.</p>
<p>Examples include:</p>
<ul>
<li><p>Web Search</p>
</li>
<li><p>Weather API</p>
</li>
<li><p>Calculator</p>
</li>
<li><p>Database</p>
</li>
<li><p>Terminal</p>
</li>
<li><p>File System</p>
</li>
<li><p>GitHub</p>
</li>
<li><p>Gmail</p>
</li>
<li><p>Calendar</p>
</li>
</ul>
<p>Without tools, an LLM can only generate text.</p>
<p>With tools, it can perform real-world tasks.</p>
<h2>Image</h2>
<p><strong>AI Image Prompt</strong></p>
<blockquote>
<p>Create a modern educational illustration showing an LLM in the center connected to multiple tools. Around the LLM place icons for Web Search, Terminal, Database, Weather API, File System, Email, GitHub, and Calendar. Show arrows between the LLM and each tool. Use a flat vector style with blue and purple gradients, clean typography, white background, and a modern developer documentation aesthetic.</p>
</blockquote>
<h2>How Tools Change an AI Agent</h2>
<p>Without tools, an AI behaves like this:</p>
<pre><code class="language-text">User
   ↓
LLM
   ↓
Text Response
</code></pre>
<p>With tools, the flow becomes:</p>
<pre><code class="language-text">User
   ↓
LLM
   ↓
Tool Request
   ↓
External Service
   ↓
Result
   ↓
LLM
   ↓
Final Answer
</code></pre>
<p>This extra step is what transforms a chatbot into an intelligent assistant.</p>
<h2>Real-World Examples of Tools</h2>
<table>
<thead>
<tr>
<th>User Request</th>
<th>Tool Used</th>
</tr>
</thead>
<tbody><tr>
<td>What's the weather today?</td>
<td>Weather API</td>
</tr>
<tr>
<td>Search the latest AI news</td>
<td>Web Search</td>
</tr>
<tr>
<td>Read this project</td>
<td>File System</td>
</tr>
<tr>
<td>Fix this bug</td>
<td>Terminal + File System</td>
</tr>
<tr>
<td>Send an email</td>
<td>Gmail API</td>
</tr>
<tr>
<td>Check GitHub issue</td>
<td>GitHub API</td>
</tr>
</tbody></table>
<p>Every modern AI application relies on these kinds of tools.</p>
<h2>How Does an LLM Know It Should Use a Tool?</h2>
<p>This is where things get interesting.</p>
<p>An LLM cannot directly call an API.</p>
<p>It cannot execute JavaScript.</p>
<p>It cannot make an HTTP request.</p>
<p>It only generates text.</p>
<p>So how does it ask for a tool?</p>
<p>The answer is surprisingly simple.</p>
<p>The model has been trained to generate a <strong>special structured response</strong> whenever it decides a tool is needed.</p>
<p>Instead of answering the user directly, it first says something equivalent to:</p>
<blockquote>
<p>"Please execute this function."</p>
</blockquote>
<p>The application receives that request, runs the tool, and sends the result back to the model.</p>
<h2>Understanding the Tool Calling Process</h2>
<p>Imagine you ask:</p>
<blockquote>
<p><strong>"What's the weather in Delhi?"</strong></p>
</blockquote>
<p>Here's what happens behind the scenes.</p>
<h3>Step 1</h3>
<p>The user sends the question.</p>
<pre><code class="language-text">What's the weather in Delhi?
</code></pre>
<h3>Step 2</h3>
<p>The LLM realizes it doesn't know the current weather.</p>
<p>Instead of guessing, it asks for the Weather Tool.</p>
<p>Something similar to:</p>
<pre><code class="language-text">Call Weather Tool

City: Delhi
</code></pre>
<h3>Step 3</h3>
<p>Your backend executes the Weather API.</p>
<p>The API responds:</p>
<pre><code class="language-text">31°C

Sunny
</code></pre>
<h3>Step 4</h3>
<p>That result is added back into the conversation.</p>
<p>Now the model knows the answer.</p>
<h3>Step 5</h3>
<p>Finally, the model generates a natural response.</p>
<p>For example:</p>
<blockquote>
<p>"The current weather in Delhi is 31°C with sunny conditions."</p>
</blockquote>
<p>The user never sees the tool call.</p>
<p>They only see the final answer.</p>
<h2>Image</h2>
<p><strong>AI Image Prompt</strong></p>
<blockquote>
<p>Design a flowchart showing Tool Calling. Steps: User asks "What's the weather in Delhi?" → LLM requests Weather Tool → Backend calls Weather API → Weather API returns 31°C → LLM generates final answer. Use colorful arrows, modern flat vector style, white background, minimal developer documentation look.</p>
</blockquote>
<h2>Why Doesn't the LLM Call the API Directly?</h2>
<p>Because the model isn't an application.</p>
<p>It's simply a prediction engine.</p>
<p>It doesn't know:</p>
<ul>
<li><p>How to send HTTP requests</p>
</li>
<li><p>How to authenticate APIs</p>
</li>
<li><p>Where your Weather API lives</p>
</li>
<li><p>Which API key to use</p>
</li>
</ul>
<p>Those responsibilities belong to your backend.</p>
<p>The LLM simply decides <strong>what</strong> it needs.</p>
<p>Your application decides <strong>how</strong> to get it.</p>
<h2>The Backend Plays an Important Role</h2>
<p>Your backend acts like the coordinator.</p>
<p>Its responsibilities include:</p>
<ul>
<li><p>Sending prompts to the model</p>
</li>
<li><p>Executing requested tools</p>
</li>
<li><p>Managing API keys</p>
</li>
<li><p>Handling authentication</p>
</li>
<li><p>Validating inputs</p>
</li>
<li><p>Returning tool results</p>
</li>
</ul>
<p>Without the backend, the LLM cannot interact with external systems.</p>
<h2>How Does the LLM Know Which Tools Exist?</h2>
<p>Whenever your application sends a request to the model, it also includes information about the available tools.</p>
<p>For example:</p>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>Web Search</td>
<td>Search the internet</td>
</tr>
<tr>
<td>Weather</td>
<td>Get live weather information</td>
</tr>
<tr>
<td>Calculator</td>
<td>Perform calculations</td>
</tr>
<tr>
<td>Read File</td>
<td>Read project files</td>
</tr>
<tr>
<td>Run Command</td>
<td>Execute terminal commands</td>
</tr>
</tbody></table>
<p>The model reads these descriptions before answering.</p>
<p>If it believes one of them can help solve the user's request, it asks to use that tool.</p>
<h2>Can an LLM Use Multiple Tools?</h2>
<p>Yes.</p>
<p>Suppose a user asks:</p>
<blockquote>
<p><strong>"Find today's AI news and summarize it."</strong></p>
</blockquote>
<p>The agent may perform several steps:</p>
<ol>
<li><p>Use Web Search.</p>
</li>
<li><p>Collect relevant articles.</p>
</li>
<li><p>Read their content.</p>
</li>
<li><p>Summarize everything.</p>
</li>
</ol>
<p>The user sees only the final answer, but multiple tool calls happened in the background.</p>
<h2>Coding Agents Use Even More Tools</h2>
<p>A coding agent typically has access to tools like:</p>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>Read File</td>
<td>Understand code</td>
</tr>
<tr>
<td>Write File</td>
<td>Modify source code</td>
</tr>
<tr>
<td>Terminal</td>
<td>Execute commands</td>
</tr>
<tr>
<td>Search Files</td>
<td>Find relevant code</td>
</tr>
<tr>
<td>Git</td>
<td>Check repository status</td>
</tr>
<tr>
<td>Tests</td>
<td>Validate changes</td>
</tr>
</tbody></table>
<p>These tools allow the AI to work almost like a developer.</p>
<h2>Why Tool Calling Is So Important</h2>
<p>Without tool calling, an AI assistant can only explain how to solve a problem.</p>
<p>With tool calling, it can actually solve it.</p>
<p>For example:</p>
<p>Instead of saying:</p>
<blockquote>
<p>"Run <code>npm install</code>."</p>
</blockquote>
<p>The agent can actually execute:</p>
<pre><code class="language-bash">npm install
</code></pre>
<p>Instead of explaining how to fix a file, it can edit the file itself.</p>
<p>That's the biggest difference between a chatbot and a coding agent.</p>
<h2>What is an Agent Loop?</h2>
<p>An <strong>Agent Loop</strong> is a cycle where the AI repeatedly:</p>
<ol>
<li><p>Understands the current situation.</p>
</li>
<li><p>Decides what to do next.</p>
</li>
<li><p>Uses a tool.</p>
</li>
<li><p>Observes the result.</p>
</li>
<li><p>Decides the next action.</p>
</li>
<li><p>Repeats until the task is complete.</p>
</li>
</ol>
<p>Instead of producing an answer immediately, the AI keeps thinking and acting until it reaches its goal.</p>
<p>This is what makes an AI agent feel intelligent.</p>
<h2>Image</h2>
<p><strong>AI Image Prompt</strong></p>
<blockquote>
<p>Create a modern infographic illustrating the AI Agent Loop. Show a circular flow with six steps: Goal → Think → Select Tool → Execute Tool → Observe Result → Repeat Until Complete. Use blue and purple gradients, clean vector icons, white background, minimal documentation style, arrows connecting each step, 16:9.</p>
</blockquote>
<h2>Understanding the Agent Loop with an Example</h2>
<p>Suppose you ask:</p>
<blockquote>
<p><strong>"Fix the login bug in my project."</strong></p>
</blockquote>
<p>A coding agent might internally perform these steps.</p>
<h3>Step 1: Understand the Task</h3>
<p>The agent first reads your request.</p>
<p>It understands that the goal is to fix a login issue.</p>
<p>No code has been modified yet.</p>
<h3>Step 2: Explore the Project</h3>
<p>Next, it tries to understand the project.</p>
<p>It may:</p>
<ul>
<li><p>Read the README file.</p>
</li>
<li><p>Check the project structure.</p>
</li>
<li><p>Identify authentication-related files.</p>
</li>
</ul>
<p>At this stage, the agent is gathering context.</p>
<h3>Step 3: Read Relevant Files</h3>
<p>After finding possible files, it starts reading them.</p>
<p>For example:</p>
<ul>
<li><p><code>auth.ts</code></p>
</li>
<li><p><code>login.ts</code></p>
</li>
<li><p><code>middleware.ts</code></p>
</li>
</ul>
<p>The agent doesn't randomly read every file.</p>
<p>Instead, it explores the project just like a developer would.</p>
<h3>Step 4: Decide the Fix</h3>
<p>Once it has enough information, the LLM reasons about the problem.</p>
<p>It identifies:</p>
<ul>
<li><p>The likely cause.</p>
</li>
<li><p>The required changes.</p>
</li>
<li><p>The files that need modification.</p>
</li>
</ul>
<h3>Step 5: Edit the Code</h3>
<p>Now the Write File tool is used.</p>
<p>The agent updates the necessary files.</p>
<h3>Step 6: Verify the Fix</h3>
<p>A good coding agent doesn't stop after editing code.</p>
<p>It often runs:</p>
<ul>
<li><p>Tests</p>
</li>
<li><p>Build commands</p>
</li>
<li><p>Linters</p>
</li>
</ul>
<p>If something fails, it continues the loop.</p>
<p>If everything succeeds, the task is complete.</p>
<h2>The Entire Flow</h2>
<pre><code class="language-text">User Goal
      ↓
Understand Request
      ↓
Explore Project
      ↓
Read Files
      ↓
Reason About Solution
      ↓
Edit Code
      ↓
Run Tests
      ↓
Task Complete
</code></pre>
<p>Notice that several tool calls happened before the final response.</p>
<p>This entire workflow is the Agent Loop.</p>
<h2>Why Doesn't the AI Solve Everything in One Step?</h2>
<p>Because real-world software development is iterative.</p>
<p>When developers fix a bug, they rarely know the solution immediately.</p>
<p>Instead, they:</p>
<ul>
<li><p>Read documentation.</p>
</li>
<li><p>Search files.</p>
</li>
<li><p>Understand existing code.</p>
</li>
<li><p>Make changes.</p>
</li>
<li><p>Test those changes.</p>
</li>
</ul>
<p>AI coding agents follow a very similar process.</p>
<h2>Thinking Like a Developer</h2>
<p>One interesting point from the transcript is that modern language models have become very good at exploring codebases independently.</p>
<p>Instead of requiring complicated workflows, they often perform surprisingly well by simply repeating this process:</p>
<ol>
<li><p>Read a file.</p>
</li>
<li><p>Learn something.</p>
</li>
<li><p>Decide what to read next.</p>
</li>
<li><p>Repeat.</p>
</li>
</ol>
<p>This is similar to how an experienced developer approaches an unfamiliar project.</p>
<h2>Why Pi Performs Surprisingly Well</h2>
<p>One of the main discussions in the video is about <strong>Pi</strong>, an open-source terminal coding agent.</p>
<p>At first glance, Pi looks extremely simple.</p>
<p>It has:</p>
<ul>
<li><p>A small codebase.</p>
</li>
<li><p>Minimal architecture.</p>
</li>
<li><p>Very little abstraction.</p>
</li>
</ul>
<p>Yet it performs remarkably well.</p>
<p>Why?</p>
<p>Because today's LLMs are already excellent at exploring codebases and reasoning about code.</p>
<p>The orchestration layer has become less important than it used to be.</p>
<h2>Complex Agents vs Simple Agents</h2>
<p>The instructor compares two approaches.</p>
<h3>Complex Agent</h3>
<p>A complex coding agent might:</p>
<ul>
<li><p>Spawn multiple sub-agents.</p>
</li>
<li><p>Maintain long-term memory.</p>
</li>
<li><p>Create task planners.</p>
</li>
<li><p>Generate summaries.</p>
</li>
<li><p>Coordinate several workflows simultaneously.</p>
</li>
</ul>
<p>This architecture is powerful but also much more complicated.</p>
<h3>Simple Agent</h3>
<p>A simple agent usually follows one loop:</p>
<ol>
<li><p>Think.</p>
</li>
<li><p>Use a tool.</p>
</li>
<li><p>Observe.</p>
</li>
<li><p>Repeat.</p>
</li>
</ol>
<p>Despite its simplicity, it often performs just as well because modern LLMs are capable of handling much of the reasoning themselves.</p>
<h2>Comparison</h2>
<table>
<thead>
<tr>
<th>Simple Agent</th>
<th>Complex Agent</th>
</tr>
</thead>
<tbody><tr>
<td>Easier to build</td>
<td>Difficult architecture</td>
</tr>
<tr>
<td>Easy to debug</td>
<td>More moving parts</td>
</tr>
<tr>
<td>Lower maintenance</td>
<td>Higher maintenance</td>
</tr>
<tr>
<td>Works well with strong LLMs</td>
<td>Useful for advanced workflows</td>
</tr>
</tbody></table>
<p>The key takeaway is that <strong>simplicity often wins</strong>.</p>
<h2>Multi-Agent Systems</h2>
<p>Some coding agents divide work among multiple specialized agents.</p>
<p>For example:</p>
<table>
<thead>
<tr>
<th>Agent</th>
<th>Responsibility</th>
</tr>
</thead>
<tbody><tr>
<td>Planner</td>
<td>Understand the task</td>
</tr>
<tr>
<td>Explorer</td>
<td>Search the codebase</td>
</tr>
<tr>
<td>Coder</td>
<td>Modify files</td>
</tr>
<tr>
<td>Reviewer</td>
<td>Verify changes</td>
</tr>
<tr>
<td>Tester</td>
<td>Run tests</td>
</tr>
</tbody></table>
<p>Each agent has its own responsibility.</p>
<p>They collaborate to solve a larger problem.</p>
<p>This approach can improve performance for very large or complex tasks, but it also increases implementation complexity.</p>
<h2>Do You Always Need Multiple Agents?</h2>
<p>Not necessarily.</p>
<p>The transcript emphasizes that many modern coding agents perform extremely well without complicated multi-agent orchestration.</p>
<p>Today's models are strong enough to handle many tasks using a single reasoning loop.</p>
<p>If you're building your first AI agent, start with one agent before introducing multiple specialized agents.</p>
<h2>How Coding Agents Explore a Codebase</h2>
<p>When you ask a coding agent to fix a bug, it doesn't magically know where the problem is.</p>
<p>Instead, it explores the project step by step.</p>
<p>For example:</p>
<pre><code class="language-text">Read README
      ↓
Understand Project
      ↓
Search Authentication Files
      ↓
Read auth.ts
      ↓
Read middleware.ts
      ↓
Identify Bug
      ↓
Fix Code
</code></pre>
<p>This process closely resembles how human developers work.</p>
<h2>Image</h2>
<p><strong>AI Image Prompt</strong></p>
<blockquote>
<p>Create a software architecture diagram showing how an AI coding agent explores a project. The flow should be: User Task → Read README → Search Files → Read Relevant Files → Understand Context → Modify Code → Run Tests → Success. Use folder icons, file icons, terminal icons, clean arrows, flat vector illustration, white background, developer documentation style.</p>
</blockquote>
<h2>Why Understanding the Agent Loop Matters</h2>
<p>If you're building an AI-powered application, the Agent Loop is one of the first architectural decisions you'll make.</p>
<p>Questions you'll need to answer include:</p>
<ul>
<li><p>When should the loop stop?</p>
</li>
<li><p>Which tools should the AI have access to?</p>
</li>
<li><p>How many iterations are allowed?</p>
</li>
<li><p>Should the AI verify its own work?</p>
</li>
<li><p>Should it ask for user confirmation before making changes?</p>
</li>
</ul>
<p>These decisions define how reliable and useful your agent will be.</p>
<h2>Applying This in Your Own Projects</h2>
<p>Suppose you're building an AI code review tool.</p>
<p>Your agent loop might look like this:</p>
<table>
<thead>
<tr>
<th>Step</th>
<th>Action</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Read Pull Request</td>
</tr>
<tr>
<td>2</td>
<td>Read Modified Files</td>
</tr>
<tr>
<td>3</td>
<td>Analyze Changes</td>
</tr>
<tr>
<td>4</td>
<td>Generate Suggestions</td>
</tr>
<tr>
<td>5</td>
<td>Return Feedback</td>
</tr>
</tbody></table>
<p>Or imagine building a documentation assistant.</p>
<p>The loop could be:</p>
<table>
<thead>
<tr>
<th>Step</th>
<th>Action</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Read Documentation</td>
</tr>
<tr>
<td>2</td>
<td>Search Related Files</td>
</tr>
<tr>
<td>3</td>
<td>Collect Context</td>
</tr>
<tr>
<td>4</td>
<td>Generate Documentation</td>
</tr>
<tr>
<td>5</td>
<td>Save Markdown File</td>
</tr>
</tbody></table>
<p>The Agent Loop stays the same.</p>
<p>Only the tools and objectives change.</p>
<h2>Why Supporting Multiple AI Providers Is Difficult</h2>
<p>At first glance, switching between AI providers seems simple.</p>
<p>You might think changing the API URL is enough.</p>
<p>In reality, every provider has its own way of handling:</p>
<ul>
<li><p>Requests</p>
</li>
<li><p>Responses</p>
</li>
<li><p>Streaming</p>
</li>
<li><p>Tool calls</p>
</li>
<li><p>Authentication</p>
</li>
<li><p>Error handling</p>
</li>
</ul>
<p>This means every integration requires additional work.</p>
<h2>Different Providers, Different APIs</h2>
<p>Some popular AI providers include:</p>
<ul>
<li><p>OpenAI</p>
</li>
<li><p>Anthropic</p>
</li>
<li><p>Google Gemini</p>
</li>
<li><p>DeepSeek</p>
</li>
<li><p>Grok</p>
</li>
<li><p>OpenRouter</p>
</li>
</ul>
<p>Even though they all expose language models, their APIs are structured differently.</p>
<p>For example:</p>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Can Differ Between Providers</th>
</tr>
</thead>
<tbody><tr>
<td>Request Body</td>
<td>Yes</td>
</tr>
<tr>
<td>Streaming Format</td>
<td>Yes</td>
</tr>
<tr>
<td>Tool Calling Format</td>
<td>Yes</td>
</tr>
<tr>
<td>Authentication</td>
<td>Yes</td>
</tr>
<tr>
<td>Response Structure</td>
<td>Yes</td>
</tr>
</tbody></table>
<p>Because of these differences, developers can't simply replace one provider with another without modifying their code.</p>
<h2>Why This Becomes a Problem</h2>
<p>Imagine you're building an AI coding assistant.</p>
<p>Today, you're using OpenAI.</p>
<p>Tomorrow, you decide to switch to Anthropic.</p>
<p>If your application directly depends on OpenAI's response format, you'll need to rewrite large parts of your code.</p>
<p>Now imagine supporting five different providers at the same time.</p>
<p>The complexity grows quickly.</p>
<h2>The Solution: Provider Abstraction</h2>
<p>Instead of writing provider-specific logic throughout the application, coding agents introduce a <strong>provider abstraction layer</strong>.</p>
<p>This layer acts as a translator.</p>
<p>It converts different provider APIs into one common interface.</p>
<p>Your application only communicates with that interface.</p>
<p>The abstraction layer handles everything else.</p>
<h2>Image</h2>
<p><strong>AI Image Prompt</strong></p>
<blockquote>
<p>Create a software architecture diagram. Show multiple AI providers (OpenAI, Anthropic, Gemini, DeepSeek) connected to a central "Provider Abstraction Layer". From there, connect to an AI Coding Agent. Use modern flat vector design, white background, clean arrows, blue and purple developer theme, 16:9 aspect ratio.</p>
</blockquote>
<h2>Benefits of a Provider Abstraction Layer</h2>
<p>Using an abstraction layer offers several advantages.</p>
<ul>
<li><p>Switching providers becomes easier.</p>
</li>
<li><p>The rest of the application remains unchanged.</p>
</li>
<li><p>Adding new providers requires less effort.</p>
</li>
<li><p>Maintenance becomes simpler.</p>
</li>
</ul>
<p>Instead of writing custom logic for every provider, developers only need to update the abstraction layer.</p>
<h2>Why Pi Uses This Approach</h2>
<p>The instructor explains that <strong>Pi</strong> supports multiple AI providers.</p>
<p>Each provider behaves differently.</p>
<p>Instead of exposing those differences throughout the codebase, Pi converts every provider into a common format.</p>
<p>This allows the rest of the application to remain provider-independent.</p>
<p>As a result, developers can switch models without redesigning the entire agent.</p>
<h2>Tool Calling Isn't Standardized</h2>
<p>Earlier, we learned how tool calling works.</p>
<p>Unfortunately, there isn't a universal standard for how providers implement it.</p>
<p>For example:</p>
<ul>
<li><p>One provider may return tool calls in one JSON format.</p>
</li>
<li><p>Another provider may use a completely different structure.</p>
</li>
<li><p>Some providers even use different streaming formats.</p>
</li>
</ul>
<p>This means the abstraction layer has to normalize all these differences before the agent can use them consistently.</p>
<h2>Why This Matters</h2>
<p>Imagine your coding agent expects tool calls like this:</p>
<pre><code class="language-json">{
  "tool": "read_file",
  "arguments": {
    "path": "auth.ts"
  }
}
</code></pre>
<p>Now imagine another provider returns:</p>
<pre><code class="language-json">{
  "function": "read_file",
  "params": {
    "file": "auth.ts"
  }
}
</code></pre>
<p>Both represent the same action.</p>
<p>However, your application must understand both formats.</p>
<p>That's exactly what the provider abstraction layer handles.</p>
<h2>Streaming Responses Also Differ</h2>
<p>Streaming isn't implemented identically by every provider.</p>
<p>Some stream plain text.</p>
<p>Others stream structured JSON events.</p>
<p>Some include additional metadata alongside generated tokens.</p>
<p>Without a common abstraction, your frontend would need custom handling for every provider.</p>
<p>A well-designed provider layer converts all of them into one consistent stream.</p>
<h2>Supporting New Models</h2>
<p>Suppose tomorrow a brand-new AI company releases an impressive language model.</p>
<p>If your application already has a provider abstraction layer, adding support usually involves:</p>
<ol>
<li><p>Creating a new provider implementation.</p>
</li>
<li><p>Mapping requests.</p>
</li>
<li><p>Mapping responses.</p>
</li>
<li><p>Registering the provider.</p>
</li>
</ol>
<p>The rest of the application remains unchanged.</p>
<p>That's one of the biggest advantages of good software architecture.</p>
<h2>Skills vs Tools</h2>
<p>Another concept discussed in the video is <strong>Skills</strong>.</p>
<p>Although they sound similar, Skills and Tools solve different problems.</p>
<h3>Tools</h3>
<p>Tools perform actions.</p>
<p>Examples include:</p>
<ul>
<li><p>Reading files</p>
</li>
<li><p>Executing terminal commands</p>
</li>
<li><p>Searching the web</p>
</li>
<li><p>Calling APIs</p>
</li>
</ul>
<p>They interact with external systems.</p>
<h3>Skills</h3>
<p>Skills don't perform actions.</p>
<p>Instead, they provide <strong>additional knowledge or instructions</strong> to the AI.</p>
<p>Think of them as reusable documentation.</p>
<p>For example, a company might create a deployment skill explaining:</p>
<ul>
<li><p>How deployments work</p>
</li>
<li><p>Infrastructure requirements</p>
</li>
<li><p>Naming conventions</p>
</li>
<li><p>Internal workflows</p>
</li>
</ul>
<p>Instead of repeating those instructions in every prompt, the agent loads the relevant Skill whenever it's needed.</p>
<h2>Tools vs Skills</h2>
<table>
<thead>
<tr>
<th>Tools</th>
<th>Skills</th>
</tr>
</thead>
<tbody><tr>
<td>Perform actions</td>
<td>Provide knowledge</td>
</tr>
<tr>
<td>Execute APIs</td>
<td>Provide context</td>
</tr>
<tr>
<td>Interact with systems</td>
<td>Guide the model</td>
</tr>
<tr>
<td>Dynamic execution</td>
<td>Static documentation</td>
</tr>
</tbody></table>
<p>Both improve an AI agent, but they serve different purposes.</p>
<h2>Real Example</h2>
<p>Suppose your company has a custom deployment process.</p>
<p>Instead of writing a huge prompt every time, you create a Skill describing:</p>
<ul>
<li><p>Deployment steps</p>
</li>
<li><p>Kubernetes configuration</p>
</li>
<li><p>Environment variables</p>
</li>
<li><p>Domain setup</p>
</li>
<li><p>Load balancer configuration</p>
</li>
</ul>
<p>Whenever the AI needs to deploy an application, it loads this Skill before starting.</p>
<p>This gives the model project-specific knowledge without changing the underlying LLM.</p>
<h2>Why Skills Are Useful</h2>
<p>Skills help reduce prompt size while improving consistency.</p>
<p>Instead of embedding hundreds of lines into every request, the agent loads only the information relevant to the current task.</p>
<p>This approach keeps prompts smaller and makes responses more reliable.</p>
<h1>Understanding AI Coding Agents from Scratch (Part 6)</h1>
<h2>Introduction</h2>
<p>Throughout this guide, we've learned how AI coding agents understand tasks, use tools, interact with files, and continuously improve their responses using the Agent Loop.</p>
<p>Now let's look at two final topics discussed in the video:</p>
<ul>
<li><p>How AI coding agents are evaluated.</p>
</li>
<li><p>Why simple agent architectures often outperform complex multi-agent systems.</p>
</li>
</ul>
<p>We'll also wrap everything together by understanding how you can apply these concepts when building your own AI-powered applications.</p>
<h2>How Do We Know if an AI Coding Agent is Good?</h2>
<p>When a new language model or coding agent is released, one obvious question arises:</p>
<blockquote>
<p><strong>How do we measure its performance?</strong></p>
</blockquote>
<p>The answer is through <strong>benchmarks</strong>.</p>
<p>A benchmark is a collection of standardized tasks used to compare different AI models and coding agents under the same conditions.</p>
<p>Instead of relying on opinions, benchmarks provide measurable results.</p>
<h2>Why Benchmarks Matter</h2>
<p>Imagine comparing two developers.</p>
<p>Instead of asking who is better, you give both developers the same set of programming tasks.</p>
<p>The one who solves more problems correctly performs better.</p>
<p>Benchmarks work in exactly the same way.</p>
<p>They provide:</p>
<ul>
<li><p>Fixed tasks</p>
</li>
<li><p>Common evaluation criteria</p>
</li>
<li><p>Comparable scores</p>
</li>
</ul>
<p>This allows researchers and developers to compare different AI systems fairly.</p>
<h2>Common AI Benchmarks</h2>
<p>The video mentions several well-known benchmarks.</p>
<table>
<thead>
<tr>
<th>Benchmark</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>SWE Bench</td>
<td>Evaluates software engineering tasks</td>
</tr>
<tr>
<td>Terminal Bench</td>
<td>Evaluates terminal-based coding agents</td>
</tr>
</tbody></table>
<p>Each benchmark focuses on different abilities.</p>
<p>For coding agents, Terminal Bench has become particularly important because it measures how well an agent can solve real software development problems.</p>
<h2>What is Terminal Bench?</h2>
<p>Terminal Bench evaluates coding agents that operate inside a terminal.</p>
<p>Instead of asking simple programming questions, it measures whether an AI can complete realistic development tasks.</p>
<p>These tasks may include:</p>
<ul>
<li><p>Exploring a project</p>
</li>
<li><p>Reading source code</p>
</li>
<li><p>Editing files</p>
</li>
<li><p>Running commands</p>
</li>
<li><p>Fixing bugs</p>
</li>
<li><p>Completing coding workflows</p>
</li>
</ul>
<p>This makes it much closer to real-world software development.</p>
<h2>Why Pi Performs Surprisingly Well</h2>
<p>One interesting observation from the video is that <strong>Pi</strong>, despite being a relatively simple coding agent, performs exceptionally well on Terminal Bench.</p>
<p>This surprises many developers because they expect more complex systems to perform better.</p>
<p>However, that's not always true.</p>
<h2>Why Simplicity Often Wins</h2>
<p>Earlier generations of AI models required complex orchestration.</p>
<p>Developers built systems with:</p>
<ul>
<li><p>Memory modules</p>
</li>
<li><p>Multiple planners</p>
</li>
<li><p>Sub-agents</p>
</li>
<li><p>Reflection loops</p>
</li>
<li><p>Long reasoning pipelines</p>
</li>
</ul>
<p>These additions compensated for weaker language models.</p>
<p>Modern LLMs are much stronger.</p>
<p>They can often reason through complex tasks without requiring heavy orchestration.</p>
<p>As a result, a lightweight architecture paired with a capable model can perform remarkably well.</p>
<h2>Complex Doesn't Always Mean Better</h2>
<p>It's tempting to believe that adding more components automatically improves an AI system.</p>
<p>In practice, every additional component introduces:</p>
<ul>
<li><p>More complexity</p>
</li>
<li><p>More maintenance</p>
</li>
<li><p>More debugging</p>
</li>
<li><p>More failure points</p>
</li>
</ul>
<p>A simpler system is often:</p>
<ul>
<li><p>Easier to understand</p>
</li>
<li><p>Easier to extend</p>
</li>
<li><p>Easier to maintain</p>
</li>
<li><p>More reliable</p>
</li>
</ul>
<p>This is one of the biggest lessons from the transcript.</p>
<h2>Image</h2>
<p><strong>AI Image Prompt</strong></p>
<blockquote>
<p>Create an infographic comparing two AI coding agent architectures. On the left, show a complex architecture with Planner, Memory, Multiple Agents, Reflection, and Orchestrator connected together. On the right, show a simple architecture with User → LLM → Tools → Agent Loop. Highlight that the simpler architecture performs efficiently with modern LLMs. Use a clean developer documentation style with blue and purple accents.</p>
</blockquote>
<h2>Where Do Frameworks Like LangChain Fit In?</h2>
<p>The instructor also shares an important industry perspective.</p>
<p>Frameworks such as LangChain and LangGraph are useful because they simplify development.</p>
<p>However, many companies build their own orchestration layers instead of depending entirely on these frameworks.</p>
<p>Why?</p>
<p>Because every product has unique requirements.</p>
<p>Custom implementations provide:</p>
<ul>
<li><p>Better control</p>
</li>
<li><p>Higher flexibility</p>
</li>
<li><p>Easier optimization</p>
</li>
<li><p>Lower dependency on external libraries</p>
</li>
</ul>
<p>This doesn't mean frameworks are bad.</p>
<p>They're excellent for learning and rapid development.</p>
<p>But understanding the underlying concepts is much more valuable than memorizing framework APIs.</p>
<h2>Focus on Fundamentals</h2>
<p>One of the strongest messages throughout the video is this:</p>
<blockquote>
<p>Learn <strong>how agents work</strong>, not just how to use an agent framework.</p>
</blockquote>
<p>If you understand:</p>
<ul>
<li><p>LLMs</p>
</li>
<li><p>Tokens</p>
</li>
<li><p>Prompts</p>
</li>
<li><p>Streaming</p>
</li>
<li><p>Tool Calling</p>
</li>
<li><p>Agent Loops</p>
</li>
</ul>
<p>then learning any framework becomes much easier.</p>
<p>The reverse is not always true.</p>
<p>Someone who only knows a framework may struggle when debugging or designing custom AI systems.</p>
<h2>Building Your Own AI Coding Agent</h2>
<p>By now, you have enough conceptual knowledge to build a basic coding agent.</p>
<p>A simplified architecture might look like this:</p>
<pre><code class="language-text">User
   ↓
Frontend
   ↓
Backend
   ↓
System Prompt
   ↓
LLM
   ↓
Agent Loop
   ↓
Tools
   ↓
File System / Terminal / APIs
   ↓
LLM
   ↓
Streaming Response
</code></pre>
<p>Every concept we've covered fits somewhere in this workflow.</p>
<h2>Image</h2>
<p><strong>AI Image Prompt</strong></p>
<blockquote>
<p>Create a complete architecture diagram for an AI coding agent. Show the flow: User → Frontend → Backend → System Prompt → LLM → Agent Loop → Tools (File System, Terminal, Web Search, APIs) → Tool Results → LLM → Streaming Response → User. Use a modern software architecture style, clean arrows, white background, flat vector illustrations, and blue-purple gradients.</p>
</blockquote>
<h2>How Can You Apply These Concepts?</h2>
<p>These ideas aren't limited to coding assistants.</p>
<p>The same architecture can power many AI applications.</p>
<table>
<thead>
<tr>
<th>Project</th>
<th>Tools You Might Use</th>
</tr>
</thead>
<tbody><tr>
<td>Customer Support Bot</td>
<td>CRM, Email, Knowledge Base</td>
</tr>
<tr>
<td>AI Research Assistant</td>
<td>Web Search, PDFs, Databases</td>
</tr>
<tr>
<td>AI Code Reviewer</td>
<td>GitHub, File System, Terminal</td>
</tr>
<tr>
<td>Documentation Generator</td>
<td>Source Code, Markdown Files</td>
</tr>
<tr>
<td>DevOps Assistant</td>
<td>Kubernetes, Docker, Shell Commands</td>
</tr>
<tr>
<td>Personal Productivity Agent</td>
<td>Calendar, Email, Notes</td>
</tr>
</tbody></table>
<p>The only thing that changes is the set of tools available to the agent.</p>
<p>The overall architecture remains largely the same.</p>
<h2>Complete Learning Journey</h2>
<p>Let's quickly recap everything we've covered throughout this guide.</p>
<table>
<thead>
<tr>
<th>Topic</th>
<th>What You Learned</th>
</tr>
</thead>
<tbody><tr>
<td>Large Language Models</td>
<td>How AI predicts text</td>
</tr>
<tr>
<td>Tokens</td>
<td>How models process language</td>
</tr>
<tr>
<td>System Prompts</td>
<td>How AI behavior is controlled</td>
</tr>
<tr>
<td>APIs</td>
<td>How applications communicate with models</td>
</tr>
<tr>
<td>Streaming</td>
<td>Why responses appear gradually</td>
</tr>
<tr>
<td>Server-Sent Events</td>
<td>How streaming is implemented</td>
</tr>
<tr>
<td>AI Agents</td>
<td>Goal-oriented AI systems</td>
</tr>
<tr>
<td>Tools</td>
<td>How AI interacts with external systems</td>
</tr>
<tr>
<td>Tool Calling</td>
<td>How LLMs request actions</td>
</tr>
<tr>
<td>Agent Loop</td>
<td>Continuous reasoning and execution</td>
</tr>
<tr>
<td>Coding Agents</td>
<td>AI systems designed for software development</td>
</tr>
<tr>
<td>Provider Abstraction</td>
<td>Supporting multiple AI providers</td>
</tr>
<tr>
<td>Skills</td>
<td>Injecting project-specific knowledge</td>
</tr>
<tr>
<td>Benchmarks</td>
<td>Measuring coding agent performance</td>
</tr>
</tbody></table>
<p>These concepts form the foundation of nearly every modern AI agent.</p>
]]></content:encoded></item><item><title><![CDATA[System Role vs Temperature in LLMs Complete Guide : Part 3 ]]></title><description><![CDATA[AI Engineering Series – Part 3

If you've started building AI applications, you've probably seen terms like System Role and Temperature.
At first, they look like two simple API parameters. But in real]]></description><link>https://blog.adityaguptareal.com/system-role-vs-temperature-in-llms-complete-guide-part-3</link><guid isPermaLink="true">https://blog.adityaguptareal.com/system-role-vs-temperature-in-llms-complete-guide-part-3</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Wed, 08 Jul 2026 06:16:49 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><strong>AI Engineering Series – Part 3</strong></p>
</blockquote>
<p>If you've started building AI applications, you've probably seen terms like <strong>System Role</strong> and <strong>Temperature</strong>.</p>
<p>At first, they look like two simple API parameters. But in reality, these two settings control <strong>how an AI behaves</strong> and <strong>how it generates responses</strong>.</p>
<p>Many beginners confuse them because both affect the final output.</p>
<p>The difference is actually very simple.</p>
<ul>
<li><p><strong>System Role</strong> decides <strong>who the AI should behave as.</strong></p>
</li>
<li><p><strong>Temperature</strong> decides <strong>how creative or predictable the AI should be.</strong></p>
</li>
</ul>
<p>By the end of this article, you'll understand both concepts with simple examples, Python code, and interview questions.</p>
<h2>What is a System Role?</h2>
<p>Think about joining a new company.</p>
<p>Before your manager assigns work, they first assign your <strong>role</strong>.</p>
<p>You could be:</p>
<ul>
<li><p>A Software Engineer</p>
</li>
<li><p>A Product Manager</p>
</li>
<li><p>A QA Engineer</p>
</li>
<li><p>A Technical Writer</p>
</li>
</ul>
<p>Even if everyone gets the same task, each person approaches it differently because their responsibilities are different.</p>
<p>LLMs work in exactly the same way.</p>
<p>A <strong>System Role</strong> tells the AI what role it should play before it starts answering your questions.</p>
<blockquote>
<p><strong>Simple Definition</strong></p>
<p>A System Role is an instruction that tells an LLM how it should behave throughout the conversation.</p>
</blockquote>
<h2>How System Role Works</h2>
<pre><code class="language-mermaid">flowchart LR

A[System Role] --&gt; B[LLM]
C[User Prompt] --&gt; B
B --&gt; D[Response Based on Assigned Role]
</code></pre>
<p>The model first reads the <strong>System Role</strong>, then the <strong>User Prompt</strong>, and finally generates a response based on the assigned role.</p>
<h2>Let's Understand with an Example</h2>
<p>Suppose the user sends this message.</p>
<pre><code class="language-text">I love you.
</code></pre>
<p>The prompt is always the same.</p>
<p>Only the System Role changes.</p>
<table>
<thead>
<tr>
<th>System Role</th>
<th>AI Response</th>
</tr>
</thead>
<tbody><tr>
<td>Romantic Partner</td>
<td>I love you too.</td>
</tr>
<tr>
<td>Office Manager</td>
<td>That's not appropriate in a professional workplace.</td>
</tr>
<tr>
<td>Therapist</td>
<td>Why do you feel this way?</td>
</tr>
<tr>
<td>Customer Support</td>
<td>How can I help you today?</td>
</tr>
</tbody></table>
<p>This is why the same prompt can produce completely different responses.</p>
<h2>The Three Roles in Chat APIs</h2>
<p>Every chat-based LLM API uses three message roles.</p>
<table>
<thead>
<tr>
<th>Role</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><strong>System</strong></td>
<td>Defines the AI's behavior.</td>
</tr>
<tr>
<td><strong>User</strong></td>
<td>Sends the question.</td>
</tr>
<tr>
<td><strong>Assistant</strong></td>
<td>Stores previous AI responses.</td>
</tr>
</tbody></table>
<p>You can remember them like this:</p>
<table>
<thead>
<tr>
<th>Think of it as...</th>
<th>Role</th>
</tr>
</thead>
<tbody><tr>
<td>Rules</td>
<td>System</td>
</tr>
<tr>
<td>Question</td>
<td>User</td>
</tr>
<tr>
<td>Reply</td>
<td>Assistant</td>
</tr>
</tbody></table>
<h2>Why Do We Need a System Role?</h2>
<p>Imagine you're building an AI application for a software company.</p>
<p>Instead of creating one AI for everything, you create multiple AI agents.</p>
<table>
<thead>
<tr>
<th>AI Agent</th>
<th>Responsibility</th>
</tr>
</thead>
<tbody><tr>
<td>Developer</td>
<td>Writes code</td>
</tr>
<tr>
<td>Architect</td>
<td>Reviews system design</td>
</tr>
<tr>
<td>QA Tester</td>
<td>Finds bugs</td>
</tr>
<tr>
<td>Technical Writer</td>
<td>Writes documentation</td>
</tr>
</tbody></table>
<p>Even though all agents use the same LLM, each receives a different <strong>System Role</strong>.</p>
<p>That allows the same model to behave like different professionals.</p>
<h2>Using System Role in Practice</h2>
<p>Now that you understand what a System Role is, let's see how it works in a real application.</p>
<p>We'll use the <strong>same user prompt</strong> in both examples.</p>
<p>The only thing we'll change is the <strong>System Role</strong>.</p>
<p>This will help you understand why System Roles are so powerful.</p>
<h2>Example 1: AI Behaves Like a Loving Partner</h2>
<pre><code class="language-python">from groq import Groq

client = Groq()

messages = [
    {
        "role": "system",
        "content": "You are my loving girlfriend."
    },
    {
        "role": "user",
        "content": "I love you."
    }
]

response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=messages
)

print(response.choices[0].message.content)
</code></pre>
<h3>Possible Output</h3>
<pre><code class="language-text">I love you too! That means a lot to me.
</code></pre>
<p>The response sounds natural because the model was instructed to behave like a loving partner before processing the user's message.</p>
<h2>Example 2: AI Behaves Like an Office Manager</h2>
<p>Now let's change only the System Role.</p>
<pre><code class="language-python">from groq import Groq

client = Groq()

messages = [
    {
        "role": "system",
        "content": "You are my strict office manager."
    },
    {
        "role": "user",
        "content": "I love you."
    }
]

response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=messages
)

print(response.choices[0].message.content)
</code></pre>
<h3>Possible Output</h3>
<pre><code class="language-text">That isn't appropriate in a professional workplace. Let's keep our conversation work-related.
</code></pre>
<p>Notice something interesting.</p>
<ul>
<li><p>The <strong>user prompt is exactly the same</strong>.</p>
</li>
<li><p>The <strong>LLM model is also the same</strong>.</p>
</li>
<li><p>Only the <strong>System Role</strong> has changed.</p>
</li>
</ul>
<p>Because of that single change, the response is completely different.</p>
<h2>How the Model Processes the Request</h2>
<p>The model always follows this sequence:</p>
<ol>
<li><p>Read the <strong>System Role</strong>.</p>
</li>
<li><p>Understand how it should behave.</p>
</li>
<li><p>Read the user's prompt.</p>
</li>
<li><p>Generate a response according to the assigned role.</p>
</li>
</ol>
<p>This is why the System Role has a significant impact on the final output.</p>
<h2>Real-World Example</h2>
<p>System Roles become much more useful when building AI applications.</p>
<p>Imagine you're creating an AI platform for a software company.</p>
<p>Instead of using one AI for every task, you can create multiple specialized AI agents.</p>
<table>
<thead>
<tr>
<th>System Role</th>
<th>Responsibility</th>
</tr>
</thead>
<tbody><tr>
<td>Senior Software Architect</td>
<td>Reviews architecture and scalability</td>
</tr>
<tr>
<td>Python Developer</td>
<td>Writes and fixes code</td>
</tr>
<tr>
<td>QA Engineer</td>
<td>Finds bugs and edge cases</td>
</tr>
<tr>
<td>Technical Writer</td>
<td>Creates documentation</td>
</tr>
<tr>
<td>Product Manager</td>
<td>Writes product requirements</td>
</tr>
</tbody></table>
<p>Although all of these agents use the same underlying LLM, each behaves differently because each receives a different System Role.</p>
<p>This allows one model to perform multiple responsibilities without retraining it.</p>
<h2>What is Temperature?</h2>
<p>Now that you know how to tell an LLM <strong>who it should behave as</strong>, let's understand how to control <strong>the way it responds</strong>.</p>
<p>This is where <strong>Temperature</strong> comes into the picture.</p>
<p>Many beginners think Temperature changes the intelligence of an AI model.</p>
<p>It doesn't.</p>
<p>Instead, it controls <strong>how creative or predictable the model's responses should be</strong>.</p>
<blockquote>
<p>Temperature is a parameter that controls the randomness of an LLM's output. A lower value makes the response more predictable, while a higher value makes it more creative.</p>
</blockquote>
<h2>Understanding Temperature with a Simple Example</h2>
<p>Imagine you're starting a food delivery company and ask an AI:</p>
<pre><code class="language-text">Suggest a name for my food delivery startup.
</code></pre>
<p>Now let's change only the Temperature value.</p>
<table>
<thead>
<tr>
<th>Temperature</th>
<th>Possible Response</th>
</tr>
</thead>
<tbody><tr>
<td><strong>0.0</strong></td>
<td>Food House</td>
</tr>
<tr>
<td><strong>1.0</strong></td>
<td>Tasteo</td>
</tr>
<tr>
<td><strong>2.0</strong></td>
<td>Swivora</td>
</tr>
</tbody></table>
<p>The prompt didn't change.</p>
<p>The model didn't change.</p>
<p>Only the <strong>Temperature</strong> changed.</p>
<p>As the Temperature increases, the model starts generating more creative and unique names.</p>
<h2>How Temperature Works</h2>
<pre><code class="language-mermaid">flowchart LR
    A[User Prompt] --&gt; B[LLM]
    C[Temperature] --&gt; B
    B --&gt; D[Final Response]
</code></pre>
<p>Unlike the System Role, Temperature doesn't tell the model <strong>who it is</strong>.</p>
<p>Instead, it influences <strong>how the model chooses the next words while generating a response</strong>.</p>
<h2>Why Does Temperature Change the Output?</h2>
<p>To understand this, you first need to know how an LLM works.</p>
<p>Many people think an LLM searches for the correct answer like Google.</p>
<p>That's not true.</p>
<p>An LLM is a <strong>prediction model</strong>.</p>
<p>It predicts the next most likely word based on the previous words in the conversation.</p>
<p>Temperature changes <strong>how safe or adventurous those predictions become</strong>.</p>
<table>
<thead>
<tr>
<th>Low Temperature</th>
<th>High Temperature</th>
</tr>
</thead>
<tbody><tr>
<td>Chooses the most likely word</td>
<td>Explores multiple possibilities</td>
</tr>
<tr>
<td>More predictable</td>
<td>More creative</td>
</tr>
<tr>
<td>Less random</td>
<td>More random</td>
</tr>
</tbody></table>
<p>This is why the same prompt can produce different outputs when the Temperature changes.</p>
<h2>Python Example</h2>
<p>By default, if you don't specify a Temperature, most models use their default value.</p>
<p>You can control it by passing the <code>temperature</code> parameter while creating the chat completion.</p>
<pre><code class="language-python">from groq import Groq

client = Groq()

messages = [
    {
        "role": "system",
        "content": "You are a branding expert. Suggest only one name."
    },
    {
        "role": "user",
        "content": "Suggest a name for my food delivery startup."
    }
]

response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=messages,
    temperature=0
)

print(response.choices[0].message.content)
</code></pre>
<h3>Possible Output</h3>
<pre><code class="language-text">Food House
</code></pre>
<p>Now, change only the Temperature.</p>
<pre><code class="language-python">response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=messages,
    temperature=1
)
</code></pre>
<h3>Possible Output</h3>
<pre><code class="language-text">Tasteo
</code></pre>
<p>Let's increase it once more.</p>
<pre><code class="language-python">response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=messages,
    temperature=2
)
</code></pre>
<h3>Possible Output</h3>
<pre><code class="language-text">Swivora
</code></pre>
<p>As you can see, increasing the Temperature encourages the model to generate more creative names.</p>
<blockquote>
<p><strong>Note:</strong> Most LLMs support Temperature values between 0.0 and 2.0. Values outside this range are generally not allowed.</p>
</blockquote>
<h2>When Should You Use Different Temperature Values?</h2>
<p>The ideal Temperature depends on your use case.</p>
<table>
<thead>
<tr>
<th>Use Case</th>
<th>Recommended Temperature</th>
<th>Reason</th>
</tr>
</thead>
<tbody><tr>
<td>Medical Assistant</td>
<td>0.0 – 0.2</td>
<td>Accurate and consistent responses</td>
</tr>
<tr>
<td>Coding Assistant</td>
<td>0.1 – 0.4</td>
<td>Generates reliable code</td>
</tr>
<tr>
<td>Customer Support Bot</td>
<td>0.2 – 0.5</td>
<td>Professional and predictable answers</td>
</tr>
<tr>
<td>Blog Writing</td>
<td>0.7 – 1.2</td>
<td>More engaging content</td>
</tr>
<tr>
<td>Story Generator</td>
<td>1.2 – 2.0</td>
<td>Encourages creativity</td>
</tr>
<tr>
<td>Brand Name Generator</td>
<td>1.5 – 2.0</td>
<td>Produces unique names</td>
</tr>
</tbody></table>
<h2>System Role vs Temperature</h2>
<p>Now let's compare both concepts.</p>
<table>
<thead>
<tr>
<th>System Role</th>
<th>Temperature</th>
</tr>
</thead>
<tbody><tr>
<td>Defines <strong>who the AI should behave as</strong></td>
<td>Defines <strong>how the AI should respond</strong></td>
</tr>
<tr>
<td>Changes the AI's identity</td>
<td>Changes the AI's creativity</td>
</tr>
<tr>
<td>Used to assign responsibilities</td>
<td>Used to control randomness</td>
</tr>
<tr>
<td>Example: Developer, Architect, Teacher</td>
<td>Example: Conservative vs Creative</td>
</tr>
</tbody></table>
<p>A simple way to remember this is:</p>
<ul>
<li><p><strong>System Role = Who the AI is</strong></p>
</li>
<li><p><strong>Temperature = How the AI thinks</strong></p>
</li>
</ul>
<h2>Conclusion</h2>
<p>System Role and Temperature are two of the most important parameters you'll use while working with Large Language Models.</p>
<p>Although they are often mentioned together, they solve different problems.</p>
<p>A <strong>System Role</strong> gives the AI an identity and defines how it should behave throughout the conversation.</p>
<p>A <strong>Temperature</strong> value controls how safe, predictable, or creative the generated responses should be.</p>
<p>When these two parameters are used correctly, you can build AI applications that are more reliable, consistent, and tailored to specific use cases.</p>
<p>Whether you're preparing for interviews or building your own AI applications, understanding these concepts will help you design better prompts, create specialized AI agents, and generate higher-quality responses.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Promises Explained: From Callbacks to Async Programming]]></title><description><![CDATA[If you've ever worked with APIs, databases, file uploads, authentication, or payment gateways in JavaScript, you've already worked with asynchronous programming—even if you didn't realize it.
Before l]]></description><link>https://blog.adityaguptareal.com/javascript-promises-explained</link><guid isPermaLink="true">https://blog.adityaguptareal.com/javascript-promises-explained</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Thu, 02 Jul 2026 20:01:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/430d239f-93ec-4059-a9e0-4dd79ab8b816.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you've ever worked with APIs, databases, file uploads, authentication, or payment gateways in JavaScript, you've already worked with asynchronous programming—even if you didn't realize it.</p>
<p>Before learning Promises and Async/Await, it's important to understand <strong>why asynchronous programming exists</strong>. Once you understand the problem, the solutions become much easier to remember.</p>
<p>Let's start from the beginning.</p>
<h2>What is Synchronous JavaScript?</h2>
<p>JavaScript is a <strong>single-threaded</strong> programming language. This simply means it can execute <strong>one task at a time</strong>.</p>
<p>Consider this example:</p>
<pre><code class="language-javascript">console.log("Start");
console.log("Learning JavaScript");
console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Start
Learning JavaScript
End
</code></pre>
<p>JavaScript executes each line one after another.</p>
<p>It doesn't move to the next statement until the current one has finished executing.</p>
<p>This behavior is called <strong>synchronous execution</strong>.</p>
<h2>Why Synchronous Execution Isn't Always Enough</h2>
<p>Imagine you're building an e-commerce application.</p>
<p>A user clicks the <strong>Place Order</strong> button.</p>
<p>Your application now needs to:</p>
<ul>
<li><p>Verify payment</p>
</li>
<li><p>Save the order in the database</p>
</li>
<li><p>Send a confirmation email</p>
</li>
<li><p>Update inventory</p>
</li>
</ul>
<p>All of these operations take time.</p>
<p>Now imagine JavaScript waited for every operation to finish before executing the next line of code.</p>
<p>During that time:</p>
<ul>
<li><p>The page could become unresponsive.</p>
</li>
<li><p>The user couldn't interact with the application.</p>
</li>
<li><p>The overall experience would feel slow.</p>
</li>
</ul>
<p>Clearly, this isn't ideal.</p>
<p>This is exactly why asynchronous programming exists.</p>
<h2>Understanding Asynchronous JavaScript</h2>
<p>Instead of waiting for a long-running task to finish, JavaScript delegates that work to the browser or the Node.js runtime.</p>
<p>Once the task completes, JavaScript is notified and continues executing the required code.</p>
<p>A simple example looks like this:</p>
<pre><code class="language-javascript">console.log("Order Pizza");

setTimeout(() =&gt; {
    console.log("Pizza Delivered");
}, 3000);

console.log("Watching Netflix");
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Order Pizza
Watching Netflix
Pizza Delivered
</code></pre>
<p>Notice something interesting.</p>
<p>JavaScript didn't stop for three seconds.</p>
<p>Instead, it continued executing the remaining code while the timer was running in the background.</p>
<h2>A Simple Real-World Analogy</h2>
<p>Imagine you've ordered a pizza from Zomato.</p>
<h3>Synchronous Approach</h3>
<ol>
<li><p>Place the order.</p>
</li>
<li><p>Stand outside the restaurant for 30 minutes.</p>
</li>
<li><p>Do absolutely nothing.</p>
</li>
<li><p>Collect the pizza.</p>
</li>
</ol>
<p>This wastes your time.</p>
<h3>Asynchronous Approach</h3>
<ol>
<li><p>Place the order.</p>
</li>
<li><p>Continue working.</p>
</li>
<li><p>Watch a movie.</p>
</li>
<li><p>Complete your assignment.</p>
</li>
<li><p>Receive a notification when the pizza is ready.</p>
</li>
</ol>
<p>This is exactly how asynchronous JavaScript works.</p>
<p>Instead of waiting, it continues executing other tasks until the long-running operation finishes.</p>
<h2>Who Actually Performs Asynchronous Operations?</h2>
<p>One of the biggest misconceptions among beginners is that JavaScript performs asynchronous operations.</p>
<p>It doesn't.</p>
<p>JavaScript simply asks another component to perform those operations.</p>
<p>For example:</p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Performed By</th>
</tr>
</thead>
<tbody><tr>
<td><code>setTimeout()</code></td>
<td>Browser or Node.js Runtime</td>
</tr>
<tr>
<td><code>fetch()</code></td>
<td>Browser</td>
</tr>
<tr>
<td>File System</td>
<td>Node.js</td>
</tr>
<tr>
<td>Database Queries</td>
<td>Database Driver / Node.js</td>
</tr>
<tr>
<td>DOM Events</td>
<td>Browser</td>
</tr>
</tbody></table>
<p>When you write:</p>
<pre><code class="language-javascript">setTimeout(() =&gt; {
    console.log("Done");
}, 2000);
</code></pre>
<p>JavaScript is essentially saying:</p>
<blockquote>
<p>"Please start this timer. Let me know once it's finished."</p>
</blockquote>
<p>While the timer is running, JavaScript continues executing other code.</p>
<h2>What is a Callback Function?</h2>
<p>A callback is simply a function passed as an argument to another function.</p>
<p>Example:</p>
<pre><code class="language-javascript">function greet(name) {
    console.log(`Hello ${name}`);
}

function processUser(callback) {
    const name = "Aditya";
    callback(name);
}

processUser(greet);
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Hello Aditya
</code></pre>
<p>Here, <code>greet</code> is passed as an argument and executed later.</p>
<p>That's all a callback really is.</p>
<p>A callback itself is <strong>not asynchronous</strong>.</p>
<p>It's just a function.</p>
<p>Whether it's executed immediately or later depends on the function using it.</p>
<h2>Callbacks in Asynchronous Code</h2>
<p>Callbacks become especially useful when working with asynchronous operations.</p>
<p>Example:</p>
<pre><code class="language-javascript">console.log("Order Placed");

setTimeout(() =&gt; {
    console.log("Pizza Delivered");
}, 3000);

console.log("Watching Netflix");
</code></pre>
<p>The function inside <code>setTimeout()</code> is a callback.</p>
<p>Instead of executing immediately, the browser waits for three seconds before asking JavaScript to execute it.</p>
<p>This is one of the most common examples of asynchronous callbacks.</p>
<h2>The Problem with Callbacks</h2>
<p>Callbacks work well for simple tasks.</p>
<p>However, problems start appearing when multiple asynchronous operations depend on one another.</p>
<p>Imagine an application that needs to:</p>
<ol>
<li><p>Authenticate the user.</p>
</li>
<li><p>Fetch the user's profile.</p>
</li>
<li><p>Retrieve their recent orders.</p>
</li>
<li><p>Fetch payment history.</p>
</li>
</ol>
<p>Using callbacks, the code might look like this:</p>
<pre><code class="language-javascript">login(() =&gt; {
    getProfile(() =&gt; {
        getOrders(() =&gt; {
            getPaymentHistory(() =&gt; {
                console.log("Everything Completed");
            });
        });
    });
});
</code></pre>
<p>As more operations are added, the code becomes deeply nested.</p>
<p>Reading, debugging, and maintaining this structure quickly becomes difficult.</p>
<p>This problem is known as <strong>Callback Hell</strong>, also called the <strong>Pyramid of Doom</strong>.</p>
<h2>Why Were Promises Introduced?</h2>
<p>Promises were introduced to solve the problems caused by callback hell.</p>
<p>Instead of nesting one callback inside another, Promises allow asynchronous operations to be chained together in a much cleaner way.</p>
<p>Instead of writing:</p>
<pre><code class="language-javascript">login(() =&gt; {
    getProfile(() =&gt; {
        getOrders(() =&gt; {
            getPaymentHistory(() =&gt; {

            });
        });
    });
});
</code></pre>
<p>You can write:</p>
<pre><code class="language-javascript">login()
    .then(getProfile)
    .then(getOrders)
    .then(getPaymentHistory)
    .catch(handleError);
</code></pre>
<p>The execution flow becomes much easier to understand.</p>
<p>Error handling also becomes significantly simpler.</p>
<h2>Understanding Promises</h2>
<p>A Promise represents the <strong>future result of an asynchronous operation</strong>.</p>
<p>Think about ordering a laptop online.</p>
<p>After placing the order, the website gives you an order confirmation.</p>
<p>That confirmation isn't the laptop itself.</p>
<p>Instead, it's a guarantee that one of two things will happen in the future:</p>
<ul>
<li><p>You'll receive the laptop.</p>
</li>
<li><p>You'll receive a notification explaining why the order couldn't be completed.</p>
</li>
</ul>
<p>A Promise works in exactly the same way.</p>
<p>It doesn't contain the final result immediately.</p>
<p>Instead, it represents a value that will become available sometime in the future.</p>
<h2>Promise States</h2>
<p>Every Promise can exist in only one of three states.</p>
<table>
<thead>
<tr>
<th>State</th>
<th>Meaning</th>
<th>Real-World Example</th>
</tr>
</thead>
<tbody><tr>
<td>Pending</td>
<td>The operation is still running.</td>
<td>Pizza is being prepared.</td>
</tr>
<tr>
<td>Fulfilled</td>
<td>The operation completed successfully.</td>
<td>Pizza has been delivered.</td>
</tr>
<tr>
<td>Rejected</td>
<td>The operation failed.</td>
<td>The restaurant cancelled the order.</td>
</tr>
</tbody></table>
<p>The lifecycle looks like this:</p>
<pre><code class="language-text">Pending
   │
   ├────────► Fulfilled
   │
   └────────► Rejected
</code></pre>
<p>A Promise changes its state only once.</p>
<p>Once fulfilled or rejected, it can never change again.</p>
<h2>Creating Your Own Promise</h2>
<p>Many APIs such as <code>fetch()</code> already return a Promise.</p>
<p>However, sometimes you'll build your own asynchronous function.</p>
<p>In those cases, you create a Promise yourself.</p>
<p>Example:</p>
<pre><code class="language-javascript">function sleep(milliseconds) {
    return new Promise((resolve) =&gt; {
        setTimeout(resolve, milliseconds);
    });
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-javascript">await sleep(2000);

console.log("Two seconds completed.");
</code></pre>
<p>Here, the Promise is fulfilled only after the timer finishes.</p>
<h2>When Should You Create Your Own Promise?</h2>
<p>A common question is:</p>
<blockquote>
<p>If <code>fetch()</code> already returns a Promise, why do we ever write <code>new Promise()</code>?</p>
</blockquote>
<p>The answer is simple.</p>
<p>You create your own Promise whenever you're building your own asynchronous API.</p>
<p>Imagine you're implementing an image upload feature.</p>
<p>The upload may finish in two seconds, five seconds, or even twenty seconds.</p>
<p>You don't know beforehand.</p>
<p>Your function should resolve only when the upload actually completes.</p>
<pre><code class="language-javascript">function uploadImage(file) {
    return new Promise((resolve, reject) =&gt; {

        cloudinary.upload(file, (error, result) =&gt; {

            if (error) {
                reject(error);
                return;
            }

            resolve(result);

        });

    });
}
</code></pre>
<p>Notice that we never guessed the time.</p>
<p>The Promise is resolved only when Cloudinary reports that the upload has finished.</p>
<h2>Understanding <code>resolve()</code> and <code>reject()</code></h2>
<p>Whenever you create a Promise, JavaScript provides two functions.</p>
<pre><code class="language-javascript">new Promise((resolve, reject) =&gt; {

});
</code></pre>
<p>These functions control the Promise's final state.</p>
<table>
<thead>
<tr>
<th>Function</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>resolve(value)</code></td>
<td>Marks the Promise as fulfilled and returns a value.</td>
</tr>
<tr>
<td><code>reject(error)</code></td>
<td>Marks the Promise as rejected and returns an error.</td>
</tr>
</tbody></table>
<p>Example:</p>
<pre><code class="language-javascript">const payment = new Promise((resolve, reject) =&gt; {

    const success = true;

    if (success) {
        resolve("Payment Successful");
    } else {
        reject("Payment Failed");
    }

});
</code></pre>
<p>The important thing to remember is that <code>resolve()</code> is <strong>not based on time</strong>.</p>
<p>It's based on completion.</p>
<p>If a database query finishes, call <code>resolve()</code>.</p>
<p>If a payment gateway confirms a transaction, call <code>resolve()</code>.</p>
<p>If an image upload completes, call <code>resolve()</code>.</p>
<p>The event decides when the Promise settles—not a timer.</p>
<h2>Common Misconceptions</h2>
<table>
<thead>
<tr>
<th>Myth</th>
<th>Reality</th>
</tr>
</thead>
<tbody><tr>
<td>JavaScript performs asynchronous work.</td>
<td>The browser or Node.js runtime performs it.</td>
</tr>
<tr>
<td>A Promise immediately contains the data.</td>
<td>A Promise represents data that will arrive in the future.</td>
</tr>
<tr>
<td><code>resolve()</code> should always be called after <code>setTimeout()</code>.</td>
<td><code>resolve()</code> should be called when the asynchronous operation actually finishes.</td>
</tr>
<tr>
<td>Callbacks are always asynchronous.</td>
<td>A callback is simply a function. It can be synchronous or asynchronous depending on how it's used.</td>
</tr>
<tr>
<td>Promises and Async/Await are completely different concepts.</td>
<td>Async/Await is built on top of Promises.</td>
</tr>
</tbody></table>
<h2>Frequently Asked Interview Questions</h2>
<h3>Why were Promises introduced?</h3>
<p>Promises were introduced to solve callback hell, improve readability, and provide better error handling for asynchronous operations.</p>
<h3>What are the three states of a Promise?</h3>
<p>Pending, Fulfilled, and Rejected.</p>
<h3>Can a Promise change its state multiple times?</h3>
<p>No.</p>
<p>Once a Promise is fulfilled or rejected, its state becomes permanent.</p>
<h3>Does <code>fetch()</code> return the response data?</h3>
<p>No.</p>
<p><code>fetch()</code> returns a Promise that eventually resolves to a <code>Response</code> object.</p>
<h3>When should you create your own Promise?</h3>
<p>Whenever you're building your own asynchronous function that doesn't already return a Promise.</p>
<h3>What's the biggest mistake beginners make?</h3>
<p>Many beginners think JavaScript performs asynchronous work itself.</p>
<p>In reality, asynchronous operations are handled by the browser or Node.js runtime, while JavaScript coordinates the execution.</p>
<h2>Working with Promises</h2>
<p>Now that you understand what a Promise is and why it exists, it's time to learn how we actually work with it.</p>
<p>Creating a Promise is only one side of the story.</p>
<p>The more common task in real-world applications is <strong>consuming Promises</strong> returned by APIs like <code>fetch()</code>, database queries, authentication libraries, payment gateways, and cloud services.</p>
<p>Let's understand how JavaScript provides different methods to handle these Promises.</p>
<h2>Understanding <code>.then()</code></h2>
<p>Whenever a Promise is fulfilled, JavaScript executes the function passed to <code>.then()</code>.</p>
<p>Think of <code>.then()</code> as saying:</p>
<blockquote>
<p>"Once this task finishes successfully, execute this code."</p>
</blockquote>
<p>Example:</p>
<pre><code class="language-javascript">fetch("/api/users")
    .then((response) =&gt; {
        console.log(response);
    });
</code></pre>
<p>Here, <code>fetch()</code> immediately returns a Promise.</p>
<p>JavaScript doesn't wait for the server response.</p>
<p>Instead, it registers the callback inside <code>.then()</code> and continues executing the remaining code.</p>
<p>When the server finally responds, JavaScript executes the callback.</p>
<h3>Real-World Example</h3>
<p>Imagine you ordered a laptop online.</p>
<p>You don't sit in front of the warehouse waiting for it.</p>
<p>Instead, you continue doing your work.</p>
<p>When the delivery arrives, you receive a notification.</p>
<p>That notification is similar to <code>.then()</code>.</p>
<p>It runs only after the task completes successfully.</p>
<h2>Returning Values from <code>.then()</code></h2>
<p>One important thing many beginners don't know is that every <code>.then()</code> returns a <strong>new Promise</strong>.</p>
<p>This makes Promise chaining possible.</p>
<p>Example:</p>
<pre><code class="language-javascript">fetch("/api/users")
    .then((response) =&gt; response.json())
    .then((users) =&gt; {
        console.log(users);
    });
</code></pre>
<p>Flow:</p>
<pre><code class="language-text">fetch()
      ↓
Response Object
      ↓
response.json()
      ↓
Actual User Data
</code></pre>
<p>Notice that the second <code>.then()</code> receives the value returned from the previous <code>.then()</code>.</p>
<p>This is known as <strong>Promise Chaining</strong>.</p>
<h2>Understanding <code>.catch()</code></h2>
<p>Asynchronous operations don't always succeed.</p>
<p>A server might crash.</p>
<p>The internet connection may fail.</p>
<p>A database might become unavailable.</p>
<p>A payment could be rejected.</p>
<p>Whenever a Promise is rejected, JavaScript executes the function inside <code>.catch()</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">fetch("/invalid-api")
    .then((response) =&gt; response.json())
    .catch((error) =&gt; {
        console.log(error);
    });
</code></pre>
<p>Think of <code>.catch()</code> as a centralized error handler.</p>
<p>Instead of checking errors after every step, you can handle them in one place.</p>
<h3>Real-World Example</h3>
<p>Imagine you're booking movie tickets.</p>
<p>If the payment succeeds, you receive the ticket.</p>
<p>If the payment fails, the app immediately shows an error message.</p>
<p>The error screen behaves just like <code>.catch()</code>.</p>
<h2>Understanding <code>.finally()</code></h2>
<p>Sometimes you want to execute code regardless of success or failure.</p>
<p>That's exactly what <code>.finally()</code> does.</p>
<p>Example:</p>
<pre><code class="language-javascript">fetch("/api/users")
    .then((response) =&gt; response.json())
    .catch((error) =&gt; {
        console.log(error);
    })
    .finally(() =&gt; {
        console.log("Request Finished");
    });
</code></pre>
<p>Whether the request succeeds or fails, <code>"Request Finished"</code> will always be printed.</p>
<h3>Common Use Cases</h3>
<ul>
<li><p>Hide loading spinner</p>
</li>
<li><p>Close database connection</p>
</li>
<li><p>Stop progress bar</p>
</li>
<li><p>Clean temporary resources</p>
</li>
</ul>
<h2>Promise Chaining</h2>
<p>Suppose your application performs these steps.</p>
<ol>
<li><p>Login</p>
</li>
<li><p>Fetch Profile</p>
</li>
<li><p>Fetch Orders</p>
</li>
<li><p>Fetch Payment History</p>
</li>
</ol>
<p>Each operation depends on the previous one.</p>
<p>Instead of nesting callbacks, we can chain Promises.</p>
<pre><code class="language-javascript">login()
    .then(() =&gt; getProfile())
    .then(() =&gt; getOrders())
    .then(() =&gt; getPaymentHistory())
    .catch((error) =&gt; {
        console.log(error);
    });
</code></pre>
<p>This code is much easier to read than callback hell.</p>
<p>The flow becomes almost identical to normal English.</p>
<h2>Real-World Example: User Dashboard</h2>
<p>Imagine you're building a dashboard.</p>
<p>The dashboard needs:</p>
<ul>
<li><p>User Profile</p>
</li>
<li><p>Notifications</p>
</li>
<li><p>Latest Orders</p>
</li>
</ul>
<p>A beginner might write:</p>
<pre><code class="language-javascript">const profile = await getProfile();
const notifications = await getNotifications();
const orders = await getOrders();
</code></pre>
<p>Although this works, the requests are executed one after another.</p>
<p>If each request takes one second, the total time becomes roughly three seconds.</p>
<p>A better solution is to execute them together.</p>
<pre><code class="language-javascript">const [profile, notifications, orders] = await Promise.all([
    getProfile(),
    getNotifications(),
    getOrders(),
]);
</code></pre>
<p>Now all requests start at the same time.</p>
<p>The total execution time becomes approximately the duration of the slowest request instead of the sum of all requests.</p>
<p>This is one of the most common Promise optimizations used in production applications.</p>
<h2>Promise Utility Methods</h2>
<p>JavaScript provides four utility methods that are frequently asked in interviews.</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Waits For</th>
<th>Rejects?</th>
<th>Best Use Case</th>
</tr>
</thead>
<tbody><tr>
<td><code>Promise.all()</code></td>
<td>All Promises to succeed</td>
<td>Yes</td>
<td>Loading multiple independent APIs</td>
</tr>
<tr>
<td><code>Promise.allSettled()</code></td>
<td>All Promises to finish</td>
<td>No</td>
<td>Dashboard widgets, analytics</td>
</tr>
<tr>
<td><code>Promise.race()</code></td>
<td>First settled Promise</td>
<td>Depends</td>
<td>Timeouts, fastest response</td>
</tr>
<tr>
<td><code>Promise.any()</code></td>
<td>First successful Promise</td>
<td>Only if all fail</td>
<td>CDN mirrors, backup servers</td>
</tr>
</tbody></table>
<p>Let's understand each one.</p>
<h2>Promise.all()</h2>
<p><code>Promise.all()</code> waits until <strong>every Promise is fulfilled</strong>.</p>
<p>If even one Promise rejects, the entire Promise rejects immediately.</p>
<p>Example:</p>
<pre><code class="language-javascript">const [user, posts, comments] = await Promise.all([
    getUser(),
    getPosts(),
    getComments(),
]);
</code></pre>
<h3>Timeline</h3>
<pre><code class="language-text">User ---------- 1s

Posts ---------------- 2s

Comments ------- 1s

Total Time = 2s
</code></pre>
<p>If <code>getPosts()</code> fails, the entire operation fails.</p>
<p>This behavior is called <strong>Fail Fast</strong>.</p>
<h3>Best Use Cases</h3>
<ul>
<li><p>Dashboard APIs</p>
</li>
<li><p>Loading product details</p>
</li>
<li><p>Fetching independent resources</p>
</li>
<li><p>Parallel database queries</p>
</li>
</ul>
<h2>Promise.allSettled()</h2>
<p>Unlike <code>Promise.all()</code>, this method never fails because of one rejected Promise.</p>
<p>Instead, it returns the result of every Promise.</p>
<p>Example:</p>
<pre><code class="language-javascript">const results = await Promise.allSettled([
    getProfile(),
    getNotifications(),
    getBlogs(),
]);
</code></pre>
<p>Example Output:</p>
<pre><code class="language-javascript">[
    {
        status: "fulfilled",
        value: { name: "Aditya" },
    },
    {
        status: "rejected",
        reason: Error("Server Error"),
    },
    {
        status: "fulfilled",
        value: [],
    },
]
</code></pre>
<p>This method is perfect when partial success is acceptable.</p>
<h3>Real-World Example</h3>
<p>Suppose a homepage contains:</p>
<ul>
<li><p>Hero Banner</p>
</li>
<li><p>Trending Products</p>
</li>
<li><p>Blogs</p>
</li>
<li><p>Recommendations</p>
</li>
</ul>
<p>If the Blogs API fails, you still want to show the remaining sections.</p>
<p><code>Promise.allSettled()</code> makes this possible.</p>
<h2>Promise.race()</h2>
<p><code>Promise.race()</code> returns the first Promise that settles.</p>
<p>A Promise is considered settled when it is either fulfilled or rejected.</p>
<p>Example:</p>
<pre><code class="language-javascript">const result = await Promise.race([
    fetch(serverA),
    fetch(serverB),
    fetch(serverC),
]);
</code></pre>
<p>Timeline:</p>
<pre><code class="language-text">Server A ---------- 300ms

Server B ---------------- 500ms

Server C ---- 150ms
</code></pre>
<p>The response from Server C will be returned first.</p>
<h3>Common Use Cases</h3>
<ul>
<li><p>API timeout implementation</p>
</li>
<li><p>Selecting the fastest server</p>
</li>
<li><p>Network fallback mechanisms</p>
</li>
</ul>
<h2>Promise.any()</h2>
<p><code>Promise.any()</code> waits for the first <strong>successful</strong> Promise.</p>
<p>Unlike <code>Promise.race()</code>, it ignores rejected Promises.</p>
<p>Example:</p>
<pre><code class="language-javascript">const response = await Promise.any([
    fetch(primaryServer),
    fetch(backupServer),
    fetch(thirdServer),
]);
</code></pre>
<p>Timeline:</p>
<pre><code class="language-text">Primary Server ----- Error

Backup Server ---------------- 400ms

Third Server --------- 200ms
</code></pre>
<p>The third server wins because it is the first successful Promise.</p>
<p>If every Promise fails, JavaScript throws an <code>AggregateError</code>.</p>
<h3>Common Use Cases</h3>
<ul>
<li><p>CDN mirrors</p>
</li>
<li><p>Multiple backend regions</p>
</li>
<li><p>Backup APIs</p>
</li>
<li><p>Image delivery networks</p>
</li>
</ul>
<h2>Promise.all() vs Promise.allSettled()</h2>
<table>
<thead>
<tr>
<th>Promise.all()</th>
<th>Promise.allSettled()</th>
</tr>
</thead>
<tbody><tr>
<td>Requires every Promise to succeed</td>
<td>Waits for every Promise to finish</td>
</tr>
<tr>
<td>Rejects immediately on first failure</td>
<td>Never rejects because of one failure</td>
</tr>
<tr>
<td>Faster fail-fast behavior</td>
<td>Better when partial data is acceptable</td>
</tr>
<tr>
<td>Common for critical workflows</td>
<td>Common for dashboards</td>
</tr>
</tbody></table>
<h2>Promise.race() vs Promise.any()</h2>
<table>
<thead>
<tr>
<th>Promise.race()</th>
<th>Promise.any()</th>
</tr>
</thead>
<tbody><tr>
<td>First settled Promise wins</td>
<td>First successful Promise wins</td>
</tr>
<tr>
<td>Error can win the race</td>
<td>Errors are ignored until every Promise fails</td>
</tr>
<tr>
<td>Useful for timeouts</td>
<td>Useful for multiple mirror servers</td>
</tr>
</tbody></table>
<h2>Common Mistakes</h2>
<table>
<thead>
<tr>
<th>Mistake</th>
<th>Better Approach</th>
</tr>
</thead>
<tbody><tr>
<td>Using <code>Promise.all()</code> when partial data is acceptable</td>
<td>Use <code>Promise.allSettled()</code></td>
</tr>
<tr>
<td>Running independent API calls sequentially</td>
<td>Use <code>Promise.all()</code></td>
</tr>
<tr>
<td>Forgetting to return a Promise inside <code>.then()</code></td>
<td>Always return the next Promise when chaining</td>
</tr>
<tr>
<td>Ignoring rejected Promises</td>
<td>Always handle errors with <code>.catch()</code> or <code>try...catch</code></td>
</tr>
</tbody></table>
<h2>Interview Questions</h2>
<h3>What is Promise Chaining?</h3>
<p>Promise chaining is the process of connecting multiple asynchronous operations using consecutive <code>.then()</code> calls, where each step receives the result of the previous Promise.</p>
<h3>When should you use <code>Promise.all()</code>?</h3>
<p>When multiple independent asynchronous operations must all succeed before continuing.</p>
<h3>When should you use <code>Promise.allSettled()</code>?</h3>
<p>When you want the result of every Promise, regardless of whether some succeed or fail.</p>
<h3>What is the difference between <code>Promise.race()</code> and <code>Promise.any()</code>?</h3>
<p><code>Promise.race()</code> returns the first settled Promise (success or failure), while <code>Promise.any()</code> returns the first fulfilled Promise and ignores failures until every Promise is rejected.</p>
<h3>Which Promise method is most commonly used in production?</h3>
<p>For most web applications:</p>
<ul>
<li><p><code>Promise.all()</code> is used for parallel API requests.</p>
</li>
<li><p><code>Promise.allSettled()</code> is used when partial failures should not break the UI.</p>
</li>
<li><p><code>Promise.race()</code> is commonly used for request timeouts.</p>
</li>
<li><p><code>Promise.any()</code> is useful for redundant servers and CDN fallback systems.</p>
</li>
</ul>
<h2>Understanding Async/Await</h2>
<p>Promises solved the problem of callback hell, but developers still had one complaint.</p>
<p>Long Promise chains were sometimes difficult to read.</p>
<p>Consider this example.</p>
<pre><code class="language-javascript">fetch("/api/user")
    .then((response) =&gt; response.json())
    .then((user) =&gt; getOrders(user.id))
    .then((orders) =&gt; getPaymentHistory(orders))
    .catch((error) =&gt; {
        console.log(error);
    });
</code></pre>
<p>Although this is much cleaner than callback hell, it still doesn't look like normal JavaScript code.</p>
<p>To improve readability, JavaScript introduced <strong>Async/Await</strong>.</p>
<p>The important thing to remember is:</p>
<blockquote>
<p><strong>Async/Await does not replace Promises. It is built on top of Promises.</strong></p>
</blockquote>
<p>Every <code>await</code> works with a Promise.</p>
<p>Every <code>async</code> function returns a Promise.</p>
<h2>What Does <code>async</code> Do?</h2>
<p>Whenever you add the <code>async</code> keyword before a function, JavaScript automatically makes that function return a Promise.</p>
<p>Example:</p>
<pre><code class="language-javascript">async function greet() {
    return "Hello";
}
</code></pre>
<p>Many beginners think this function returns a string.</p>
<p>It doesn't.</p>
<p>It returns:</p>
<pre><code class="language-javascript">Promise { "Hello" }
</code></pre>
<p>The above code is almost equivalent to:</p>
<pre><code class="language-javascript">function greet() {
    return Promise.resolve("Hello");
}
</code></pre>
<p>This is why you can write:</p>
<pre><code class="language-javascript">const message = await greet();
console.log(message);
</code></pre>
<h2>What Does <code>await</code> Do?</h2>
<p>The <code>await</code> keyword pauses the execution of the current async function until the Promise settles.</p>
<p>Example:</p>
<pre><code class="language-javascript">async function getUser() {
    const response = await fetch("/api/user");
    const user = await response.json();

    return user;
}
</code></pre>
<p>Notice something important.</p>
<p>JavaScript doesn't block the entire application.</p>
<p>It only pauses the current async function.</p>
<p>Other JavaScript tasks can continue executing.</p>
<h2>How Async/Await Works Internally</h2>
<p>Many developers think <code>await</code> is magic.</p>
<p>It isn't.</p>
<p>Internally, JavaScript is still working with Promises.</p>
<p>Example:</p>
<pre><code class="language-javascript">const response = await fetch("/api/user");
</code></pre>
<p>Conceptually behaves like:</p>
<pre><code class="language-javascript">fetch("/api/user")
    .then((response) =&gt; {
        // Continue execution
    });
</code></pre>
<p>This is why understanding Promises first is extremely important.</p>
<p>If you understand Promises, Async/Await becomes very easy.</p>
<h2>Why Can't We Use <code>await</code> Everywhere?</h2>
<p>The following code is invalid.</p>
<pre><code class="language-javascript">const response = await fetch("/api/users");
</code></pre>
<p>It throws an error because <code>await</code> can only be used:</p>
<ul>
<li><p>Inside an async function.</p>
</li>
<li><p>At the top level of an ES Module.</p>
</li>
</ul>
<p>Correct example:</p>
<pre><code class="language-javascript">async function getUsers() {
    const response = await fetch("/api/users");

    return response.json();
}
</code></pre>
<h2>Error Handling with Try...Catch</h2>
<p>With Promises, errors are handled using <code>.catch()</code>.</p>
<pre><code class="language-javascript">fetch("/api/user")
    .then((response) =&gt; response.json())
    .catch((error) =&gt; {
        console.log(error);
    });
</code></pre>
<p>With Async/Await, we use <code>try...catch</code>.</p>
<pre><code class="language-javascript">async function getUser() {

    try {

        const response = await fetch("/api/user");
        const user = await response.json();

        return user;

    } catch (error) {

        console.log(error);

    }

}
</code></pre>
<p>Think of the mapping like this.</p>
<table>
<thead>
<tr>
<th>Promise</th>
<th>Async/Await</th>
</tr>
</thead>
<tbody><tr>
<td><code>.then()</code></td>
<td><code>await</code></td>
</tr>
<tr>
<td><code>.catch()</code></td>
<td><code>try...catch</code></td>
</tr>
<tr>
<td><code>.finally()</code></td>
<td><code>finally</code></td>
</tr>
</tbody></table>
<h2>When Should You Use <code>.then()</code>?</h2>
<p>Although Async/Await is more popular today, <code>.then()</code> is still useful.</p>
<p>Good use cases:</p>
<ul>
<li><p>Simple Promise chains</p>
</li>
<li><p>Event listeners</p>
</li>
<li><p>Library code</p>
</li>
<li><p>Functional Promise composition</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">button.addEventListener("click", () =&gt; {

    fetch("/api/user")
        .then((response) =&gt; response.json())
        .then((user) =&gt; {
            console.log(user);
        });

});
</code></pre>
<p>This is perfectly valid code.</p>
<h2>When Should You Use Async/Await?</h2>
<p>Async/Await is usually preferred when you're writing business logic.</p>
<p>Example:</p>
<pre><code class="language-javascript">async function checkout() {

    const user = await getUser();

    const payment = await verifyPayment();

    const order = await createOrder();

    await sendConfirmationEmail();

    return order;

}
</code></pre>
<p>This reads almost like normal English.</p>
<p>That is why modern applications heavily prefer Async/Await.</p>
<h2>Async/Await vs Promise.then()</h2>
<table>
<thead>
<tr>
<th>Async/Await</th>
<th>Promise.then()</th>
</tr>
</thead>
<tbody><tr>
<td>Cleaner syntax</td>
<td>Slightly more verbose</td>
</tr>
<tr>
<td>Easy to read</td>
<td>Can become difficult with long chains</td>
</tr>
<tr>
<td>Uses try...catch</td>
<td>Uses .catch()</td>
</tr>
<tr>
<td>Preferred in business logic</td>
<td>Useful in short Promise chains</td>
</tr>
<tr>
<td>Built on top of Promises</td>
<td>Native Promise API</td>
</tr>
</tbody></table>
<p>Neither approach is better.</p>
<p>Choose the one that makes your code easier to understand.</p>
<h2>Should You Still Learn Promises?</h2>
<p>Absolutely.</p>
<p>Many beginners try to skip Promises and directly learn Async/Await.</p>
<p>This is a mistake.</p>
<p>Consider this line.</p>
<pre><code class="language-javascript">const response = await fetch("/api/user");
</code></pre>
<p>Why does <code>await</code> work here?</p>
<p>Because <code>fetch()</code> returns a Promise.</p>
<p>Without understanding Promises, Async/Await becomes difficult to reason about.</p>
<p>Promises are the foundation.</p>
<p>Async/Await is simply a cleaner way to consume them.</p>
<h2>Real-World Example: User Login</h2>
<p>Imagine you're building an authentication system.</p>
<p>The steps are:</p>
<ol>
<li><p>Validate credentials.</p>
</li>
<li><p>Generate JWT.</p>
</li>
<li><p>Save session.</p>
</li>
<li><p>Return user profile.</p>
</li>
</ol>
<p>Using Async/Await:</p>
<pre><code class="language-javascript">async function login(credentials) {

    const user = await validateUser(credentials);

    const token = await generateToken(user);

    await saveSession(user.id, token);

    return {
        user,
        token,
    };

}
</code></pre>
<p>This flow is easy to understand and maintain.</p>
<h2>Real-World Example: File Upload</h2>
<p>Suppose a user uploads an image.</p>
<p>The application should:</p>
<ul>
<li><p>Upload image.</p>
</li>
<li><p>Save URL in database.</p>
</li>
<li><p>Send notification.</p>
</li>
<li><p>Return updated profile.</p>
</li>
</ul>
<pre><code class="language-javascript">async function updateProfile(file) {

    const image = await uploadImage(file);

    const profile = await saveProfile(image.url);

    await sendNotification(profile.id);

    return profile;

}
</code></pre>
<p>Notice that each step depends on the previous one.</p>
<p>This is an ideal use case for Async/Await.</p>
<h2>Common Mistakes</h2>
<h3>Forgetting <code>await</code></h3>
<pre><code class="language-javascript">const user = fetch("/api/user");

console.log(user);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">Promise { &lt;pending&gt; }
</code></pre>
<p>Correct:</p>
<pre><code class="language-javascript">const user = await fetch("/api/user");
</code></pre>
<h3>Forgetting <code>async</code></h3>
<pre><code class="language-javascript">function getUser() {

    const response = await fetch("/api/user");

}
</code></pre>
<p>This throws an error.</p>
<p>Correct:</p>
<pre><code class="language-javascript">async function getUser() {

    const response = await fetch("/api/user");

}
</code></pre>
<h3>Using Sequential Requests Unnecessarily</h3>
<p>Bad:</p>
<pre><code class="language-javascript">const users = await getUsers();

const posts = await getPosts();

const comments = await getComments();
</code></pre>
<p>Good:</p>
<pre><code class="language-javascript">const [users, posts, comments] = await Promise.all([
    getUsers(),
    getPosts(),
    getComments(),
]);
</code></pre>
<p>If the requests are independent, run them in parallel.</p>
<h2>Best Practices</h2>
<ul>
<li><p>Prefer Async/Await for application logic.</p>
</li>
<li><p>Use <code>Promise.all()</code> for independent requests.</p>
</li>
<li><p>Always handle errors.</p>
</li>
<li><p>Don't wrap an existing Promise inside another Promise unless necessary.</p>
</li>
<li><p>Avoid unnecessary sequential requests.</p>
</li>
<li><p>Keep async functions focused on one responsibility.</p>
</li>
</ul>
<h2>Interview Questions</h2>
<h3>Does Async/Await replace Promises?</h3>
<p>No.</p>
<p>Async/Await is built on top of Promises.</p>
<h3>Does every async function return a Promise?</h3>
<p>Yes.</p>
<p>Even if you return a string or a number, JavaScript automatically wraps it inside a Promise.</p>
<h3>Can <code>await</code> work without a Promise?</h3>
<p>No.</p>
<p><code>await</code> is designed to work with Promises (or thenables).</p>
<h3>Why is Async/Await preferred?</h3>
<p>Because it improves readability and makes asynchronous code look like synchronous code.</p>
<h3>Which is faster: Promises or Async/Await?</h3>
<p>Neither.</p>
<p>Async/Await internally uses Promises.</p>
<p>The performance difference is negligible.</p>
<p>Choose the one that improves readability.</p>
<h3>What is the biggest advantage of Async/Await?</h3>
<p>The biggest advantage is maintainability.</p>
<p>Large asynchronous workflows become much easier to understand, debug, and modify.</p>
<h2>Final Thoughts</h2>
<p>Asynchronous programming is one of the most important concepts in modern JavaScript.</p>
<p>Everything from API calls and database queries to authentication, file uploads, payments, and cloud services relies on it.</p>
<p>Instead of memorizing syntax, focus on understanding the problem each feature solves.</p>
<p>Remember the evolution of asynchronous JavaScript:</p>
<pre><code class="language-text">Callback
      ↓
Callback Hell
      ↓
Promise
      ↓
Async/Await
</code></pre>
<p>Once you understand this journey, every asynchronous API in JavaScript starts making much more sense.</p>
<p>Most importantly, don't treat Promises and Async/Await as separate topics.</p>
<p>They are different ways of solving the same problem, with Async/Await simply providing a cleaner syntax on top of Promises.</p>
]]></content:encoded></item><item><title><![CDATA[Docker Compose Complete Guide: From Beginner to Interview Ready]]></title><description><![CDATA[What is Docker Compose?
Docker Compose is a tool used to define and manage multiple Docker containers using a single YAML file.
Instead of running multiple docker commands manually, Docker Compose all]]></description><link>https://blog.adityaguptareal.com/docker-compose-complete-guide-from-beginner-to-interview-ready</link><guid isPermaLink="true">https://blog.adityaguptareal.com/docker-compose-complete-guide-from-beginner-to-interview-ready</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sun, 21 Jun 2026 09:01:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/f1aff978-2f52-40ec-bc90-8ff5899eb4de.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>What is Docker Compose?</h3>
<p>Docker Compose is a tool used to define and manage multiple Docker containers using a single YAML file.</p>
<p>Instead of running multiple docker commands manually, Docker Compose allows you to define all services in one configuration file.</p>
<p>Without Compose:</p>
<pre><code class="language-bash">docker run postgres
docker run redis
docker run backend
docker run frontend
</code></pre>
<p>With Compose:</p>
<pre><code class="language-bash">docker compose up
</code></pre>
<p>Everything starts automatically.</p>
<hr />
<h3>Why Do We Need Docker Compose?</h3>
<p>Modern applications rarely consist of a single container.</p>
<p>A typical application may contain:</p>
<table>
<thead>
<tr>
<th>Service</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>Frontend</td>
<td>React / Next.js</td>
</tr>
<tr>
<td>Backend</td>
<td>Node.js / Express</td>
</tr>
<tr>
<td>Database</td>
<td>PostgreSQL</td>
</tr>
<tr>
<td>Cache</td>
<td>Redis</td>
</tr>
<tr>
<td>Reverse Proxy</td>
<td>Nginx</td>
</tr>
</tbody></table>
<p>Managing these individually becomes difficult.</p>
<p>Docker Compose solves this problem.</p>
<hr />
<h3>Docker Compose Workflow</h3>
<pre><code class="language-text">compose.yml
      ↓
docker compose up
      ↓
Network Creation
      ↓
Volume Creation
      ↓
Container Creation
      ↓
Application Running
</code></pre>
<p>Compose automatically creates:</p>
<ul>
<li><p>Containers</p>
</li>
<li><p>Networks</p>
</li>
<li><p>Volumes</p>
</li>
<li><p>Service communication</p>
</li>
</ul>
<hr />
<h3>Basic Docker Compose File</h3>
<pre><code class="language-yaml">services:
  app:
    build: .

  db:
    image: postgres:16
</code></pre>
<p>This starts:</p>
<ul>
<li><p>One application container</p>
</li>
<li><p>One PostgreSQL container</p>
</li>
</ul>
<hr />
<h3>Services</h3>
<p>Services are the most important concept in Docker Compose.</p>
<p>Each service represents a container.</p>
<pre><code class="language-yaml">services:
  frontend:
    build: ./frontend

  backend:
    build: ./backend

  postgres:
    image: postgres:16
</code></pre>
<p>Three services create three containers.</p>
<hr />
<h3>Build</h3>
<p>Used when Docker should build an image using a Dockerfile.</p>
<pre><code class="language-yaml">services:
  backend:
    build: .
</code></pre>
<p>Equivalent command:</p>
<pre><code class="language-bash">docker build .
</code></pre>
<p>Custom path:</p>
<pre><code class="language-yaml">services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile.prod
</code></pre>
<hr />
<h3>Image</h3>
<p>Used when Docker should pull an image from Docker Hub.</p>
<pre><code class="language-yaml">services:
  postgres:
    image: postgres:16
</code></pre>
<p>Examples:</p>
<pre><code class="language-yaml">image: redis:7

image: nginx:latest

image: mongo:7
</code></pre>
<hr />
<h3>Build vs Image</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Build</th>
<th>Image</th>
</tr>
</thead>
<tbody><tr>
<td>Uses Dockerfile</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Builds Locally</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Pulls From Registry</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Used For Custom Apps</td>
<td>Yes</td>
<td>Yes</td>
</tr>
</tbody></table>
<p>Interview Question:</p>
<blockquote>
<p>When should you use build instead of image?</p>
</blockquote>
<p><strong>Answer</strong></p>
<p>Use build when creating your own application image. Use image when using pre-built images from Docker Hub.</p>
<hr />
<h3>Container Name</h3>
<p>Provides a custom container name.</p>
<pre><code class="language-yaml">services:
  backend:
    container_name: backend-app
</code></pre>
<p>Without this:</p>
<pre><code class="language-text">project_backend_1
</code></pre>
<p>With this:</p>
<pre><code class="language-text">backend-app
</code></pre>
<hr />
<h3>Ports</h3>
<p>Maps host ports to container ports.</p>
<pre><code class="language-yaml">ports:
  - "3000:3000"
</code></pre>
<p>Format:</p>
<pre><code class="language-text">HOST:CONTAINER
</code></pre>
<p>Example:</p>
<pre><code class="language-yaml">ports:
  - "8080:3000"
</code></pre>
<p>Request:</p>
<pre><code class="language-text">localhost:8080
</code></pre>
<p>Container receives:</p>
<pre><code class="language-text">3000
</code></pre>
<p>Interview Question:</p>
<blockquote>
<p>What is the format of port mapping?</p>
</blockquote>
<p><strong>Answer</strong></p>
<p>HOST_PORT</p>
<hr />
<h3>Environment Variables</h3>
<p>Pass runtime variables.</p>
<pre><code class="language-yaml">environment:
  NODE_ENV: production
  PORT: 3000
</code></pre>
<p>Example:</p>
<pre><code class="language-yaml">services:
  backend:
    environment:
      DATABASE_URL: postgres://user:pass@db:5432/app
</code></pre>
<p>Access:</p>
<pre><code class="language-javascript">process.env.DATABASE_URL
</code></pre>
<hr />
<h3>Env File</h3>
<p>Store variables in a separate file.</p>
<p><code>.env</code></p>
<pre><code class="language-env">DATABASE_URL=mydb
PORT=3000
</code></pre>
<p>Compose:</p>
<pre><code class="language-yaml">env_file:
  - .env
</code></pre>
<p>Benefits:</p>
<ul>
<li><p>Cleaner configuration</p>
</li>
<li><p>Easier secret management</p>
</li>
</ul>
<hr />
<h3>Volumes</h3>
<p>Volumes persist data.</p>
<pre><code class="language-yaml">volumes:
  - postgres-data:/var/lib/postgresql/data
</code></pre>
<p>Without volumes:</p>
<pre><code class="language-text">Container Deleted
      ↓
Data Deleted
</code></pre>
<p>With volumes:</p>
<pre><code class="language-text">Container Deleted
      ↓
Data Preserved
</code></pre>
<p>Common use cases:</p>
<ul>
<li><p>PostgreSQL</p>
</li>
<li><p>MySQL</p>
</li>
<li><p>MongoDB</p>
</li>
<li><p>File uploads</p>
</li>
</ul>
<hr />
<h3>Named Volumes</h3>
<pre><code class="language-yaml">services:
  postgres:
    image: postgres:16
    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  postgres-data:
</code></pre>
<p>Docker manages storage automatically.</p>
<hr />
<h3>Bind Mounts</h3>
<p>Map local folders into containers.</p>
<pre><code class="language-yaml">volumes:
  - .:/app
</code></pre>
<p>Benefits:</p>
<ul>
<li><p>Live code updates</p>
</li>
<li><p>Faster development</p>
</li>
</ul>
<p>Common for Next.js and Node.js projects.</p>
<hr />
<h3>Networks</h3>
<p>Compose automatically creates a network.</p>
<p>Example:</p>
<pre><code class="language-yaml">services:
  backend:
  postgres:
</code></pre>
<p>Backend can connect to database using:</p>
<pre><code class="language-text">postgres
</code></pre>
<p>instead of:</p>
<pre><code class="language-text">localhost
</code></pre>
<p>Connection string:</p>
<pre><code class="language-env">DATABASE_URL=postgresql://user:pass@postgres:5432/db
</code></pre>
<p>Interview Question:</p>
<blockquote>
<p>How do containers communicate inside Docker Compose?</p>
</blockquote>
<p><strong>Answer</strong></p>
<p>Containers communicate through the automatically created Docker network using service names.</p>
<hr />
<h3>Depends On</h3>
<p>Controls startup order.</p>
<pre><code class="language-yaml">services:
  backend:
    depends_on:
      - postgres
</code></pre>
<p>Docker starts:</p>
<pre><code class="language-text">Postgres
    ↓
Backend
</code></pre>
<p>Important:</p>
<p>depends_on does not wait until the database is ready.</p>
<p>It only starts containers in order.</p>
<p>Interview Question:</p>
<blockquote>
<p>Does depends_on guarantee database readiness?</p>
</blockquote>
<p><strong>Answer</strong></p>
<p>No. It only guarantees startup order.</p>
<hr />
<h3>Restart Policies</h3>
<p>Automatically restart containers.</p>
<pre><code class="language-yaml">restart: always
</code></pre>
<p>Options:</p>
<pre><code class="language-yaml">restart: always

restart: unless-stopped

restart: on-failure

restart: no
</code></pre>
<p>Common production setting:</p>
<pre><code class="language-yaml">restart: unless-stopped
</code></pre>
<hr />
<h3>Command</h3>
<p>Override Dockerfile CMD.</p>
<p>Dockerfile:</p>
<pre><code class="language-dockerfile">CMD ["npm", "start"]
</code></pre>
<p>Compose:</p>
<pre><code class="language-yaml">command: npm run dev
</code></pre>
<p>Compose command takes precedence.</p>
<hr />
<h3>Healthcheck</h3>
<p>Monitors container health.</p>
<pre><code class="language-yaml">healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost:3000"]
  interval: 30s
  timeout: 10s
  retries: 3
</code></pre>
<p>Benefits:</p>
<ul>
<li><p>Better monitoring</p>
</li>
<li><p>Automatic recovery</p>
</li>
<li><p>Production readiness</p>
</li>
</ul>
<hr />
<h3>Profiles</h3>
<p>Run only selected services.</p>
<pre><code class="language-yaml">services:
  postgres:
    profiles:
      - development
</code></pre>
<p>Run:</p>
<pre><code class="language-bash">docker compose --profile development up
</code></pre>
<p>Useful for:</p>
<ul>
<li><p>Development</p>
</li>
<li><p>Testing</p>
</li>
<li><p>Production</p>
</li>
</ul>
<hr />
<h3>Real World Example</h3>
<p>Node.js + PostgreSQL</p>
<pre><code class="language-yaml">services:
  backend:
    build: .

    ports:
      - "3000:3000"

    environment:
      DATABASE_URL: postgresql://admin:secret@postgres:5432/app

    depends_on:
      - postgres

  postgres:
    image: postgres:16

    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app

    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  postgres-data:
</code></pre>
<p>Start:</p>
<pre><code class="language-bash">docker compose up
</code></pre>
<p>Everything starts automatically.</p>
<hr />
<h3>Common Docker Compose Commands</h3>
<p>Start:</p>
<pre><code class="language-bash">docker compose up
</code></pre>
<p>Background mode:</p>
<pre><code class="language-bash">docker compose up -d
</code></pre>
<p>Stop:</p>
<pre><code class="language-bash">docker compose down
</code></pre>
<p>View logs:</p>
<pre><code class="language-bash">docker compose logs
</code></pre>
<p>Follow logs:</p>
<pre><code class="language-bash">docker compose logs -f
</code></pre>
<p>List containers:</p>
<pre><code class="language-bash">docker compose ps
</code></pre>
<p>Restart:</p>
<pre><code class="language-bash">docker compose restart
</code></pre>
<p>Build:</p>
<pre><code class="language-bash">docker compose build
</code></pre>
<p>Rebuild:</p>
<pre><code class="language-bash">docker compose up --build
</code></pre>
<hr />
<h3>Common Interview Questions</h3>
<h4>What is Docker Compose?</h4>
<p>A tool used to define and manage multi-container Docker applications using a YAML file.</p>
<hr />
<h4>Dockerfile vs Docker Compose?</h4>
<table>
<thead>
<tr>
<th>Dockerfile</th>
<th>Docker Compose</th>
</tr>
</thead>
<tbody><tr>
<td>Builds Images</td>
<td>Runs Containers</td>
</tr>
<tr>
<td>Defines Environment</td>
<td>Defines Services</td>
</tr>
<tr>
<td>Creates Images</td>
<td>Creates Application Stack</td>
</tr>
</tbody></table>
<hr />
<h4>How do containers communicate?</h4>
<p>Through Docker networks using service names.</p>
<hr />
<h4>What is depends_on?</h4>
<p>Defines container startup order.</p>
<hr />
<h4>Does depends_on wait for readiness?</h4>
<p>No.</p>
<hr />
<h4>What is the purpose of volumes?</h4>
<p>Persistent data storage.</p>
<hr />
<h4>What is the difference between bind mounts and named volumes?</h4>
<table>
<thead>
<tr>
<th>Bind Mount</th>
<th>Named Volume</th>
</tr>
</thead>
<tbody><tr>
<td>Uses Host Directory</td>
<td>Managed By Docker</td>
</tr>
<tr>
<td>Good For Development</td>
<td>Good For Production</td>
</tr>
</tbody></table>
<hr />
<h4>What happens when docker compose down is executed?</h4>
<p>Containers and networks are removed.</p>
<p>Volumes remain unless explicitly deleted.</p>
<hr />
<h4>Can Compose build images?</h4>
<p>Yes.</p>
<p>Using:</p>
<pre><code class="language-yaml">build: .
</code></pre>
<hr />
<h3>Production Best Practices</h3>
<ol>
<li>Use explicit image versions.</li>
</ol>
<pre><code class="language-yaml">image: postgres:16
</code></pre>
<p>Avoid:</p>
<pre><code class="language-yaml">image: postgres:latest
</code></pre>
<ol>
<li><p>Use healthchecks.</p>
</li>
<li><p>Use named volumes for databases.</p>
</li>
<li><p>Store secrets in environment files.</p>
</li>
<li><p>Separate development and production configurations.</p>
</li>
<li><p>Use restart policies.</p>
</li>
<li><p>Avoid hardcoded credentials.</p>
</li>
<li><p>Keep services isolated.</p>
</li>
</ol>
<hr />
<h3>Common Mistakes</h3>
<table>
<thead>
<tr>
<th>Mistake</th>
<th>Problem</th>
</tr>
</thead>
<tbody><tr>
<td>Using latest tag</td>
<td>Unexpected updates</td>
</tr>
<tr>
<td>No volumes</td>
<td>Data loss</td>
</tr>
<tr>
<td>No healthchecks</td>
<td>Difficult monitoring</td>
</tr>
<tr>
<td>Hardcoded secrets</td>
<td>Security risk</td>
</tr>
<tr>
<td>Using localhost for DB</td>
<td>Container communication failure</td>
</tr>
</tbody></table>
<hr />
<h3>Docker Compose Revision Sheet</h3>
<table>
<thead>
<tr>
<th>Keyword</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>services</td>
<td>Define containers</td>
</tr>
<tr>
<td>build</td>
<td>Build image</td>
</tr>
<tr>
<td>image</td>
<td>Pull image</td>
</tr>
<tr>
<td>container_name</td>
<td>Custom name</td>
</tr>
<tr>
<td>ports</td>
<td>Port mapping</td>
</tr>
<tr>
<td>environment</td>
<td>Runtime variables</td>
</tr>
<tr>
<td>env_file</td>
<td>External variables</td>
</tr>
<tr>
<td>volumes</td>
<td>Persistent storage</td>
</tr>
<tr>
<td>networks</td>
<td>Service communication</td>
</tr>
<tr>
<td>depends_on</td>
<td>Startup order</td>
</tr>
<tr>
<td>restart</td>
<td>Auto restart</td>
</tr>
<tr>
<td>command</td>
<td>Override CMD</td>
</tr>
<tr>
<td>healthcheck</td>
<td>Health monitoring</td>
</tr>
<tr>
<td>profiles</td>
<td>Environment-specific services</td>
</tr>
</tbody></table>
<h2>Docker Compose Interview Scenarios</h2>
<p>In real interviews, Docker Compose questions are usually scenario-based.</p>
<p>Interviewers want to evaluate:</p>
<ul>
<li><p>Service communication</p>
</li>
<li><p>Networking knowledge</p>
</li>
<li><p>Volume management</p>
</li>
<li><p>Environment variables</p>
</li>
<li><p>Startup dependencies</p>
</li>
<li><p>Production readiness</p>
</li>
</ul>
<p>This guide contains common interview scenarios and their solutions.</p>
<hr />
<h2>Scenario 1: Backend + PostgreSQL</h2>
<h3>Interview Question</h3>
<p>You have a Node.js backend and PostgreSQL database.</p>
<p>Requirements:</p>
<ul>
<li><p>Backend should run on port 3000</p>
</li>
<li><p>PostgreSQL should run on port 5432</p>
</li>
<li><p>Backend should connect to PostgreSQL</p>
</li>
<li><p>Database data should persist after container restart</p>
</li>
</ul>
<p>Write a Docker Compose file.</p>
<hr />
<h3>Solution</h3>
<pre><code class="language-yaml">services:
  backend:
    build: .

    ports:
      - "3000:3000"

    environment:
      DATABASE_URL: postgresql://admin:secret@postgres:5432/app

    depends_on:
      - postgres

  postgres:
    image: postgres:16

    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app

    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  postgres-data:
</code></pre>
<hr />
<h3>Interview Explanation</h3>
<p>Backend connects using:</p>
<pre><code class="language-text">postgres
</code></pre>
<p>NOT</p>
<pre><code class="language-text">localhost
</code></pre>
<p>Because containers communicate through service names.</p>
<p>Correct:</p>
<pre><code class="language-env">DATABASE_URL=postgresql://admin:secret@postgres:5432/app
</code></pre>
<p>Wrong:</p>
<pre><code class="language-env">DATABASE_URL=postgresql://admin:secret@localhost:5432/app
</code></pre>
<hr />
<h3>Follow-Up Questions</h3>
<h4>Why use a volume?</h4>
<p>To prevent database data loss.</p>
<h4>Why use depends_on?</h4>
<p>To ensure PostgreSQL starts before Backend.</p>
<h4>Does depends_on wait for database readiness?</h4>
<p>No.</p>
<hr />
<h2>Scenario 2: Backend + Redis</h2>
<h3>Interview Question</h3>
<p>Create a Compose file where:</p>
<ul>
<li><p>Backend runs on port 3000</p>
</li>
<li><p>Redis runs on port 6379</p>
</li>
<li><p>Backend uses Redis for caching</p>
</li>
</ul>
<hr />
<h3>Solution</h3>
<pre><code class="language-yaml">services:
  backend:
    build: .

    ports:
      - "3000:3000"

    environment:
      REDIS_URL: redis://redis:6379

    depends_on:
      - redis

  redis:
    image: redis:7
</code></pre>
<hr />
<h3>Interview Explanation</h3>
<p>Backend can access Redis using:</p>
<pre><code class="language-text">redis
</code></pre>
<p>because Redis service name becomes DNS hostname.</p>
<hr />
<h3>Follow-Up Question</h3>
<p>How does Backend discover Redis?</p>
<p>Answer:</p>
<p>Docker Compose automatically creates a network and service names become hostnames.</p>
<hr />
<h2>Scenario 3: Frontend + Backend</h2>
<h3>Interview Question</h3>
<p>You have:</p>
<ul>
<li><p>React Frontend</p>
</li>
<li><p>Express Backend</p>
</li>
</ul>
<p>Both should communicate through Docker network.</p>
<p>Frontend runs on:</p>
<pre><code class="language-text">localhost:5173
</code></pre>
<p>Backend runs on:</p>
<pre><code class="language-text">localhost:3000
</code></pre>
<hr />
<h3>Solution</h3>
<pre><code class="language-yaml">services:
  frontend:
    build: ./frontend

    ports:
      - "5173:5173"

  backend:
    build: ./backend

    ports:
      - "3000:3000"
</code></pre>
<hr />
<h3>Communication</h3>
<p>Frontend should call:</p>
<pre><code class="language-text">http://backend:3000
</code></pre>
<p>inside Docker network.</p>
<p>Not:</p>
<pre><code class="language-text">http://localhost:3000
</code></pre>
<hr />
<h3>Interview Trap</h3>
<p>Many candidates use:</p>
<pre><code class="language-text">localhost
</code></pre>
<p>This is wrong because each container has its own localhost.</p>
<hr />
<h2>Scenario 4: Full Stack Application</h2>
<h3>Interview Question</h3>
<p>Create a Compose file containing:</p>
<ul>
<li><p>Next.js</p>
</li>
<li><p>Express</p>
</li>
<li><p>PostgreSQL</p>
</li>
<li><p>Redis</p>
</li>
</ul>
<p>All services should communicate.</p>
<hr />
<h3>Solution</h3>
<pre><code class="language-yaml">services:
  frontend:
    build: ./frontend

    ports:
      - "3000:3000"

  backend:
    build: ./backend

    ports:
      - "4000:4000"

    environment:
      DATABASE_URL: postgresql://admin:secret@postgres:5432/app

      REDIS_URL: redis://redis:6379

    depends_on:
      - postgres
      - redis

  postgres:
    image: postgres:16

    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app

    volumes:
      - postgres-data:/var/lib/postgresql/data

  redis:
    image: redis:7

volumes:
  postgres-data:
</code></pre>
<hr />
<h3>Architecture</h3>
<pre><code class="language-text">Frontend
    ↓
Backend
   ↓ ↓
Redis PostgreSQL
</code></pre>
<hr />
<h3>Follow-Up Questions</h3>
<p>How many networks are created?</p>
<p>Answer:</p>
<p>One default network.</p>
<hr />
<p>How does Backend connect to PostgreSQL?</p>
<p>Answer:</p>
<p>Using hostname:</p>
<pre><code class="language-text">postgres
</code></pre>
<hr />
<p>How does Backend connect to Redis?</p>
<p>Answer:</p>
<p>Using hostname:</p>
<pre><code class="language-text">redis
</code></pre>
<hr />
<h2>Scenario 5: Custom Network</h2>
<h3>Interview Question</h3>
<p>Create two services that communicate using a custom Docker network.</p>
<hr />
<h3>Solution</h3>
<pre><code class="language-yaml">services:
  backend:
    build: .

    networks:
      - app-network

  postgres:
    image: postgres:16

    networks:
      - app-network

networks:
  app-network:
</code></pre>
<hr />
<h3>Architecture</h3>
<pre><code class="language-text">backend
     ↓
app-network
     ↑
postgres
</code></pre>
<hr />
<h3>Interview Explanation</h3>
<p>Both services belong to the same network.</p>
<p>Therefore:</p>
<pre><code class="language-text">backend
</code></pre>
<p>can communicate with:</p>
<pre><code class="language-text">postgres
</code></pre>
<hr />
<h2>Scenario 6: Multiple Networks</h2>
<h3>Interview Question</h3>
<p>You have:</p>
<ul>
<li><p>Frontend</p>
</li>
<li><p>Backend</p>
</li>
<li><p>Database</p>
</li>
</ul>
<p>Database should NOT be accessible by Frontend.</p>
<p>Design the network architecture.</p>
<hr />
<h3>Solution</h3>
<pre><code class="language-yaml">services:
  frontend:
    build: ./frontend

    networks:
      - public

  backend:
    build: ./backend

    networks:
      - public
      - private

  postgres:
    image: postgres:16

    networks:
      - private

networks:
  public:
  private:
</code></pre>
<hr />
<h3>Architecture</h3>
<pre><code class="language-text">Frontend
    |
 Public
    |
Backend
    |
 Private
    |
Postgres
</code></pre>
<hr />
<h3>Why?</h3>
<p>Frontend cannot directly access PostgreSQL.</p>
<p>Only Backend can.</p>
<p>This is a common production setup.</p>
<hr />
<h2>Scenario 7: Persistent Database</h2>
<h3>Interview Question</h3>
<p>Your PostgreSQL data disappears after container recreation.</p>
<p>How would you fix it?</p>
<hr />
<h3>Solution</h3>
<pre><code class="language-yaml">services:
  postgres:
    image: postgres:16

    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  postgres-data:
</code></pre>
<hr />
<h3>Follow-Up Question</h3>
<p>What happens if the container is deleted?</p>
<p>Answer:</p>
<p>Data remains inside the volume.</p>
<hr />
<h2>Scenario 8: Environment Variables</h2>
<h3>Interview Question</h3>
<p>Move all sensitive values out of compose.yml.</p>
<hr />
<h3>Solution</h3>
<p>.env</p>
<pre><code class="language-env">POSTGRES_USER=admin
POSTGRES_PASSWORD=secret
POSTGRES_DB=app
</code></pre>
<p>compose.yml</p>
<pre><code class="language-yaml">services:
  postgres:
    image: postgres:16

    env_file:
      - .env
</code></pre>
<hr />
<h3>Why?</h3>
<p>Better security.</p>
<p>Cleaner configuration.</p>
<hr />
<h2>Scenario 9: Health Checks</h2>
<h3>Interview Question</h3>
<p>Ensure Backend starts only when PostgreSQL becomes healthy.</p>
<hr />
<h3>Solution</h3>
<pre><code class="language-yaml">services:
  postgres:
    image: postgres:16

    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]

      interval: 10s

      timeout: 5s

      retries: 5
</code></pre>
<hr />
<h3>Interview Explanation</h3>
<p>Health checks allow Docker to monitor service readiness.</p>
<hr />
<h2>Scenario 10: Production Ready Compose</h2>
<h3>Interview Question</h3>
<p>What would you add before deploying to production?</p>
<hr />
<h3>Expected Answer</h3>
<ul>
<li><p>Named volumes</p>
</li>
<li><p>Health checks</p>
</li>
<li><p>Restart policies</p>
</li>
<li><p>Environment files</p>
</li>
<li><p>Fixed image versions</p>
</li>
<li><p>Separate networks</p>
</li>
<li><p>Resource limits</p>
</li>
<li><p>Logging configuration</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-yaml">restart: unless-stopped
</code></pre>
<pre><code class="language-yaml">healthcheck:
</code></pre>
<pre><code class="language-yaml">volumes:
</code></pre>
<pre><code class="language-yaml">env_file:
</code></pre>
<hr />
<h2>Most Common Interview Traps</h2>
<h3>Trap 1</h3>
<p>Using localhost between containers.</p>
<p>Wrong:</p>
<pre><code class="language-text">localhost
</code></pre>
<p>Correct:</p>
<pre><code class="language-text">service-name
</code></pre>
<hr />
<h3>Trap 2</h3>
<p>No volume for database.</p>
<p>Result:</p>
<pre><code class="language-text">Container Deleted
      ↓
Data Lost
</code></pre>
<hr />
<h3>Trap 3</h3>
<p>Using latest image tag.</p>
<p>Wrong:</p>
<pre><code class="language-yaml">image: postgres:latest
</code></pre>
<p>Correct:</p>
<pre><code class="language-yaml">image: postgres:16
</code></pre>
<hr />
<h3>Trap 4</h3>
<p>Thinking depends_on waits for readiness.</p>
<p>It does not.</p>
<p>It only controls startup order.</p>
<hr />
<h3>Trap 5</h3>
<p>Exposing database publicly.</p>
<p>Wrong:</p>
<pre><code class="language-yaml">ports:
  - "5432:5432"
</code></pre>
<p>Not always necessary.</p>
<p>Expose only when needed.</p>
<hr />
<h2>15-Minute Interview Revision</h2>
<table>
<thead>
<tr>
<th>Question</th>
<th>Expected Answer</th>
</tr>
</thead>
<tbody><tr>
<td>How do containers communicate?</td>
<td>Service Name</td>
</tr>
<tr>
<td>What creates networking?</td>
<td>Docker Compose</td>
</tr>
<tr>
<td>How to persist data?</td>
<td>Volumes</td>
</tr>
<tr>
<td>Build vs Image?</td>
<td>Custom vs Existing Image</td>
</tr>
<tr>
<td>What is depends_on?</td>
<td>Startup Order</td>
</tr>
<tr>
<td>Does depends_on wait?</td>
<td>No</td>
</tr>
<tr>
<td>How to store secrets?</td>
<td>env_file</td>
</tr>
<tr>
<td>Why healthchecks?</td>
<td>Readiness Monitoring</td>
</tr>
<tr>
<td>Why custom networks?</td>
<td>Isolation</td>
</tr>
<tr>
<td>Why named volumes?</td>
<td>Data Persistence</td>
</tr>
</tbody></table>
<h3>Conclusion</h3>
<p>Docker Compose is used to manage multiple containers as a single application. It simplifies networking, storage, environment configuration, startup order, and deployment. Understanding services, build, image, ports, environment variables, volumes, networks, and depends_on is sufficient for handling most real-world projects and Docker-related interviews.</p>
]]></content:encoded></item><item><title><![CDATA[Sharding, Replication and System Design Week 51.1 Cohort 3.0
]]></title><description><![CDATA[Stateless vs Stateful Backend
Stateless backend
Each request is independent. The server does not keep client session state between requests.
Any server instance can handle any request if it has access]]></description><link>https://blog.adityaguptareal.com/sharding-replication-and-system-design</link><guid isPermaLink="true">https://blog.adityaguptareal.com/sharding-replication-and-system-design</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Tue, 26 May 2026 04:12:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/194b0bf4-416f-4d8b-afae-04fcee66a227.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Stateless vs Stateful Backend</h2>
<h3>Stateless backend</h3>
<p>Each request is independent. The server does not keep client session state between requests.</p>
<p>Any server instance can handle any request if it has access to shared resources (database, cache).</p>
<h3>Stateful backend</h3>
<p>Server keeps client-specific state across requests (session, in-memory game state, websocket connection state).</p>
<p>Requests from the same client often need the same server instance or a way to retrieve that state.</p>
<h3>When to choose</h3>
<ul>
<li><p>Use stateless when possible (typical web APIs, microservices, REST/HTTP services).</p>
</li>
<li><p>Use stateful when you need low-latency in-memory state or long-lived bidirectional connections and state replication is impractical.</p>
</li>
</ul>
<h3>Examples</h3>
<ul>
<li><p>Stateless: REST API, microservices reading DB, serverless functions.</p>
</li>
<li><p>Stateful: multiplayer game servers, WebSocket chat servers maintaining connection-specific state, in-memory queued tasks per user.</p>
</li>
</ul>
<h3>Common designs to combine strengths</h3>
<ul>
<li><p>Keep core logic stateless; store session or user state in a shared store (Redis, DB).</p>
</li>
<li><p>Use stateful servers only where needed and front them with a load balancer and sticky sessions, or use a dedicated routing layer.</p>
</li>
</ul>
<hr />
<h2>Stateless vs Stateful</h2>
<table>
<thead>
<tr>
<th>Aspect</th>
<th>Stateless</th>
<th>Stateful</th>
</tr>
</thead>
<tbody><tr>
<td>Request handling</td>
<td>Any instance can handle any request</td>
<td>Requests may need a specific instance</td>
</tr>
<tr>
<td>Horizontal scaling</td>
<td>Easy</td>
<td>Harder (needs sticky routing / replication)</td>
</tr>
<tr>
<td>Failure recovery</td>
<td>Simple (restart any instance)</td>
<td>Complex (must recover in-memory state)</td>
</tr>
<tr>
<td>Session storage</td>
<td>External (DB/Redis)</td>
<td>Often in-process memory</td>
</tr>
<tr>
<td>Use cases</td>
<td>REST APIs, microservices, serverless</td>
<td>Game servers, long-lived sockets, session-heavy apps</td>
</tr>
<tr>
<td>Best for</td>
<td>High scale, simple deployment</td>
<td>Low-latency, connection-oriented workloads</td>
</tr>
</tbody></table>
<hr />
<h2>Scaling Node.js With the Cluster Module</h2>
<h3>What Cluster does</h3>
<p>Node.js Cluster runs multiple Node.js worker processes that share the same server port.</p>
<p>Each worker is a separate process using its own event loop and memory - lets you use multi-core machines.</p>
<p>master process distributes connections to workers (Node handles the LB across workers).</p>
<h3>Benefits</h3>
<ul>
<li><p>Simple way to utilize all CPU cores on one machine.</p>
</li>
<li><p>Auto-restart crashed workers (supervisor behavior via master).</p>
</li>
</ul>
<h3>Limitations &amp; considerations</h3>
<ul>
<li><p>Works only on a single host. To scale across machines you still need a load balancer or service mesh.</p>
</li>
<li><p>Workers do not share memory — use Redis/DB for shared state.</p>
</li>
<li><p>Not a replacement for process managers (PM2, Docker orchestration). Use cluster + process manager or container orchestrator.</p>
</li>
<li><p>Sticky sessions: if your app is stateful (needs the same worker), Node’s default distribution is not sticky. You may need an external sticky LB or a custom master distribution.</p>
</li>
</ul>
<h3>Alternatives / complements</h3>
<ul>
<li><p>PM2 cluster mode (manages forks and restarts).</p>
</li>
<li><p>Worker threads (for CPU-bound tasks within one process).</p>
</li>
<li><p>Multiple containers / pods behind a load balancer for multi-host scaling (Kubernetes, ECS).</p>
</li>
</ul>
<p><strong>Example</strong></p>
<h2>Scaling Stateless Backend: Load Balancer Patterns</h2>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/9575ec79-fd5d-4b82-8217-85e554bc9e1b.png" alt="" style="display:block;margin:0 auto" />

<h3>Why load balancers</h3>
<ul>
<li><p>Distribute incoming requests across multiple backend instances.</p>
</li>
<li><p>Improve availability (health checks, failover).</p>
</li>
<li><p>Centralize cross-cutting concerns (SSL termination, rate limits, authentication gateways).</p>
</li>
</ul>
<h3>Types of load balancers (simple)</h3>
<ul>
<li><p>Layer 4 (Transport): TCP/UDP level; efficient, fast. e.g., many cloud LBs in TCP mode.</p>
</li>
<li><p>Layer 7 (Application): HTTP-aware; can route by URL, headers; supports SSL termination and advanced routing. e.g., NGINX, HAProxy, ALB (AWS).</p>
</li>
</ul>
<h3>Key features to use for stateless services</h3>
<ul>
<li><p><strong>Health checks:</strong> automatically remove unhealthy instances.</p>
</li>
<li><p><strong>Auto-scaling integration:</strong> add/remove instances based on metrics.</p>
</li>
<li><p><strong>SSL/TLS termination:</strong> offload crypto to LB to simplify backends.</p>
</li>
<li><p><strong>HTTP routing and path-based rules:</strong> send traffic to appropriate services.</p>
</li>
<li><p><strong>Sticky sessions:</strong> not needed for stateless backends — avoid when possible.</p>
</li>
<li><p><strong>Rate limiting + WAF:</strong> protect backends from abuse and attacks.</p>
</li>
<li><p><strong>Connection reuse and keepalive:</strong> improve latency and resource usage.</p>
</li>
</ul>
<h3>Load balancing algorithms</h3>
<ul>
<li><p><strong>Round robin:</strong> simple, evenly distributes.</p>
</li>
<li><p><strong>Least connections:</strong> prefers less-busy instances (good for uneven request durations).</p>
</li>
<li><p><strong>IP hash:</strong> deterministic routing (can be used for “soft” stickiness).</p>
</li>
<li><p><strong>Weighted routing:</strong> prefer stronger/faster instances.</p>
</li>
</ul>
<h3>Sticky sessions and statelessness</h3>
<p>Avoid sticky sessions for stateless services — they reduce scheduler flexibility and can cause hot spots.</p>
<p>If you must support sessions: store session in a fast shared store (Redis) and keep backends stateless.</p>
<h2>SSL Termination on Load Balancer</h2>
<h2>Rate Limiting on Load Balancer Level</h2>
<h2>DDos Protection on Load Balancer Level</h2>
<h2>Auto Scaling VS Mannual Scaling</h2>
<h2>Sticky Backend (Sticky Connection)</h2>
<h2>Scaling Stateful Backend Server</h2>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/e9a2df1f-1260-402e-813f-6251e85f8928.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/7de53171-27e6-4aea-ac07-d7c6066c2365.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/8ebdd620-2ed3-492f-bbca-7d5643a58473.png" alt="" style="display:block;margin:0 auto" />

<p>Mostly done manually</p>
<p>ASGs/MIGs let you do metric based scaling</p>
<p>K8s has HPA that lets you scale pods and nodes</p>
<p>Karpenter lets you scale node pools based on applications</p>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/ece46f85-b871-438f-bc20-1ec66d6fc9a2.png" alt="" style="display:block;margin:0 auto" />

<h2>Stopping bot abuse and bulk buying for high-demand releases like tickets and sneaker drops</h2>
<p>Distributed bots use many IPs, like proxies and botnets, making IP limits useless. Attackers can bypass IP or session limits with multiple accounts or stolen credentials. Bots mimic human-like requests to avoid detection.</p>
<p><strong>CAPTCHA farms</strong> let attackers use real people to solve challenges, making low-rate defenses weak. Strict limits can hurt real users during traffic spikes, so thresholds are kept low, which attackers exploit. Attackers also spread requests over time and different endpoints to avoid simple rate limits.</p>
<h3>CAPTCHAs + rate limiting - why combine them</h3>
<ul>
<li><p><strong>Layered defense:</strong> rate limits slow mass requests; CAPTCHAs raise attacker cost by requiring human (or costly solver) involvement.</p>
</li>
<li><p><strong>Adaptive application:</strong> show CAPTCHAs only after suspicious behavior or rate-thresholds, reducing friction for normal users.</p>
</li>
<li><p><strong>Reduce solver ROI:</strong> limits constrain how many CAPTCHA solves an attacker can use, making bulk buys expensive or slow.</p>
</li>
<li><p><strong>Complementary signals:</strong> CAPTCHA failures, challenge frequency, and rate-limit hits feed a risk score for stronger actions (block, require verification, queue).</p>
</li>
</ul>
<p>Combine adaptive rate limiting, targeted CAPTCHAs, behavioral analysis, and policies (per-user quotas, verified accounts, lotteries/queues) for effective protection without wrecking UX.</p>
<h2>How to Add Frontend Page Captcha with Cloudflare</h2>
<p>Cloudflare provides an easy way to protect your frontend pages from spam, bots, fake signups, credential stuffing, and automated attacks using <strong>Turnstile Captcha</strong>. Unlike traditional captchas, Cloudflare Turnstile focuses on user privacy and smooth user experience.</p>
<h3>Steps to Add Cloudflare Turnstile Captcha</h3>
<h3>1. Create a Turnstile Site</h3>
<ol>
<li><p>Go to Cloudflare Turnstile</p>
</li>
<li><p>Login to your Cloudflare account</p>
</li>
<li><p>Create a new Turnstile widget</p>
</li>
<li><p>Add your domain</p>
</li>
<li><p>Copy:</p>
<ul>
<li><p><strong>Site Key</strong></p>
</li>
<li><p><strong>Secret Key</strong></p>
</li>
</ul>
</li>
</ol>
<h3>2. Add Captcha Widget in Frontend</h3>
<pre><code class="language-html">&lt;form id="signup-form"&gt;
  &lt;input type="email" placeholder="Enter Email" /&gt;

  &lt;div
    class="cf-turnstile"
    data-sitekey="YOUR_SITE_KEY"&gt;
  &lt;/div&gt;

  &lt;button type="submit"&gt;Submit&lt;/button&gt;
&lt;/form&gt;

&lt;script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer&gt;&lt;/script&gt;
</code></pre>
<h3>3. Verify Captcha on Backend</h3>
<p>Never trust only frontend validation. Always verify captcha response from backend.</p>
<p>Example using Node.js:</p>
<pre><code class="language-js">const axios = require("axios");

app.post("/submit", async (req, res) =&gt; {

   const token = req.body["cf-turnstile-response"];

   const response = await axios.post(
      "https://challenges.cloudflare.com/turnstile/v0/siteverify",
      new URLSearchParams({
         secret: process.env.TURNSTILE_SECRET,
         response: token
      })
   );

   if(response.data.success){
      return res.send("Human Verified");
   }

   res.status(400).send("Captcha Failed");

});
</code></pre>
<hr />
<h3>Features of Cloudflare Turnstile</h3>
<ul>
<li><p>No annoying image puzzles in many cases</p>
</li>
<li><p>Privacy-focused alternative to reCAPTCHA</p>
</li>
<li><p>Reduces fake signup attacks</p>
</li>
<li><p>Works against automated scripts and bots</p>
</li>
<li><p>Easy frontend integration</p>
</li>
<li><p>Backend verification support</p>
</li>
<li><p>Supports invisible verification mode</p>
</li>
</ul>
<h2>Frontend Captcha vs Backend Captcha</h2>
<p>Both frontend and backend captchas are important, but they serve different purposes.</p>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Frontend Captcha</th>
<th>Backend Captcha Verification</th>
</tr>
</thead>
<tbody><tr>
<td>Runs On</td>
<td>Browser/UI</td>
<td>Server</td>
</tr>
<tr>
<td>Purpose</td>
<td>User interaction validation</td>
<td>Actual security verification</td>
</tr>
<tr>
<td>Security Level</td>
<td>Medium</td>
<td>High</td>
</tr>
<tr>
<td>Can Be Bypassed</td>
<td>Yes</td>
<td>Harder</td>
</tr>
<tr>
<td>Prevents Fake Requests</td>
<td>Partially</td>
<td>Strongly</td>
</tr>
<tr>
<td>User Experience</td>
<td>Visible to user</td>
<td>Invisible</td>
</tr>
<tr>
<td>Recommended</td>
<td>Yes</td>
<td>Mandatory</td>
</tr>
</tbody></table>
<h3>Frontend Captcha</h3>
<p>Frontend captcha is the visible challenge shown to the user before form submission.</p>
<p>Examples:</p>
<ul>
<li><p>Checkbox verification</p>
</li>
<li><p>Image selection</p>
</li>
<li><p>Invisible behavioral detection</p>
</li>
</ul>
<h4>Limitation</h4>
<p>Attackers can directly hit your backend API and bypass frontend checks if backend verification is missing.</p>
<h3>Backend Captcha Verification</h3>
<p>Backend verification validates the captcha token with Cloudflare servers.</p>
<h4>Why It Is Important</h4>
<p>Without backend verification:</p>
<ul>
<li><p>Anyone can fake requests</p>
</li>
<li><p>Bots can bypass frontend UI</p>
</li>
<li><p>API endpoints remain vulnerable</p>
</li>
</ul>
<h4>Best Practice</h4>
<p>Always use:</p>
<ol>
<li><p>Frontend captcha widget</p>
</li>
<li><p>Backend token verification</p>
</li>
<li><p>Rate limiting</p>
</li>
<li><p>WAF protection</p>
</li>
</ol>
<p>Together they create layered security.</p>
<h2>Invisible Captchas vs Visible Captchas in Cloudflare</h2>
<p>Cloudflare Turnstile supports both invisible and visible captcha modes.</p>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Invisible Captcha</th>
<th>Visible Captcha</th>
</tr>
</thead>
<tbody><tr>
<td>User Interaction</td>
<td>Minimal</td>
<td>Required sometimes</td>
</tr>
<tr>
<td>UX Experience</td>
<td>Smooth</td>
<td>Slight interruption</td>
</tr>
<tr>
<td>Bot Detection</td>
<td>Behavioral analysis</td>
<td>Challenge-based</td>
</tr>
<tr>
<td>Accessibility</td>
<td>Better</td>
<td>Moderate</td>
</tr>
<tr>
<td>Security</td>
<td>Good</td>
<td>Strong</td>
</tr>
<tr>
<td>Best Use Case</td>
<td>Modern apps</td>
<td>High-risk forms</td>
</tr>
</tbody></table>
<h2>Bot Protection with Cloudflare by Proxied Request</h2>
<p>One of Cloudflare’s strongest security advantages is its <strong>reverse proxy architecture</strong>.</p>
<p>When Cloudflare proxy is enabled:</p>
<pre><code class="language-text">User → Cloudflare → Your Server
</code></pre>
<p>Your real server IP remains hidden behind Cloudflare infrastructure.</p>
<h3>How Cloudflare Bot Protection Works</h3>
<p>Cloudflare analyzes requests before they reach your server.</p>
<p>It checks IP reputation, request frequency, browser fingerprint, ASN/network reputation, bot signatures, JavaScript execution, TLS fingerprinting, and conducts behavioral analysis. Suspicious traffic can be blocked, challenged, rate limited, redirected, or logged.</p>
<h4>Common Cloudflare Security Features</h4>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>WAF</td>
<td>Blocks malicious requests</td>
</tr>
<tr>
<td>Rate Limiting</td>
<td>Prevents spam/flood attacks</td>
</tr>
<tr>
<td>Bot Protection</td>
<td>Detects automated traffic</td>
</tr>
<tr>
<td>DDoS Protection</td>
<td>Prevents server overload</td>
</tr>
<tr>
<td>SSL/TLS</td>
<td>Encrypts traffic</td>
</tr>
<tr>
<td>CDN</td>
<td>Improves speed globally</td>
</tr>
</tbody></table>
<hr />
<h3>AWS Has Similar Service Called WAF</h3>
<p>Amazon Web Services also provides security services similar to Cloudflare.</p>
<p>The major one is: AWS WAF helps filter and monitor HTTP requests reaching your applications.</p>
<h3>AWS WAF vs Cloudflare</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Cloudflare</th>
<th>AWS WAF</th>
</tr>
</thead>
<tbody><tr>
<td>Works As</td>
<td>Reverse Proxy CDN</td>
<td>Cloud Firewall</td>
</tr>
<tr>
<td>DDoS Protection</td>
<td>Built-in</td>
<td>Via AWS Shield</td>
</tr>
<tr>
<td>Global CDN</td>
<td>Included</td>
<td>CloudFront needed</td>
</tr>
<tr>
<td>Bot Protection</td>
<td>Strong built-in</td>
<td>Additional configs</td>
</tr>
<tr>
<td>Setup Complexity</td>
<td>Easier</td>
<td>More AWS-oriented</td>
</tr>
<tr>
<td>Best For</td>
<td>General web apps</td>
<td>AWS ecosystem apps</td>
</tr>
</tbody></table>
<h3>When to Use Cloudflare</h3>
<p>Use Cloudflare if:</p>
<ul>
<li><p>You want easy setup</p>
</li>
<li><p>You need CDN + security together</p>
</li>
<li><p>You want origin IP protection</p>
</li>
<li><p>You need strong bot mitigation</p>
</li>
<li><p>You want fast global delivery</p>
</li>
</ul>
<h3>When to Use AWS WAF</h3>
<p>Use AWS WAF if:</p>
<ul>
<li><p>Your infrastructure is fully on AWS</p>
</li>
<li><p>You already use CloudFront</p>
</li>
<li><p>You need deep AWS integrations</p>
</li>
<li><p>You want custom enterprise security rules</p>
</li>
</ul>
<h3>How Rate Limiting Can Be Bypassed</h3>
<p>Rate limiting controls incoming server requests to allocate resources fairly and prevent abuse.</p>
<p>However, attackers can bypass limits by distributing requests across multiple IPs or using botnets.</p>
<p>They might also exploit flaws in rate limiting logic, like resetting counters or targeting unprotected endpoints. Understanding these vulnerabilities is key to enhancing security.</p>
<h2>What is CDN ?</h2>
<p>A <em><strong>Content Delivery Network (CDN)</strong></em> is a system of distributed servers that work together to deliver web content quickly to users based on their geographic location.</p>
<p>By caching content closer to the user's location, CDNs reduce latency and improve load times. They also help handle large volumes of traffic and protect against certain types of cyber attacks by distributing the load across multiple servers.</p>
<p>This makes them essential for enhancing the performance and reliability of websites and applications.</p>
<h3>How to Distribute React Frontend with CDN different ways</h3>
<h2>Scaling Databases</h2>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/31d8c384-23f3-45de-8170-9d0526bee2f5.png" alt="" style="display:block;margin:0 auto" />

<h3>Serverless Databases</h3>
<h3>Managed Database</h3>
<h3>Self Hosted Databases</h3>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/f626b3c6-3480-462e-98fd-3437ce9cf8ad.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/49b0de19-1f01-45ce-84a4-360a6435ca0b.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/5151205e-bfc3-4cd3-a69b-f652c022b479.png" alt="" style="display:block;margin:0 auto" />

<p>Good questions</p>
<ol>
<li><p>Distributed vs in mem cache</p>
</li>
<li><p>Write first or read first</p>
</li>
</ol>
<h3>In memory Cache vs Redis Cache</h3>
<h2>Which is the Right operation ordering (client → cache → database)</h2>
<p>Below are common candidate orders for handling a write when you have a client, a Redis cache, and a database.</p>
<ul>
<li><p>Option A — Update the cache, then update the database, then return to the client.</p>
</li>
<li><p>Option B — Update the database, then update the cache, then return to the client.</p>
</li>
<li><p>Option C — Update the database, then invalidate (clear) the cache, then return to the client.</p>
</li>
<li><p>Option D — Invalidate (clear) the cache, then update the database, then return to the client.</p>
</li>
</ul>
<p>Answer : Option D</p>
<h2>Indexing in Databases</h2>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/12f5e567-d4aa-4190-aa03-6e63a5da86a7.png" alt="" style="display:block;margin:0 auto" />

<p>Indexing is a database optimization technique used to make data searching faster. Without indexing, the database scans every row one by one, which is called a <strong>Full Table Scan</strong>.</p>
<p>With indexing, the database can directly locate the required data, similar to how we use an index page in a book to quickly find a topic.</p>
<p>In real-world applications containing millions of records, indexing is extremely important because users expect very fast responses.</p>
<p>Most production databases heavily rely on indexes for performance optimization.</p>
<h3>How Indexing Works</h3>
<p>An index stores a special data structure (commonly B-Tree) that maintains references to the actual rows in sorted order. When a query searches indexed columns, the database engine uses the index instead of scanning the whole table.</p>
<p><strong>Example:</strong></p>
<pre><code class="language-sql">SELECT * FROM users WHERE email = "test@gmail.com";
</code></pre>
<p>If <code>email</code> is indexed:</p>
<ul>
<li>Database directly finds the row.</li>
</ul>
<p>If <code>email</code> is not indexed:</p>
<ul>
<li>Database checks every row manually.</li>
</ul>
<p><strong>Common Columns Used for Indexing</strong></p>
<p>User ID</p>
<ul>
<li><p>Email</p>
</li>
<li><p>Username</p>
</li>
<li><p>Phone Number</p>
</li>
<li><p>Frequently searched fields</p>
</li>
</ul>
<table>
<thead>
<tr>
<th>Advantages of Indexing</th>
<th>Disadvantages of Indexing</th>
</tr>
</thead>
<tbody><tr>
<td>Faster search operations</td>
<td>Requires additional storage</td>
</tr>
<tr>
<td>Improves query performance</td>
<td>Insert/Update/Delete becomes slightly slower</td>
</tr>
<tr>
<td>Reduces response time</td>
<td>Too many indexes can reduce write performance</td>
</tr>
<tr>
<td>Useful for filtering and sorting</td>
<td></td>
</tr>
</tbody></table>
<h2>Database Replicas</h2>
<img src="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/963e9e61-edc3-4722-8d8f-2a91dad4a09d.png" alt="" style="display:block;margin:0 auto" />

<p>Database replication means creating copies of a primary database server. These copies are called replicas or read replicas. Replication is mainly used to improve scalability, availability, and performance in large-scale systems.</p>
<p>In most real-world applications, read operations are much higher than write operations. To reduce load on the primary database, read requests are distributed across multiple replicas.</p>
<h3>Primary Database vs Read Replica</h3>
<table>
<thead>
<tr>
<th>Database Type</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>Primary DB</td>
<td>Handles write operations</td>
</tr>
<tr>
<td>Read Replica</td>
<td>Handles read operations</td>
</tr>
</tbody></table>
<h3>95% Reads and 5% Writes Scenario</h3>
<p>In applications like social media platforms, where 95% of traffic involves reading data and only 5% involves writing, multiple read replicas should be created to reduce the load on the primary database.</p>
<h3>Replication Lag</h3>
<p>Replication lag occurs because, in many systems, replication is asynchronous, meaning the primary database updates instantly while replicas receive updates after a short delay, which can cause replicas to become temporarily outdated during high traffic.</p>
<h3>What Should Be the Configuration of Read Replicas?</h3>
<p>In a system where most operations are <strong>read operations</strong> (for example 95% reads and 5% writes), the number of <strong>Read Replicas</strong> should be configured according to the read traffic load.</p>
<p>The general idea is:</p>
<ul>
<li><p>More read traffic → More read replicas</p>
</li>
<li><p>Fewer read replicas → Higher load on each replica</p>
</li>
</ul>
<p>If the replicas are not sufficient to handle incoming requests, the database can experience <strong>Replication Lag</strong>.</p>
<h3>Recommended Configuration</h3>
<table>
<thead>
<tr>
<th>Traffic Type</th>
<th>Suggested Configuration</th>
</tr>
</thead>
<tbody><tr>
<td>Low read traffic</td>
<td>1–2 Read Replicas</td>
</tr>
<tr>
<td>Medium read traffic</td>
<td>3–5 Read Replicas</td>
</tr>
<tr>
<td>Very high read traffic</td>
<td>Multiple replicas with load balancer</td>
</tr>
</tbody></table>
<h3>Real-World Example</h3>
<p>User changes profile photo:</p>
<ul>
<li><p>Primary DB updates immediately</p>
</li>
<li><p>Replica may still show old photo for few seconds</p>
</li>
</ul>
<pre><code class="language-html">
&lt;img 
  src="database-replica-system-design.png" 
  alt="System design architecture showing one primary database and multiple read replicas handling read traffic"
/&gt;
</code></pre>
<table>
<thead>
<tr>
<th>Advantages</th>
<th>Disadvantages</th>
</tr>
</thead>
<tbody><tr>
<td>Handles large read traffic</td>
<td>Replication lag</td>
</tr>
<tr>
<td>Improves scalability</td>
<td>Increased infrastructure cost</td>
</tr>
<tr>
<td>Better fault tolerance</td>
<td>Data consistency challenges</td>
</tr>
<tr>
<td>Reduces database load</td>
<td>Replicas may temporarily show outdated data</td>
</tr>
<tr>
<td>Read requests can be distributed across multiple servers</td>
<td>More infrastructure management complexity</td>
</tr>
<tr>
<td>Improves application performance and response time</td>
<td>Network synchronization overhead between databases</td>
</tr>
</tbody></table>
<h2>Archiving Old Data (Cold Storage)</h2>
<p>As applications grow, databases store massive amounts of data such as logs, analytics, transactions, and user activity. Keeping all historical data inside the main database becomes expensive and affects performance.</p>
<p>To solve this problem, old or rarely accessed data is moved to cheaper storage systems called cold storage or archive storage.</p>
<h3>AWS Glacier</h3>
<p>A typical strategy involves storing recent data (0–1 year) in the main database and moving older data (1+ years) to Amazon S3 Glacier, which is designed for long-term storage, backup systems, and archived data, keeping the active database small and efficient.</p>
<table>
<thead>
<tr>
<th>Advantages</th>
<th>Disadvantages</th>
</tr>
</thead>
<tbody><tr>
<td>Reduces storage cost</td>
<td>Archived data retrieval is slower</td>
</tr>
<tr>
<td>Improves DB performance</td>
<td>Extra management complexity</td>
</tr>
<tr>
<td>Easier database scaling</td>
<td>Data recovery may take additional time</td>
</tr>
<tr>
<td>Better long-term storage management</td>
<td>Requires archive policies and monitoring</td>
</tr>
<tr>
<td>Keeps active database smaller and faster</td>
<td>Accessing old data is less convenient</td>
</tr>
<tr>
<td>Helps optimize production database resources</td>
<td>Additional storage architecture setup required</td>
</tr>
</tbody></table>
<pre><code class="language-html">&lt;img 
  src="aws-glacier-archive-system.png" 
  alt="Architecture diagram showing recent data in active database and old data archived to AWS Glacier"
/&gt;
</code></pre>
<h2>Sharding in Databases</h2>
<p>Sharding is a database scaling technique where one large database is divided into multiple smaller databases called <strong>shards</strong>. Each shard stores only a portion of the total data.</p>
<p>Sharding is used when a single database server cannot handle massive traffic, storage, or millions of users.</p>
<p>Large-scale companies like:</p>
<ul>
<li><p>Instagram</p>
</li>
<li><p>Netflix</p>
</li>
<li><p>Facebook</p>
</li>
</ul>
<p>use sharding to scale their systems.</p>
<h3>Types of Database Sharding</h3>
<p>When a database becomes too large to handle on a single server, engineers divide the data into smaller parts called <strong>shards</strong>. This technique is known as <strong>Sharding</strong>. It helps applications scale horizontally and manage large amounts of traffic and data efficiently.</p>
<h3>1. Range-Based Sharding</h3>
<p>In range-based sharding, data is divided according to a specific range of values such as IDs, dates, or numbers. This method is simple because records are stored in sequential order.</p>
<pre><code class="language-text">Users 1-1000    → Shard 1
Users 1001-2000 → Shard 2
Users 2001-3000 → Shard 3
</code></pre>
<h3>Advantages and Disadvantages</h3>
<table>
<thead>
<tr>
<th>Advantages</th>
<th>Disadvantages</th>
</tr>
</thead>
<tbody><tr>
<td>Simple implementation</td>
<td>Uneven load distribution</td>
</tr>
<tr>
<td>Easy to understand</td>
<td>One shard may become overloaded</td>
</tr>
<tr>
<td>Easy debugging</td>
<td>Hotspot problem can occur</td>
</tr>
<tr>
<td>Works well for ordered data</td>
<td>Scaling becomes difficult later</td>
</tr>
</tbody></table>
<h3>2. Hash-Based Sharding</h3>
<p>In hash-based sharding, a hash function decides which shard will store the data. This helps distribute records more evenly across multiple servers. This technique is commonly used in high-scale systems to balance traffic.</p>
<h3>Advantages and Disadvantages</h3>
<table>
<thead>
<tr>
<th>Advantages</th>
<th>Disadvantages</th>
</tr>
</thead>
<tbody><tr>
<td>Better load balancing</td>
<td>Difficult resharding</td>
</tr>
<tr>
<td>Prevents hotspot issues</td>
<td>Complex shard management</td>
</tr>
<tr>
<td>More even data distribution</td>
<td>Harder debugging</td>
</tr>
<tr>
<td>Useful for high-scale systems</td>
<td>Migration becomes difficult</td>
</tr>
</tbody></table>
<hr />
<h3>3. Geo-Based Sharding</h3>
<p>Geo-based sharding divides data according to geographic regions or user locations. Different regions use different database servers.</p>
<pre><code class="language-text">India Users  → India Server
US Users     → US Server
Europe Users → Europe Server
</code></pre>
<p>This approach improves speed for global users by keeping data closer to their location.</p>
<h3>Advantages and Disadvantages</h3>
<table>
<thead>
<tr>
<th>Advantages</th>
<th>Disadvantages</th>
</tr>
</thead>
<tbody><tr>
<td>Faster local response time</td>
<td>Difficult cross-region queries</td>
</tr>
<tr>
<td>Reduced latency</td>
<td>Complex data synchronization</td>
</tr>
<tr>
<td>Better user experience</td>
<td>Higher infrastructure complexity</td>
</tr>
<tr>
<td>Improved regional performance</td>
<td>Cross-region transactions are difficult</td>
</tr>
</tbody></table>
<h2>Problems with Sharding</h2>
<p><strong>1. Complex Queries</strong></p>
<p>Joining data across shards becomes difficult and slow.</p>
<p><strong>2. Rebalancing Issues</strong></p>
<p>When one shard becomes overloaded, moving data between shards is complicated.</p>
<p><strong>3. Cross-Shard Transactions</strong></p>
<p>Transactions involving multiple shards are difficult to maintain consistently.</p>
<p><strong>4. Hotspot Problem</strong></p>
<p>Some shards may receive much higher traffic than others.</p>
<p><em>Example:</em></p>
<ul>
<li><p>Viral users</p>
</li>
<li><p>Celebrity accounts</p>
</li>
</ul>
<p><strong>5. Increased Complexity</strong></p>
<p>Application architecture becomes harder to manage.</p>
<p>Need:</p>
<ul>
<li><p>Routing logic</p>
</li>
<li><p>Monitoring</p>
</li>
<li><p>Shard management</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[WebSocket and Socket.IO: A Comprehensive Guide for Full-Stack Developers]]></title><description><![CDATA[WebSocket is a protocol that enables full-duplex communication between the client and server. Unlike HTTP, which is designed for stateless requests, WebSocket supports long-lived connections. This mak]]></description><link>https://blog.adityaguptareal.com/websocket-and-socket-io-comprehensive-guide</link><guid isPermaLink="true">https://blog.adityaguptareal.com/websocket-and-socket-io-comprehensive-guide</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sat, 18 Apr 2026 19:34:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/bb0f023c-e71d-46a7-a155-e65411e4b396.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>WebSocket is a protocol that enables full-duplex communication between the client and server. Unlike HTTP, which is designed for stateless requests, WebSocket supports long-lived connections. This makes it ideal for real-time applications such as chat apps, trading platforms, live dashboards, and surveillance systems.</p>
<h3>Why HTTP Isn't Suitable for Real-Time Apps</h3>
<ul>
<li><p><strong>Statelessness</strong>: HTTP is a stateless protocol, meaning each request contains all necessary information. This can lead to issues in maintaining client sessions.</p>
</li>
<li><p><strong>Longest Request Lifetime</strong>: HTTP has a maximum request lifetime of 75 seconds due to the Keep-alive connection being closed after a period.</p>
</li>
</ul>
<h3>Real-world Examples: Chat Apps, Trading Apps, Live Dashboards</h3>
<p>Real-world examples include:</p>
<ol>
<li><p><strong>Chat Apps</strong>: Users can send and receive messages in real-time.</p>
</li>
<li><p><strong>Trading Apps</strong>: Traders can monitor stock prices in real-time and perform trades.</p>
</li>
<li><p><strong>Live Dashboards</strong>: Data is updated in real-time to provide the most up-to-date information.</p>
</li>
</ol>
<h3>One-Line Mental Models</h3>
<ul>
<li><p><strong>HTTP vs WebSocket</strong>: HTTP is suitable for stateless, one-way requests; WebSocket is ideal for maintaining long-lived connections and full-duplex communication.</p>
</li>
<li><p><strong>Persistent Connection</strong>: A persistent connection remains active on both sides until explicitly closed by either party.</p>
</li>
</ul>
<h2>How WebSocket Works Internally</h2>
<p>WebSocket operates as an upgrade to the HTTP protocol. Here’s a step-by-step breakdown:</p>
<ol>
<li><p><strong>Client Request</strong>:</p>
<ul>
<li><p>Client initiates a request to connect to the WebSocket server.</p>
</li>
<li><p>The client sends a <code>GET</code> request with the <code>Upgrade: websocket</code> header.</p>
</li>
</ul>
</li>
<li><p><strong>Server Response</strong>:</p>
<ul>
<li><p>Server responds with a <code>HTTP/1.1 101 Switching Protocols</code>.</p>
</li>
<li><p>It includes the <code>Sec-WebSocket-Accept</code> header, which is generated using the <code>SHA-1</code> hash of a nonce and a secret key sent by the client.</p>
</li>
</ul>
</li>
<li><p><strong>Handshake</strong>:</p>
<ul>
<li><p>After receiving the upgrade request, the server sends back an HTTP response with the necessary headers to establish the WebSocket connection.</p>
</li>
<li><p>The handshake completes when both parties send a confirmation message (e.g., <code>HTTP/1.1 200 OK</code>).</p>
</li>
</ul>
</li>
<li><p><strong>Full-Duplex Communication</strong>:</p>
<ul>
<li>Once connected, the client and server can send messages in both directions through the same socket.</li>
</ul>
</li>
</ol>
<h3>Lifecycle: Connect → Message → Close</h3>
<ul>
<li><p><strong>Connect</strong>: The client initiates a connection to the WebSocket server.</p>
</li>
<li><p><strong>Message</strong>: Messages are sent and received between the client and server.</p>
</li>
<li><p><strong>Close</strong>: Both parties close the connection when they’re done exchanging messages.</p>
</li>
</ul>
<h2>HTTP vs WebSocket (Deep Comparison)</h2>
<ul>
<li><p><strong>Connection Behavior</strong>: WebSocket establishes a persistent connection, while HTTP is stateless.</p>
</li>
<li><p><strong>Performance Difference</strong>: WebSocket can be more efficient for real-time applications due to its long-lived connections.</p>
</li>
<li><p><strong>When to Use What</strong>: Use WebSocket for applications requiring real-time communication and high-performance data transfer.</p>
</li>
</ul>
<h2>Node.js Architecture Understanding</h2>
<p>Node.js has a modular architecture where the HTTP server is built on top of the underlying event loop. Here’s how it works:</p>
<ol>
<li><p><strong>HTTP Server</strong>:</p>
<ul>
<li><p>The HTTP server uses <code>http.createServer()</code> to create an HTTP server.</p>
</li>
<li><p>It listens for incoming requests and sends responses.</p>
</li>
</ul>
</li>
<li><p><strong>WebSocket Server</strong>:</p>
<ul>
<li><p>The WebSocket server attaches itself to the HTTP server through the <code>ws</code> library.</p>
</li>
<li><p>It provides a <code>websocket</code> object that can be used to handle WebSocket connections.</p>
</li>
</ul>
</li>
<li><p><strong>Internal Flow Diagram (text-based)</strong>:</p>
</li>
</ol>
<pre><code class="language-plaintext">HTTP Server
  |
  V
 WebSocket Server
  |
  V
 Event Loop
  |
  V
 WebSocket Connection
</code></pre>
<h3>Native WebSocket Implementation (ws library)</h3>
<p>To implement a WebSocket server in Node.js, you can use the <code>ws</code> library. Here’s an example of how to set it up:</p>
<pre><code class="language-javascript">const http = require('http');
const WebSocket = require('ws');

// Create an HTTP server
const server = http.createServer((req, res) =&gt; {
  res.writeHead(200);
  res.end('Hello from Node.js!');
});

server.listen(3000, () =&gt; {
  console.log('Server is running on port 3000');
});

// WebSocket server attached to the HTTP server
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) =&gt; {
  console.log('Client connected');

  ws.on('message', (data) =&gt; {
    console.log(`Received: ${data}`);

    // Broadcast message to all clients
    wss.clients.forEach(client =&gt; client.send(data));
  });

  ws.on('close', () =&gt; {
    console.log('Client disconnected');
  });
});
</code></pre>
<h3>Socket.IO Deep Dive</h3>
<p>Socket.IO is a library that simplifies the implementation of WebSocket in Node.js. Here’s how it works:</p>
<ol>
<li><p><strong>Setup</strong>:</p>
<ul>
<li><p>Install <code>socket.io</code> using npm.</p>
</li>
<li><p>Initialize an HTTP server and create a <code>io</code> object.</p>
</li>
</ul>
</li>
<li><p><strong>Connection Handling</strong>:</p>
<ul>
<li>The <code>io.on('connection', (socket) =&gt; {...})</code> function handles new connections.</li>
</ul>
</li>
<li><p><strong>Sending and Receiving Messages</strong>:</p>
<ul>
<li><p>Use the <code>socket.emit('message', message)</code> function to send messages.</p>
</li>
<li><p>Attach event listeners to handle incoming messages: <code>socket.on('custom_event', handler)</code>.</p>
</li>
</ul>
</li>
<li><p><strong>Broadcasting</strong>:</p>
<ul>
<li>Use <code>io.emit('custom_event')</code> to broadcast a message to all connected clients.</li>
</ul>
</li>
<li><p><strong>Handling Disconnect</strong>:</p>
<ul>
<li>Use <code>socket.disconnect()</code> to disconnect the client.</li>
</ul>
</li>
</ol>
<h3>Socket.IO Implementation (Complete Code)</h3>
<p>Here’s an example of how to set up a WebSocket server with Socket.IO:</p>
<pre><code class="language-javascript">const http = require('http');
const socketIo = require('socket.io');

// Create an HTTP server
const server = http.createServer((req, res) =&gt; {
  res.writeHead(200);
  res.end('Hello from Node.js!');
});

server.listen(3000, () =&gt; {
  console.log('Server is running on port 3000');
});

// WebSocket server using Socket.IO
const io = socketIo(server);

io.on('connection', (socket) =&gt; {
  console.log('Client connected');

  // Emit a custom event
  socket.emit('welcome_message', 'Welcome to the chat room!');

  // Listen for incoming messages
  socket.on('message', (data) =&gt; {
    console.log(`Received: ${data}`);

    // Broadcast message to all clients except the sender
    io.to(socket.id).emit('receive_message', data);
  });

  socket.on('disconnect', () =&gt; {
    console.log('Client disconnected');
  });
});
</code></pre>
<h2>Real-World Mini Projects (VERY IMPORTANT)</h2>
<h3>A. Chat Application (1-to-1)</h3>
<p><strong>Unique Room Creation Logic</strong>: Each user creates their own room based on a unique identifier.</p>
<pre><code class="language-javascript">const { v4: uuidv4 } = require('uuid');

// Create a new room for each client
socket.on('join_room', (roomName) =&gt; {
  if (!io.sockets.adapter.rooms.has(roomName)) {
    io.sockets.adapter.rooms.set(roomName, []);
  }
  socket.join(roomName);
});
</code></pre>
<p><strong>Save Messages in Database</strong>: Use a database like MongoDB to store messages for each user.</p>
<pre><code class="language-javascript">// Example using mongoose

const Message = new Schema({
  sender: { type: String },
  message: { type: String },
  timestamp: { type: Date, default: Date.now }
});

const ChatRoom = mongoose.model('ChatRoom', Message);
</code></pre>
<p><strong>Load Chat History</strong>: Retrieve chat history from the database.</p>
<pre><code class="language-javascript">// Example using MongoDB

async function getChatHistory(roomName) {
  const messages = await ChatRoom.find({ room: roomName }).sort({ timestamp: -1 });
  return messages;
}
</code></pre>
<h3>B. Fight Detection Alert System</h3>
<p><strong>AI → Backend → WebSocket → Frontend</strong>: Use AI to detect potential fights, send alerts to the server, and broadcast them to all connected users.</p>
<pre><code class="language-javascript">// Example using AI

function detectFight(data) {
  // Implement AI logic here
}

// Server listens for fight detection events
io.on('fight_detected', (data) =&gt; {
  console.log(`Fight detected: ${data}`);

  // Broadcast alert to all clients
  io.emit('fight_alert', data);
});
</code></pre>
<h3>C. Live Dashboard</h3>
<p><strong>Real-time Metrics Update</strong>: Use WebSocket to send updates to the frontend with real-time metrics.</p>
<pre><code class="language-javascript">// Example using WebSocket

setInterval(() =&gt; {
  const metricData = { cpu: '50%', memory: '75%' };
  io.emit('metric_update', metricData);
}, 1000);
</code></pre>
<h2>Advanced Concepts (Builder Level)</h2>
<h3>Rooms (multi-user grouping)</h3>
<ul>
<li><p>Use <code>io.in(roomName)</code> to join a room.</p>
</li>
<li><p>Use <code>socket.join(roomName);</code> to leave a room.</p>
</li>
<li><p>Use <code>io.to(roomName).emit('event_name', data);</code> to broadcast an event to all clients in the room.</p>
</li>
</ul>
<pre><code class="language-javascript">// Example of joining and leaving a room

socket.on('join_room', (roomName) =&gt; {
  socket.join(roomName);
});

socket.on('leave_room', (roomName) =&gt; {
  socket.leave(roomName);
});
</code></pre>
<h3>Namespaces (separation of concerns)</h3>
<ul>
<li><p>Use <code>io.of('/namespace').on('connection', function(socket) {...})</code> to create a namespace.</p>
</li>
<li><p>Use <code>io.emit('/namespace', 'event_name', data);</code> to broadcast an event to all clients in the namespace.</p>
</li>
</ul>
<pre><code class="language-javascript">// Example of creating a namespace

const io = socketIo(server, { path: '/chat' });

io.on('connection', (socket) =&gt; {
  console.log('Chat room connection');

  socket.on('send_message', (data) =&gt; {
    io.emit('/chat', 'user:', data);
  });
});
</code></pre>
<h3>Broadcasting Types:</h3>
<ul>
<li><p><code>io.emit</code>: Broadcast to all connected clients.</p>
</li>
<li><p><code>socket.emit</code>: Broadcast to the client who sent the event.</p>
</li>
<li><p><code>socket.broadcast.emit</code>: Broadcast to all other clients in the same room.</p>
</li>
</ul>
<pre><code class="language-javascript">// Example of broadcasting different types of messages

socket.on('send_message', (data) =&gt; {
  io.emit('receive_message', data);

  socket.broadcast.emit('private_message', { sender: socket.username, message: data });
});
</code></pre>
<h2>Performance &amp; Optimization</h2>
<ul>
<li><p><strong>Avoid Sending Large Payloads</strong>: Only send necessary data and avoid large payloads.</p>
</li>
<li><p><strong>Why Not to Stream Video via WebSocket</strong>: Streaming video can be expensive in terms of bandwidth and latency.</p>
</li>
</ul>
<h3>Common Mistakes (Critical Section)</h3>
<ul>
<li><p><strong>Creating socket multiple times</strong>: Ensure each client only has one WebSocket connection.</p>
</li>
<li><p><strong>Not cleaning up listeners</strong>: Unsubscribe from event listeners when the client disconnects.</p>
</li>
<li><p><strong>No reconnection strategy</strong>: Implement a reconnection strategy to handle disconnections gracefully.</p>
</li>
<li><p><strong>Bad event naming</strong>: Avoid using reserved keywords and ensure event names are descriptive.</p>
</li>
</ul>
<h2>Security Considerations</h2>
<ul>
<li><p><strong>Authentication (JWT with sockets)</strong>: Use JSON Web Tokens (JWT) for authentication.</p>
</li>
<li><p><strong>Prevent Unauthorized Access</strong>: Implement access controls based on user roles and permissions.</p>
</li>
<li><p><strong>Rate Limiting</strong>: Limit the number of messages sent per client to prevent abuse.</p>
</li>
<li><p><strong>Input Validation</strong>: Validate all incoming data to prevent injection attacks.</p>
</li>
</ul>
<h2>Interview Questions &amp; Answers</h2>
<p><strong>Difference between WebSocket and HTTP</strong>:</p>
<ul>
<li><p><strong>WebSocket</strong>: Long-lived connections, full-duplex communication.</p>
</li>
<li><p><strong>HTTP</strong>: Stateless, one-way requests.</p>
</li>
<li><p><strong>When to Use What</strong>: Use WebSocket for real-time applications requiring high-performance data transfer.</p>
</li>
</ul>
<p><strong>Why Use Socket.IO Over WebSocket</strong>:</p>
<ul>
<li><p><strong>Socket.IO</strong>: Simplifies the implementation of WebSocket in Node.js.</p>
</li>
<li><p><strong>Event-driven architecture</strong>.</p>
</li>
<li><p><strong>WebSocket vs REST</strong>.</p>
</li>
<li><p><strong>Real-time system thinking</strong>.</p>
</li>
</ul>
<p><strong>How Scaling Works</strong>:</p>
<ul>
<li><p><strong>Sticky sessions</strong>: Keep connections open even after client disconnects.</p>
</li>
<li><p><strong>Redis Pub/Sub for scaling</strong>: Use Redis to distribute load across multiple servers.</p>
</li>
<li><p><strong>Handling 1000+ Connections</strong>: Implement connection pooling and efficient data handling.</p>
</li>
<li><p><strong>Load balancing concept</strong>: Distribute incoming requests among available servers.</p>
</li>
</ul>
<p><strong>Common Mistakes (Critical Section)</strong>:</p>
<ul>
<li><p><strong>Creating socket multiple times</strong>.</p>
</li>
<li><p><strong>Not cleaning up listeners</strong>.</p>
</li>
<li><p><strong>No reconnection strategy</strong>.</p>
</li>
<li><p><strong>Bad event naming</strong>.</p>
</li>
<li><p><strong>Tight coupling of logic</strong>.</p>
</li>
</ul>
<h2>Final Mental Models (Revision Section)</h2>
<ul>
<li><p><strong>io vs socket</strong>: <code>io</code> is the global namespace for all clients, while <code>socket</code> is used to handle individual client connections.</p>
</li>
<li><p><strong>event-driven architecture</strong>: Events are handled by functions attached to specific events.</p>
</li>
<li><p><strong>WebSocket vs REST</strong>: WebSocket is ideal for real-time communication, while REST is suitable for stateless requests.</p>
</li>
<li><p><strong>Real-time system thinking</strong>: Focus on the need for instant feedback and updates in applications.</p>
</li>
</ul>
<h2>Bonus: When to Use What</h2>
<ul>
<li><p><strong>WebSocket</strong>: For real-time communication between clients and server.</p>
</li>
<li><p><strong>Socket.IO</strong>: For building web-based applications with real-time features like chat, notifications, and live dashboards.</p>
</li>
<li><p><strong>REST</strong>: For building stateless, API-driven applications where data is fetched once and used for subsequent requests.</p>
</li>
</ul>
<h2>Conclusion</h2>
<p>WebSocket and Socket.IO are powerful tools for building scalable and high-performance real-time applications. By understanding the underlying concepts, designing a robust system architecture, and addressing common issues, you can create engaging and interactive experiences for your users.</p>
]]></content:encoded></item><item><title><![CDATA[Cohort 3.0 Complete Notes Harkirat Singh]]></title><description><![CDATA[C++ is a compiler language first it converts the code in the binary and then runs into your machine. the compilation takes time, but once it's completed, it is swift after the deployment. In the case ]]></description><link>https://blog.adityaguptareal.com/cohort-3-0-complete-notes-harkirat-singh</link><guid isPermaLink="true">https://blog.adityaguptareal.com/cohort-3-0-complete-notes-harkirat-singh</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Fri, 27 Feb 2026 03:27:23 GMT</pubDate><content:encoded><![CDATA[<p>C++ is a compiler language first it converts the code in the binary and then runs into your machine. the compilation takes time, but once it's completed, it is swift after the deployment. In the case of production, it is well-suited.</p>
<p>JS is an interpreted language that is executed line by line. It doesn't need compilation. It is dynamically typed.</p>
<p>This means the variable in JavaScript is not bound to a specific data type. Types are determined at runtime and can change when the program is executed. JavaScript code is executed in a single thread.</p>
<p>Memory Management is a process of storing variable data in RAM. The Garbage Collector manages memory in JavaScript.</p>
<p>Java and JavaScript use a Garbage Collector. The single-threaded nature makes the app not scalable</p>
<p>The downside of JavaScript:-</p>
<p>Runtime Error</p>
<p>Performance Overhead</p>
<h2>File I/O Heavy Operations</h2>
<p>Filo I/O refers to a computer program that transfers much data between the program and external systems or devices. These operations usually require waiting for data to be read from or written to sources like disks, networks, databases, or other external devices, which can be time-consuming compared to in-memory computations.</p>
<h4><strong>Examples of I/O Heavy Operations:</strong></h4>
<ol>
<li><p>Reading a file</p>
</li>
<li><p>Starting a clock</p>
</li>
<li><p>HTTP Requests</p>
</li>
</ol>
<h2>Callback Function</h2>
<p>Callback Functions are the functions that are passed as an argument to another function.</p>
<h3>What are Classes in JavaScript?</h3>
<p>Classes in JavaScript are a blueprint for creating objects with predefined properties and methods.</p>
<h4>Defining a Class</h4>
<p>To define a class in JavaScript, you use the <code>class</code> keyword followed by the class name. Inside the class, we define a constructor method, a special method for creating and initialising an object created with a class. You can also define other methods that belong to the class.</p>
<pre><code class="language-javascript">class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is \({this.name} and I am \){this.age} years old.`);
  }
}
</code></pre>
<p>In the example above, we have defined a <code>Person</code> class with a constructor that takes <code>name</code> and <code>age</code> as parameters. The <code>greet</code> method is a regular method that prints a greeting message.</p>
<h4>Creating an Instance</h4>
<p>To create an instance of a class, you use the <code>new</code> keyword followed by the class name and pass any required arguments to the constructor.</p>
<pre><code class="language-javascript">const person1 = new Person('Alice', 30);
person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.
</code></pre>
<h1>Async Await</h1>
<h2>What is DOM?</h2>
<p>DOM stands for Document Object Model. It represents the structure of a web page as a tree of objects.</p>
<h2>Why do we need DOM?</h2>
<p>The DOM is used to represent the structure of a webpage as a tree of objects, allowing scripts to manipulate the content dynamically.</p>
<h2>What is Static HTML?</h2>
<p>A Static HTML page is a web document that remains unchanged over time. Unlike dynamic web pages, which can update and display new content based on user interactions or other factors, a static HTML page displays the same information to every visitor.</p>
<p>It is similar to a digital signboard that consistently shows the same message without any alterations. This type of web page is often used for content that does not need to be updated frequently, such as informational pages, company profiles, or contact information.</p>
<h2>What is Dynamic HTML?</h2>
<p>Dynamic HTML is a web page document where the HTML and its content can change dynamically based on user interactions or other events. This means that the content of the web page is not fixed and can be updated in real time without needing to reload the entire page.</p>
<p>For instance, when you click a button to add a task to a to-do list, the new task appears immediately on the page. This dynamic behaviour is often achieved using JavaScript, which can manipulate the DOM to update the content, styles, and structure of the web page on the fly.</p>
<h2>Fetching Elements in DOM</h2>
<p>There are 5 Popular methods in which we can fetch our Elements from HTML documents.</p>
<ul>
<li><p>querySelector</p>
</li>
<li><p>querySelectorAll</p>
</li>
<li><p>getElementById</p>
</li>
<li><p>getElementByClassName</p>
</li>
<li><p>getElementsByClassName</p>
</li>
</ul>
<p><strong>For Example -</strong></p>
<pre><code class="language-xml">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
   &lt;h1&gt;To Do List&lt;/h1&gt;
    &lt;h4 id="task1"&gt;1. Go to Gym&lt;/h4&gt;
    &lt;h4  id="task2"&gt;2. Take Class&lt;/h4&gt;
    &lt;h4 id="task3"&gt;3 Go&lt;/h4&gt;
    &lt;input type="text" placeholder="Type your Task"&gt;&lt;/input&gt;
    &lt;button onclick="AddTask()"&gt;Add Task&lt;/button&gt;
&lt;/body&gt;
   &lt;script&gt;
var input=document.querySelector("input")
// used to get the value inside the input box
console.log(input.value);
// Selecting Elements using ID
    let task3=document.querySelector("#task3")
    console.log(task3);
   &lt;/script&gt;
    
&lt;/html&gt;
</code></pre>
<h2>State-Derived Frontend</h2>
<p>The concepts of components and state were introduced to simplify our code and make it more maintainable. Components are reusable, self-contained pieces of UI that can be combined to build complex interfaces.</p>
<p>Each component can manage its own state, which represents the data or properties that control its behaviour and appearance. For example, consider a to-do list application. Each task in the list can be represented as a component.</p>
<p>The application's state might include the list of tasks, the current input value, and any filters applied to the list. When a user adds a new task, the state is updated to include the new task, and the UI re-renders to display it.</p>
<p>We can build more modular, scalable, and interactive web applications using components and states.</p>
<h2>Reconciliation</h2>
<p>Reconciliation is identifying the differences between the old state and the new state of an application. This process is crucial in modern web development, especially when dealing with dynamic user interfaces that frequently change in response to user actions or data updates.</p>
<h2>Node Js</h2>
<p>Node.js is a powerful runtime environment that allows developers to execute JavaScript code outside of a web browser. Built on Chrome's V8 JavaScript engine, Node.js is designed to build scalable network applications.</p>
<p>It uses an event-driven, non-blocking I/O model, which makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.</p>
<h2>What is HTTP Servers</h2>
<p>HTTP Servers are essential components that enable communication between clients and servers over the Internet. When a client, such as a web browser, sends a request to access a webpage or resource, the HTTP server processes this request and returns the appropriate response. This response could be an HTML page, a file, or data in formats like JSON or XML.</p>
<p>The server runs various processes to handle these requests efficiently. It listens for incoming requests on specific ports, typically port 80 for HTTP and port 443 for HTTPS.</p>
<p>Upon receiving a request, the server parses it to understand what the client is asking for. It then routes the request to the appropriate handler, which might involve querying a database, executing server-side scripts, or fetching static files from the server's storage.</p>
<h2>Why the HTTP Protocol?</h2>
<p>The HTTP protocol is essential because it enables machines to communicate with each other over the Internet.</p>
<p>This communication is the backbone of web interactions, allowing browsers to request and receive web pages from servers.</p>
<p>When you type a URL into your browser, an HTTP request is sent to the server hosting the website.</p>
<p>The server then processes this request and returns the appropriate response, which your browser displays as a web page.</p>
<h2>What is an IP Address</h2>
<p>An IP address, or Internet Protocol address, is a unique identifier assigned to each device connected to a network that uses the Internet Protocol for communication.</p>
<p>Think of it as the digital address of your computer, smartphone, or any other device that connects to the internet.</p>
<p>Just like your home address allows mail to be delivered to your house, an IP address ensures that data sent over the internet reaches the correct destination.</p>
<p>Use the command to check the IP address of any website.</p>
<pre><code class="language-bash">ping website.com
</code></pre>
<h2>Domain</h2>
<p>A domain is a human-readable name mapped to a server's IP address. When someone types the domain name into their browser, the domain name system (DNS) translates this name into the corresponding IP address of the server hosting the website. This process allows users to access websites without remembering complex numerical IP addresses.</p>
<p>For example, when you type "example.com" into your browser, the DNS resolves this domain name to the server's IP address where the website's content is stored. This seamless translation is what makes navigating the internet user-friendly and efficient.</p>
<h1>Headers, Query params in Express</h1>
<h2>What is Headers</h2>
<p>Headers are key-value pairs exchanged between the client and the server during HTTP requests and responses. They carry additional metadata that can be used for various purposes, such as authentication, specifying content types, caching policies, and more.</p>
<p>For instance, headers can include information about the type of content being sent (like JSON or HTML), the preferred language of the client, or the credentials needed to access a resource.</p>
<p>When a client makes a request to the server, it can include headers to provide context about the request. For example, the <code>Authorization</code> header might contain a token that the server uses to verify the client's identity.</p>
<p>Similarly, the <code>Content-Type</code> header tells the server what kind of data is being sent, so it knows how to process it.</p>
<h2>How to Create Dynamic Endpoints in Express</h2>
<p>Creating dynamic endpoints in Express is an essential skill for building flexible and robust web applications. Dynamic endpoints allow your application to handle various routes and parameters, making it more versatile and capable of responding to different user requests.</p>
<ol>
<li><p><strong>Set Up Your Express Application</strong> First, ensure you have Express installed in your project. If not, you can install it using npm:</p>
<pre><code class="language-bash">npm install express
</code></pre>
<p> Then, create a basic Express application:</p>
<pre><code class="language-javascript">const express = require('express');
const app = express();
const port = 3000;

app.listen(port, () =&gt; {
  console.log(`Server is running on port ${port}`);
});
</code></pre>
</li>
<li><p><strong>Define a Basic Route</strong> Start by defining a simple route to ensure your server is working correctly:</p>
<pre><code class="language-javascript">app.get('/', (req, res) =&gt; {
  res.send('Hello, World!');
});
</code></pre>
</li>
<li><p><strong>Create Dynamic Routes with Route Parameters</strong> Dynamic routes use parameters to capture values from the URL. For example, you can create a route that captures a user ID:</p>
<pre><code class="language-javascript">app.get('/user/:id', (req, res) =&gt; {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});
</code></pre>
<p> In this example, <code>:id</code> is a route parameter that captures the value provided in the URL.</p>
</li>
</ol>
<h2>Types of Routes in Express js</h2>
<h3>What is Middleware in Express</h3>
<p>Middleware in Express is a function that runs during the request-response cycle. It can modify the request or response or end the process. Middleware functions handle tasks like logging, authentication, and error handling.</p>
<p>In simple terms, middleware functions are like a series of steps that a request goes through before getting a response. Each step can perform a specific task, making the process more organized and efficient.</p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

// Middleware function to modify request
function modifyRequestMiddleware(req, res, next) {
    // Add a custom property to the request object
    req.customProperty = 'This was added by middleware';

    // Log the original and modified request method and path
    console.log(`Original request URL: ${req.originalUrl}`);
    console.log(`Modified request custom property: ${req.customProperty}`);

    // Continue to the next middleware or route handler
    next();
}

// Use the middleware with a specific route or all routes
app.use(modifyRequestMiddleware);

// Example route
app.get('/', (req, res) =&gt; {
    res.send(`Hello, World! Custom Property: ${req.customProperty}`);
});

// Start the server
const port = 3000;
app.listen(port, () =&gt; {
    console.log(`Server is running on port ${port}`);
});
</code></pre>
<h3>CORS Middleware - Cross-Origin Resource Sharing</h3>
<p>Cross-Origin Resource Sharing (CORS) is a security feature used by web browsers to control how web pages can request resources from a different domain than the one they came from. This is important for keeping the web secure and private. CORS is especially important for web apps that need to talk to APIs on other domains.</p>
<p>For example, if your web app is on <code>example.com</code> and needs to get data from <code>api.example.com</code>, CORS rules will decide if this request is allowed. Without the right CORS setup, these requests might be blocked by the browser, stopping your app from getting the data it needs. So, knowing how to set up CORS correctly is crucial for developers making web apps that use external APIs, ensuring smooth and safe data sharing between different domains.</p>
<p><strong>For Example :</strong></p>
<p>Imagine you have a web application hosted on <a href="http://example.com"><code>example.com</code></a>, and it needs to fetch data from an API hosted on <a href="http://api.example.com"><code>api.example.com</code></a>. By default, web browsers block these cross-origin requests for security reasons. However, if <a href="http://api.example.com"><code>api.example.com</code></a> it wants to allow requests from <a href="http://example.com"><code>example.com</code></a>, it can do so by including specific HTTP headers in its response.</p>
<p>For instance, <a href="http://api.example.com"><code>api.example.com</code></a> it can include the <code>Access-Control-Allow-Origin</code> header in its response, specifying which domains are allowed to access its resources. If the header is set to <code>Access-Control-Allow-Origin: *</code>, it means any domain can access the resources. Alternatively, it can specify a particular domain like <code>Access-Control-Allow-Origin:</code> <a href="http://example.com"><code>example.com</code></a>, to allow only that domain to access the resources.</p>
<h4>Why Use CORS?</h4>
<p>When building web applications, you often need to make requests to APIs that are hosted on different domains. Without CORS, these requests would be blocked by the browser's same-origin policy. CORS allows you to specify which domains are permitted to access your resources, thereby enabling secure cross-domain communication.</p>
<h4>Setting Up CORS in Express</h4>
<p>To enable CORS in your Express application, you need to use the <code>cors</code> middleware. First, install the <code>cors</code> package using npm:</p>
<pre><code class="language-bash">npm install cors
</code></pre>
<p>Next, integrate the <code>cors</code> middleware into your Express application. Here’s how you can do it:</p>
<pre><code class="language-javascript">const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;

// Use the CORS middleware
app.use(cors());

app.listen(port, () =&gt; {
  console.log(`Server is running on port ${port}`);
});
</code></pre>
<h2>How to Serve Files on IntraNet</h2>
<p>Sometimes we need to share files within the same network. A common example is when we host the front end and back end on different ports on our local system. In such cases, we can use an npm library called <code>serve</code>, which allows us to share our files on the local network.</p>
<h3>How to use Serve</h3>
<p>To share files on the same network, or when hosting frontend and backend on different ports locally, you can use an npm library called serve. This allows you to share files on the local network.</p>
<p><strong>Serve Installation</strong></p>
<pre><code class="language-bash">npm i serve
</code></pre>
<p><strong>How to Use Serve</strong></p>
<p>Open the terminal in the folder you want to share, then run the command:</p>
<pre><code class="language-bash">npx serve
</code></pre>
<h2>What is an Authentication Token</h2>
<p>An authentication token is a piece of data that is used to verify the identity of a user or a system. It acts as a digital key that allows access to various resources and services.</p>
<p>Authentication tokens are commonly used in web applications to manage user sessions and ensure secure communication between the client and the server.</p>
<h3>How Authentication Tokens Work</h3>
<ol>
<li><p><strong>User Login</strong>: When users log in to an application, they provide their credentials, such as a username and password.</p>
</li>
<li><p><strong>Token Generation</strong>: The server verifies the credentials and, if they are correct, generates an authentication token. This token is usually a long string of characters that is difficult to guess.</p>
</li>
<li><p><strong>Token Storage</strong>: The token is sent back to the client, where it is stored, typically in local storage or a cookie.</p>
</li>
<li><p><strong>Token Usage</strong>: For subsequent requests, the client includes the token in the request headers. The server then verifies the token to ensure the request is coming from an authenticated user.</p>
</li>
<li><p><strong>Token Expiry</strong>: Tokens usually have an expiration time. After this time, the user will need to log in again to get a new token.</p>
</li>
</ol>
<h4>Types of Authentication Tokens</h4>
<ul>
<li><p><strong>JWT (JSON Web Tokens)</strong>: These are widely used tokens that contain encoded JSON objects. They are self-contained and can include user information and claims.</p>
</li>
<li><p><strong>OAuth Tokens</strong>: These tokens are used in OAuth authentication, allowing third-party applications to access user data without exposing user credentials.</p>
</li>
<li><p><strong>Session Tokens</strong>: These are simpler tokens used to maintain user sessions. They are often stored on the server side.</p>
</li>
</ul>
<h4>Benefits of Using Authentication Tokens</h4>
<ul>
<li><p><strong>Security</strong>: Tokens help secure user data and ensure that only authenticated users can access certain resources.</p>
</li>
<li><p><strong>Scalability</strong>: Tokens can be easily managed and validated, making them suitable for scalable applications.</p>
</li>
</ul>
<p><strong>Statelessness</strong>: Tokens allow for stateless authentication, meaning the server does not need to store session information, which can improve performance.</p>
<h2>How to Create an Authentication in Express</h2>
<p>Step 1. Initialise an <code>npm</code> project using <code>npm init</code> command.</p>
<p>Step 2. Install the express using <code>npm i express</code>.</p>
<p>Step 3. Create a basic Express app with two endpoints: <code>signin</code> and <code>signup</code>, both using the POST method.</p>
<pre><code class="language-javascript">const express = require("express")
const app = express()
const port = 3000
app.use(express.json())
const userDetails = []

app.post("/signup", function (req, res) {
const username = req.body.username
const password = req.body.password
userDetails.push({ username: username, password: password })
res.json({ msg: "You are succefully signed up" })
console.log(userDetails);
})

app.post("/signin")
</code></pre>
<p>Step 4. Add middleware <code>app.use(express.json())</code> to parse the JSON body.</p>
<p>Step 5. Define a sign-up endpoint with middleware that takes username and password from the body.</p>
<p>Step 6. Next, define a global variable that will store the user details in an array.</p>
<p>Step 7. In the sign-up route, push the username and password into the global variable that stores the users' data in JSON format.</p>
<h3>Generating a Random Token for the Authentication Process</h3>
<p>Step 1. Define a function that generates a random token for the authentication process.</p>
<p>Step 2. Define a token variable as an empty string.</p>
<p>Step 3. Next, define arrays consisting of numbers and alphabets to help generate a unique token.</p>
<p>Step 5. Run a loop through the arrays multiple times to generate a long token, then update the token variable and return it.</p>
<pre><code class="language-javascript">function genearateToken() {
    let token = ""
    let options = [
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
    ];
    for (let index = 0; index &lt; 32; index++) {
        token = token + options[Math.floor(Math.random() * options.length)]
    }
    return token
}
</code></pre>
<h3>Generating a Token When Users Sign In to the App</h3>
<p>Step 1. Go to the sign-in endpoint and define variables for the username and password, extracting their values from <code>req.body</code>.</p>
<p>Step 2. Check if the given username and password exist in the global variable using the <code>find</code> method and an if-else statement.</p>
<p>Step 3. If the username and password are valid, call the random token generator function, store the generated token in a variable, and push that token into the global variable.</p>
<p>Step 4. If the username and password are not valid, return a message stating that the username and password are not valid.</p>
<pre><code class="language-javascript">app.post("/signin", function (req, res) {
    const username = req.body.username
    const password = req.body.password
    const user = userDetails.find((u) =&gt; {
        if (u.username == username &amp;&amp; u.password == password) {
            const userToken = genearateToken()
            u.token = userToken
            res.json({ "username":username,"password":password,"Token": userToken })

        }
        else {
            res.status(403).send({
                msg: "Invalid Username and Password"
            })

        }
    })
    console.log(userDetails);
    
})
</code></pre>
<h3>Defining an Authentication Endpoint</h3>
<p>Step 1. Define an authentication endpoint with the Get method.</p>
<p>Step 2. Define a variable in the end-points named user token that take value from the <code>req.headers.token</code></p>
<p>Step 3. And then you have to check if that token in present in the global variable then you can send the actual username and password or else you can send an Invalid Token</p>
<h4>Code Example</h4>
<ul>
<li><pre><code class="language-javascript">                                                        const express = require("express")
                                                        const app = express()
                                                        const port = 3000
                                                        app.use(express.json())
                                                        const userDetails = []
                                                        
                                                        function genearateToken() {
                                                            let token = ""
                                                            let options = [
                                                                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                                                                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
                                                            ];
                                                            for (let index = 0; index &lt; 32; index++) {
                                                                token = token + options[Math.floor(Math.random() * options.length)]
                                                        
                                                        
                                                            }
                                                            return token
                                                        
                                                        
                                                        }
                                                        
                                                        app.get("/", function (req, res) {
                                                            res.send("Hello World")
                                                        })
                                                        
                                                        app.post("/signup", function (req, res) {
                                                            const username = req.body.username
                                                            const password = req.body.password
                                                            userDetails.push({ username: username, password: password })
                                                            res.json({ msg: "You are succefully signed up" })
                                                            console.log(userDetails);
                                                        
                                                        
                                                        })
                                                        app.post("/signin", function (req, res) {
                                                            const username = req.body.username
                                                            const password = req.body.password
                                                            const user = userDetails.find((u) =&gt; {
                                                                if (u.username == username &amp;&amp; u.password == password) {
                                                                    const userToken = genearateToken()
                                                                    u.token = userToken
                                                                    res.json({ "username": username, "password": password, "Token": userToken })
                                                        
                                                                }
                                                                else {
                                                                    res.status(403).send({
                                                                        msg: "Invalid Username and Password"
                                                                    })
                                                        
                                                                }
                                                            })
                                                            console.log(userDetails);
                                                        
                                                        })
                                                        
                                                        // Authentication End Point
                                                        app.get("/user", function (req, res) {
                                                            let userToken = req.headers.token
                                                            let users = userDetails.find(user =&gt; user.token === userToken)
                                                            console.log(users);
                                                        
                                                            if (users) {
                                                                res.send({ "username": users.username, "password": users.password })
                                                            }
                                                            else {
                                                                res.send("Invalid Token")
                                                            }
                                                            console.log(userDetails);
                                                        })
                                                        app.listen(port, () =&gt; {
                                                            console.log('App is running at port', port);
                                                        
                                                        })
</code></pre>
</li>
</ul>
<h2>How to Perform Authentication Using the JWT Library</h2>
<p>Authentication is a critical part of any application, ensuring that users are who they claim to be. In this guide, we will walk through setting up authentication using the JWT (JSON Web Token) library in a Node.js application.</p>
<p>JWT is a popular method for securing APIs, as it allows for stateless authentication, meaning the server does not need to store session information.</p>
<h2>What is JWT (JSON Web Token)</h2>
<p>JWT stands for <strong>JSON Web Token,</strong> which is mostly used for authentication and information exchange between the web application.</p>
<p>JWT is stateless, which means that we don’t have to store the session data all the data is stored in the token itself.</p>
<h2>Why we use JWT Instead of Random Token</h2>
<p>JWTs are stateless, meaning we don’t have to store them in a variable or database. The token itself contains the username and password.</p>
<p>In contrast, random tokens are stateful, meaning we need to store these tokens in a variable or database.</p>
<p>If the token is stateful, we have to send a request to the database every time to verify the token, which increases the database request time.</p>
<h3>Step 1: Setting Up Your Project</h3>
<p>First, create a new Node.js project and install the necessary dependencies. You will need Express to handle HTTP requests and JSON web tokens to generate and verify tokens.</p>
<pre><code class="language-bash">mkdir jwt-authentication
cd jwt-authentication
npm init -y
npm install express jsonwebtoken
</code></pre>
<h3>Step 2: Creating the Express Server</h3>
<p>Next, create a file named <code>server.js</code> and set up a basic Express server.</p>
<pre><code class="language-javascript">const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const port = 3000;

app.get("/", function (req, res) {
    res.send("Hello World")
})

app.listen(port, () =&gt; {
    console.log('App is running at port', port);
});
</code></pre>
<h3>Step 3: Add middleware to parse JSON and Define a global variable to store user details.</h3>
<p>In this step, we need to define a global middleware to parse the JSON body from incoming requests. This middleware will allow us to easily access the data sent in the request body, headers, or query parameters</p>
<pre><code class="language-javascript">app.use(express.json())
</code></pre>
<p>Next, we have to define a global variable that can store user details. Because in this we will not use any database.</p>
<pre><code class="language-javascript">app.use(express.json())
const userDetails = []
</code></pre>
<h3>Step 5. Define a Sign-up Route with POST method for user sign-up</h3>
<p>Now, we need to create a sign-up route using the POST method so users can sign up. We define username and password variables to get the information from <code>req.body</code>.</p>
<p>After that, we store this data by pushing it in JSON format to our global array named <code>userDetails</code>. Then, we return a message indicating that the user signed up successfully.</p>
<pre><code class="language-javascript">app.post("/signup", function (req, res) {
    const username = req.body.username
    const password = req.body.password
    userDetails.push({ username: username, password: password })
    res.json({ msg: "You are succefully signed up" })
    console.log(userDetails);
})
</code></pre>
<h3>Step 5. Define a Sign-in Route with POST method for user sign-in</h3>
<p>The next endpoint will be the sign-in endpoint using the POST method. Here, we will check if the user enters the correct username and password, and then assign them a JWT token.</p>
<p>We will define two variables, <code>username</code> and <code>password</code>, get the values from <code>req.body</code>. We will check if the username and password are in our global variable.</p>
<p>If valid, we will create a new variable to convert the username into a JWT. We will call <code>jwt.sign</code> with two arguments: the username and <code>JWT_SECRET</code>. Finally, we will return the JSON data with the username, password, and JWT token.</p>
<pre><code class="language-javascript">app.post("/signin", function (req, res) {
    const username = req.body.username
    const password = req.body.password
    const user = userDetails.find((u) =&gt; {
        if (u.username == username &amp;&amp; u.password == password) {
            const userToken = jwt.sign({username:username},JWT_SECRET)
            res.json({ "username":username,"password":password,"Token": userToken })

        }
        else {
            res.status(403).send({
                msg: "Invalid Username and Password"
            })

        }
    })
    console.log(userDetails);
    
})
</code></pre>
<h3>Step 6. Define a user Route with the GET method for Authentication</h3>
<p>Now, we will define a route for the authentication process. We will create a variable <code>userToken</code> to get the value from <code>req.headers</code>. Then, we will define a variable to verify the user token by calling <code>jwt.verify</code> with two arguments: the JWT token and the secret key.</p>
<p>Once we get the actual username, we will check if the user is in our global variable. If the user is present, we will return the username and password. Otherwise, we will return a response saying "Invalid Token".</p>
<pre><code class="language-javascript">app.get("/user",function(req,res){
    let userToken=req.headers.token
    const decordeInformation=jwt.verify(userToken,JWT_SECRET) //Convert JWT into json
    const username=decordeInformation.username
    let users=userDetails.find(user=&gt;user.username===username)
    console.log(users);
    
    if (users){
        res.send({"username":users.username,"password":users.password})
    }
    else{
        res.send("Invalid Token")
    }
    console.log(userDetails);
})
</code></pre>
<h3>Conclusion</h3>
<p>The authentication process using JSON Web Tokens (JWT) is now complete. We've set up a route to handle user authentication by verifying the provided token and returning the appropriate user details.</p>
<p>Here's a detailed breakdown of the steps involved:</p>
<ol>
<li><p><strong>Define the Route</strong>: We created a route using the GET method to handle authentication requests. This route is defined at the endpoint <code>/user</code>.</p>
</li>
<li><p><strong>Extract the Token</strong>: Within the route handler, we extract the token from the request headers. This token is expected to be provided by the client in the <code>req.headers.token</code> field.</p>
</li>
<li><p><strong>Verify the Token</strong>: We use the <code>jwt.verify</code> method to decode and verify the token. This method takes two arguments: the token itself and the secret key (<code>JWT_SECRET</code>). The result of this verification is stored in the <code>decordeInformation</code> variable, which contains the decoded information from the token.</p>
</li>
<li><p><strong>Retrieve the Username</strong>: From the decoded information, we extract the username. This is done by accessing the <code>username</code> property of the <code>decordeInformation</code> object.</p>
</li>
<li><p><strong>Find the User</strong>: We then search for the user in our global <code>userDetails</code> array. This is done using the <code>find</code> method, which checks if any user in the array has a username that matches the extracted username.</p>
</li>
<li><p><strong>Return the Response</strong>:</p>
<ul>
<li><p>If the user is found, we send a response containing the user's username and password.</p>
</li>
<li><p>If the user is not found, we send a response indicating that the token is invalid.</p>
</li>
</ul>
</li>
</ol>
<p>Here's the complete code for the route:</p>
<pre><code class="language-javascript">app.get("/user", function(req, res) {
    let userToken = req.headers.token;
    const decordeInformation = jwt.verify(userToken, JWT_SECRET); // Convert JWT into JSON
    const username = decordeInformation.username;
    let users = userDetails.find(user =&gt; user.username === username);
    console.log(users);

    if (users) {
        res.send({"username": users.username, "password": users.password});
    } else {
        res.send("Invalid Token");
    }
    console.log(userDetails);
});
</code></pre>
<p>By following these steps, we ensure that only authenticated users can access their details, providing a secure way to handle user authentication in our application.</p>
<h2>How to Connect Frontend and Backend</h2>
<h2>Week 7 Day 1</h2>
<h2>What is a Database?</h2>
<p>A database is an organized collection of data that is stored and accessed electronically. Databases are designed to manage large amounts of information by storing, retrieving, and managing data efficiently.</p>
<p>They are essential for various applications, from simple data storage to complex data analysis and transaction processing.</p>
<h2>What is NoSQL Databases</h2>
<p>NoSQL Databases are a broad category of databases that diverge from the traditional relational model used in SQL Databases.</p>
<p>They are designed to handle a variety of data models and workloads that may not fit neatly into the tabular schema of relational databases.</p>
<h2>Main Advantage of NoSQL Databases</h2>
<p>There are mainly two advantages of using NoSQL Databases</p>
<ol>
<li><p>Schema Flexibility: NoSQL Databases like MongoDB provide Schema flexibility, which means that we can store that in our database which doesn’t have any fixed structure or formats.</p>
</li>
<li><p>Scalability: Many NoSQL databases are designed to scale out horizontally, making it easier to distribute data across multiple servers and handle large volumes of traffic.</p>
</li>
</ol>
<h2>What is Schema</h2>
<p>Schema provides a detailed blueprint and a comprehensive idea of how your database will be structured. It represents the logical organization and storage of data within the database.</p>
<p>Essentially, a schema outlines the way data is organized into tables, the relationships between these tables, and the constraints that govern the data.</p>
<h3>What is the Advantage of Using NoSQL Databases?</h3>
<p>NoSQL databases offer several advantages over traditional relational databases, making them popular for many modern applications. Here are some key benefits:</p>
<ol>
<li><p><strong>Scalability</strong>: NoSQL databases are designed to scale by distributing data across multiple servers. This horizontal scaling allows them to handle large volumes of data and high traffic loads more efficiently than traditional relational databases, which typically scale up by adding more powerful hardware.</p>
</li>
<li><p><strong>Flexibility</strong>: Unlike relational databases that require a fixed schema, NoSQL databases offer flexible data models. This means you can store unstructured, semi-structured, or structured data without needing to define a rigid schema upfront. This flexibility is particularly useful for applications that deal with diverse data types or rapidly changing data structures.</p>
</li>
<li><p><strong>Performance</strong>: NoSQL databases are optimized for specific data models and access patterns, which can result in faster read and write operations. For example, key-value stores are highly efficient for simple lookups, while document stores excel at managing hierarchical data.</p>
</li>
<li><p><strong>Availability</strong>: Many NoSQL databases are designed with high availability and fault tolerance in mind. They often use replication and distributed architecture to ensure that the system remains operational even if some nodes fail. This makes NoSQL databases a reliable choice for applications that require continuous uptime.</p>
</li>
<li><p><strong>Cost-Effectiveness</strong>: By leveraging commodity hardware and open-source software, NoSQL databases can be more cost-effective than traditional relational databases. The ability to scale out using inexpensive servers reduces the overall cost of ownership.</p>
</li>
<li><p><strong>Handling Big Data</strong>: NoSQL databases are well-suited for big data applications that involve large volumes of data generated at high velocity. They can efficiently process and store massive datasets, making them ideal for use cases such as real-time analytics, IoT data storage, and social media data management.</p>
</li>
<li><p><strong>Support for Modern Applications</strong>: NoSQL databases are designed to meet the needs of modern applications, such as mobile apps, web apps, and cloud-based services. They provide features like automatic sharding, replication, and eventual consistency, which are essential for building scalable and resilient applications.</p>
</li>
</ol>
<h2>What is MongoDB</h2>
<p>MongoDB is a NoSQL database that uses a document-oriented approach to data storage. Unlike traditional relational databases, MongoDB stores data in flexible, JSON-like documents.</p>
<p>These documents can have nested structures and varied fields, allowing for a more dynamic and adaptable data model. This flexibility makes it easier to handle complex data types and structures without the need for predefined schemas.</p>
<p>MongoDB's ability to store data in this way enables developers to build applications that can evolve, adding new fields and structures as needed without requiring major changes to the database schema. This makes MongoDB an excellent choice for applications that require rapid development and iteration.</p>
<h2>What is MongoDB Clusters</h2>
<p>A MongoDB Cluster is a group of servers that work together to store and manage a collection of data. In a cluster, data is distributed across multiple machines, which helps to improve performance, scalability, and reliability.</p>
<p>Each machine in the cluster is known as a node, and these nodes can be spread across different geographic locations to ensure high availability and fault tolerance.</p>
<p>Within a MongoDB Cluster, data is stored in collections, which are similar to tables in relational databases. These collections contain documents, which are the basic units of data in MongoDB.</p>
<p>Documents are stored in a flexible, JSON-like format, allowing for nested structures and varied fields. This flexibility makes it easier to handle complex data types and structures without the need for predefined schemas.</p>
<h2>Using Mongoose for MongoDB</h2>
<p>To use the MongoDB database effectively, we will utilize the Mongoose library. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward, schema-based solution to model your application data.</p>
<p>With Mongoose, you can define schemas for your database, which helps structure and validate the data you store.</p>
<p>By defining schemas, Mongoose allows you to enforce a specific structure on the documents within a collection. This means you can specify the types of data each field should contain, set default values, and even create custom validation rules.</p>
<p>This added layer of structure and validation can be incredibly useful for maintaining data integrity and consistency across your application.</p>
<h2>Create Schema With Mongoose</h2>
<p><strong>Step 1.</strong> First Install the Mongoose library using the command given below.</p>
<pre><code class="language-bash">npm i mongoose
</code></pre>
<p><strong>Step 2.</strong> Now, create a database file with the js extension.</p>
<p><strong>Step 3.</strong> The first step is to, import the Mongoose library to a variable.</p>
<pre><code class="language-javascript">const mongoose=require("mongoose")
</code></pre>
<p><strong>Step 3.</strong> Then, You have to import schema and objectId from the Mongoose like this</p>
<pre><code class="language-javascript">const Schema=mongoose.Schema
const ObjectId=mongoose.ObjectId
</code></pre>
<p><strong>Step 4.</strong> Now, define a variable that calls the new Schema constructor and inside it, specify the data type for each field.</p>
<pre><code class="language-javascript">const user=new Schema({
    name:String,
    email:String,
    password:String
})
</code></pre>
<p><strong>Step 5.</strong> Then, you have to create a model using a model function inside the Mongoose library</p>
<pre><code class="language-javascript">const usermodel=mongoose.model("users",user)
</code></pre>
<p><strong>Step 6.</strong> Now, export this model so that we can use it on our backend.</p>
<pre><code class="language-javascript">module.exports={usermodel:usermodel}
</code></pre>
<h2>Connecting MongoDB Database With Backend</h2>
<p>To connect your MongoDB database with your backend application, follow these detailed steps:</p>
<p>To connect to your MongoDB database, use the <code>mongoose.connect</code> method. You typically do this in your main server file (e.g., <code>app.js</code> or <code>server.js</code>). Here is an example of how to connect to a MongoDB database:</p>
<pre><code class="language-javascript">const mongoose = require("mongoose");
const dataBase=mongoose.connect('mongodb://localhost:27017/yourDatabaseName')
</code></pre>
<p>Replace <code>'mongodb://localhost:27017/yourDatabaseName'</code> with the actual URI of your MongoDB database.</p>
<p>Then you also have to import the database schema</p>
<pre><code class="language-javascript">const { usermodel, Todomodel } = require("./db")
</code></pre>
<h3>Example of Inserting Data into MongoDB Database via Request</h3>
<p>Here is an example of inserting a record through an API request:</p>
<pre><code class="language-javascript">app.post("/signup", async function (req, res) {
    const name = req.body.name
    const password = req.body.password
    const email = req.body.email

    try {
        let userData = await usermodel.create({
            "name": name,
            "email": email,
            "password": password
        })
        await userData.save()
    } catch (error) {
        res.status(403).json("Some error has been Occured")
    }
    res.json({ msg: "Send Successfully" })
})
</code></pre>
<h3>Example of Finding Records in MongoDB</h3>
<pre><code class="language-javascript">app.post("/signin", async function (req, res) {
    const password = req.body.password
    const email = req.body.email
    const user = await usermodel.findOne({
        email: email,
        password: password
    })
    if (user) {
        const token = jwt.sign({ id: user._id }, JWT_Secret)
        res.json({
            "Token": token
        })
    }
    else {
        res.status(403).json({ message: "Incorrect Credentials" })
    }
})
</code></pre>
<h2>Conclusion</h2>
<p>In conclusion, the MongoDB section of this article explores NoSQL databases, highlighting their benefits like schema flexibility and scalability. It introduces MongoDB as a document-oriented database that stores data in a flexible, JSON-like format, suitable for handling complex and evolving data structures.</p>
<p>The section also explains MongoDB clusters, which improve performance, scalability, and reliability by distributing data across multiple nodes. This guide is a valuable resource for developers looking to use MongoDB for their data storage and management needs.</p>
<h2>Storing Passwords in the Database with Hashing</h2>
<h2>Week 7 Day 2</h2>
<h3>What is Hashing?</h3>
<p>Hashing is a process used in computer science and cryptography to transform data into a fixed-size string of characters, which is typically a hash code.</p>
<p>This transformation is accomplished using a hash function, which takes an input (or 'message') and returns a unique hash value. The primary purpose of hashing is to enable fast data retrieval and to ensure data integrity.</p>
<h3>Why we should use Hashing</h3>
<p>Password hashing is a special technique used to securely store passwords, making them hard to misuse. Instead of storing passwords directly in our database, we should convert them to hashes and then store them.</p>
<h3>What is Salt?</h3>
<p>A randomly generated value is added to the password before the hashing. This prevents attackers from using precomputed tables (rainbow tables) to crack passwords.</p>
<h3>What is Salting?</h3>
<p>Salting is a technique used with hashing to make passwords stronger. If two users have the same password, the hash will be the same, making it easy for an attacker to crack. Salting adds randomly generated text to the password and then converts it in the hash, so each hash value differs.</p>
<h3>B-Crypt</h3>
<p><strong>B-Crypt</strong> is a popular password hashing function designed to be computationally intensive to resist brute-force attacks.</p>
<p>It incorporates a salt to protect against rainbow table attacks and includes a work factor, which determines how slow the hashing process will be.</p>
<p>This work factor can be adjusted to make the hashing process more time-consuming, thereby increasing the security of the hashed passwords.</p>
<h3>How to use the Bcrypt Library</h3>
<p><strong>Convert Password with Hashing</strong></p>
<p><strong>Step 1.</strong> First, download the Bcrypt library using the npm command shown below.</p>
<pre><code class="language-javascript">npm i bcrypt
</code></pre>
<p><strong>Step 2.</strong> Next, you need to import bcrypt into your project.</p>
<p><strong>Step 3.</strong> Then, convert the user's password using the hash function provided by the bcrypt library.</p>
<pre><code class="language-javascript">bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
    // Store hash in your password DB.
});
///Example
const hashPassword = await bcrypt.hash(password, 8)
</code></pre>
<p><strong>Step 4.</strong> Now, save the hashed password in the database.</p>
<p><strong>Hash Password Verification with Bycrypt</strong></p>
<p>Once the user sends you the username and password to the signup route, you need to retrieve it from the request header and store it in a variable.</p>
<p>Next, you must check if the user's email is in your database. For example:</p>
<pre><code class="language-javascript">app.post("/signin", async function (req, res) {
    const email = req.body.email;
    const password = req.body.password;
    const response = await UserModel.findOne({
        email: email,
    });
</code></pre>
<p>If the user's email is not in your database, you need to send a response indicating that the email is not found.</p>
<pre><code class="language-javascript">  if(!response){
        res.status(403)
        .json({
            Message:"User Not Found"
        })
    }
</code></pre>
<p>But if the user's email is present, you need to check if the password is correct. The question is, how do you check this since the password stored in the database is hashed, and the password the user sends is in plain text?</p>
<p>To do this, you use the <code>compare</code> function from the bcrypt library. It takes two arguments: the first is the password entered by the user, and the second is the hashed password stored in your database, which you can retrieve with a database call.</p>
<pre><code class="language-javascript">const passwordMatch= await bcrypt.compare(password,response.password)
</code></pre>
<p>The compare function will return true or false. If the password is correct, you can assign a JWT token. If the password doesn't match, you can return an error message.</p>
<pre><code class="language-javascript">
    if (passwordMatch) {
        const token = jwt.sign({
            id: response._id.toString()
        }, JWT_SECRET);

        res.json({
            token
        })
    } else {
        res.status(403).json({
            message: "Incorrect creds"
        })
    }
</code></pre>
<h2>Adding Schema Validation Using Zod</h2>
<p>When building applications, ensuring that the data you receive and process is valid and structured correctly is crucial.</p>
<p>This is where schema validation comes into play. By using a library like Zod, we can define schemas that your data must adhere to, providing a robust way to validate incoming data.</p>
<h3>Why Use Zod for Schema Validation?</h3>
<p><strong>Zod</strong> is a TypeScript-first schema declaration and validation library. It allows you to define the shape of your data and automatically validate it against this schema.</p>
<p>This helps catch errors early in the development process and ensures that your application handles data consistently.</p>
<h3>Setting Up Zod</h3>
<p>To get started with Zod, you first need to install it in your project. You can do this using npm or yarn:</p>
<pre><code class="language-bash">npm install zod
</code></pre>
<p>Step 1. Import the z variable from the zod module.</p>
<pre><code class="language-javascript">const {z}=require("zod")
</code></pre>
<p>Step 2. We are adding it for the signup details validation, so we will define a variable under the signup routes and use the z.object() function from Zod to create a Zod object.</p>
<pre><code class="language-javascript">const requiredBody=z.object({})
</code></pre>
<p>Step 3. In the next step, we will define some keys and their validation rules inside the object method like this:</p>
<pre><code class="language-javascript"> const requiredBody=z.object({
//check for email shoud be string
        email:z.string(),
        name:z.string(),
//check for password shoud string with max and min lenght        
        password:z.string().min(6).max(8)
    })
</code></pre>
<p>Step 4.Then we need to parse the data, so we will use the <code>.safeParse</code> method from the Zod library, which will pass this data to the request handler.</p>
<pre><code class="language-javascript">    const parsebody=requiredBody.safeParse(req.body)
</code></pre>
<p>Step 5. After you pass the data to the request handler, it will return two things: success and error. If the validation is correct, the<code>success</code> the key will be true. If not, the success key will be false, and the <code>error</code> will return an object with details about what caused the error and if success is true then <code>data</code> will return an object</p>
<pre><code class="language-javascript">const requiredBody=z.object({
        email:z.string(),
        name:z.string(),
        // adding check password should be string with mininum of 6 and maximum of 8 character.
        password:z.string().min(6).max(8)
    })

    const parsebody=requiredBody.safeParse(req.body)
    if(!parsebody.success){
        res.json({
            "Error":"Invalid Format",
            "Exact Error":parsebody.error
        })
        return
    }
//To Access the data
const { email, password, firstName, lastName } = validateData.data
</code></pre>
<h2>Week 9 React Basics</h2>
<h2>Why do we need React?</h2>
<p>React is a powerful JavaScript library that significantly enhances the process of building front-end applications. It streamlines the development of user interfaces by simplifying the way we write and manage HTML, CSS, and JavaScript code.</p>
<p>With React, developers can use a special syntax called JSX, which allows them to write HTML-like code within JavaScript.</p>
<p>This JSX is then transformed into standard HTML, CSS, and JavaScript, making it easier to create dynamic and interactive web applications.</p>
<p>One of the key advantages of using React is its component-based architecture. This approach enables developers to break down complex user interfaces into smaller, reusable components.</p>
<p>Each component manages its own state and renders independently, which promotes modularity and code reusability. This makes it easier to maintain and update applications as they grow in size and complexity.</p>
<p>To convert React code into a format that browsers can understand, we use the command <code>npm run build</code>. This command compiles the entire application, transforming the JSX and other React-specific code into plain HTML, CSS, and JavaScript files.</p>
<p>These files can then be deployed to a web server, allowing users to access the application through their web browsers. This build process ensures that the application runs efficiently and is optimized for performance.</p>
<h2>Why do we use React?</h2>
<p>When using DOM manipulation, it's very hard to build large-scale applications. Before React and other frameworks, there were popular libraries like jQuery and Backbone.js that made DOM manipulation easier.</p>
<p>However, the problem wasn't fully solved because building big applications was still difficult to maintain, and developers had to write a lot of code, which is much less with frameworks like React.</p>
<h2>What is State in React?</h2>
<p>State in React is a JavaScript object representing the application's current status or condition at any given time. It holds information about the app's dynamic parts, which are the elements that can change over time as users interact with the application.</p>
<p>For example, the state can track user inputs, form data, or the results of API calls. By managing the state effectively, React components can update and render themselves automatically whenever the state changes, ensuring the user interface remains in sync with the underlying data.</p>
<h2>What is a Component in React?</h2>
<p>A component in React is a reusable piece of code that serves as a building block for the user interface. It is designed to take in data, known as "state" or "props," and use this data to render a specific part of the UI.</p>
<p>Components can be as simple as a button or as complex as an entire form. By breaking down the UI into smaller, manageable components, developers can create more organized and maintainable code.</p>
<p>Each component can manage its state and lifecycle, allowing for dynamic and interactive applications. Components can also be nested within each other, enabling the creation of complex interfaces by combining simpler elements.</p>
<h2>What is Re-Rendering in React?</h2>
<p>A re-render in React refers to the process where the Document Object Model (DOM) is updated to reflect changes in a component's state or props.</p>
<p>When the state of a component changes, React automatically triggers a re-render to ensure that the user interface accurately represents the current data.</p>
<p>This involves recalculating the component's output and updating the DOM with any differences. Re-rendering is a crucial part of React's efficient update mechanism, allowing the UI to stay in sync with the application's data without needing to reload the entire page.</p>
<h2>What is JSX?</h2>
<p>JSX stands for JavaScript XML. It is a syntax extension that is most commonly used with React, a popular JavaScript library for building user interfaces. JSX allows developers to write HTML-like code directly within JavaScript files.</p>
<p>This capability makes it easier to create and manage the user interface in React applications by allowing developers to visually structure their UI components in a way that resembles HTML. With JSX, you can seamlessly integrate HTML tags with JavaScript logic, making your code more readable and maintainable.</p>
<p>This integration simplifies the process of designing complex user interfaces by enabling developers to use familiar HTML syntax while leveraging the power of JavaScript to handle dynamic data and interactions.</p>
<p>Additionally, JSX helps in catching errors early during compilation, as it provides a more structured way to define UI components. Overall, JSX is a powerful tool that enhances the development experience by bridging the gap between HTML and JavaScript in React applications.</p>
<h2>What is useState in React?</h2>
<p><code>useState</code> is a hook provided by React that allows you to add state management to your functional components. Before hooks, state management was primarily handled in class components, but <code>useState</code> enables you to manage the state in a more concise and functional way.</p>
<p>When you call <code>useState</code>, it returns an array with two elements: the current state value and a function to update that state. This hook is particularly useful for managing the local state within a component, such as form inputs, toggles, or any other data that might change over time.</p>
<p>By using <code>useState</code>, you can easily track and update your component's state, ensuring that your user interface reflects the latest data. This makes it a fundamental tool for building interactive and dynamic applications in React.</p>
<h2>What is useEffect in React ?</h2>
<p>The <code>useEffect</code> hook in React is a powerful tool that allows you to perform side effects in your functional components. Side effects are operations that can affect other parts of your application or interact with external systems, such as fetching data from an API, subscribing to a data stream, or manually changing the DOM.</p>
<p>When you use <code>useEffect</code>, you can specify a function that React will run after the component renders. This function can contain any logic you need to execute as a side effect, and it can also return a cleanup function to tidy up resources when the component unmounts or before the effect runs again.</p>
<p>This cleanup is particularly useful for tasks like unsubscribing from a data stream or clearing timers. The <code>useEffect</code> hook takes two arguments: the effect function and an optional array of dependencies.</p>
<p>The dependencies array allows you to control when the effect should re-run. If you provide an empty array, the effect will only run once, similar to <code>componentDidMount</code> in-class components. If you include variables in the array, the effect will run whenever any of those variables change, mimicking <code>componentDidUpdate</code>.</p>
<h2>Week 9.4</h2>
<h2>Children in React</h2>
<p>In React, the concept of children refers to the elements or components that are nested within another component. This is a fundamental aspect of building React applications, as it allows developers to create complex user interfaces by composing components together.</p>
<p>The children prop is a special property that React automatically passes to every component, enabling it to access and render any nested elements. When you define a component, you can use the children prop to render the content that is placed between the opening and closing tags of that component.</p>
<p>This makes it easy to create reusable components that can display different content based on what is passed to them as children. For example, you might have a <code>Card</code> component that can wrap various types of content, such as text, images, or other components, depending on what is passed as children.</p>
<p><code>Code Example -</code></p>
<pre><code class="language-javascript">import { Children, useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    &lt;&gt;
    &lt;Card&gt;
      &lt;div style={{color:'green',}}&gt;
        What do you want to post &lt;br /&gt;
        &lt;input type="text" /&gt;
      &lt;/div&gt;
    &lt;/Card&gt;
    &lt;/&gt;
  )

  function Card({children}) {
    return &lt;div style={{background:"white",borderRadius:"10",color:"black",padding:"10", margin:"10"}}&gt;
      {children}
    &lt;/div&gt;
    
  }
}

export default App
</code></pre>
<h2>Class-based Components vs. Functional Components</h2>
<p>In the world of React, developers have the option to create components using either class-based components or functional components. Understanding the differences between these two approaches is crucial for making informed decisions about which to use in various scenarios.</p>
<h3>Class-based Components</h3>
<p>Class-based components are the traditional way of writing React components. They are defined using ES6 classes and extend from <code>React.Component</code>. This type of component allows you to use lifecycle methods, which are special methods that get called at different points in a component's life, such as when it is mounted, updated, or unmounted. These lifecycle methods provide a structured way to handle side effects and manage component state over time.</p>
<p>For example, a class-based component might look like this:</p>
<pre><code class="language-jsx">class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  componentDidMount() {
    // Code to run after the component is mounted
  }

  render() {
    return (
      &lt;div&gt;
        &lt;p&gt;Count: {this.state.count}&lt;/p&gt;
        &lt;button onClick={() =&gt; this.setState({ count: this.state.count + 1 })}&gt;
          Increment
        &lt;/button&gt;
      &lt;/div&gt;
    );
  }
}
</code></pre>
<h3>Functional Components</h3>
<p>Functional components, on the other hand, are a more modern approach and have gained popularity with the introduction of React Hooks. These components are simply JavaScript functions that return JSX. They are often easier to read and write, especially for components that do not require complex logic or state management.</p>
<p>With Hooks like <code>useState</code> and <code>useEffect</code>, functional components can now manage state and side effects, which were previously possible only in class-based components.</p>
<p>Here is an example of a functional component using Hooks:</p>
<pre><code class="language-jsx">function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() =&gt; {
    // Code to run after the component is mounted
  }, []);

  return (
    &lt;div&gt;
      &lt;p&gt;Count: {count}&lt;/p&gt;
      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;
        Increment
      &lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<h4>Key Differences</h4>
<ul>
<li><p><strong>Syntax</strong>: Class-based components use class syntax and require the <code>render()</code> method, while functional components are plain functions that return JSX.</p>
</li>
<li><p><strong>State Management</strong>: Initially, only class-based components could manage the state, but with Hooks, functional components can also handle the state.</p>
</li>
<li><p><strong>Lifecycle Methods</strong>: Class-based components have built-in lifecycle methods, whereas functional components use Hooks like <code>useEffect</code> to achieve similar functionality.</p>
</li>
<li><p><strong>Readability and Simplicity</strong>: Functional components are generally considered more concise and easier to read, making them a preferred choice for many developers.</p>
</li>
</ul>
<h2>Life Cycle Events in React</h2>
<p>Lifecycle events in React refer to specific points in a component's life when the component changes. These events help us manage tasks like data fetching, subscriptions, and cleaning up resources.</p>
<p>By leveraging these lifecycle events, developers can ensure that their components behave predictably and efficiently throughout their existence. For instance, when a component is first added to the DOM, developers might use these events to initiate data loading or establish connections.</p>
<p>Similarly, when a component is about to be removed, these events can be used to tidy up any ongoing processes or connections, ensuring that the application remains performant and free of unnecessary resource consumption.</p>
<h2>Error Boundaries in React</h2>
<p>Error Boundaries in React are an essential feature designed to enhance the stability and reliability of applications. They act as a safety net, preventing the entire application from crashing if an error occurs within a component.</p>
<p>This is particularly useful in large applications where a single component failure could otherwise lead to a poor user experience. Error Boundaries are implemented using class-based components.</p>
<p>They work by catching JavaScript errors anywhere in their child component tree, logging those errors, and displaying a fallback UI instead of the component tree that crashed. This ensures that users can continue interacting with other parts of the application without disruption.</p>
<h2>Fragments in React</h2>
<p>In React, each component is required to return a single parent element, which can contain multiple child elements within it. This requirement can sometimes lead to the need for unnecessary wrapper elements, which can clutter the DOM and make the code less clean.</p>
<p>To address this issue, React provides a feature called <strong>Fragments.</strong> Fragments allow developers to group multiple elements without adding extra nodes to the DOM. By using Fragments, we can return various child elements from a component without the need for an additional parent element, thereby keeping the DOM structure clean and efficient.</p>
<p>This is particularly useful when you want to maintain a simple and organized codebase while ensuring that your component structure remains logical and easy to manage.</p>
<h2>Week 10 Day 1</h2>
<h2>Single Page Application in React</h2>
<p>A Single Page Application (SPA) in React is a type of web application that loads a single HTML page and dynamically updates the content as the user interacts with the app.</p>
<p>Unlike traditional multi-page applications that require a full page reload for each new piece of content, SPAs offer a smoother and more seamless user experience by only loading the necessary resources and updating the page dynamically.</p>
<h2>Routing in React</h2>
<p>Routing in React is a crucial concept that allows developers to create a seamless navigation experience within a Single Page Application (SPA). By using routing, you can define multiple routes in your application, each corresponding to a different component or view. This enables users to navigate through various sections of the app without triggering a full page reload, thereby maintaining the fluidity and speed that SPAs are known for.</p>
<h3>Steps to Setup Routes in React</h3>
<p><strong>Step 1.</strong> First Install the <code>react-router-dom</code> package in your project</p>
<p><strong>Step 2.</strong> Then, import the <code>BrowserRouter</code>, <code>Routes</code>, <code>Route</code> from the react-router-dom package</p>
<pre><code class="language-javascript">import { BrowserRouter, Routes, Route } from 'react-router-dom'
</code></pre>
<p><strong>Step 3.</strong> Next, define your Route, place it inside the Routes, and then wrap the Routes with BrowserRouter.</p>
<p>The Route will take 2 props: the first is the path where you want to set it up, and the second is the element you want to set up.</p>
<p>Example -</p>
<pre><code class="language-javascript">import { BrowserRouter, Routes, Route } from 'react-router-dom'
import './App.css'

function App() {

  return (
    &lt;&gt;
      &lt;BrowserRouter&gt;
        &lt;Routes&gt;
          &lt;Route path='/' element={&lt;Allen/&gt;} /&gt;
          &lt;Route path='/Class11' element={&lt;Class11/&gt;} /&gt;
          &lt;Route path='/Class12' element={&lt;Class12/&gt;} /&gt;
        &lt;/Routes&gt;
      &lt;/BrowserRouter&gt;
    &lt;/&gt;
  )

  function Allen() {
    return (
      &lt;&gt;
        &lt;div&gt;Welcome to the allen home page&lt;/div&gt;
      &lt;/&gt;
    )
  }

  function Class11() {
    return (
      &lt;&gt;
        &lt;div&gt;This is class 11th Program&lt;/div&gt;
      &lt;/&gt;
    )
  }
  function Class12() {
    return (
      &lt;&gt;
        &lt;div&gt;This is class 12th Program&lt;/div&gt;
      &lt;/&gt;
    )
  }
}
export default App
</code></pre>
<h2>Link Tag and useNavigate Hook in React</h2>
<p>When we need to redirect a user to a new page within a React application, we have two primary methods at our disposal. The first method involves using the <code>Link</code> tag, which is a component provided by the <code>react-router-dom</code> package.</p>
<p>By using the <code>Link</code> tag, we can create navigation links that allow users to move between different routes defined in our application without causing a full page reload. This approach is efficient and maintains the single-page application experience.</p>
<p>The second method for redirecting users is by utilizing the <code>useNavigate</code> hook, also part of the <code>react-router-dom</code> package. This hook provides a programmatic way to navigate between routes. It is particularly useful when you need to redirect users in response to certain actions, such as form submissions or button clicks, where a <code>Link</code> tag might not be appropriate.</p>
<p>The <code>useNavigate</code> hook returns a function that can be called with the desired path, allowing for dynamic and conditional navigation based on the application's state or user interactions.</p>
<h3>Routing with the help of link tag</h3>
<pre><code class="language-javascript">import { BrowserRouter, Routes, Route, Link} from 'react-router-dom'
import './App.css'
function App() {
  return (
    &lt;&gt;
      &lt;BrowserRouter&gt;
    &lt;div&gt;
      &lt;Link to="/"&gt;Allen |&lt;/Link&gt; 
      &lt;Link to="/Class11"&gt;Class 11 |&lt;/Link&gt;
      &lt;Link to="/Class12"&gt;Class 12 |&lt;/Link&gt;
    &lt;/div&gt;
        &lt;Routes&gt;
          &lt;Route path='/' element={&lt;Allen/&gt;} /&gt;
          &lt;Route path='/Class11' element={&lt;Class11/&gt;} /&gt;
          &lt;Route path='/Class12' element={&lt;Class12/&gt;} /&gt;
        &lt;/Routes&gt;
      &lt;/BrowserRouter&gt;
    &lt;/&gt;
  )
</code></pre>
<h2>Routing with useNavigate Hook</h2>
<p>In React, another effective way to handle routing is by using the <code>useNavigate</code> hook, which is part of the <code>react-router-dom</code> package. This hook is particularly valuable when you want to implement routing that responds to specific user actions, such as clicking a button or submitting a form. Unlike the <code>Link</code> component, which is used for static navigation, <code>useNavigate</code> allows for more dynamic and flexible routing.</p>
<p>The <code>useNavigate</code> hook returns a function that you can call with the path you want to navigate to. This makes it possible to redirect users based on various conditions or application states.</p>
<p>For instance, you might want to redirect a user to a different page after they successfully submit a form or complete a certain task. By using <code>useNavigate</code>, you can achieve this programmatically, ensuring a smooth and responsive user experience.</p>
<p>Here's a basic example of how you might use the <code>useNavigate</code> hook in a React component:</p>
<pre><code class="language-jsx">import { useNavigate } from 'react-router-dom';

function MyComponent() {
  const navigate = useNavigate();

  const handleButtonClick = () =&gt; {
    // Perform some logic here
    navigate('/target-path');
  };

  return (
    &lt;button onClick={handleButtonClick}&gt;
      Go to Target Page
    &lt;/button&gt;
  );
}
</code></pre>
<p>In this example, when the button is clicked, the <code>handleButtonClick</code> the function is triggered, which then calls the <code>navigate</code> function with the desired path. This approach provides a seamless way to manage navigation in response to user interactions, enhancing the overall functionality of your application.</p>
<h2>Setup Error Page Route in React</h2>
<p>In React, setting up error pages for routes that are not available in our application is a crucial step in improving the overall user experience. When users navigate to a URL that doesn't match any of the defined routes, they can be greeted with a custom error page, often referred to as a "404 page."</p>
<p>This page informs users that the page they are looking for cannot be found, and it can also provide helpful navigation options to guide them back to the main sections of the app.</p>
<p>To implement this, you can define a route that matches all paths not covered by other routes. This is typically done using a wildcard route that catches any unmatched paths. Here’s a detailed example of how you can set up an error page route in a React application using <code>react-router-dom</code>:</p>
<pre><code class="language-jsx">import React from 'react';
import { BrowserRouter, Router, Routes, Route } from 'react-router-dom';

function HomePage() {
  return &lt;h1&gt;Welcome to the Home Page&lt;/h1&gt;;
}

function AboutPage() {
  return &lt;h1&gt;About Us&lt;/h1&gt;;
}

function ErrorPage() {
  return (
    &lt;div&gt;
      &lt;h1&gt;404 - Page Not Found&lt;/h1&gt;
      &lt;p&gt;Sorry, the page you are looking for does not exist.&lt;/p&gt;
      &lt;a href="/"&gt;Go back to Home&lt;/a&gt;
    &lt;/div&gt;
  );
}

function App() {
  return (
    &lt;Router&gt;
      &lt;Routes&gt;
        &lt;Route path="/" element={&lt;HomePage /&gt;} /&gt;
        &lt;Route path="/about" element={&lt;AboutPage /&gt;} /&gt;
        &lt;Route path="*" element={&lt;ErrorPage /&gt;} /&gt;
      &lt;/Routes&gt;
    &lt;/Router&gt;
  );
}

export default App;
</code></pre>
<p>In this example, we have a simple React application with three components: <code>HomePage</code>, <code>AboutPage</code>, and <code>ErrorPage</code>. The <code>ErrorPage</code> component is designed to display a message indicating that the requested page could not be found. It also includes a link to redirect users back to the homepage.</p>
<p>The <code>App</code> component uses <code>react-router-dom</code> to define routes for the home and about pages. The wildcard route (<code>path="*"</code>) is used to catch all unmatched URLs, directing users to the <code>ErrorPage</code> component.</p>
<p>This setup ensures that users have a clear understanding of what went wrong and provides them with an easy way to navigate back to familiar territory, thereby enhancing the overall usability and professionalism of your application.</p>
<h2>Layout in React with Outlet</h2>
<p>In React JS, the <code>Outlet</code> component plays a crucial role when working with nested routes, particularly in applications using <code>react-router-dom</code>. It acts as a placeholder that renders child routes within a parent route.</p>
<p>This is especially useful when you want to create a layout that remains consistent across different sections of your application while allowing specific content to change based on the current route.</p>
<p>For instance, consider a scenario where you have a main dashboard page with several sub-sections like "Profile," "Settings," and "Notifications." You can define a parent route for the dashboard and use the <code>Outlet</code> component to render the appropriate child component based on the user's navigation. This approach not only simplifies the routing logic but also ensures that the overall structure and layout of the dashboard remain intact, providing a seamless user experience.</p>
<pre><code class="language-javascript">function App() {
  return (
    &lt;&gt;
      &lt;BrowserRouter&gt;
        &lt;Routes&gt;
          &lt;Route path='/' element={&lt;Layout /&gt;} &gt;
            &lt;Route index element={&lt;Allen /&gt;} /&gt;
            &lt;Route path='/Class11' element={&lt;Class11 /&gt;} /&gt;
            &lt;Route path='/Class12' element={&lt;Class12 /&gt;} /&gt;
          &lt;/Route&gt;
        &lt;/Routes&gt;
      &lt;/BrowserRouter&gt;
    &lt;/&gt;
  )

  function Layout() {
    return (
      &lt;&gt;
        &lt;div&gt;
          &lt;Header /&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;Outlet /&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;Footer /&gt;
        &lt;/div&gt;
      &lt;/&gt;
    )
  }
</code></pre>
<h2>useRef Hook in React?</h2>
<p>In React, useRef is a hook that provides a way to create a <strong>reference</strong> to a value or a DOM element that persists across renders but <strong>does not trigger a re-render</strong> when the value changes.</p>
<h3>Key Characteristics of useRef:</h3>
<ol>
<li><p><strong>Persistent Across Renders</strong>: The value stored in <code>useRef</code> stays the same between component re-renders. This means the value of a <code>ref</code> doesn't reset when the component re-renders, unlike regular variables.</p>
</li>
<li><p><strong>No Re-Renders on Change</strong>:Changing the value of a <code>ref</code> (<code>ref.current</code>) does <strong>not</strong> make a component re-render. This is different from state (<code>useState</code>), which causes a re-render when it changes.</p>
</li>
</ol>
<p>Example</p>
<pre><code class="language-javascript">const btnRef=useRef()
  return (
    &lt;&gt;
    Signup Form
    &lt;input ref={btnRef} type="text" /&gt;
    &lt;input  type="text" /&gt;
    &lt;button onClick={()=&gt;{
      btnRef.current.focus()
    }}&gt;Submit&lt;/button&gt;
</code></pre>
<h2>Week 10 Day 2</h2>
<p>Prop Drilling</p>
<h2>Rolling up State in React</h2>
<p>Rolling up state refers to combining several related state variables into one cohesive state object. Instead of having multiple <code>useState</code> hooks for each individual piece of state, you use a single <code>useState</code> hook with an object that holds all the related state values. This can make your component's state easier to manage and understand.</p>
<h3><strong>Benefits of Rolling Up State</strong></h3>
<ol>
<li><p><strong>Simplified State Management</strong>: By consolidating state variables, you reduce the number of <code>useState</code> hooks, making your component's logic more straightforward and easier to follow.</p>
</li>
<li><p><strong>Easier Updates</strong>: When you need to update multiple related state values, you can do so in one operation, reducing the risk of errors and ensuring consistency.</p>
</li>
<li><p><strong>Improved Readability</strong>: With a single state object, it becomes clearer how different pieces of state relate to each other, improving the readability of your code.</p>
</li>
</ol>
<p>Example</p>
<pre><code class="language-javascript">import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

function App() {
  return (
    &lt;&gt;
      &lt;LightBulb&gt;&lt;/LightBulb&gt;
    &lt;/&gt;
  )
}

function LightBulb() {
  const [bulb, setbulb] = useState(false)
  return (
    &lt;&gt;
      &lt;BulbState bulb={bulb}&gt;&lt;/BulbState&gt;
      &lt;ToggleButton setbulb={setbulb} bulb={bulb}&gt;&lt;/ToggleButton&gt;
    &lt;/&gt;
  )
}

function BulbState({bulb}) {
  return (
    &lt;&gt;
      {bulb ? "Bulb is on" : "Bulb is off"}
    &lt;/&gt;
  )
}

function ToggleButton({setbulb}) {
  return (
    &lt;&gt;
    &lt;br /&gt;
     &lt;button onClick={()=&gt;setbulb(currentState=&gt;!currentState)}&gt;Toggle Button&lt;/button&gt;
    &lt;/&gt;
  )
}
export default App
</code></pre>
<h2>Context API</h2>
<p>Context API is a powerful tool in React that helps us manage state more effectively across our app, especially with deeply nested components.</p>
<p>It allows us to share values (like state or functions) directly with a component without manually passing props down through each level. By using the Context API, we can create a context object that holds the data or functions we want to share.</p>
<p>This context object can then be accessed by any component within the application that subscribes to it, allowing for a more efficient and cleaner way to manage the state.</p>
<h2>Setting up Context API in React</h2>
<p><strong>Step 1.</strong> Import the useContext and createContext from react.</p>
<pre><code class="language-javascript">import { useContext, createContext } from 'react'
</code></pre>
<p><strong>Step 2.</strong> Define a variable and call the createContext() function.</p>
<pre><code class="language-javascript">const BulbContext = createContext()
</code></pre>
<p><strong>Step 3.</strong> Next, you have to wrap the component under the context provider to specify the value of its context.</p>
<pre><code class="language-javascript">import { useState, useContext, createContext } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

const BulbContext = createContext()

function App() {
  const [bulb, setbulb] = useState(false)
  return (
    &lt;&gt;
      &lt;BulbContext.Provider&gt;
        &lt;LightBulb&gt;&lt;/LightBulb&gt;
      &lt;/BulbContext.Provider&gt;
    &lt;/&gt;
  )
}
</code></pre>
<p><strong>Step 4.</strong> Now, you must provide the value you want to pass on in the provider wrapper.</p>
<pre><code class="language-javascript">import { useState, useContext, createContext } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

const BulbContext = createContext()

function App() {
  const [bulb, setbulb] = useState(false)
  return (
    &lt;&gt;
      &lt;BulbContext.Provider value={{ bulb: bulb, setbulb: setbulb }}&gt;
        &lt;LightBulb&gt;&lt;/LightBulb&gt;
      &lt;/BulbContext.Provider&gt;
    &lt;/&gt;
  )
}
</code></pre>
<p><strong>Step 5.</strong> To utilize the variable you have passed through the context provider, you need to destructure it and define a hook using <code>useContext</code>.</p>
<p>This hook requires the context you created as its argument. By doing so, you can easily access the context values within your component.</p>
<pre><code class="language-javascript">function BulbState() {
  const { bulb } = useContext(BulbContext)
  return (
    &lt;&gt;
      {bulb ? "Bulb is on" : "Bulb is off"}
    &lt;/&gt;
  )
}
</code></pre>
<h2>Custom Hook</h2>
<p>A custom hook in React is a special function that internally leverages one or more built-in React hooks. This allows you to encapsulate and reuse stateful logic across different components cleanly and efficiently.</p>
<p>By creating custom hooks, you can extract component logic into reusable functions, making your code more modular and easier to maintain.</p>
<p>Example</p>
<pre><code class="language-javascript">import React from "react";
import { useState } from "react";

function useCounter() {
  const [count, setCount] = useState(0)
  function increaseCount() {
    setCount(c =&gt; c + 1)
  }
  return {
    count: count,
    increaseCount: increaseCount
  }
}

function App() {
  const{count,increaseCount}=useCounter()
  return (
    &lt;&gt;
      &lt;button onClick={increaseCount}&gt;Counter {count}&lt;/button&gt;
    &lt;/&gt;
  )
}
export default App
</code></pre>
<h2>useFetch Hook</h2>
<p>The <code>useFetch</code> hook in React is a custom hook designed to simplify the process of making server requests and retrieving data. This hook is particularly useful when you need to perform asynchronous operations, such as fetching data from an API endpoint.</p>
<p><strong>useFetch Hook Example</strong></p>
<pre><code class="language-bash">import { useEffect } from "react";
import { useState } from "react";
export function useFetch(url) {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({})
    async function fetchData() {
        setLoading(true);
        const requestURL = await fetch(url)
        const response = await requestURL.json()
        setData(response)
        setLoading(false);
    }
    useEffect(() =&gt; {
        fetchData()
    }, [url])
    return {data,loading}
}
</code></pre>
<p><strong>uses of useFetch Hook</strong></p>
<pre><code class="language-bash">import React, { useState, useEffect } from "react";
import { useFetch } from "./useFetch";
function App() {
  const [post,setPost]=useState(1)
  const { data, loading } = useFetch("https://jsonplaceholder.typicode.com/posts/"+post)
  return (
    &lt;&gt;
      &lt;button onClick={()=&gt;setPost(1)}&gt;Post 1&lt;/button&gt;
      &lt;button onClick={()=&gt;setPost(2)}&gt;Post 2&lt;/button&gt;
      &lt;button onClick={()=&gt;setPost(3)}&gt;Post 3&lt;/button&gt;
      {loading ? 
      &lt;div&gt;Loading...&lt;/div&gt; :
      &lt;pre&gt;{JSON.stringify(data.title)}&lt;/pre&gt;}
    &lt;/&gt;
  )

}
export default App;
</code></pre>
<pre><code class="language-javascript">import React, { useEffect } from "react"
import { useState } from "react"

export function useFetch(url,retryTimeout) {
    const [post, setPost] = useState({})
    const [loading,setLoading]=useState(false)

    async function getPost() {
        setLoading(true)
        let data = await fetch(url)
        let response= await data.json()
        setPost(response)
        setLoading(false)
    }

    useEffect(() =&gt; {
        getPost()
    }, [url])

    useEffect(() =&gt; {
    let autoPostFetch= setInterval(() =&gt; {
        getPost()
     }, retryTimeout*1000);
    
      return () =&gt; {
        clearTimeout(autoPostFetch)
      }
    }, [])
    
return {
    post,
    loading
}
}
</code></pre>
<h2>usePrev Hook</h2>
<p>The usePrev hook is a custom hook that uses the useRef hook to keep track of the previous value of a state. For example, if a state changes from 0 to 1 and then from 1 to 2, it stores the previous state value, which is 1, when the state updates from 1 to 2.</p>
<p><strong>usePrev hook Example -</strong></p>
<pre><code class="language-javascript">import { useEffect, useRef } from "react";
export function usePrev(value) {
const ref = useRef()
// effect will run afeter the ref.current
   useEffect(()=&gt;{
    ref.current=value
   },[value])
   // React return first and then update
   return ref.current
// ref.current first run first
}
</code></pre>
<p><strong>Use Case of usePrev hook</strong></p>
<pre><code class="language-javascript">import React from "react";
import { useState } from "react";
import { useFetch } from "./hooks/UseFetch";
import { usePrev } from "./hooks/UsePrev";

function App() {
  const [count,setCount]=useState(0)
  const prev=usePrev(count)
  return (
    &lt;&gt;
    &lt;p&gt;Counter value {count}&lt;/p&gt;
    &lt;button onClick={()=&gt;{setCount((c)=&gt;c+1)}}&gt;Increae Value&lt;/button&gt;
    &lt;p&gt;Previous value {prev}&lt;/p&gt;
    &lt;/&gt;
  )
}
export default App
</code></pre>
<h3>useDebounce Hook</h3>
<p>The <code>useDebounce</code> hook is a custom hook that delays the execution of a function until a certain amount of time has passed since it was last called. This is useful for optimizing performance by limiting the number of times a function runs, especially in response to user input or other frequent events.</p>
<p>Here's a simple example of how you might use the <code>useDebounce</code> hook:</p>
<pre><code class="language-javascript">import React from 'react';
import { useRef } from 'react';
import { useState } from 'react';

function useDebounce(originalfn) {
  const currentClock = useRef()
  const fn = () =&gt; {
    clearTimeout(currentClock.current)
    currentClock.current = setTimeout(originalfn, 200)
  }
  return fn
}

function DebounceHook() {
  function callFunction() {
    fetch("https://jsonplaceholder.typicode.com/posts/1/")
  }
  const debounceHook = useDebounce(callFunction)
  return (
    &lt;&gt;
      &lt;input type="text" onChange={debounceHook} /&gt;
    &lt;/&gt;
  );
}

export default DebounceHook;
</code></pre>
<h1>Recoil (State Management Library)</h1>
<p>Recoil in React is a state management library that provides a way to manage the global state with fine-grained controls. It minimises unnecessary re-renders by rendering the component that depends on the changed atom.</p>
<h2>Atom in Recoil</h2>
<p>Atoms in Recoil are the units of states that can be read and written from any component. The component that subscribes or uses those atoms will re-render if the atom state changes</p>
<h2>How to use Recoil in our Project</h2>
<p><strong>Step 1.</strong> First, install the recoil npm package for your project.</p>
<pre><code class="language-bash">npm i recoil
</code></pre>
<p><strong>Step 2.</strong> Wrap the main component with <code>&lt;RecoilRoot&gt;</code></p>
<pre><code class="language-javascript">function App() {
  return (
    &lt;&gt;
      &lt;RecoilRoot&gt;
        &lt;Counter /&gt;
      &lt;/RecoilRoot&gt;
    &lt;/&gt;
  )
}
</code></pre>
<p><strong>Step 3.</strong> Create a counter atom that takes two values: the first is a the key to uniquely uniquely identifying the atom, and the second its its default value. You can define these atoms in a separate file and import them into your app or component.</p>
<pre><code class="language-javascript">const counterAtom=atom({key:"counter",default:0})
</code></pre>
<p><strong>Step 4.</strong> Now, use the <code>useRecoilValue(atomName)</code> hook and pass the name of the atom you want to display in the app or component.</p>
<pre><code class="language-javascript">import React from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import { RecoilRoot,useRecoilState,useRecoilValue,useSetRecoilState } from 'recoil'
import {counterAtom} from './store/Counter'

function App() {
  return (
    &lt;&gt;
      &lt;RecoilRoot&gt;
        &lt;Counter /&gt;
      &lt;/RecoilRoot&gt;
    &lt;/&gt;
  )
}

function Counter() {
    return (
    &lt;&gt;
      &lt;CurrentCount/&gt;
      &lt;Increase/&gt;
      &lt;Decrease/&gt;
    &lt;/&gt;

  )
}
function CurrentCount(){
  const count=useRecoilValue(counterAtom)
  return(
    &lt;div&gt;{count}&lt;/div&gt;
  )
}
</code></pre>
<p><strong>Step 5.</strong> Next, you need to use the <code>useSetRecoilState(atomName)</code> hook, which is a setter function to update the atom's value. This is how you can change the atom's value.</p>
<pre><code class="language-javascript">import React from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import { RecoilRoot,useRecoilState,useRecoilValue,useSetRecoilState } from 'recoil'
import {counterAtom} from './store/Counter'

function App() {

  return (
    &lt;&gt;
      &lt;RecoilRoot&gt;
        &lt;Counter /&gt;
      &lt;/RecoilRoot&gt;
    &lt;/&gt;
  )
}

function Counter() {
    return (
    &lt;&gt;
      &lt;CurrentCount/&gt;
      &lt;Increase/&gt;
      &lt;Decrease/&gt;
    &lt;/&gt;

  )
}
function CurrentCount(){
  const count=useRecoilValue(counterAtom)
  return(
    &lt;div&gt;{count}&lt;/div&gt;
  )
}
function Increase() {
 const setCount=useSetRecoilState(counterAtom)
  function increase() {
    setCount(c =&gt; c + 1)
  }
  return (
    &lt;button onClick={increase}&gt;Increase&lt;/button&gt;
  )
}

function Decrease() {
  
  const setCount=useSetRecoilState(counterAtom)
  function decrease() {
    setCount(c =&gt; c - 1)
  }
  return (
    &lt;button onClick={decrease}&gt;Decrease&lt;/button&gt;
  )
}
export default App
</code></pre>
<h2>Memo API in React</h2>
<p>The <strong>Memo API</strong> in React is a powerful tool designed to optimize the performance of functional components. It allows developers to prevent unnecessary re-renders by memoizing the output of a component.</p>
<p>This means that React will only re-render the component if its props have changed, thus saving computational resources and improving the overall efficiency of the application.</p>
<p>When you use the <code>React.memo</code> function, you wrap your component with it, and React will remember the result of the last render. If the component receives the same props as before, React will skip rendering the component and reuse the last rendered output.</p>
<p>This is particularly useful in scenarios where components rely on expensive calculations or when dealing with large data lists.</p>
<p>To implement the Memo API, you simply import <code>React</code> and use <code>React.memo</code> to wrap your component. For example:</p>
<pre><code class="language-jsx">import React from 'react';

const MyComponent = React.memo((props) =&gt; {
  // Component logic here
  return &lt;div&gt;{props.value}&lt;/div&gt;;
});
</code></pre>
<p>In this example, <code>MyComponent</code> will only re-render if the <code>value</code> prop changes. This can significantly enhance the performance of your application, especially when dealing with complex UI structures or when components are nested deeply within the component tree.</p>
<p>Additionally, <code>React.memo</code> can accept a second argument, a custom comparison function, which allows you to define more complex logic for determining when a component should re-render. This function receives the previous and next props as arguments and should return <code>true</code> if the props are equal and <code>false</code> if they are not.</p>
<p>By leveraging the Memo API, developers can create more efficient, responsive, and performant React applications that provide a better user experience.</p>
<h1>UI/UX for Developers</h1>
<h2>Typography</h2>
<p>A typeface is the design of the letter. Font means a specific weight and style within the typeface like <code>Poppins Bold 16px</code> . A typeface is the family and a font is an individual font member.</p>
<h3>TailwindCSS: A Utility-First CSS Framework</h3>
<p>TailwindCSS is a popular utility-first CSS framework that provides developers with a set of predefined classes to build custom designs directly in their markup.</p>
<p>Unlike traditional CSS frameworks that offer a set of pre-designed components, TailwindCSS focuses on providing low-level utility classes that enable developers to create unique designs without having to write custom CSS.</p>
<h4>Key Features of TailwindCSS</h4>
<ol>
<li><p><strong>Utility-First Approach</strong>: TailwindCSS is built around the concept of utility classes, which are single-purpose classes that apply specific styles. This approach allows developers to quickly style elements by combining these classes directly in the HTML.</p>
</li>
<li><p><strong>Highly Customizable</strong>: TailwindCSS offers extensive customization options. Developers can easily configure the framework to fit their design requirements by modifying the default theme, extending it with custom styles, or even replacing it entirely.</p>
</li>
<li><p><strong>Responsive Design</strong>: TailwindCSS includes responsive utility variants, making it straightforward to create responsive designs. Developers can apply different styles at various breakpoints by using responsive prefixes, ensuring that their designs look great on all devices.</p>
</li>
<li><p><strong>Built-in Dark Mode Support</strong>: Tailwindcss provides built-in support for dark mode, allowing developers to switch between light and dark themes easily. This feature is increasingly important as more users prefer dark mode for its aesthetic and potential eye strain reduction.</p>
</li>
<li><p><strong>Community and Ecosystem</strong>: TailwindCSS has a vibrant community and a growing ecosystem of plugins and tools. Developers can leverage these resources to extend the framework's functionality and integrate it seamlessly into their projects.</p>
</li>
</ol>
<h4>Benefits of Using TailwindCSS</h4>
<ul>
<li><p><strong>Rapid Prototyping</strong>: With its utility-first approach, TailwindCSS allows developers to quickly prototype designs without writing custom CSS. This speed is invaluable during the early stages of development when iterating on design ideas.</p>
</li>
<li><p><strong>Consistent Design</strong>: By using predefined utility classes, developers can maintain a consistent design language across their projects. This consistency helps in creating cohesive and professional-looking interfaces.</p>
</li>
<li><p><strong>Reduced CSS Bloat</strong>: TailwindCSS encourages the use of utility classes over custom styles, which can lead to a significant reduction in CSS bloat. The JIT compiler further minimises the final CSS size by including only the styles used in the project.</p>
</li>
<li><p><strong>Improved Collaboration</strong>: TailwindCSS's class-based approach makes it easier for teams to collaborate on design and development. Designers and developers can work together more effectively, as the design language is clearly defined and easy to understand.</p>
</li>
</ul>
<h3>Setting Up TailwindCSS v4 in a React Project</h3>
<p>Integrating TailwindCSS into a React project can significantly enhance your development workflow by providing a streamlined and efficient way to style your application. Here’s a step-by-step guide to setting up TailwindCSS in a React project:</p>
<ol>
<li><p><strong>Create a New React Project</strong>: If you haven't already, start by creating a new React project. You can do this using <code>npm create vite@latest</code>, which sets up a modern web development environment with no configuration needed. Run the following command in your terminal:</p>
<pre><code class="language-bash">npm create vite@latest
</code></pre>
</li>
<li><p><strong>Install TailwindCSS</strong>: Once your React project is ready, you need to install TailwindCSS. Use npm or yarn to add these packages to your project:</p>
<pre><code class="language-bash">npm install tailwindcss @tailwindcss/vite
</code></pre>
</li>
<li><p><strong>Configure Vite Plugin</strong>: After installing TailwindCSS, you need to configure it in <code>vite.config.js</code> the file.</p>
<pre><code class="language-javascript">import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
// Import TailwindCSS and add in the condigutation
export default defineConfig({
  plugins: [
    vite(),tailwindcss(),
  ],
})
</code></pre>
</li>
<li><p><strong>CSS Imports</strong>: Add the <code>@import "tailwindcss";</code> is your main CSS file like <code>app.css</code> <code>index.css</code></p>
<pre><code class="language-css">@import "tailwindcss";
</code></pre>
</li>
<li><p><strong>Start Your Development Server</strong>: Now that TailwindCSS is set up, you can start your development server to see TailwindCSS in action. Run the following command:</p>
<pre><code class="language-bash">npm run dev
</code></pre>
</li>
</ol>
<p>Following these steps will help you effectively set up TailwindCSS in your React project, enabling you to take advantage of its powerful utility-first approach to styling. This setup will not only speed up the development process but also ensure a consistent and maintainable design system across your application.</p>
<h2>Customisation in TailwindCSS</h2>
<h2>Manual Dark Mode and Light Mode in TailwindCSS</h2>
<h2>Creating a Transition in TailwindCSS</h2>
<h2>Creating a Transition Slidebar with TailwindCSS</h2>
<h2>Mobile First Approach</h2>
<h1>Week-14 TypeScript</h1>
<h2>What is Typescript?</h2>
<p>TypeScript is a language developed and maintained by Microsoft. It is built on top of JavaScript, meaning it includes type safety checks that help catch errors during compilation, similar to compilers used for languages like Java and C++.</p>
<p>TypeScript code can't run directly in your browser or even in Node.js. First, it must be compiled into JavaScript, which can then be used for deployment. When TypeScript compiles the code into JavaScript, it performs type checks similar to other languages like Java and C++. The compilation will stop if there is an error.</p>
<p>This process allows you to catch compilation errors and safeguard your code, preventing runtime errors when users are using the application.</p>
<h2>TypeScript Compiler</h2>
<p>Types of Languages</p>
<ol>
<li><p><strong>Strongly typed languages</strong> - Languages that have strict type-checking are known as strongly typed languages, like C++, Java, Rust, etc. For example, suppose we initialise a variable and define it will store a number, and in the next step we store a string value, then in this case it will throw an error.</p>
</li>
<li><p>Loosely typed languages - Languages that do not have strict type-checking are known as loosely typed languages, like JavaScript and Python, etc. For example, suppose we initialise a variable and define it will store a number, and in the next step we store a string value, then in this case these languages don’t throw an error.</p>
</li>
<li><p>Compiled Language</p>
</li>
<li><p>Interpreted Language</p>
</li>
<li><p>High-Level Language - Languages that are readable by humans and understandable are called high-level languages like Java, c++, python, and javascript</p>
</li>
<li><p>Low-Level Language - Languages that are not readable by humans and not understandable these languages are called low-level language example -Assembly language</p>
</li>
</ol>
<h2>Compilation</h2>
<p>A process of checking whether the code is correct or not. If the code has a mistake, then the compilation will fail and give a compilation error. The compiler do the compiler process</p>
<h2>Interpreted Language</h2>
<p>The interpreted language does both compile and run the code. If the code has a mistake or any issue, then it will throw a runtime error. An interpreted language is faster while writing code because of its two-way combined steps, including compilation and interpretation</p>
<h2>Initialise the typescript project</h2>
<p><strong>Step 1.</strong> <code>npm i -g typescript</code> used to install the typescript in your system globally</p>
<p><strong>Step 2</strong>. <code>npx tsc —init</code> to initialise the typescript project</p>
<h2>Types in TypeScript</h2>
<ol>
<li><p>Number</p>
</li>
<li><p>String</p>
</li>
<li><p>Any</p>
</li>
</ol>
<h2>Callback function type in TypeScript</h2>
<pre><code class="language-typescript">function delayedCall(anotherFunction:()=&gt;void){
//code

}
</code></pre>
<h2>tsConfig File</h2>
<p>tsConfig file has some options that you can choose to configure your tsc compiler.</p>
<p>Some of the most common configuration options are</p>
<ol>
<li><p>target is configuring which ECMAScript version of JavaScript code you want to convert. This is important if you want your code will work on older browsers.</p>
</li>
<li><p>rootDir: used to set the root directory of the TypeScript code to split out the js code. So, that you will have a better and more manageable folder structure.</p>
</li>
<li><p>outDir: used to set the output directory of the TypeScript code to store the split-out compiler js code.</p>
</li>
</ol>
<h2>Interface in TypeScript</h2>
<p>In TypeScript, interfaces are a powerful way to define the structure of an object. They allow you to specify the types of properties that an object should have, making your code more robust and easier to understand. When you pass an interface as a type, you are essentially using it to enforce a specific shape for the objects you work with. This ensures that the objects conform to the expected structure, reducing errors and improving code quality.</p>
<h2>Optional Parameter in TypeScript</h2>
<pre><code class="language-typescript">interface user{
    name:string,
    age:number,
    address:{
        // addind ? after city makes it optional
        city?:string,
        country:string
    }
}

let user:user ={
    name:"Aditya",
    age:21,
    address:{
        // city:"Haryanya",
        country:"India"
    }
}
</code></pre>
<h2>Passing Interface as a Type</h2>
<p>When you pass an interface as a type, you are essentially using it to enforce a specific shape for the objects you work with. This ensures that the objects conform to the expected structure, reducing errors and improving code quality.</p>
<p>To pass an interface as a type, you first define the interface with the desired properties and their types. For example, consider an interface named <code>User</code>:</p>
<pre><code class="language-typescript">interface User {
    name: string;
    age: number;
    address: {
        city?: string; // The question mark indicates that this property is optional
        country: string;
    };
}
</code></pre>
<p>In this example, the <code>User</code> The interface specifies that a user object must have a <code>name</code> of type <code>string</code>, an <code>age</code> of type <code>number</code>, and an <code>address</code> object. The <code>address</code> The object must include a <code>country</code> of type <code>string</code>, and may optionally include a <code>city</code> of type <code>string</code>.</p>
<p>Once the interface is defined, you can use it to type-check objects. For instance, you can create a variable <code>user</code> and assign it an object that adheres to the <code>User</code> interface:</p>
<pre><code class="language-typescript">let user: User = {
    name: "Aditya",
    age: 21,
    address: {
        country: "India"
    }
};
</code></pre>
<p>In this case, the <code>user</code> The object meets the requirements of the <code>User</code> interface. It includes the mandatory <code>name</code> and <code>age</code> properties, as well as the <code>address</code> object with the required <code>country</code> property. The optional <code>city</code> The property is omitted, which is perfectly acceptable due to its optional nature.</p>
<p>By using interfaces as types, you can ensure that your objects are consistently structured, making your TypeScript code more predictable and easier to maintain. This practice is especially useful in larger projects where the complexity of data structures can increase significantly.</p>
<h2>Difference Between Interfaces and Types</h2>
<p>Interfaces can be implemented as classes you can’t to in types</p>
<table>
<thead>
<tr>
<th>Aspect</th>
<th>Interface</th>
<th>Type</th>
</tr>
</thead>
<tbody><tr>
<td>Definition</td>
<td>Used to define a contract for classes, specifying what methods and properties should be implemented.</td>
<td>Used to define a type for variables, functions, or objects, specifying the shape of data.</td>
</tr>
<tr>
<td>Extensibility</td>
<td>It can be extended by other interfaces or classes using the <code>extends</code> keyword.</td>
<td>Can be extended using intersection types with <code>&amp;</code>.</td>
</tr>
<tr>
<td>Declaration Merging</td>
<td>Supports declaration merging, allowing multiple declarations to be combined.</td>
<td>Does not support declaration merging.</td>
</tr>
<tr>
<td>Use Cases</td>
<td>Best for defining the structure of classes and ensuring they adhere to a specific contract.</td>
<td>Best for defining complex types, unions, and intersections.</td>
</tr>
<tr>
<td>Implementation</td>
<td>It can be implemented by classes to ensure they follow the defined structure.</td>
<td>It cannot be implemented by classes.</td>
</tr>
<tr>
<td>union &amp; intersection</td>
<td>Interfaces don’t allow union and intersection</td>
<td>Type allows union and intersection</td>
</tr>
<tr>
<td>Syntax</td>
<td>Uses the <code>interface</code> keyword.</td>
<td>Uses the <code>type</code> keyword.</td>
</tr>
</tbody></table>
<h2>Difference Between Abstract Class and Interfaces</h2>
<ol>
<li>We can implement</li>
</ol>
<h2>Types in TypeScript</h2>
<h1>Week 16</h1>
<h2>Websockets</h2>
<p>Websockets provide a way to establish a persistent connection between the client and the backend, full duplex communication channel over a single TCP connection between the client (typically a web browser) and the server.</p>
<p>Websockets offer a robust method for creating a continuous, two-way communication channel between a client, such as a web browser, and a backend server.</p>
<p>Unlike traditional HTTP requests, which require a new connection for each interaction, websockets maintain a single, persistent connection.</p>
<p>This allows for real-time data exchange, making it particularly useful for applications that require instant updates, such as chat applications, live sports scores, or financial trading platforms.</p>
<p>The WebSocket protocol begins its life as an HTTP handshake, which is then upgraded to the WebSocket protocol, enabling this efficient, ongoing data transfer.</p>
<p>This setup not only reduces the latency associated with starting new connections but also decreases the overhead of HTTP headers, resulting in a more efficient and responsive user experience.</p>
<h2>Persistent Connection</h2>
<p>A persistent connection, also known as a long-lived connection, is a communication link that stays open for a long time, enabling ongoing data exchange between a client and a server. This connection is important when real-time data transfer is needed, like in online gaming, live video streaming, or instant messaging apps.</p>
<h3>3-Way Handshake</h3>
<p>The 3-way handshake is a fundamental process used to establish a reliable connection between a client and a server over a network. This process is crucial for ensuring that both parties are ready to communicate and that the data can be transferred reliably. The handshake involves three distinct steps:</p>
<ol>
<li><p><strong>SYN (Synchronise)</strong>: The client initiates the connection by sending a SYN packet to the server. This packet contains an initial sequence number, which is used to synchronise the sequence numbers between the client and the server. The SYN packet essentially acts as a request to establish a connection.</p>
</li>
<li><p><strong>SYN-ACK (Synchronise-Acknowledge)</strong>: Upon receiving the SYN packet, the server responds with a SYN-ACK packet. This packet serves two purposes: it acknowledges the receipt of the client's SYN packet by including an acknowledgement number, and it also sends its own SYN packet with a sequence number to the client. This step ensures that the server is ready to establish a connection and synchronise sequence numbers.</p>
</li>
<li><p><strong>ACK (Acknowledge)</strong>: Finally, the client sends an ACK packet back to the server. This packet acknowledges the receipt of the server's SYN-ACK packet. Once the server receives this ACK packet, the connection is fully established, and data can begin to flow between the client and the server.</p>
</li>
</ol>
<h1>Week-17</h1>
<h2>PostgreSQL SQL</h2>
<h2>What are NoSQL databases</h2>
<p>NoSQL databases don't have a fixed structure. This means you can store any type of data without limits. MongoDB is a well-known example of a NoSQL database.</p>
<p><strong>Note:</strong> When we define a schema with Mongoose, it's done at the Node.js level, and having a schema is helpful.</p>
<h2>Advantages of NoSQL Databases</h2>
<ul>
<li><p>NoSQL databases are great for handling large volumes of data and complex structures.</p>
</li>
<li><p>They scale horizontally, allowing you to add more servers as data grows, which is easier than vertical scaling in traditional databases.</p>
</li>
<li><p>They are schema-less, so you don't need a predefined structure, making it easy to change the data model without complex migrations or downtime.</p>
</li>
<li><p>NoSQL databases handle complex data types well, such as unstructured or semi-structured data like JSON or XML.</p>
</li>
<li><p>They are ideal for applications with diverse data formats or those that need rapid development cycles.</p>
</li>
<li><p>Their adaptability and ease of use make them a popular choice for modern applications that require high performance and flexibility..</p>
</li>
</ul>
<h2>Why Not NoSQL Databases</h2>
<ol>
<li><p><strong>Data Inconsistency</strong>: One of the main challenges with NoSQL databases is the potential for data inconsistency. Since they do not enforce a strict schema, there is a risk that different parts of the application may interpret the data differently. This can lead to situations where the data is not uniformly updated or maintained, causing discrepancies.</p>
</li>
<li><p><strong>Runtime Errors</strong>: The flexibility of NoSQL databases can sometimes lead to runtime errors. Without a predefined schema to validate the data before it is stored, errors may only surface during application execution. This can make debugging more difficult, as issues may not be detected until the application is running in a production environment.</p>
</li>
<li><p><strong>Excessive Flexibility</strong>: While flexibility is often seen as an advantage, it can be a drawback for applications that require strict data integrity and consistency. In scenarios where data relationships and constraints are crucial, the lack of enforced structure in NoSQL databases can lead to challenges in maintaining data accuracy and reliability. For applications that demand a high level of strictness, a more structured database approach may be necessary to ensure data quality.</p>
</li>
</ol>
<h2>When to Use?</h2>
<p>When we want to do rapid development like hackathons,</p>
<h2>Types of Databases</h2>
<h3>SQL Databases</h3>
<p>SQL databases are structured databases that use a fixed schema to define data organisation. They are ideal for applications requiring complex queries and transactions. SQL databases ensure data integrity and consistency, making them suitable for applications where data accuracy is crucial.</p>
<h3>Vector Databases</h3>
<p>Vector databases, such as Pinecone, are designed to handle high-dimensional data, which is often used in machine learning and AI applications. They efficiently store and retrieve vector embeddings, enabling fast similarity searches and recommendations. These databases are optimised for performance and scalability in handling large datasets.</p>
<h3>NoSQL Databases</h3>
<p>NoSQL databases are flexible databases that do not rely on a fixed schema, allowing for the storage of unstructured and semi-structured data. They are highly scalable and can easily adapt to changes in data models. NoSQL databases are well-suited for applications with large volumes of diverse data, such as social media platforms and real-time analytics.</p>
<ol>
<li><p>Store data without a fixed schema for speed and efficiency.</p>
</li>
<li><p>Examples - MongoDB</p>
</li>
</ol>
<h3>Graph Databases</h3>
<p>Graph databases, like Neo4j, are designed to represent and store data in a graph format, with nodes and edges. They excel at managing relationships between data points, making them ideal for applications like social networks, recommendation engines, and fraud detection. Graph databases provide efficient querying of complex relationships and patterns within data.</p>
<ol>
<li><p>Data is stored as a graph, which is especially useful for storing <code>relationships</code> (like in social networks).</p>
</li>
<li><p>Examples - Neo4j</p>
</li>
</ol>
<h2>SQL Databases</h2>
<p>SQL databases use structured query language (SQL) to manage data. They organise data in rows and columns. Many full-stack applications use SQL databases. Examples include MySQL and PostgreSQL.</p>
<ol>
<li><p>Stores data in rows</p>
</li>
<li><p>Most full-stack applications use this</p>
</li>
<li><p>Examples - MySQL, Postgres</p>
</li>
</ol>
<h2><strong>Why Not NoSQL</strong></h2>
<p>You might have used <code>MongoDB</code> it in your projects. Its <code>schemaless</code> Properties make it an excellent choice for quickly bootstrapping a project. This flexibility allows developers to start building applications without the need to define a rigid schema upfront, which can significantly speed up initial development.</p>
<p>However, this lack of structure can lead to challenges as your application grows and becomes more complex. Without a fixed schema, it becomes very easy for data to become <code>corrupted</code> or inconsistent, as different parts of the application might write data in varying formats or with unexpected fields.</p>
<h3><strong>What Does Schemaless Mean?</strong></h3>
<p>In a <code>schemaless</code> databases, different rows, or documents, can have different <code>schemas</code> (keys/types). This means that each entry in the database can have its own unique structure, with different fields and data types.</p>
<p>While this offers great flexibility, it also requires careful management and validation to ensure data integrity as the application scales. Without proper oversight, data structure diversity can lead to data consistency and reliability issues, making it harder to maintain and query the database effectively over time.</p>
<img src="https://www.notion.so/image/https%3A%2F%2Fprod-files-secure.s3.us-west-2.amazonaws.com%2F085e8ad8-528e-47d7-8922-a23dc4016453%2F3f3641a6-337a-45bb-a9d0-2cf110b459be%2FScreenshot_2024-02-02_at_6.50.17_PM.png?table=block&amp;id=c9ee2bbd-97d3-4dd1-aec0-fd7ffa75d8e9&amp;cache=v2" alt="notion image" />

<h4><strong>Problems?</strong></h4>
<ol>
<li><p>Can make the database inconsistent</p>
</li>
<li><p>Can cause errors during runtime</p>
</li>
<li><p>Is too flexible for apps that need strict rules</p>
</li>
</ol>
<h4><strong>Upsides?</strong></h4>
<ol>
<li><p>Can develop quickly</p>
</li>
<li><p>Can easily modify the schema</p>
</li>
</ol>
<p>Creating a PostgreSQL Database</p>
<p>You can start a PostgreSQL database in several ways:</p>
<ul>
<li><p><strong>Using neondb</strong></p>
</li>
<li><p><strong>Using Docker locally</strong></p>
</li>
<li><p><strong>Using Docker on Windows</strong></p>
</li>
</ul>
<p>The connection string is similar to the one used in Mongoose.</p>
<h3>Connection String</h3>
<h4>Using a Library to Connect and Store Data</h4>
<ol>
<li><strong>psql</strong></li>
</ol>
<p><code>psql</code> is a powerful terminal tool for working with PostgreSQL (or TimescaleDB) databases. It allows you to execute SQL queries, create tables, add data, and run complex queries. It also supports scripting and automation, making it useful for database administrators and developers. <code>psql</code> offers various options to customize your database interaction.</p>
<p><strong>Connecting to Your Database</strong></p>
<p><code>psql</code> is included with PostgreSQL and provides a robust command-line interface for database management. However, for this tutorial, we'll focus on connecting to the database directly from Node.js, allowing us to manage database tasks using JavaScript within our app. This approach keeps everything in the same programming environment, simplifying app maintenance and growth.</p>
<p>Example command to connect using <code>psql</code>:</p>
<pre><code class="language-typescript">psql -h p-broken-frost-69135494.us-east-2.aws.neon.tech -d database1 -U 100xdevs
</code></pre>
<ol>
<li><strong>pg</strong></li>
</ol>
<p><code>pg</code> is a Node.js library that allows you to interact with a PostgreSQL database in your backend application, similar to <code>mongoose</code>. We will install this library in our app later.</p>
<h3>Connecting PostgreSQL and Storing Data in an SQL Table</h3>
<p><strong>Step 1:</strong> Visit <a href="http://neon.tech">neon.tech</a> and set up your database.</p>
<p><strong>Step 2:</strong> Create a SQL table and copy the connection string.</p>
<h4>Creating a Table and Defining Its Schema</h4>
<p>In SQL, a single database can have multiple tables, similar to collections in a MongoDB database. With Postgres, the next step is to define the schema for your tables.</p>
<p>SQL (Structured Query Language) is used to specify how data is stored in the database. To create a table, use the following command:</p>
<pre><code class="language-sql">CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
</code></pre>
<p><strong>Decoding the SQL Statement:</strong></p>
<ol>
<li><p><strong>CREATE TABLE users</strong>: Initiates the creation of a new table named <code>users</code>.</p>
</li>
<li><p><strong>id SERIAL PRIMARY KEY</strong>:</p>
<ul>
<li><p><code>id</code>: The first column, uniquely identifying each row (user), similar to <code>_id</code> in MongoDB.</p>
</li>
<li><p><code>SERIAL</code>: A PostgreSQL data type that auto-increments for each new row, ensuring unique <code>id</code>s.</p>
</li>
<li><p><code>PRIMARY KEY</code>: Ensures the <code>id</code> column is the main identifier, with unique, non-empty values.</p>
</li>
</ul>
</li>
<li><p><strong>email VARCHAR(255) UNIQUE NOT NULL</strong>:</p>
<ul>
<li><p><code>email</code>: The second column, storing the user's email address.</p>
</li>
<li><p><code>VARCHAR(255)</code>: A text data type allowing up to 255 characters.</p>
</li>
<li><p><code>UNIQUE</code>: Ensures all emails are distinct.</p>
</li>
<li><p><code>NOT NULL</code>: Prevents empty values; every user must have an email.</p>
</li>
</ul>
</li>
<li><p><strong>password VARCHAR(255) NOT NULL</strong>: Similar to the email column, but can be non-unique.</p>
</li>
<li><p><strong>created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP</strong>:</p>
<ul>
<li><p><code>created_at</code>: Records when the user was created.</p>
</li>
<li><p><code>TIMESTAMP WITH TIME ZONE</code>: Stores date, time, and time zone for accurate tracking.</p>
</li>
<li><p><code>DEFAULT CURRENT_TIMESTAMP</code>: Automatically sets the current date and time when a row is added.</p>
</li>
</ul>
</li>
</ol>
<p><strong>Step 3:</strong> Install the <code>pg</code> Using the command:</p>
<pre><code class="language-typescript">npm i pg
</code></pre>
<p><strong>Step 4:</strong> Create an Express server and import the <code>Client</code> method from the <code>pg</code> package.</p>
<p><strong>Step 5:</strong> Connect the database using the connection string.</p>
<pre><code class="language-javascript">import { Client } from "pg";
import express from "express";

const app = express();
const port = 3000;
const pgClient = new Client("yourConnectionStringURL");

pgClient.connect();
app.use(express.json());

app.post("/signup", (req, res) =&gt; {
    const { username, email, password } = req.body;

    try {
        // SQL Query to insert data into the table, preventing SQL injections
        const insertQuery = `INSERT INTO users (username, email, password) VALUES (\(1, \)2, $3)`;
        const responseQuery = pgClient.query(insertQuery, [username, email, password]);
        console.log(responseQuery);
    } catch (error) {
        console.log(error);
    }
});
</code></pre>
<p>This setup allows you to manage your PostgreSQL database using Node.js, ensuring efficient data handling and integration with your application logic.</p>
<h2>Primary Key and Foregin Key in SQL</h2>
<p>In SQL databases, primary keys and foreign keys are essential for establishing relationships between tables and ensuring data integrity.</p>
<p><strong>Primary Key:</strong> A primary key is a unique identifier for each record in a table. It ensures that no two rows have the same value in the primary key column(s). A primary key must contain unique values and cannot contain NULLs.</p>
<p><strong>Syntax for Primary Key:</strong></p>
<pre><code class="language-sql">CREATE TABLE table_name (
    column1 datatype PRIMARY KEY,
    column2 datatype,
    ...
);
</code></pre>
<p><strong>Foreign Key:</strong> A foreign key is a column or a set of columns in one table that refers to the primary key in another table. It establishes a relationship between the two tables, ensuring that the value in the foreign key column matches a value in the referenced primary key column.</p>
<p><strong>Syntax for Foreign Key:</strong></p>
<pre><code class="language-sql">CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    ...
    FOREIGN KEY (column_name) REFERENCES other_table_name(primary_key_column)
);
</code></pre>
<p><strong>Connecting Primary Key and Foreign Key:</strong> To connect a primary key and a foreign key, you define the foreign key in the child table, which references the primary key in the parent table. This relationship enforces referential integrity, ensuring that the foreign key value always corresponds to an existing primary key value in the parent table.</p>
<p><strong>Example:</strong></p>
<pre><code class="language-sql">CREATE TABLE departments (
    department_id INT PRIMARY KEY,
    department_name VARCHAR(100)
);

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100),
    department_id INT,
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
</code></pre>
<p>In this example, <code>department_id</code> is the primary key in the <code>departments</code> table and a foreign key in the <code>employees</code> table, linking the two tables.</p>
<h3>Relationships in SQL</h3>
<p>In SQL, relationships between tables are established using keys. The most common types of relationships are:</p>
<ol>
<li><p><strong>One-to-One</strong>: Each row in Table A is linked to one and only one row in Table B. This is often implemented using a foreign key in one table that references the primary key of another table.</p>
<pre><code class="language-sql">CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(255)
);

CREATE TABLE profiles (
    id SERIAL PRIMARY KEY,
    user_id INT REFERENCES users(id),
    bio TEXT
);
</code></pre>
</li>
<li><p><strong>One-to-Many</strong>: A row in Table A can be linked to multiple rows in Table B. This is implemented by having a foreign key in Table B that references the primary key of Table A.</p>
<pre><code class="language-sql">CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(255)
);

CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    user_id INT REFERENCES users(id),
    content TEXT
);
</code></pre>
</li>
<li><p><strong>Many-to-Many</strong>: Rows in Table A can be linked to multiple rows in Table B and vice versa. This is typically implemented using a junction table.</p>
<pre><code class="language-sql">CREATE TABLE students (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255)
);

CREATE TABLE courses (
    id SERIAL PRIMARY KEY,
    title VARCHAR(255)
);

CREATE TABLE enrollments (
    student_id INT REFERENCES students(id),
    course_id INT REFERENCES courses(id),
    PRIMARY KEY (student_id, course_id)
);
</code></pre>
</li>
</ol>
<h3>Transactions in SQL</h3>
<p>A transaction in SQL is a sequence of operations performed as a single logical unit of work. Transactions ensure data integrity and consistency. They follow the ACID properties:</p>
<ul>
<li><p><strong>Atomicity</strong>: Ensures that all operations within a transaction are completed; if not, the transaction is aborted.</p>
</li>
<li><p><strong>Consistency</strong>: Ensures that a transaction brings the database from one valid state to another.</p>
</li>
<li><p><strong>Isolation</strong>: Ensures that transactions are executed in isolation from one another.</p>
</li>
<li><p><strong>Durability</strong>: Ensures that once a transaction is committed, it remains so, even in the event of a system failure.</p>
</li>
</ul>
<p>Example of a transaction:</p>
<pre><code class="language-sql">BEGIN;

INSERT INTO accounts (user_id, balance) VALUES (1, 1000);
UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;

COMMIT;
</code></pre>
<h3>Types of Joins</h3>
<ol>
<li><p><strong>INNER JOIN</strong>: Returns records that have matching values in both tables.</p>
<pre><code class="language-sql">SELECT users.username, posts.content
FROM users
INNER JOIN posts ON users.id = posts.user_id;
</code></pre>
</li>
<li><p><strong>LEFT JOIN (or LEFT OUTER JOIN)</strong>: Returns all records from the left table and the matched records from the right table. If no match, NULL values are returned for columns from the right table.</p>
<pre><code class="language-sql">SELECT users.username, posts.content
FROM users
LEFT JOIN posts ON users.id = posts.user_id;
</code></pre>
</li>
<li><p><strong>RIGHT JOIN (or RIGHT OUTER JOIN)</strong>: Returns all records from the right table and the matched records from the left table. If no match, NULL values are returned for columns from the left table.</p>
<pre><code class="language-sql">SELECT users.username, posts.content
FROM users
RIGHT JOIN posts ON users.id = posts.user_id;
</code></pre>
</li>
<li><p><strong>FULL JOIN (or FULL OUTER JOIN)</strong>: Returns all records when there is a match in either left or right table records. If there is no match, NULL values are returned for columns from the table without a match.</p>
<pre><code class="language-sql">SELECT users.username, posts.content
FROM users
FULL JOIN posts ON users.id = posts.user_id;
</code></pre>
</li>
</ol>
<p>These concepts are fundamental to understanding how data is organised and manipulated in relational databases using SQL.</p>
<h1>Week 18</h1>
<h2>Introduction to ORMs</h2>
<h3>What are ORMs?</h3>
<p><strong>Official Definition:</strong> ORM stands for Object-Relational Mapping, a programming technique used in software development to convert data between incompatible type systems in object-oriented programming languages. This technique creates a "virtual object database" that can be used from within the programming language.</p>
<p><strong>Simplified Definition:</strong> ORMs let you easily interact with your database without worrying too much about the underlying syntax, such as SQL.</p>
<h2>Why Use ORMs?</h2>
<ol>
<li><p><strong>Simpler Syntax:</strong> ORMs convert objects to SQL queries under the hood, making database interactions more intuitive.</p>
</li>
<li><p><strong>Database Abstraction:</strong> They provide a unified API, allowing you to switch databases without changing your code.</p>
</li>
<li><p><strong>Type Safety and Auto-Completion:</strong> ORMs offer type safety and auto-completion features, enhancing development efficiency.</p>
</li>
<li><p><strong>Automatic Migrations:</strong> ORMs handle database migrations automatically, simplifying schema evolution.</p>
</li>
</ol>
<h2>What is Prisma?</h2>
<p>Prisma is a modern ORM that offers several advantages:</p>
<ol>
<li><p><strong>Data Model:</strong> Define your schema in a single file, specifying tables, fields, and relationships.</p>
</li>
<li><p><strong>Automated Migrations:</strong> Prisma generates and runs database migrations based on changes to the schema.</p>
</li>
<li><p><strong>Type Safety:</strong> It generates a type-safe database client.</p>
</li>
<li><p><strong>Auto-Completion:</strong> Provides auto-completion features for efficient coding.</p>
</li>
</ol>
<h2>Setting Up Prisma in a New Application</h2>
<h3>Step 1: Initialise a Node.js Project</h3>
<ol>
<li><p>Create a new Node.js project:</p>
<pre><code class="language-bash">npm init -y
</code></pre>
</li>
<li><p>Add necessary dependencies:</p>
<pre><code class="language-bash">npm install prisma typescript ts-node @types/node --save-dev
</code></pre>
</li>
<li><p>Initialise TypeScript:</p>
<pre><code class="language-bash">npx tsc --init
</code></pre>
<ul>
<li><p>Change <code>rootDir</code> to <code>src</code></p>
</li>
<li><p>Change <code>outDir</code> to <code>dist</code></p>
</li>
</ul>
</li>
</ol>
<h3>Step 2: Initialise a Prisma Project</h3>
<ol>
<li><p>Initialise Prisma:</p>
<pre><code class="language-bash">npx prisma init
</code></pre>
</li>
</ol>
<h3>Step 3: Select Your Database</h3>
<p>Prisma supports multiple databases like MySQL, Postgres, and MongoDB. Update <code>prisma/schema.prisma</code> to set up your chosen database and replace the database URL with your test URL.</p>
<h3>Step 4: Define Your Data Model</h3>
<p>In the <code>schema.prisma</code> file, define the shape of your data. For example, a <code>User</code> the table might look like this:</p>
<p><code>@id</code> is used to define the primary key, and <code>@default(autoincrement())</code> It is used to increase the value automatically.</p>
<pre><code class="language-typescript">model User {
  id         Int      @id @default(autoincrement())
  username   String   @unique
  password   String
  firstName  String
  lastName   String
}
</code></pre>
<h3>Step 5: Generate the Prisma Client</h3>
<p>Generate the client to use in your Node.js app:</p>
<pre><code class="language-bash">npx prisma generate
</code></pre>
<h3>Step 6: Create Your First Application</h3>
<h4>Insert Data</h4>
<p>Write a function to insert data into the <code>Users</code> table:</p>
<pre><code class="language-typescript">import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function insertUser(email: string, password: string, cit: string, age: number) {
  
  await client.users.create({
        data: {
            email: "adityagupcsadasxcsdtapro@gmail.com",
            age: 23,
            city: "sdsdcsdc",
            password: "4324324@",
        }
    })
}
</code></pre>
<h4>Update Data</h4>
<p>Write a function to update the data in the <code>Users</code> table:</p>
<pre><code class="language-typescript">import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();


async function updateUser() {
  await client.users.update({
        where: {
            email:"adityaguptapro@gmail.com"
        },
        data:{
            email:"adityakumargupta@gmail.com"
        }
    })
}
</code></pre>
<h4>Fetch User Details</h4>
<p>Write a function to fetch user details by email:</p>
<pre><code class="language-typescript">import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function getUser(username: string) {
  // Implementation here
}
</code></pre>
<h3>Step 7: Define Relationships</h3>
<p>Prisma allows you to define relationships between tables, such as One-to-One, One-to-Many, and Many-to-Many. For example, in a TODO app, you might have a One-to-Many relationship.</p>
<pre><code class="language-typescript">generator client {
  provider = "prisma-client-js"
  output   = "../src/generated/prisma"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}


model Users {
  id Int @default(autoincrement()) @id
  email String @unique
  password String 
  age Int
  city String
  todo Todo[]
}

model Todo{
  id Int @default(autoincrement()) @id
  title String
  description String
  done Boolean
  userId Int
  time DateTime 
  user Users @relation(fields: [userId],references: [id])
}
</code></pre>
<h4>Update the Schema</h4>
<p>Update your schema to reflect these relationships and run migrations:</p>
<pre><code class="language-bash">npx prisma migrate dev --name relationship
npx prisma generate
</code></pre>
<h1>Week 21</h1>
<h2>What is a Monorepo?</h2>
<ul>
<li><p><strong>Monorepo</strong> stands for "mono-repository."</p>
</li>
<li><p>It's a single repository that holds the code for multiple projects.</p>
</li>
<li><p>Imagine having all your apps, libraries, and tools in one big folder!</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<ul>
<li><p>A company has a web app, a mobile app, and shared libraries.</p>
</li>
<li><p>Instead of separate repositories, they keep everything in one monorepo.</p>
</li>
</ul>
<h3>Advantages and Disadvantages of Monorepo</h3>
<table>
<thead>
<tr>
<th><strong>Advantages</strong></th>
<th><strong>Disadvantages</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Easier code sharing and reuse</td>
<td>Can become large and complex</td>
</tr>
<tr>
<td>Simplified dependency management</td>
<td>Longer build times</td>
</tr>
<tr>
<td>Consistent tooling and configuration</td>
<td>Requires more robust CI/CD pipelines</td>
</tr>
<tr>
<td>Easier refactoring across projects</td>
<td>Potential for merge conflicts</td>
</tr>
</tbody></table>
<h2>Common Interview Questions and Answers</h2>
<ol>
<li><p><strong>What is a monorepo?</strong></p>
<ul>
<li>A single repository containing multiple projects.</li>
</ul>
</li>
<li><p><strong>Why use a monorepo?</strong></p>
<ul>
<li>For easier code sharing and consistent tooling.</li>
</ul>
</li>
<li><p><strong>What is Turborepo?</strong></p>
<ul>
<li>A tool to manage monorepos efficiently.</li>
</ul>
</li>
<li><p><strong>How does Turborepo improve monorepos?</strong></p>
<ul>
<li>By optimising build times and simplifying workflows.</li>
</ul>
</li>
</ol>
<h2>What is Turborepo and Why It's Useful</h2>
<ul>
<li><p><strong>Turborepo</strong> is a high-performance build system for JavaScript and TypeScript monorepos.</p>
</li>
<li><p>It speeds up builds by caching and running tasks in parallel.</p>
</li>
<li><p>Useful for large teams and projects to maintain efficiency.</p>
</li>
</ul>
<p><strong>Run the command to set up your turbo repo project</strong></p>
<ul>
<li><p><strong>Install Turborepo:</strong></p>
<pre><code class="language-bash">npx create-turbo@latest
</code></pre>
<p>  The turbo repo's folder structure. The apps folder contains multiple apps that you can add or remove.</p>
</li>
<li><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753783983350/21046083-0feb-45f0-a3fb-6c30fff08eba.png" alt="" style="display:block;margin:0 auto" />
  
<p>  All the Ui of the app will be created inside the UI directory, which is inside the package folder</p>
</li>
<li><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753797069946/9415dd7d-2bdb-4c3c-adc3-b39360cc5056.png" alt="" style="display:block;margin:0 auto" />
  
<p>  To Import Ui components from the ui directory to all your apps.</p>
</li>
<li><p>We have to use<code>import componentname "@repo/ui/componentname</code>" syntax to import any ui component from the ui package.</p>
</li>
</ul>
<pre><code class="language-javascript">"use client"
import TextInput from "@repo/ui/TextInput"
import Button from "@repo/ui/button"
import { useRouter } from "next/navigation"
import { useState } from "react"

export default function Home() {
  const [roomId, setroomId] = useState("")
  const router = useRouter()
  function handleChange(e: any) {
    setroomId(e.target.value)

  }
  function handleSubmit() {
    if (roomId.trim() == "") {
      alert("Please Enter Room id")
      return
    }
    else {
      router.push(`/chat/room/${roomId}`)
    }
  }
  return (
    &lt;div style={{ display: "flex", justifyContent: "center", alignItems: "center", width: "99vw", height: "100vh", background: "black", color: "white" }}&gt;
      &lt;div style={{display:"flex",flexDirection:"column",gap:"10px"}}&gt;
        &lt;TextInput onChange={handleChange} placeholder="Enter Room Id" /&gt;
        &lt;Button onClick={handleSubmit}&gt;Join Meeting&lt;/Button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}
</code></pre>
<h2>Adding the Common ts-Config file for all the backends</h2>
<p><strong>Step 1.</strong> Create a common JSON file in the package folder inside the typescript-config file</p>
<p><strong>Step 2.</strong> Copy your typescript configuration.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753854886051/7f19d9c3-fa77-41b1-ae0b-52d2761867fc.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Step 3.</strong> Now, whenever you use the backend, you don't need to add the full TypeScript configuration. You can simply extend it and provide the path to your config file that you created in the typescript-config file.</p>
<pre><code class="language-json">{
  "extends":"@repo/typescript-config/backend.json"
}
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753855245604/e6db53df-a49b-41c6-afa4-6501b1f0543f.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Step 4.</strong> Also specify the rootdir and outdir with the compiler option in each backend app inside the tsconfig.json file</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753855856727/4b928b06-c894-451f-9ae6-3575ddb696be.png" alt="" style="display:block;margin:0 auto" />

<p>When working with Turborepo, remember that changes in environment files for Node.js applications might not trigger a rebuild by default. To ensure updates are reflected, configure your tasks to include these files as inputs.</p>
<h2>About the Turbo.json File</h2>
<pre><code class="language-json">{
  "$schema": "https://turborepo.com/schema.json",
  "ui": "tui",
  "tasks": {
    "build": {
      "dependsOn": ["^build"],
      
      "inputs": ["\(TURBO_DEFAULT\)", ".env*"],
      "outputs": [".next/**", "!.next/cache/**"]
    },
    "lint": {
      "dependsOn": ["^lint"]
    },
    "check-types": {
      "dependsOn": ["^check-types"]
    },
    "dev": {
      "cache": false,
      "persistent": true
    }
  }
}
</code></pre>
<p>The provided JSON snippet is a configuration file for Turborepo, which is used to manage tasks and dependencies in a monorepo setup. Here's a breakdown of each line and its meaning:</p>
<ol>
<li><p><code>"$schema": "</code><a href="https://turborepo.com/schema.json"><code>https://turborepo.com/schema.json</code></a><code>"</code>: This line specifies the schema for the JSON file, which helps validate the configuration's structure and content.</p>
</li>
<li><p><code>"ui": "tui"</code>: This line sets the user interface for Turborepo to "tui" (text user interface), which might be a custom or specific UI configuration.</p>
</li>
<li><p><code>"tasks"</code>: This section defines various tasks that Turborepo can execute, such as build, lint, check-types, and dev.</p>
<ul>
<li><p><code>"build"</code>:</p>
<ul>
<li><p><code>"dependsOn": ["^build"]</code>: This indicates that the build task depends on the build tasks of all dependencies. The caret (^) symbol is used to denote dependency tasks.</p>
</li>
<li><p><code>"inputs": ["\(TURBO_DEFAULT\)", ".env*"]</code>: Specifies the inputs for the build task. <code>\(TURBO_DEFAULT\)</code> is a placeholder for default inputs, and <code>.env*</code> includes any environment files.</p>
</li>
<li><p><code>"outputs": [".next/**", "!.next/cache/**"]</code>: Defines the outputs of the build task. It includes everything in the <code>.next</code> directory except for the cache.</p>
</li>
</ul>
</li>
<li><p><code>"lint"</code>:</p>
<ul>
<li><code>"dependsOn": ["^lint"]</code>: Similar to the build task, this indicates that the lint task depends on the lint tasks of all dependencies.</li>
</ul>
</li>
<li><p><code>"check-types"</code>:</p>
<ul>
<li><code>"dependsOn": ["^check-types"]</code>: This indicates that the check-types task depends on the check-types tasks of all dependencies.</li>
</ul>
</li>
<li><p><code>"dev"</code>:</p>
<ul>
<li><p><code>"cache": false</code>: This setting disables caching for the dev task, meaning it will run fresh each time.</p>
</li>
<li><p><code>"persistent": true</code>: This indicates that the dev task should run persistently, likely for development purposes where continuous watching is needed.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>To configure Turborepo so that changes in the server folder or independent files trigger a rebuild of the <code>dist</code> directory, you can modify the <code>inputs</code> section of the relevant task (e.g., <code>build</code>) to include the server folder or specific files. For example:</p>
<pre><code class="language-json">"inputs": ["\(TURBO_DEFAULT\)", ".env*", "server/**", "independent-file.js"]
</code></pre>
<p>This configuration will ensure that any changes in the <code>server</code> directory or <code>independent-file.js</code> will trigger the build process, updating the <code>dist</code> directory accordingly.</p>
<h2>How to Configure Backend Rebuilds to Respond to Changes and Manage Caching</h2>
<p>When we run the <code>npm run build</code> command, all the packages are built and cached. If we make changes to the Node.js application code and run the build command again, it uses the cached version instead of building a fresh app. To force a fresh build of the backend, we need to modify the configuration.</p>
<p><strong>Step 1.</strong> Create a turbo.json file inside the backend application.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753859436712/1cdea6c5-403d-4076-942a-2c4e0be80a4f.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Step 2.</strong> Then extend the code and specify the output to also include the dist folder.</p>
<pre><code class="language-json">{
  "extends": ["//"],
  "task": {
    "build": {
      "outputs": ["dist/**"]
    }
  }
}
</code></pre>
<p>In this case, when we run the npm run build command globally, Turborepo is forced to build a fresh backend app and not use the cached version if the backend files change.</p>
<p>If we want to include any custom files in the fresh build, we can specify them globally.</p>
<pre><code class="language-json">"build": {
  "dependsOn": ["^build"],
  "inputs": ["\(TURBO_DEFAULT\)", ".env*", "server/**", "independent-file.js"],
  "outputs": ["dist/**"]
}
</code></pre>
<h1>Week 21 Offline</h1>
<h2>Client Side Rendering</h2>
<p><strong>Client-side rendering (CSR)</strong> is a modern technique used in web development where the rendering of a webpage is performed in the browser using JavaScript. Instead of the server sending a fully rendered HTML page to the client, the server sends a minimal HTML page with a JavaScript file that takes over the rendering process on the client side.</p>
<p>A good example of CSR is React, a popular JavaScript library for building user interfaces. In a React project, the initial HTML file sent from the server is often empty or contains minimal content. The JavaScript code, once executed in the browser, dynamically generates and populates the content on the page.</p>
<p>Here's a simple demonstration of setting up a React project using Vite, a build tool that provides a fast development environment:</p>
<ol>
<li><p><strong>Initialize a React Project:</strong></p>
<pre><code class="language-bash">npm create vite@latest
</code></pre>
</li>
<li><p><strong>Add Dependencies:</strong></p>
<pre><code class="language-bash">npm i
</code></pre>
</li>
<li><p><strong>Start the Project:</strong></p>
<pre><code class="language-bash">npm run build
</code></pre>
</li>
<li><p><strong>Serve the Project:</strong></p>
<pre><code class="language-bash">cd dist/
serve
</code></pre>
</li>
</ol>
<p>When you open the network tab in your browser's developer tools, you'll notice that the initial HTML file doesn't have any content. This is because the JavaScript runs and actually populates/renders the contents on the page.</p>
<p>React (or CSR) simplifies the development process by allowing developers to write components, which JavaScript then renders to the DOM. However, CSR has some downsides:</p>
<ul>
<li><p><strong>Not SEO Optimised:</strong> Since the content is rendered on the client side, search engines may have difficulty indexing the page content.</p>
</li>
<li><p><strong>Flash of Unstyled Content (FOUC):</strong> Users may see a flash before the page fully renders, as the JavaScript needs to load and execute.</p>
</li>
<li><p><strong>Waterfalling Problem:</strong> The loading of resources can be sequential, leading to delays in rendering.</p>
</li>
</ul>
<p>In comparison to other rendering techniques like Server-Side Rendering (SSR) and Static Site Generation (SSG), CSR offers a unique set of advantages and challenges. Understanding these differences is crucial for choosing the right approach for your web application.</p>
<h2>Server Side Rendering</h2>
<p>Server-side rendering (SSR) occurs when the server converts JavaScript components into HTML before sending them to the client.</p>
<p><strong>Why Use SSR?</strong></p>
<ul>
<li><p><strong>SEO Benefits</strong>: Improves search engine optimisation by providing fully rendered HTML to search engines.</p>
</li>
<li><p><strong>Eliminates Waterfalling</strong>: Avoids the sequential loading of resources, leading to faster page loads.</p>
</li>
<li><p><strong>No Flash of Unstyled Content</strong>: Ensures content is visible immediately without a white flash.</p>
</li>
</ul>
<p><strong>Try It Out with Next.js:</strong></p>
<ol>
<li><p>Create a Next.js app: <code>npx create-next-app</code></p>
</li>
<li><p>Build the project: <code>npm run build</code></p>
</li>
<li><p>Start the server: <code>npm run start</code></p>
</li>
<li><p>Observe that the initial HTML page is already populated with content.</p>
</li>
</ol>
<p><strong>Downsides of SSR:</strong></p>
<ul>
<li><p><strong>Costly</strong>: Each request requires server-side rendering, increasing server load.</p>
</li>
<li><p><strong>Scalability Challenges</strong>: Difficult to scale as caching with CDNs is not possible.</p>
</li>
</ul>
<h2>Static Site Generation</h2>
<p><strong>Static Site Generation (SSG)</strong> is a powerful feature in Next.js that allows you to generate HTML pages at build time. This means that the HTML is pre-rendered and can be served quickly to users, often cached by a Content Delivery Network (CDN) for even faster delivery.</p>
<h2>Why Use Static Site Generation?</h2>
<p>Using SSG defers the expensive operation of rendering a page to the build time, so it only happens once. This approach is beneficial for pages that do not change often and can be served as static content. It improves performance and reduces server load, making it ideal for pages with content that is the same for all users.</p>
<h2>How to Implement Static Site Generation</h2>
<p>Let's walk through an example of implementing SSG in a Next.js application using a global todos endpoint.</p>
<h3>Step 1: Create a New Next.js Project</h3>
<p>First, create a new Next.js project if you haven't already:</p>
<pre><code class="language-bash">npx create-next-app@latest my-next-app
cd my-next-app
</code></pre>
<h3>Step 2: Create a Static Page</h3>
<p>Create a new file <code>todos/page.tsx</code> in your project:</p>
<pre><code class="language-typescript">export default async function Todos() {
    const res = await fetch('https://sum-server.100xdevs.com/todos');
    const data = await res.json();
    const todos = data.todos;

    return (
        &lt;div&gt;
            {todos.map((todo: any) =&gt; (
                &lt;div key={todo.id}&gt;
                    &lt;h3&gt;{todo.title}&lt;/h3&gt;
                    &lt;p&gt;{todo.description}&lt;/p&gt;
                &lt;/div&gt;
            ))}
        &lt;/div&gt;
    );
}
</code></pre>
<h3>Step 3: Update Fetch Requests for Revalidation</h3>
<p>To ensure the data is fresh, you can set the cache to clear every 10 seconds:</p>
<pre><code class="language-typescript">const res = await fetch('https://sum-server.100xdevs.com/todos', {
    next: { revalidate: 10 }
});
</code></pre>
<h3>Step 4: Clear Cache with Next.js Actions</h3>
<p>You can also clear the cache using Next.js actions:</p>
<pre><code class="language-typescript">import { revalidateTag } from 'next/cache';

const res = await fetch('https://sum-server.100xdevs.com/todos', { next: { tags: ['todos'] } });

'use server';

export default async function revalidate() {
    revalidateTag('todos');
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How to Build a Form with React Hook Form]]></title><description><![CDATA[Are you having trouble making a contact form with a lot of custom validation?
Don't worry anymore. In today's comprehensive guide, I'll walk you through the entire process of creating any form, comple]]></description><link>https://blog.adityaguptareal.com/react-hook-form</link><guid isPermaLink="true">https://blog.adityaguptareal.com/react-hook-form</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Fri, 27 Feb 2026 03:11:39 GMT</pubDate><content:encoded><![CDATA[<p>Are you having trouble making a contact form with a lot of custom validation?</p>
<p>Don't worry anymore. In today's comprehensive guide, I'll walk you through the entire process of creating any form, complete with custom validation, in just a few minutes. We will delve into the step-by-step method of building a form using the powerful React Hook Form library.</p>
<p>This library is designed to simplify form handling in React applications, making it much easier to manage form state and validation.</p>
<p>By the end of this guide, you'll understand how to efficiently set up forms that capture user input and ensure that the data is validated correctly before submission.</p>
<p>We'll explore various validation techniques and demonstrate how React Hook Form can significantly save time and effort compared to traditional form handling methods. Whether you're dealing with simple contact or complex multi-step forms, this guide will equip you with the knowledge and tools to streamline your form development process.</p>
<h2>Brief Overview of React Hook Form</h2>
<p><strong>React Hook Form</strong> is a library that helps you handle forms in React apps. It makes it easy to manage form data and validation. With this tool, you can quickly set up forms that collect user input and check the data before it's submitted. This library saves time and effort compared to older ways of handling forms.</p>
<h3>Importance of Form Handling in React Applications</h3>
<p>Form handling is a crucial aspect in developing React applications, as it directly impacts how users interact with your app. Proper form management ensures that user inputs are captured accurately, validated effectively, and processed efficiently, which is essential for maintaining a seamless user experience</p>
<p>However, sometimes handling forms can become very complex due to state management and writing custom validation logic, especially when the form has various fields. Here are some importance of Form Handling in React Applications.</p>
<ul>
<li><p>Ensures data integrity by validating user inputs before submission, preventing invalid data from being processed.</p>
</li>
<li><p>Enhances user experience by providing immediate feedback on input errors and guiding users to correct mistakes in real-time.</p>
</li>
<li><p>Improves the maintainability of the codebase by organising form logic clearly and concisely.</p>
</li>
<li><p>Reduces the amount of boilerplate code and enhances application performance by minimising re-renders.</p>
</li>
<li><p>Simplifies the complexities involved in managing form state and validation, especially in intricate forms with multiple fields and validation rules.</p>
</li>
</ul>
<h2>Setting Up the React Environment</h2>
<p>Here's a complete blog post guiding you on how to write a form using React Hook Form, complete with code examples:</p>
<hr />
<h2>A Comprehensive Guide to Building Forms with React Hook Form</h2>
<p>Are you struggling with creating forms in React applications? React Hook Form is here to simplify the process. In this guide, we'll walk through setting up a form using React Hook Form, covering everything from basic setup to advanced features.</p>
<h3>Setting Up the React Environment</h3>
<p><strong>Step 1:</strong> Create a new Vite project.</p>
<pre><code class="language-shell">npm create vite@latest
</code></pre>
<p><strong>Step 2:</strong> Navigate to your project directory and install React Hook Form.</p>
<pre><code class="language-shell">npm install react-hook-form
</code></pre>
<h3>Creating a Basic Form Using React Hook Form</h3>
<h4>Setting up the form</h4>
<p>Start by creating a new component for your form.</p>
<pre><code class="language-javascript">import React from 'react';
import { useForm } from 'react-hook-form';

const ContactForm = () =&gt; {
  const { register, handleSubmit, formState: { errors } } = useForm();

  const onSubmit = data =&gt; {
    console.log(data);
  };

  return (
    &lt;form onSubmit={handleSubmit(onSubmit)}&gt;
      &lt;div&gt;
        &lt;label&gt;Name&lt;/label&gt;
        &lt;input {...register('name', { required: 'Name is required' })} /&gt;
        {errors.name &amp;&amp; &lt;p&gt;{errors.name.message}&lt;/p&gt;}
      &lt;/div&gt;

      &lt;div&gt;
        &lt;label&gt;Email&lt;/label&gt;
        &lt;input {...register('email', { required: 'Email is required' })} /&gt;
        {errors.email &amp;&amp; &lt;p&gt;{errors.email.message}&lt;/p&gt;}
      &lt;/div&gt;

      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  );
};

export default ContactForm;
</code></pre>
<p><strong>Importing necessary hooks</strong></p>
<p>In the above code, we import <code>useForm</code> from <code>react-hook-form</code> to manage form state and validation.</p>
<h4>Initialising the useForm hook</h4>
<p>We initialise <code>useForm</code> and destructure <code>register</code>, <code>handleSubmit</code>, and <code>formState</code> to manage form inputs and handle submissions.</p>
<h4>Defining form fields</h4>
<p>We define form fields using a <code>register</code> function to connect inputs to the form state.</p>
<h4>Managing form state and validation</h4>
<p>Validation is handled by passing validation rules to the <code>register</code> function. Error messages are displayed using the <code>errors</code> object.</p>
<h3>Handling Form Submission</h3>
<h4>Writing a submit handler function</h4>
<p>The <code>handleSubmit</code> Function is used to handle form submissions, passing the form data to the <code>onSubmit</code> function.</p>
<h4>Implementing validation logic</h4>
<p>Validation logic is implemented directly in the <code>register</code> function, allowing for custom error messages.</p>
<h4>Displaying error messages</h4>
<p>Error messages are displayed conditionally based on the presence of errors in the <code>errors</code> object.</p>
<h3>Advanced Features of React Hook Form</h3>
<h4>Custom validation</h4>
<p>Custom validation can be added using the <code>validate</code> option in the <code>register</code> function.</p>
<h4>Dynamic form fields and conditional rendering</h4>
<p>React Hook Form supports dynamic form fields and conditional rendering, allowing for complex form structures.</p>
<h4>Integration with third-party components</h4>
<p>React Hook Form can be easily integrated with third-party UI components, enhancing the form's appearance and functionality.</p>
<h3>Performance Optimization</h3>
<h4>Minimizing re-renders</h4>
<p>React Hook Form minimises re-renders by isolating component re-renders to only the fields that change.</p>
<h4>Using React Hook Form’s performance optimisation techniques</h4>
<p>Utilise React Hook Form's built-in performance optimisation techniques to enhance form performance.</p>
<h3>Conclusion</h3>
<p>React Hook Form simplifies form handling in React applications, offering a robust solution for managing form state and validation. Following this guide, you can efficiently create forms that enhance user experience and maintain data integrity.</p>
]]></content:encoded></item><item><title><![CDATA[Step-by-Step Guide to Creating AI Agents Using JavaScript]]></title><description><![CDATA[What is an AI Agent
LLM + TOOLS = AI AGENT
What is LLM?
It is a large neural network which is trained on large amount of data and is used to predict the word or the text given as a input. Example gpt3]]></description><link>https://blog.adityaguptareal.com/step-by-step-guide-to-creating-ai-agents-using-javascript</link><guid isPermaLink="true">https://blog.adityaguptareal.com/step-by-step-guide-to-creating-ai-agents-using-javascript</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sun, 22 Feb 2026 07:25:24 GMT</pubDate><content:encoded><![CDATA[<p>What is an AI Agent</p>
<p>LLM + TOOLS = AI AGENT</p>
<p>What is LLM?</p>
<p>It is a large neural network which is trained on large amount of data and is used to predict the word or the text given as a input. Example gpt3.0, gemini, etc</p>
<p>Working of LLM</p>
<p>Prompt —&gt; LLM —&gt; Output</p>
<p>LLM does not know what happened after because it is trained at a particular time of data.</p>
<p>Prompt —&gt; LLM —&gt; Tools —&gt; LLM —&gt; Output</p>
<p>What is Langchain</p>
]]></content:encoded></item><item><title><![CDATA[Step-by-Step Tutorial: Redis and Express Integration]]></title><description><![CDATA[Redis is an open-source, in-memory data store used by millions of developers worldwide.
It is known for its speed and efficiency, making it a popular choice for caching, real-time applications, and message brokering.
Redis supports various data struc...]]></description><link>https://blog.adityaguptareal.com/redis-complete-guide-with-express-integration</link><guid isPermaLink="true">https://blog.adityaguptareal.com/redis-complete-guide-with-express-integration</guid><category><![CDATA[Redis]]></category><category><![CDATA[Full Stack Development]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sun, 15 Feb 2026 10:18:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1771150656244/af1a955f-ac02-4217-a49b-202ba577b8e6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Redis is an open-source, in-memory data store used by millions of developers worldwide.</p>
<p>It is known for its speed and efficiency, making it a popular choice for caching, real-time applications, and message brokering.</p>
<p>Redis supports various data structures such as strings, hashes, lists, sets, and more.</p>
<h2 id="heading-understanding-the-problem-redis-solves">Understanding the Problem Redis Solves</h2>
<p>In a typical web app setup, a user interacts with a server, which then talks to a database. This can cause performance problems, especially with complex queries. For example, when a user visits a website, the server might have to run several queries and joins to get data from the database.</p>
<p>This can take a long time, especially if the user refreshes the page often, leading to repeated heavy work and slower response times.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1771076648095/40b39a50-2ab7-48ee-b2e0-33c9ff928000.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-redis-as-a-solution">Redis as a Solution</h2>
<p>Redis addresses these issues by acting as an in-memory data store, providing a caching layer between the server and the database. This setup allows the server to check Redis for cached data before querying the database, significantly reducing response times and database load. Redis stores data in RAM, which is extremely fast but temporary, making it ideal for caching purposes.</p>
<h3 id="heading-benefits-of-using-redis">Benefits of Using Redis</h3>
<ul>
<li><p><strong>Fast Response Times</strong>: By caching data in memory, Redis allows for instant data retrieval, improving user experience.</p>
</li>
<li><p><strong>Reduced Database Load</strong>: Fewer database queries are needed, as Redis can serve cached data.</p>
</li>
<li><p><strong>Improved User Experience</strong>: Faster response times lead to a smoother user experience.</p>
</li>
</ul>
<h3 id="heading-common-use-cases-for-redis">Common Use Cases for Redis</h3>
<ol>
<li><p><strong>Caching</strong>: Redis is widely used for caching to improve application performance by storing frequently accessed data in memory.</p>
</li>
<li><p><strong>Rate Limiting</strong>: Redis can control the number of requests a user can make, preventing abuse and ensuring fair usage.</p>
</li>
<li><p><strong>Session Management</strong>: Redis provides a fast and scalable solution for storing session data in web applications.</p>
</li>
<li><p><strong>Background Jobs</strong>: Redis can be used to manage task queues and background jobs efficiently.</p>
</li>
<li><p><strong>Pub/Sub Messaging</strong>: Redis supports publish/subscribe messaging, useful for chat systems and notifications.</p>
</li>
<li><p><strong>Geo-Based Queries</strong>: Redis can handle geospatial data, enabling location-based features in applications.</p>
</li>
<li><p><strong>Ranking Systems</strong>: Sorted sets in Redis are ideal for implementing leaderboards and ranking systems.</p>
</li>
</ol>
<h3 id="heading-redis-data-structures">Redis Data Structures</h3>
<ul>
<li><p><strong>Strings</strong>: Basic values stored in Redis.</p>
</li>
<li><p><strong>Lists</strong>: Ordered collections that can be used as queues or stacks.</p>
</li>
<li><p><strong>Sets</strong>: Unordered collections of unique values.</p>
</li>
<li><p><strong>Hashes</strong>: Key-value pairs, similar to objects in programming languages.</p>
</li>
<li><p><strong>Sorted Sets</strong>: Sets with a score, used for ranking.</p>
</li>
<li><p><strong>Streams</strong>: High-throughput data structures for event logging and analytics.</p>
</li>
<li><p><strong>Geo Data</strong>: Used for location-based queries.</p>
</li>
<li><p><strong>Pub/Sub</strong>: Messaging system for real-time communication.</p>
</li>
</ul>
<h3 id="heading-redis-cli-basics">Redis CLI Basics</h3>
<p>Redis provides a command-line interface (CLI) for interacting with the database. Common commands include setting and getting keys, managing lists and sets, and performing operations on hashes and sorted sets.</p>
<h2 id="heading-setting-up-and-installing-redis-with-docker">Setting Up and Installing Redis with Docker</h2>
<p>To get started with Redis using Docker, follow these steps:</p>
<ol>
<li><p><strong>Install Docker</strong>: Ensure Docker is installed on your system. You can download it from the <a target="_blank" href="https://www.docker.com/products/docker-desktop">official Docker website</a>.</p>
</li>
<li><p><strong>Pull the Redis Image</strong>: Open your terminal and run the following command to pull the Redis image from Docker Hub:</p>
<pre><code class="lang-bash"> docker pull redis
</code></pre>
</li>
<li><p><strong>Run Redis Container</strong>: Start a Redis container using the command:</p>
<pre><code class="lang-bash"> docker run --name my-redis -d redis
</code></pre>
</li>
<li><p><strong>Access Redis CLI</strong>: To interact with Redis, you can use the Redis CLI by executing:</p>
<pre><code class="lang-bash"> docker <span class="hljs-built_in">exec</span> -it my-redis redis-cli
</code></pre>
</li>
</ol>
<h2 id="heading-redis-gui">Redis GUI</h2>
<p>A Redis GUI can help visualise and manage your Redis data more effectively. Some popular Redis GUI tools include:</p>
<ul>
<li><p><strong>RedisInsight</strong>: A powerful tool for visualising and optimising Redis data.</p>
</li>
<li><p><strong>Medis</strong>: A cross-platform, open-source Redis GUI management tool.</p>
</li>
<li><p><strong>RDM (Redis Desktop Manager)</strong>: A fast, open-source Redis database management application.</p>
</li>
</ul>
<h2 id="heading-redis-cli-commands">Redis CLI Commands</h2>
<p>Redis provides a command-line interface (CLI) for interacting with the database. Here are some common commands:</p>
<ul>
<li><p><strong>Keys</strong>:</p>
<ul>
<li><p><code>KEYS *</code>: List all keys.</p>
</li>
<li><p><code>DEL key</code>: Delete a key.</p>
</li>
<li><p><code>EXISTS key</code>: Check if a key exists.</p>
</li>
<li><p><code>TTL key</code>: Get the time-to-live of a key.</p>
</li>
<li><p><code>EXPIRE key 60</code>: Set a key to expire in 60 seconds.</p>
</li>
</ul>
</li>
<li><p><strong>Strings</strong>:</p>
<ul>
<li><p><code>SET key value</code>: Set a string value.</p>
</li>
<li><p><code>GET key</code>: Get a string value.</p>
</li>
<li><p><code>MSET key1 val1 key2 val2</code>: Set multiple keys.</p>
</li>
</ul>
</li>
<li><p><strong>Lists</strong>:</p>
<ul>
<li><p><code>LPUSH list value</code>: Push a value to the left of a list.</p>
</li>
<li><p><code>RPUSH list value</code>: Push a value to the right of a list.</p>
</li>
<li><p><code>LPOP list</code>: Pop a value from the left of a list.</p>
</li>
<li><p><code>LRANGE list 0 -1</code>: Get all elements in a list.</p>
</li>
</ul>
</li>
<li><p><strong>Sets</strong>:</p>
<ul>
<li><p><code>SADD set value</code>: Add a value to a set.</p>
</li>
<li><p><code>SREM set value</code>: Remove a value from a set.</p>
</li>
<li><p><code>SISMEMBER set value</code>: Check if a value is a member of a set.</p>
</li>
</ul>
</li>
<li><p><strong>Hashes</strong>:</p>
<ul>
<li><p><code>HSET bike model R15 price 200000</code>: Set fields in a hash.</p>
</li>
<li><p><code>HGET bike price</code>: Get a field from a hash.</p>
</li>
<li><p><code>HGETALL bike</code>: Get all fields and values in a hash.</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-redis-implementation-with-nodejs">Redis Implementation with Node.js</h2>
<p>To set up and use ioredis in a Node.js application, follow these steps with code examples for various use cases:</p>
<p><strong>Step 1: Install ioredis</strong></p>
<p>First, you need to install the <code>ioredis</code> package in your Node.js project. You can do this using npm:</p>
<pre><code class="lang-bash">npm install ioredis
</code></pre>
<p><strong>Step 2: Connect to Redis</strong></p>
<p>Create a connection to your Redis server using ioredis:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> Redis = <span class="hljs-built_in">require</span>(<span class="hljs-string">'ioredis'</span>);
<span class="hljs-keyword">const</span> redis = <span class="hljs-keyword">new</span> Redis(); <span class="hljs-comment">// Connects to 127.0.0.1:6379 by default</span>
</code></pre>
<h2 id="heading-1-basic-string-operations">1. Basic String Operations</h2>
<p><strong>Set and Get a Key:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Set a key</span>
redis.set(<span class="hljs-string">'name'</span>, <span class="hljs-string">'John Doe'</span>);

<span class="hljs-comment">// Get a key</span>
redis.get(<span class="hljs-string">'name'</span>, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-built_in">console</span>.error(err);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: John Doe</span>
  }
});
</code></pre>
<p><strong>Set a Key with Expiry:</strong></p>
<pre><code class="lang-javascript">redis.set(<span class="hljs-string">'session'</span>, <span class="hljs-string">'active'</span>, <span class="hljs-string">'EX'</span>, <span class="hljs-number">60</span>); <span class="hljs-comment">// Expires in 60 seconds</span>
</code></pre>
<h4 id="heading-2-working-with-lists">2. Working with Lists</h4>
<p><strong>Push and Pop Operations:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Push elements to a list</span>
redis.lpush(<span class="hljs-string">'tasks'</span>, <span class="hljs-string">'Task1'</span>);
redis.rpush(<span class="hljs-string">'tasks'</span>, <span class="hljs-string">'Task2'</span>);

<span class="hljs-comment">// Pop elements from a list</span>
redis.lpop(<span class="hljs-string">'tasks'</span>, <span class="hljs-function">(<span class="hljs-params">err, task</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(task); <span class="hljs-comment">// Output: Task1</span>
});
</code></pre>
<h2 id="heading-3-working-with-sets">3. Working with Sets</h2>
<p><strong>Add and Remove Members:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add members to a set</span>
redis.sadd(<span class="hljs-string">'tags'</span>, <span class="hljs-string">'nodejs'</span>, <span class="hljs-string">'redis'</span>);

<span class="hljs-comment">// Remove a member from a set</span>
redis.srem(<span class="hljs-string">'tags'</span>, <span class="hljs-string">'nodejs'</span>);

<span class="hljs-comment">// Check membership</span>
redis.sismember(<span class="hljs-string">'tags'</span>, <span class="hljs-string">'redis'</span>, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: 1 (true)</span>
});
</code></pre>
<h2 id="heading-4-working-with-hashes">4. Working with Hashes</h2>
<p><strong>Set and Get Hash Fields:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Set fields in a hash</span>
redis.hset(<span class="hljs-string">'user:1000'</span>, <span class="hljs-string">'name'</span>, <span class="hljs-string">'Alice'</span>, <span class="hljs-string">'age'</span>, <span class="hljs-string">'30'</span>);

<span class="hljs-comment">// Get a field from a hash</span>
redis.hget(<span class="hljs-string">'user:1000'</span>, <span class="hljs-string">'name'</span>, <span class="hljs-function">(<span class="hljs-params">err, name</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(name); <span class="hljs-comment">// Output: Alice</span>
});

<span class="hljs-comment">// Get all fields and values in a hash</span>
redis.hgetall(<span class="hljs-string">'user:1000'</span>, <span class="hljs-function">(<span class="hljs-params">err, user</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(user); <span class="hljs-comment">// Output: { name: 'Alice', age: '30' }</span>
});
</code></pre>
<h2 id="heading-5-pubsub-messaging">5. Pub/Sub Messaging</h2>
<p><strong>Subscribe and Publish:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Subscribe to a channel</span>
redis.subscribe(<span class="hljs-string">'news'</span>, <span class="hljs-function">(<span class="hljs-params">err, count</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Subscribed to <span class="hljs-subst">${count}</span> channel(s).`</span>);
});

<span class="hljs-comment">// Listen for messages</span>
redis.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">channel, message</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Received message from <span class="hljs-subst">${channel}</span>: <span class="hljs-subst">${message}</span>`</span>);
});

<span class="hljs-comment">// Publish a message</span>
<span class="hljs-keyword">const</span> publisher = <span class="hljs-keyword">new</span> Redis();
publisher.publish(<span class="hljs-string">'news'</span>, <span class="hljs-string">'Breaking News!'</span>);
</code></pre>
<p>These examples demonstrate how to set up and use ioredis in a Node.js application for various Redis operations, including basic string manipulation, list and set operations, hash management, and pub/sub messaging. Adjust the connection settings and commands as needed for your specific use case.</p>
<h2 id="heading-different-use-cases-of-redis">Different Use Cases of Redis</h2>
<p>Redis is a versatile, in-memory data structure store that can be used for a wide range of applications due to its speed and flexibility. Here are some detailed use cases where Redis can be effectively utilised:</p>
<ol>
<li><p><strong>Caching</strong></p>
</li>
<li><p><strong>Session Management</strong></p>
</li>
<li><p><strong>Real-time Analytics</strong></p>
</li>
<li><p><strong>Message Queues</strong></p>
</li>
<li><p><strong>Leaderboard/Counting Systems</strong></p>
</li>
<li><p><strong>Geospatial Data</strong></p>
</li>
<li><p><strong>Data Streaming</strong></p>
</li>
</ol>
<p>By leveraging these capabilities, Redis can significantly enhance the performance and scalability of applications across various domains. Whether it's for caching, session management, real-time analytics, or any other use case, Redis provides a robust and efficient solution.</p>
<h2 id="heading-caching-with-redis">Caching with Redis</h2>
<p>Redis is used as middleware in the endpoints of Express routes or as a function for caching to enhance application performance. Here's a simple Node.js example:</p>
<h3 id="heading-step-1-redis-client-setup-code">Step 1. Redis Client Setup Code</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { Redis } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"ioredis"</span>)
<span class="hljs-keyword">const</span> redisClient = <span class="hljs-keyword">new</span> Redis()

redisClient.on(<span class="hljs-string">"connecting"</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Redis Get Connecting"</span>)
})
redisClient.on(<span class="hljs-string">"connect"</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Redis Successfully connected"</span>)
})
redisClient.on(<span class="hljs-string">"error"</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error while connecting"</span>)
})


<span class="hljs-built_in">module</span>.exports = redisClient
</code></pre>
<h3 id="heading-step-2-redis-middleware">Step 2. Redis Middleware</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> redisClient = <span class="hljs-built_in">require</span>(<span class="hljs-string">"../utils/redisClient"</span>)

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cachedData</span>(<span class="hljs-params">key</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> (req, res, next) =&gt; {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"cached data"</span>)
            <span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">await</span> redisClient.get(key)
            <span class="hljs-keyword">if</span> (getData) {
                res.send(<span class="hljs-built_in">JSON</span>.parse(getData))
                <span class="hljs-keyword">return</span>
            }
            next()
        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.log(error)
            next()
        }

    }
}
<span class="hljs-built_in">module</span>.exports = cachedData
</code></pre>
<h3 id="heading-step-3-redis-with-express-endpoints">Step 3. Redis with Express endpoints</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { <span class="hljs-attr">default</span>: axios } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"axios"</span>)
<span class="hljs-keyword">const</span> client = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./utils/redisClient"</span>)
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>)
<span class="hljs-keyword">const</span> cachedData = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./middleware/cachedData"</span>)
<span class="hljs-keyword">const</span> redisClient = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./utils/redisClient"</span>)
<span class="hljs-keyword">const</span> app = express()


app.get(<span class="hljs-string">"/products"</span>, cachedData(<span class="hljs-string">"products"</span>), <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: productsData } = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">"https://dummyjson.com/products"</span>)
    <span class="hljs-keyword">await</span> redisClient.setex(<span class="hljs-string">"products"</span>, <span class="hljs-number">15</span>, <span class="hljs-built_in">JSON</span>.stringify(productsData))
    res.send(productsData)
})

app.get(<span class="hljs-string">"/products/:id"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> productId = req.params.id
    cachedData(<span class="hljs-string">`products:<span class="hljs-subst">${productId}</span>`</span>)
    <span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: productsData } = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">`https://dummyjson.com/products/<span class="hljs-subst">${productId}</span>`</span>)
    <span class="hljs-keyword">await</span> redisClient.setex(<span class="hljs-string">`products:<span class="hljs-subst">${productId}</span>`</span>, <span class="hljs-number">60</span>, <span class="hljs-built_in">JSON</span>.stringify(productsData))
    res.send(productsData)
})

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> cashedValue = <span class="hljs-keyword">await</span> client.get(<span class="hljs-string">"todoslist"</span>)
    <span class="hljs-keyword">if</span> (cashedValue) {
        res.json(<span class="hljs-built_in">JSON</span>.parse(cashedValue))
        <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-keyword">const</span> { data } = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>)
    <span class="hljs-keyword">await</span> client.setex(<span class="hljs-string">"todoslist"</span>, <span class="hljs-number">20</span>, <span class="hljs-built_in">JSON</span>.stringify(data))
    res.json(data)
})

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"App is running at port"</span>, <span class="hljs-number">3000</span>)
})
</code></pre>
<h2 id="heading-redis-as-a-rate-limiter">Redis as a Rate Limiter</h2>
<p>Redis can be used for rate limiting to control the number of requests a user can make:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> rateLimit = <span class="hljs-keyword">async</span> (ip) =&gt; {
  <span class="hljs-keyword">const</span> requests = <span class="hljs-keyword">await</span> client.incr(ip);
  <span class="hljs-keyword">if</span> (requests === <span class="hljs-number">1</span>) {
    client.expire(ip, <span class="hljs-number">60</span>); <span class="hljs-comment">// Set expiry to 60 seconds</span>
  }
  <span class="hljs-keyword">if</span> (requests &gt; <span class="hljs-number">100</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Too many requests'</span>;
  }
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Request allowed'</span>;
};
</code></pre>
<h3 id="heading-session-management">Session Management</h3>
<p>Redis is also used for session management in web applications, providing a fast and scalable solution for storing session data.</p>
<h2 id="heading-resources-link">Resources Link</h2>
<p><a target="_blank" href="https://www.youtube.com/watch?v=Vx2zPMPvmug&amp;t=1889s">https://www.youtube.com/watch?v=Vx2zPMPvmug&amp;t=1889s</a></p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=Y46wlauVH_o&amp;t=1s">https://www.youtube.com/watch?v=Y46wlauVH_o&amp;t=1s</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Redis is a versatile tool that can be used for various purposes, including caching, session management, and rate limiting. Its speed and efficiency make it an excellent choice for applications requiring real-time data processing. By using Docker, you can easily set up and manage Redis instances, making it accessible for development and production environments.</p>
]]></content:encoded></item><item><title><![CDATA[How to Integrate Razorpay Payments into Your MERN Project]]></title><description><![CDATA[If you are building a web application that requires online payments—such as course selling, appointment booking, SaaS billing, or e-commerce—Razorpay is one of the most reliable payment gateways avail]]></description><link>https://blog.adityaguptareal.com/how-to-integrate-razorpay-payments-into-your-mern-project</link><guid isPermaLink="true">https://blog.adityaguptareal.com/how-to-integrate-razorpay-payments-into-your-mern-project</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sun, 30 Nov 2025 05:44:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/d9ddb936-d248-4c7f-bbbc-45853ec9b507.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are building a web application that requires online payments—such as course selling, appointment booking, SaaS billing, or e-commerce—Razorpay is one of the most reliable payment gateways available in India.</p>
<p>This article explains how to integrate Razorpay in a MERN application by covering:</p>
<ul>
<li><p>Backend setup (Node.js + Express)</p>
</li>
<li><p>Razorpay order creation</p>
</li>
<li><p>Razorpay checkout integration in React</p>
</li>
<li><p>Payment verification</p>
</li>
<li><p>Webhook setup (optional but recommended)</p>
</li>
<li><p>Recommended production setup</p>
</li>
<li><p>Clean reusable code</p>
</li>
</ul>
<p>You can use this as a reference guide for any future MERN project requiring payments.</p>
<h2>1. Understanding Razorpay Payment Flow</h2>
<p>Before writing any code, here is the exact working flow:</p>
<p>React Frontend → Express Backend → Razorpay API</p>
<p>1. User clicks “Pay Now”</p>
<p>2. React calls the backend to create a Razorpay order</p>
<p>3. Backend returns order_id</p>
<p>4. Razorpay pop-up opens → user completes payment</p>
<p>5. Razorpay returns payment_id + order_id + signature to frontend</p>
<p>6. Frontend sends these values back to the backend</p>
<p>7. Backend verifies the payment signature using HMAC SHA256</p>
<p>8 If valid → mark payment as SUCCESS</p>
<p>This is the official and recommended approach.</p>
<h2>2. Project Structure</h2>
<pre><code class="language-bash">backend/
  ├── server.js
  ├── routes/
  │     └── paymentRoutes.js
  ├── controllers/
  │     └── paymentController.js
  ├── utils/
  │     └── razorpay.js
  ├── .env

frontend/
  ├── src/
  │     └── components/PayButton.jsx
  ├── public/
        └── index.html
</code></pre>
<h2>3. Install Backend Dependencies</h2>
<p>Run the following command:</p>
<pre><code class="language-javascript">npm install express razorpay cors dotenv crypto
</code></pre>
<h2>4. Configure Environment Variables (.env)</h2>
<p>Create a <code>.env</code> file in your backend folder:</p>
<pre><code class="language-javascript">RAZORPAY_KEY_ID=YOUR_TEST_OR_LIVE_KEY_ID
RAZORPAY_KEY_SECRET=YOUR_TEST_OR_LIVE_KEY_SECRET

CLIENT_URL=http://localhost:3000
SERVER_URL=http://localhost:5000
</code></pre>
<hr />
<h2>5. Create Razorpay Instance (Backend)</h2>
<p><code>backend/utils/razorpay.js</code></p>
<pre><code class="language-javascript">import Razorpay from 'razorpay';
import dotenv from 'dotenv';

dotenv.config();

export const razorpay = new Razorpay({
  key_id: process.env.RAZORPAY_KEY_ID,
  key_secret: process.env.RAZORPAY_KEY_SECRET,
});
</code></pre>
<h2>6. Backend Controller: Create Razorpay Order</h2>
<p><strong>backend/controllers/paymentController.js</strong></p>
<pre><code class="language-javascript">import crypto from "crypto";
import { razorpay } from "../utils/razorpay.js";

export const createOrder = async (req, res) =&gt; {
  try {
    const { amount } = req.body; 

    const options = {
      amount: Number(amount) * 100,  
      currency: "INR",
      receipt: "receipt_" + Date.now(),
    };

    const order = await razorpay.orders.create(options);

    res.json({ success: true, order });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
};
</code></pre>
<h2>7. Backend Controller: Verify Razorpay Payment Signature</h2>
<pre><code class="language-javascript">export const verifyPayment = async (req, res) =&gt; {
  try {
    const { razorpay_order_id, razorpay_payment_id, razorpay_signature } =
      req.body;

    const body = razorpay_order_id + "|" + razorpay_payment_id;

    const expectedSignature = crypto
      .createHmac("sha256", process.env.RAZORPAY_KEY_SECRET)
      .update(body)
      .digest("hex");

    if (expectedSignature === razorpay_signature) {
      return res.json({ success: true, message: "Payment Verified" });
    } else {
      return res.status(400).json({ success: false, message: "Invalid Signature" });
    }
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
};
</code></pre>
<h1>8. Create Express Routes</h1>
<p><strong>backend/routes/paymentRoutes.js</strong></p>
<pre><code class="language-java">import express from 'express';
import { createOrder, verifyPayment } from '../controllers/paymentController.js';

const router = express.Router();

router.post("/create-order", createOrder);
router.post("/verify-payment", verifyPayment);

export default router;
</code></pre>
<h2>9. Final Express Setup</h2>
<p><strong>backend/server.js</strong></p>
<pre><code class="language-javascript">import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import paymentRoutes from "./routes/paymentRoutes.js";

dotenv.config();

const app = express();

app.use(express.json());
app.use(cors({ origin: process.env.CLIENT_URL }));

app.use("/api/payment", paymentRoutes);

app.get("/", (req, res) =&gt; {
  res.send("Razorpay MERN Backend Running");
});

app.listen(5000, () =&gt; console.log("Server running on port 5000"));
</code></pre>
<p>Backend is now ready.</p>
<h2>10. Frontend Setup</h2>
<p>Install Axios:</p>
<pre><code class="language-bash">npm install axios
</code></pre>
<p>Add Razorpay script loader inside:</p>
<p><strong>frontend/public/index.html</strong></p>
<pre><code class="language-javascript">&lt;script src="https://checkout.razorpay.com/v1/checkout.js"&gt;&lt;/script&gt;
</code></pre>
<h2>11. Create Payment Button Component</h2>
<p><strong>frontend/src/components/PayButton.jsx</strong></p>
<pre><code class="language-javascript">import axios from "axios";

function PayButton() {
  const handlePayment = async () =&gt; {
    const { data } = await axios.post(
      "http://localhost:5000/api/payment/create-order",
      { amount: 499 }
    );

    const order = data.order;

    const options = {
      key: "YOUR_TEST_OR_LIVE_KEY_ID",
      amount: order.amount,
      currency: "INR",
      name: "My Application",
      description: "Payment for Service",
      order_id: order.id,
      handler: async function (response) {
        const verify = await axios.post(
          "http://localhost:5000/api/payment/verify-payment",
          response
        );

        if (verify.data.success) {
          alert("Payment Successful");
        } else {
          alert("Payment Verification Failed");
        }
      },
      theme: {
        color: "#121212",
      },
    };

    const razorpayObj = new window.Razorpay(options);
    razorpayObj.open();
  };

  return &lt;button onClick={handlePayment}&gt;Pay Now&lt;/button&gt;;
}

export default PayButton;
</code></pre>
<h2>12. Testing Razorpay Payments</h2>
<p>Use Razorpay’s test mode.</p>
<p>Test card:</p>
<pre><code class="language-bash">4111 1111 1111 1111
Expiry: Any future month/year
CVV: 123
</code></pre>
<p>Payment will always succeed in test mode.</p>
<h2>13. Optional: Razorpay Webhook (For 100% Accurate Payments)</h2>
<p>If the user closes the tab immediately after paying, verification might fail.<br />Webhooks ensure payment confirmation is always delivered.</p>
<p><strong>backend/routes/webhookRoutes.js</strong></p>
<pre><code class="language-javascript">import express from "express";
import crypto from "crypto";

const router = express.Router();

router.post("/razorpay", (req, res) =&gt; {
  const secret = process.env.RAZORPAY_KEY_SECRET;

  const shasum = crypto.createHmac("sha256", secret);
  shasum.update(JSON.stringify(req.body));
  const digest = shasum.digest("hex");

  if (digest === req.headers["x-razorpay-signature"]) {
    console.log("Webhook Verified");
// database update logic
    console.log("Event Data:", req.body);
  } else {
    return res.status(400).json({ message: "Invalid Signature" });
  }

  res.status(200).json({ status: "ok" });
});

export default router;
</code></pre>
<p>Add this in <code>server.js</code>:</p>
<pre><code class="language-javascript">app.use("/api/webhook", webhookRoutes);
</code></pre>
<p>Set webhook URL in Razorpay Dashboard:</p>
<pre><code class="language-bash">https://your-domain.com/api/webhook/razorpay
</code></pre>
<h2>Conclusion</h2>
<p>Integrating Razorpay into a MERN stack application can significantly enhance your project's payment capabilities, providing a seamless and secure transaction experience for users.</p>
<p>By following this guide, you have learned how to set up the backend and frontend, create and verify Razorpay orders, and implement optional webhooks for reliable payment confirmations.</p>
<p>With this knowledge, you can confidently incorporate Razorpay into any future MERN projects, ensuring a robust and efficient payment system.</p>
]]></content:encoded></item><item><title><![CDATA[Building a Multi-Tenant SaaS With Automatic Subdomains Using MERN Stack (2025 Guide)]]></title><description><![CDATA[Modern SaaS applications—LMS platforms, CRM tools, appointment management systems—often need multi-tenant architecture. A powerful (and popular) approach is subdomain-based multi-tenancy, where each business gets:
businessname.yourapp.com

Example fo...]]></description><link>https://blog.adityaguptareal.com/building-a-multi-tenant-saas-with-automatic-subdomains-using-mern-stack-2025-guide</link><guid isPermaLink="true">https://blog.adityaguptareal.com/building-a-multi-tenant-saas-with-automatic-subdomains-using-mern-stack-2025-guide</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sun, 30 Nov 2025 05:39:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1771051348422/bc53196d-3c43-41b2-9c3c-66b66208adf4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Modern SaaS applications—LMS platforms, CRM tools, appointment management systems—often need <strong>multi-tenant architecture</strong>. A powerful (and popular) approach is <strong>subdomain-based multi-tenancy</strong>, where each business gets:</p>
<pre><code class="lang-java">businessname.yourapp.com
</code></pre>
<p>Example for a salon SaaS:</p>
<pre><code class="lang-java">saloonking.glowSaaS.com
prettylooks.glowSaaS.com
divasalon.glowSaaS.com
</code></pre>
<p>In this guide, we will build a <strong>working subdomain multi-tenant system</strong> using:</p>
<ul>
<li><p><strong>MongoDB</strong></p>
</li>
<li><p><strong>Express.js</strong></p>
</li>
<li><p><strong>React</strong></p>
</li>
<li><p><strong>CORS</strong></p>
</li>
<li><p><strong>Local host mapping</strong></p>
</li>
<li><p><strong>DNS configuration for production</strong></p>
</li>
</ul>
<p>Everything is simplified so you can extend later.</p>
<hr />
<h1 id="heading-how-subdomain-multi-tenancy-works"><strong>How Subdomain Multi-Tenancy Works</strong></h1>
<p>When someone enters:</p>
<pre><code class="lang-java">saloonking.yourapp.com
</code></pre>
<p>The browser sends a request where:</p>
<pre><code class="lang-java">req.hostname = saloonking.yourapp.com
subdomain = saloonking
</code></pre>
<p>Your Express server checks the database:</p>
<pre><code class="lang-java">subdomain <span class="hljs-string">"saloonking"</span> → matches Tenant A
</code></pre>
<p>Then React loads that tenant’s website data.</p>
<hr />
<h1 id="heading-project-structure-mern">PROJECT STRUCTURE (MERN)</h1>
<pre><code class="lang-java">root/
  backend/
    server.js
    models/Tenant.js
  frontend/
    src/
      pages/
        TenantSite.jsx
        MainSite.jsx
        Dashboard.jsx
    App.js
</code></pre>
<p>Backend port: <code>5000</code><br />Frontend port: <code>3000</code></p>
<hr />
<h1 id="heading-1-mongodb-tenant-model"><strong>1. MongoDB Tenant Model</strong></h1>
<p><code>backend/models/Tenant.js</code></p>
<pre><code class="lang-java"><span class="hljs-keyword">const</span> mongoose = require(<span class="hljs-string">"mongoose"</span>);

<span class="hljs-keyword">const</span> tenantSchema = <span class="hljs-keyword">new</span> mongoose.Schema({
  name: String,
  subdomain: String,
  siteData: Object
});

<span class="hljs-keyword">module</span>.<span class="hljs-keyword">exports</span> = mongoose.model(<span class="hljs-string">"Tenant"</span>, tenantSchema);
</code></pre>
<p>Example record:</p>
<pre><code class="lang-java">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Saloon King"</span>,
  <span class="hljs-string">"subdomain"</span>: <span class="hljs-string">"saloonking"</span>,
  <span class="hljs-string">"siteData"</span>: {
    <span class="hljs-string">"title"</span>: <span class="hljs-string">"Welcome to Saloon King"</span>,
    <span class="hljs-string">"description"</span>: <span class="hljs-string">"Best salon in town"</span>
  }
}
</code></pre>
<h1 id="heading-2-express-backend-with-subdomain-detection"><strong>2. Express Backend With Subdomain Detection</strong></h1>
<p><code>backend/server.js</code></p>
<pre><code class="lang-java"><span class="hljs-keyword">const</span> express = require(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> mongoose = require(<span class="hljs-string">"mongoose"</span>);
<span class="hljs-keyword">const</span> cors = require(<span class="hljs-string">"cors"</span>);
<span class="hljs-keyword">const</span> Tenant = require(<span class="hljs-string">"./models/Tenant"</span>);

<span class="hljs-keyword">const</span> app = express();
app.use(cors());
app.use(express.json());

mongoose.connect(<span class="hljs-string">"mongodb://127.0.0.1:27017/multitenant"</span>);

<span class="hljs-comment">// Middleware: detect subdomain</span>
app.use(async (req, res, next) =&gt; {
  <span class="hljs-keyword">const</span> host = req.hostname; <span class="hljs-comment">// e.g., saloonking.yourapp.com</span>
  <span class="hljs-keyword">const</span> parts = host.split(<span class="hljs-string">"."</span>);
  <span class="hljs-keyword">const</span> sub = parts[<span class="hljs-number">0</span>];

  <span class="hljs-keyword">if</span> (sub !== <span class="hljs-string">"localhost"</span> &amp;&amp; sub !== <span class="hljs-string">"yourapp"</span> &amp;&amp; sub !== <span class="hljs-string">"app"</span>) {
    <span class="hljs-keyword">const</span> tenant = await Tenant.findOne({ subdomain: sub });
    <span class="hljs-keyword">if</span> (tenant) req.tenant = tenant;
  }

  next();
});

<span class="hljs-comment">// API to return tenant data</span>
app.get(<span class="hljs-string">"/tenant"</span>, (req, res) =&gt; {
  <span class="hljs-keyword">if</span> (!req.tenant) <span class="hljs-keyword">return</span> res.json({ tenant: <span class="hljs-keyword">null</span> });
  res.json(req.tenant);
});

app.listen(<span class="hljs-number">5000</span>, () =&gt; console.log(<span class="hljs-string">"Backend running on port 5000"</span>));
</code></pre>
<hr />
<ol start="3">
<li><h1 id="heading-react-frontend-logic-auto-detect-subdomain"><strong>React Frontend Logic (Auto-Detect Subdomain)</strong></h1>
</li>
</ol>
<p><code>frontend/src/App.js</code></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> TenantSite from <span class="hljs-string">"./pages/TenantSite"</span>;
<span class="hljs-keyword">import</span> MainSite from <span class="hljs-string">"./pages/MainSite"</span>;
<span class="hljs-keyword">import</span> Dashboard from <span class="hljs-string">"./pages/Dashboard"</span>;

<span class="hljs-function">function <span class="hljs-title">App</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">const</span> hostname = window.location.hostname.split(<span class="hljs-string">"."</span>)[<span class="hljs-number">0</span>];

  <span class="hljs-keyword">if</span> (hostname === <span class="hljs-string">"app"</span>) <span class="hljs-keyword">return</span> &lt;Dashboard /&gt;;
  <span class="hljs-keyword">if</span> (hostname === <span class="hljs-string">"yourapp"</span> || hostname === <span class="hljs-string">"localhost"</span>)
    <span class="hljs-keyword">return</span> &lt;MainSite /&gt;;

  <span class="hljs-keyword">return</span> &lt;TenantSite /&gt;;
}

export <span class="hljs-keyword">default</span> App;
</code></pre>
<hr />
<h1 id="heading-tenant-website-page">📄 Tenant Website Page</h1>
<p><code>frontend/src/pages/TenantSite.jsx</code></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> { useEffect, useState } from <span class="hljs-string">"react"</span>;

<span class="hljs-function">export <span class="hljs-keyword">default</span> function <span class="hljs-title">TenantSite</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">const</span> [tenant, setTenant] = useState(<span class="hljs-keyword">null</span>);

  useEffect(() =&gt; {
    fetch(<span class="hljs-string">"http://localhost:5000/tenant"</span>)
      .then(res =&gt; res.json())
      .then(data =&gt; setTenant(data));
  }, []);

  <span class="hljs-keyword">if</span> (!tenant) <span class="hljs-keyword">return</span> &lt;h2&gt;Loading...&lt;/h2&gt;;

  <span class="hljs-keyword">return</span> (
    &lt;div style={{ padding: <span class="hljs-number">20</span> }}&gt;
      &lt;h1&gt;{tenant.siteData.title}&lt;/h1&gt;
      &lt;p&gt;{tenant.siteData.description}&lt;/p&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<hr />
<h1 id="heading-main-saas-homepage">🏠 Main SaaS Homepage</h1>
<p><code>frontend/src/pages/MainSite.jsx</code></p>
<pre><code class="lang-java"><span class="hljs-function">export <span class="hljs-keyword">default</span> function <span class="hljs-title">MainSite</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">return</span> (
    &lt;div style={{ padding: <span class="hljs-number">20</span> }}&gt;
      &lt;h1&gt;Welcome to My SaaS&lt;/h1&gt;
      &lt;p&gt;Create your own salon website in minutes.&lt;/p&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<hr />
<h1 id="heading-tenant-dashboard">🧑‍💼 Tenant Dashboard</h1>
<p><code>frontend/src/pages/Dashboard.jsx</code></p>
<pre><code class="lang-java"><span class="hljs-function">export <span class="hljs-keyword">default</span> function <span class="hljs-title">Dashboard</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">return</span> (
    &lt;div style={{ padding: <span class="hljs-number">20</span> }}&gt;
      &lt;h1&gt;Tenant Dashboard&lt;/h1&gt;
      &lt;p&gt;Edit your website here&lt;/p&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<hr />
<h1 id="heading-4-local-testing-configure-etchosts">🧪 <strong>4. Local Testing: Configure</strong> <code>/etc/hosts</code></h1>
<p>Add:</p>
<pre><code class="lang-java"><span class="hljs-number">127.0</span>.<span class="hljs-number">0.1</span> saloonking.localhost
<span class="hljs-number">127.0</span>.<span class="hljs-number">0.1</span> prettylooks.localhost
<span class="hljs-number">127.0</span>.<span class="hljs-number">0.1</span> yourapp.localhost
<span class="hljs-number">127.0</span>.<span class="hljs-number">0.1</span> app.localhost
</code></pre>
<p>Now test:</p>
<pre><code class="lang-java">http:<span class="hljs-comment">//saloonking.localhost:3000</span>
</code></pre>
<p>You will see that salon’s website.</p>
<hr />
<h1 id="heading-5-dns-production-setup-allow-users-to-create-subdomains-automatically">🌐 <strong>5. DNS + Production Setup: Allow Users to Create Subdomains Automatically</strong></h1>
<p>This is the MOST IMPORTANT part you requested.<br />This lets your SaaS automatically create:</p>
<pre><code class="lang-java">saloonname.yourapp.com
</code></pre>
<h3 id="heading-only-one-dns-record-is-required">✔ Only ONE DNS record is required:</h3>
<h2 id="heading-step-1-add-a-wildcard-dns-record">✅ <strong>Step 1: Add a Wildcard DNS Record</strong></h2>
<p>Go to your domain provider (GoDaddy / Hostinger / Cloudflare).</p>
<p>Add:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Name</td><td>Value</td></tr>
</thead>
<tbody>
<tr>
<td><strong>A</strong></td><td><code>*.</code><a target="_blank" href="http://yourapp.com"><code>yourapp.com</code></a></td><td>Your server IP</td></tr>
<tr>
<td><strong>A</strong></td><td><a target="_blank" href="http://yourapp.com"><code>yourapp.com</code></a></td><td>Your server IP</td></tr>
</tbody>
</table>
</div><p>Example:</p>
<pre><code class="lang-java">Type: A
Host: *
Value: <span class="hljs-number">34.101</span>.<span class="hljs-number">23.88</span> (your VPS IP)
TTL: Auto
</code></pre>
<p>This means:</p>
<blockquote>
<p>ANY subdomain → points to your backend server.</p>
</blockquote>
<p>So:</p>
<ul>
<li><p><a target="_blank" href="http://saloon1.yourapp.com"><code>saloon1.yourapp.com</code></a> → goes to your Express app</p>
</li>
<li><p><a target="_blank" href="http://saloon2.yourapp.com"><code>saloon2.yourapp.com</code></a> → goes to your Express app</p>
</li>
<li><p><a target="_blank" href="http://xyz.yourapp.com"><code>xyz.yourapp.com</code></a> → also goes to your Express app</p>
</li>
</ul>
<p>You do NOT need to create each subdomain manually.</p>
<h3 id="heading-this-is-how-saas-platforms-like-shopify-wix-and-notion-do-it">🎉 This is how SaaS platforms like Shopify, Wix, and Notion do it.</h3>
<hr />
<h1 id="heading-step-2-when-a-salon-signs-up-generate-a-subdomain">🏗 <strong>Step 2: When a salon signs up, generate a subdomain</strong></h1>
<p>In your signup logic:</p>
<pre><code class="lang-java"><span class="hljs-keyword">const</span> newTenant = <span class="hljs-keyword">new</span> Tenant({
  name: req.body.name,
  subdomain: req.body.subdomain,
  siteData: { title: <span class="hljs-string">""</span>, description: <span class="hljs-string">""</span> }
});

await newTenant.save();
</code></pre>
<p>Now <a target="_blank" href="http://saloonName.yourapp.com"><code>saloonName.yourapp.com</code></a> will start working immediately because of the wildcard DNS.</p>
<hr />
<h1 id="heading-step-3-ssl-https">🔒 <strong>Step 3: SSL (HTTPS)</strong></h1>
<p>For HTTPS, use:</p>
<h3 id="heading-caddy-best-and-automatic">✔ <strong>Caddy</strong> (best and automatic)</h3>
<p>or</p>
<h3 id="heading-certbot-nginx">✔ Certbot + NGINX</h3>
<p>or</p>
<h3 id="heading-cloudflare-proxy">✔ Cloudflare proxy</h3>
<p>Caddy auto-generates SSL for ALL wildcard subdomains.</p>
]]></content:encoded></item><item><title><![CDATA[Google OAuth Authentication with React, Node.js, and Express]]></title><description><![CDATA[Google Sign-In is one of the easiest ways to authenticate users without asking them to create and remember another password. In this guide, you'll learn how to integrate Google OAuth into a React appl]]></description><link>https://blog.adityaguptareal.com/mern-google-auth</link><guid isPermaLink="true">https://blog.adityaguptareal.com/mern-google-auth</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Sat, 01 Nov 2025 07:14:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65def9438b970336d9eb270d/e6821a86-884e-4855-bb8a-55edb9ae8053.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Google Sign-In is one of the easiest ways to authenticate users without asking them to create and remember another password. In this guide, you'll learn how to integrate Google OAuth into a React application using <code>@react-oauth/google</code> and verify users securely on a Node.js backend.</p>
<p>By the end of this guide, you'll have:</p>
<ul>
<li>A React frontend with Google Sign-In</li>
<li>A Node.js backend that verifies Google ID tokens</li>
<li>JWT-based authentication</li>
<li>Automatic user creation for first-time sign-ins</li>
</ul>
<hr />
<h1>Prerequisites</h1>
<p>Before getting started, make sure you have:</p>
<table>
<thead>
<tr>
<th>Requirement</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>Node.js</td>
<td>Installed on your machine</td>
</tr>
<tr>
<td>React</td>
<td>Vite or Create React App</td>
</tr>
<tr>
<td>Express</td>
<td>Backend server</td>
</tr>
<tr>
<td>MongoDB</td>
<td>Database for storing users</td>
</tr>
<tr>
<td>Google Cloud Account</td>
<td>Required to create OAuth credentials</td>
</tr>
</tbody></table>
<hr />
<h1>Create Google OAuth Credentials</h1>
<p>Open the <strong>Google Cloud Console</strong> and navigate to the <strong>Credentials</strong> page.</p>
<p>Create a new OAuth Client ID with the following settings.</p>
<table>
<thead>
<tr>
<th>Option</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td>Credential Type</td>
<td>OAuth Client ID</td>
</tr>
<tr>
<td>Application Type</td>
<td>Web Application</td>
</tr>
</tbody></table>
<p>After creating the credentials, copy the generated <strong>Client ID</strong>. You'll use it in both the frontend and backend.</p>
<hr />
<h1>Frontend Setup</h1>
<h2>Install Required Package</h2>
<pre><code class="language-bash">npm install @react-oauth/google
</code></pre>
<hr />
<h2>Configure Environment Variables</h2>
<p>Create a <code>.env</code> file in your frontend project.</p>
<pre><code class="language-env">VITE_GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
VITE_BACKEND_URL=http://localhost:5000
</code></pre>
<hr />
<h2>Wrap Your Application</h2>
<p>Update your <code>main.tsx</code> file.</p>
<pre><code class="language-tsx">import { GoogleOAuthProvider } from "@react-oauth/google";

const clientId = import.meta.env.VITE_GOOGLE_CLIENT_ID;

&lt;GoogleOAuthProvider clientId={clientId}&gt;
  &lt;App /&gt;
&lt;/GoogleOAuthProvider&gt;;
</code></pre>
<p>This provider makes the Google authentication context available throughout your application.</p>
<hr />
<h2>Create the Google Authentication Component</h2>
<p>Create a new component called <code>GoogleAuth.tsx</code>.</p>
<pre><code class="language-tsx">import { GoogleLogin } from "@react-oauth/google";
import axios from "axios";

const GoogleAuth = () =&gt; {
  const handleSuccess = async (credentialResponse) =&gt; {
    try {
      const res = await axios.post(
        `${import.meta.env.VITE_BACKEND_URL}/api/v1/google-signin`,
        {
          credential: credentialResponse.credential,
        }
      );

      localStorage.setItem("token", res.data.token);
      alert("Login successful");
    } catch (err) {
      console.error("Login error:", err);
      alert("Login failed");
    }
  };

  return (
    &lt;GoogleLogin
      onSuccess={handleSuccess}
      onError={() =&gt; alert("Google Login Failed")}
    /&gt;
  );
};

export default GoogleAuth;
</code></pre>
<p>Once the user signs in successfully, Google returns an ID token. This token is then sent to the backend for verification.</p>
<hr />
<h1>Common Frontend Mistakes</h1>
<table>
<thead>
<tr>
<th>Mistake</th>
<th>Why It Causes Problems</th>
</tr>
</thead>
<tbody><tr>
<td>Missing <code>GoogleOAuthProvider</code></td>
<td>Google Login will not initialize</td>
</tr>
<tr>
<td>Incorrect <code>clientId</code></td>
<td>Authentication will fail</td>
</tr>
<tr>
<td>Sending requests to the frontend instead of the backend</td>
<td>OAuth verification must happen on the server</td>
</tr>
<tr>
<td>Forgetting to define environment variables</td>
<td>The application won't be able to access the Google Client ID or backend URL</td>
</tr>
</tbody></table>
<hr />
<h1>Backend Setup</h1>
<h2>Install Required Package</h2>
<pre><code class="language-bash">npm install google-auth-library
</code></pre>
<hr />
<h2>Configure Environment Variables</h2>
<p>Create a <code>.env</code> file in the backend.</p>
<pre><code class="language-env">GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
JWT_SECRET=your_jwt_secret_key
</code></pre>
<hr />
<h2>Create the Authentication Controller</h2>
<p>Create a file named <code>googleAuth.ts</code>.</p>
<pre><code class="language-ts">import { OAuth2Client } from "google-auth-library";
import User from "../models/user";
import jwt from "jsonwebtoken";

const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);

export const googleAuth = async (req, res) =&gt; {
  try {
    const { credential } = req.body;

    const ticket = await client.verifyIdToken({
      idToken: credential,
      audience: process.env.GOOGLE_CLIENT_ID,
    });

    const payload = ticket.getPayload();

    const {
      email,
      name,
      sub: googleID,
    } = payload;

    let user = await User.findOne({ email });

    if (!user) {
      user = await User.create({
        email,
        username: name,
        googleID,
      });
    }

    const token = jwt.sign(
      {
        id: user._id,
      },
      process.env.JWT_SECRET,
      {
        expiresIn: "7d",
      }
    );

    res.status(200).json({
      token,
      user,
    });
  } catch (error) {
    console.error(error);

    res.status(401).json({
      message: "Google sign-in failed",
    });
  }
};
</code></pre>
<p>The backend verifies the ID token received from Google. If the token is valid, it either creates a new user or logs in an existing one before returning a JWT.</p>
<hr />
<h1>Register the Route</h1>
<p>Import the controller into your main server file.</p>
<pre><code class="language-ts">import { googleAuth } from "./controllers/googleAuth";
</code></pre>
<p>Register the route.</p>
<pre><code class="language-ts">app.post("/api/v1/google-signin", googleAuth);
</code></pre>
<hr />
<h1>User Schema</h1>
<p>A simple user schema is enough for Google authentication.</p>
<pre><code class="language-ts">const userSchema = new mongoose.Schema({
  username: String,
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: String,
  googleID: String,
});
</code></pre>
<p>If your application supports both email/password authentication and Google Sign-In, keeping the <code>password</code> field optional is a common approach.</p>
<hr />
<h1>Authentication Flow</h1>
<p>The complete authentication process looks like this:</p>
<pre><code class="language-text">User
   │
   ▼
Google Login Button
   │
   ▼
Google Authentication
   │
   ▼
Receive ID Token
   │
   ▼
Send Token to Express Backend
   │
   ▼
Verify Token with Google
   │
   ▼
Find or Create User
   │
   ▼
Generate JWT
   │
   ▼
Return JWT + User Data
   │
   ▼
Store JWT in Frontend
</code></pre>
<hr />
<h1>Final Project Structure</h1>
<pre><code class="language-text">frontend
├── src
│   ├── components
│   │   └── GoogleAuth.tsx
│   ├── App.tsx
│   └── main.tsx
├── .env

backend
├── controllers
│   └── googleAuth.ts
├── models
│   └── user.ts
├── index.ts
└── .env
</code></pre>
<hr />
<h1>Conclusion</h1>
<p>Integrating Google OAuth removes the friction of traditional sign-up forms while providing a secure authentication flow. Instead of managing passwords yourself, you rely on Google's identity platform, verify the ID token on your backend, and issue your own JWT for application access.</p>
<p>With this setup in place, users can sign in with a single click, while your backend remains responsible for authentication, authorization, and session management.</p>
]]></content:encoded></item><item><title><![CDATA[Build Your App with Capacitor JS: A Comprehensive Guide]]></title><description><![CDATA[1. Introduction
Capacitor JS allows you to convert any web app (like Next.js) into a native Android or iOS app — without rewriting your frontend.It wraps your app inside a native WebView and lets you access mobile features like Camera, Storage, Push ...]]></description><link>https://blog.adityaguptareal.com/build-your-app-with-capacitor-js-a-comprehensive-guide</link><guid isPermaLink="true">https://blog.adityaguptareal.com/build-your-app-with-capacitor-js-a-comprehensive-guide</guid><dc:creator><![CDATA[Aditya Kumar Gupta]]></dc:creator><pubDate>Thu, 30 Oct 2025 16:27:12 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-1-introduction">1. Introduction</h2>
<p>Capacitor JS allows you to convert any <strong>web app (like Next.js)</strong> into a <strong>native Android or iOS app</strong> — without rewriting your frontend.<br />It wraps your app inside a native WebView and lets you access mobile features like Camera, Storage, Push Notifications, etc.</p>
<hr />
<h2 id="heading-2-prerequisites">2. Prerequisites</h2>
<p>Before starting, make sure you have:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Tool</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td>Node.js (v18 or above)</td><td>Build your Next.js app</td></tr>
<tr>
<td>Android Studio</td><td>For building APK/AAB</td></tr>
<tr>
<td>Java JDK 11+</td><td>Required for Android builds</td></tr>
<tr>
<td>Capacitor CLI</td><td>To integrate Capacitor</td></tr>
<tr>
<td>Git (optional)</td><td>Version control</td></tr>
</tbody>
</table>
</div><p>Check versions:</p>
<pre><code class="lang-javascript">node -v
npm -v
java -version
</code></pre>
<hr />
<h2 id="heading-3-create-and-build-a-nextjs-app">3. Create and Build a Next.js App</h2>
<p>If you don’t already have a Next.js app, create one:</p>
<pre><code class="lang-javascript">npx create-next-app@latest portfolio
cd portfolio
</code></pre>
<hr />
<h2 id="heading-4-install-capacitor">4. Install Capacitor</h2>
<p>Install Capacitor core packages:</p>
<pre><code class="lang-javascript">npm install @capacitor/core @capacitor/cli
</code></pre>
<p>Initialise Capacitor in your project:</p>
<pre><code class="lang-javascript">npx cap init
</code></pre>
<p>When prompted:</p>
<ul>
<li><p><strong>App name:</strong> Portfolio</p>
</li>
<li><p><strong>App ID:</strong> com.aditya.portfolio</p>
</li>
<li><p><strong>Web directory:</strong> <code>out</code> (for static exports)</p>
</li>
</ul>
<hr />
<h2 id="heading-5-update-capacitor-config">5. Update Capacitor Config</h2>
<p>Open <code>capacitor.config.ts</code> and set this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> type { CapacitorConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'@capacitor/cli'</span>;

<span class="hljs-keyword">const</span> config: CapacitorConfig = {
  <span class="hljs-attr">appId</span>: <span class="hljs-string">'com.aditya.portfolio'</span>,
  <span class="hljs-attr">appName</span>: <span class="hljs-string">'Portfolio'</span>,
  <span class="hljs-attr">webDir</span>: <span class="hljs-string">'out'</span>,
  <span class="hljs-attr">bundledWebRuntime</span>: <span class="hljs-literal">false</span>,
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> config;
</code></pre>
<hr />
<h2 id="heading-6-export-your-nextjs-app">6. Export Your Next.js App</h2>
<p>Next.js no longer supports <code>next export</code> CLI directly — use the <strong>new config option</strong>.</p>
<p>In <code>next.config.mjs</code>, add:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/** <span class="hljs-doctag">@type <span class="hljs-type">{import('next').NextConfig}</span> </span>*/</span>
<span class="hljs-keyword">const</span> nextConfig = {
  <span class="hljs-attr">output</span>: <span class="hljs-string">'export'</span>, <span class="hljs-comment">// Required for static build</span>
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> nextConfig;
</code></pre>
<p>Then build:</p>
<pre><code class="lang-javascript">npm run build
</code></pre>
<p>After build, Next.js will generate a static <code>out/</code> folder.</p>
<hr />
<h2 id="heading-7-add-android-platform">7. Add Android Platform</h2>
<p>Now add Android support:</p>
<pre><code class="lang-javascript">npm install @capacitor/android
npx cap add android
</code></pre>
<p>If you get an error like:</p>
<pre><code class="lang-javascript">[error] The web assets directory (.\public) must contain an index.html file.
</code></pre>
<p>👉 It means you haven’t built your app yet — <strong>run</strong> <code>npm run build</code> first.</p>
<p>Then sync your project:</p>
<pre><code class="lang-javascript">npx cap sync
</code></pre>
<hr />
<h2 id="heading-8-fix-common-errors">8. Fix Common Errors</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Error</td><td>Cause</td><td>Fix</td></tr>
</thead>
<tbody>
<tr>
<td>❌ <code>Could not find web assets directory</code></td><td>Missing <code>out</code> folder</td><td>Run <code>npm run build</code> again</td></tr>
<tr>
<td>❌ <code>Cannot run init for non-JSON config</code></td><td>You have <code>capacitor.config.ts</code></td><td>Do not run <code>npx cap init</code> again</td></tr>
<tr>
<td>❌ <code>android platform has not been added</code></td><td>Android not linked</td><td>Run <code>npx cap add android</code></td></tr>
<tr>
<td>❌ <code>Asset directory not found</code></td><td>Missing icon.png</td><td>See section below</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-9-add-custom-app-icon-and-splash-screen">9. Add Custom App Icon and Splash Screen</h2>
<p>Install Capacitor Assets tool:</p>
<pre><code class="lang-javascript">npm install @capacitor/assets --save-dev
</code></pre>
<p>Create an <code>assets/</code> folder in your root:</p>
<pre><code class="lang-javascript">/portfolio/
 ├─ android/
 ├─ assets/
 │   ├─ icon.png
 │   └─ splash.png (optional)
</code></pre>
<p>Generate assets:</p>
<pre><code class="lang-javascript">npx capacitor-assets generate --android --iconBackgroundColor <span class="hljs-string">"#FFFFFF"</span>
</code></pre>
<p>Sync changes:</p>
<pre><code class="lang-javascript">npx cap sync android
</code></pre>
<p>This replaces the default Capacitor icon with your custom one.</p>
<hr />
<h2 id="heading-10-open-in-android-studio">10. Open in Android Studio</h2>
<pre><code class="lang-javascript">npx cap open android
</code></pre>
<p>Android Studio will open your native project.</p>
<p>If you see build errors:</p>
<ul>
<li><p>Click <strong>File → Sync Project with Gradle Files</strong></p>
</li>
<li><p>Click <strong>Build → Clean Project</strong></p>
</li>
<li><p>Then <strong>Build → Rebuild Project</strong></p>
</li>
</ul>
<hr />
<h2 id="heading-11-build-the-android-app">11. Build the Android App</h2>
<h3 id="heading-option-1-debug-apk">Option 1: Debug APK</h3>
<p>Quick test version:</p>
<pre><code class="lang-javascript">Build → Build Bundle(s)/APK(s) → Build APK(s)
</code></pre>
<p>Output:</p>
<pre><code class="lang-javascript">android/app/build/outputs/apk/debug/app-debug.apk
</code></pre>
<h3 id="heading-option-2-release-aab-for-play-store">Option 2: Release AAB (for Play Store)</h3>
<pre><code class="lang-javascript">Build → Generate Signed App Bundle / APK
</code></pre>
<p>Follow the wizard:</p>
<ol>
<li><p>Create or select your keystore</p>
</li>
<li><p>Enter passwords</p>
</li>
<li><p>Choose <strong>Android App Bundle (.aab)</strong></p>
</li>
<li><p>Click <strong>Finish</strong></p>
</li>
</ol>
<p>Output:</p>
<pre><code class="lang-javascript">android/app/build/outputs/bundle/release/app-release.aab
</code></pre>
<hr />
<h2 id="heading-12-publish-your-app">12. Publish Your App</h2>
<h3 id="heading-option-1-google-play-store">🅰️ <strong>Option 1 — Google Play Store</strong></h3>
<ol>
<li><p>Go to Play Console</p>
</li>
<li><p>Pay a one-time $25 fee</p>
</li>
<li><p>Create a new app listing</p>
</li>
<li><p>Upload your <code>.aab</code> file</p>
</li>
<li><p>Fill out:</p>
<ul>
<li><p>Description</p>
</li>
<li><p>Screenshots</p>
</li>
<li><p>Privacy Policy</p>
</li>
</ul>
</li>
<li><p>Submit for review<br /> ✅ Google will publish after 1–3 days.</p>
</li>
</ol>
<hr />
<h3 id="heading-option-2-publish-on-your-website">🅱️ <strong>Option 2 — Publish on Your Website</strong></h3>
<p>If you want users to download directly:</p>
<ol>
<li><p>Build signed APK:</p>
<pre><code class="lang-javascript"> Build → Build APK(s)
</code></pre>
</li>
<li><p>Find the file:</p>
<pre><code class="lang-javascript"> android/app/build/outputs/apk/release/app-release.apk
</code></pre>
</li>
<li><p>Rename it (e.g. <code>portfolio-app.apk</code>)</p>
</li>
<li><p>Upload to your website:</p>
<pre><code class="lang-javascript"> /downloads/portfolio-app.apk
</code></pre>
</li>
<li><p>Add a download button:</p>
<pre><code class="lang-javascript"> &lt;a href=<span class="hljs-string">"/downloads/portfolio-app.apk"</span> download&gt;
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Download Android App<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
 &lt;/a&gt;
</code></pre>
</li>
<li><p>Optional: Add instructions for users to enable <em>Install from Unknown Sources</em>.</p>
</li>
</ol>
<hr />
<h3 id="heading-option-3-as-a-web-app-pwa">🅾️ <strong>Option 3 — As a Web App (PWA)</strong></h3>
<p>If you want to host it on your domain:</p>
<ol>
<li><p>Add PWA support:</p>
<pre><code class="lang-javascript"> npm install next-pwa
</code></pre>
</li>
<li><p>Update <code>next.config.mjs</code>:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> withPWA <span class="hljs-keyword">from</span> <span class="hljs-string">'next-pwa'</span>;

 <span class="hljs-keyword">const</span> nextConfig = withPWA({
   <span class="hljs-attr">dest</span>: <span class="hljs-string">'public'</span>,
   <span class="hljs-attr">register</span>: <span class="hljs-literal">true</span>,
   <span class="hljs-attr">skipWaiting</span>: <span class="hljs-literal">true</span>,
   <span class="hljs-attr">output</span>: <span class="hljs-string">'export'</span>,
 });

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> nextConfig;
</code></pre>
</li>
<li><p>Add a <code>public/manifest.json</code>:</p>
<pre><code class="lang-javascript"> {
   <span class="hljs-string">"name"</span>: <span class="hljs-string">"Portfolio"</span>,
   <span class="hljs-string">"short_name"</span>: <span class="hljs-string">"Portfolio"</span>,
   <span class="hljs-string">"start_url"</span>: <span class="hljs-string">"/"</span>,
   <span class="hljs-string">"display"</span>: <span class="hljs-string">"standalone"</span>,
   <span class="hljs-string">"background_color"</span>: <span class="hljs-string">"#ffffff"</span>,
   <span class="hljs-string">"theme_color"</span>: <span class="hljs-string">"#000000"</span>,
   <span class="hljs-string">"icons"</span>: [
     {
       <span class="hljs-string">"src"</span>: <span class="hljs-string">"/icon.png"</span>,
       <span class="hljs-string">"sizes"</span>: <span class="hljs-string">"512x512"</span>,
       <span class="hljs-string">"type"</span>: <span class="hljs-string">"image/png"</span>
     }
   ]
 }
</code></pre>
</li>
<li><p>Deploy to:</p>
<ul>
<li><p><strong>Vercel</strong></p>
</li>
<li><p><strong>Netlify</strong></p>
</li>
<li><p><strong>Firebase Hosting</strong></p>
</li>
<li><p>or your own domain</p>
</li>
</ul>
</li>
</ol>
<p>✅ Your site will become <em>installable</em> on Android and desktop browsers.</p>
<hr />
<h2 id="heading-13-pro-tips">13. Pro Tips</h2>
<ul>
<li><p>Always rebuild after editing anything in Next.js before syncing:</p>
<pre><code class="lang-javascript">  npm run build
  npx cap sync
</code></pre>
</li>
<li><p>Keep a backup of your keystore file (it’s required for updates).</p>
</li>
<li><p>Use <code>adb install app-debug.apk</code> to quickly test on your phone.</p>
</li>
<li><p>Use <code>npx cap open android</code> whenever you edit web assets.</p>
</li>
</ul>
<hr />
<hr />
]]></content:encoded></item></channel></rss>