<?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[caffeine first]]></title><description><![CDATA[caffeine first]]></description><link>https://jacked.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 17 Apr 2026 01:46:48 GMT</lastBuildDate><atom:link href="https://jacked.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[5 Clean Code Habits for Writing Better Functions]]></title><description><![CDATA[In this blog post I'll go through five functional patterns help you write code that doesn't make your coworkers want to pull their hair out.
1. Verbs over Nouns
Have you ever opened a file and seen a ]]></description><link>https://jacked.dev/5-clean-code-habits-for-writing-better-functions</link><guid isPermaLink="true">https://jacked.dev/5-clean-code-habits-for-writing-better-functions</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Fri, 27 Feb 2026 19:04:21 GMT</pubDate><content:encoded><![CDATA[<p>In this blog post I'll go through five functional patterns help you write code that doesn't make your coworkers want to pull their hair out.</p>
<h3><strong>1. Verbs over Nouns</strong></h3>
<p>Have you ever opened a file and seen a function simply named <code>Product()</code>? As a reader, I have no idea what this does. Is it creating a product in the database? Is it fetching it? Updating it? Functions do things. So, their names should always start with a verb. <code>fetchProduct()</code> or <code>createProduct()</code>.</p>
<h3>2. The Parameter Position Trap</h3>
<p>We’ve all written a function signature that looks like this: <code>createProduct(title, description, price, quantity, category, image),</code> When you have more than three parameters, you are playing a dangerous game with the person calling the function. They have to remember the exact order. If someone accidentally swaps the <code>category</code> and <code>image</code> arguments, the compiler might not catch it, and your database will silently save corrupted data.</p>
<p>A solutions to this can be - limit parameters to 2 or 3. If you need more, wrap them in an object.</p>
<pre><code class="language-typescript">
createProduct({ title, description, price, quantity, category, image });
</code></pre>
<h3>3. Fail Fast, Return Early</h3>
<p>When writing validation logic, our default instinct is to nest <code>if-else</code> blocks.</p>
<pre><code class="language-typescript">if (user.age &gt;= 18) {
   if (!userExists) {
       
   }
}
</code></pre>
<p>becomes incredibly hard to figure out which closing bracket <code>}</code> belongs to which condition. To fix this we can just Invert our conditions and return as early as possible.</p>
<pre><code class="language-typescript">if (user.age &lt; 18) return;
if (userExists) return;
</code></pre>
<h3>4. Kill the Raw Boolean Flags</h3>
<p>Imagine reviewing a pull request and seeing this line of code: <code>registerUser(userData, true)</code> What does <code>true</code> mean here? You have to stop reading, go find the <code>registerUser</code> function definition, read it, and come back. It completely breaks your reading flow.</p>
<pre><code class="language-typescript">const SHOULD_RETURN_TOKEN = true;
registerUser(userData, SHOULD_RETURN_TOKEN);
</code></pre>
<p>With that one small change, the code documents itself.</p>
<h3>5. Keep a Single Level of Abstraction</h3>
<p>This is a classic issue in Express.js or Next.js controllers. You open an API route, and inside one massive function, the code parses the HTTP request, validates the email, hashes the password, writes to the SQL database, and sends an HTTP 200 response.</p>
<p>A function should only do one thing. Don't mix high-level logic (HTTP responses) with low-level logic (database queries).</p>
<ul>
<li><p>Extract validation into a <code>validateUser()</code> function.</p>
</li>
<li><p>Extract database logic into a <code>UserService.createUser()</code> function.</p>
</li>
</ul>
<p>Your main controller shouldn't do the heavy lifting; it should just act like a traffic cop orchestrating these smaller, predictable functions.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Objects in JavaScript]]></title><description><![CDATA[I’ve been diving deep into JavaScript lately, and the best way to make sure I actually understand something is to write it down and explain it.
What Exactly is an Object?
The easiest way to think abou]]></description><link>https://jacked.dev/understanding-objects-in-javascript</link><guid isPermaLink="true">https://jacked.dev/understanding-objects-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Thu, 26 Feb 2026 18:46:05 GMT</pubDate><content:encoded><![CDATA[<p>I’ve been diving deep into JavaScript lately, and the best way to make sure I actually understand something is to write it down and explain it.</p>
<h3>What Exactly is an Object?</h3>
<p>The easiest way to think about an object is like a dictionary or the contacts app on your phone.</p>
<p>In a dictionary, you look up a word (the key), and it gives you the definition (the value). A JavaScript object is just a collection of these key value pairs. The key is the label, and the value is the data.</p>
<h3>Creating an Object</h3>
<pre><code class="language-typescript">const person = {
  name: "Raj",
  age: 28,
  city: "Jaipur"
};
</code></pre>
<h3>How to Access the Data</h3>
<p>Once your data is inside an object, you need to know how to get it out. I learned there are two ways to do this.</p>
<h4>1. Dot Notation</h4>
<pre><code class="language-typescript">console.log(person.name); 
console.log(person.city);
</code></pre>
<p><strong>2. Bracket Notation</strong></p>
<pre><code class="language-typescript">console.log(person["name"]); 
</code></pre>
<pre><code class="language-typescript">const whatIWantToKnow = "age";

console.log(person.whatIWantToKnow); // Output: undefined

console.log(person[whatIWantToKnow]); // Output: 28
</code></pre>
<h3>Changing the Data</h3>
<p>Modifying an object is pretty straightforward.</p>
<ol>
<li>**Updating a Property -**Just grab the property and give it a new value.</li>
</ol>
<pre><code class="language-typescript">person.age = 29; 
</code></pre>
<ol>
<li><strong>Adding a Property -</strong> You don't need to change the original object. Just pretend the new key already exists and assign something to it.</li>
</ol>
<pre><code class="language-typescript">person.job = "Developer";
</code></pre>
<ol>
<li><strong>Deleting a Property -</strong> If you need to completely remove something, use the <code>delete</code> keyword.</li>
</ol>
<pre><code class="language-typescript">delete person.city;
</code></pre>
<h3>Looping Through an Object</h3>
<p>what if you want to print out everything inside the object? Because objects don't have numbered indexes like arrays do, a normal for loop doesn't work.</p>
<pre><code class="language-typescript">const person = {
  name: "Raj",
  age: 28,
  city: "Jaipur"
};

for (let key in person) {
  // Notice I have to use bracket notation here because 'key' is a variable!
  console.log(`\({key} : \){person[key]}`);
}

/* Console Output:
name: Raj
age: 28
city: Jaipur
*/
</code></pre>
<p>That’s it for the basics, switching my mindset from putting everything in an array to using an object to label my data has made my code so much easier to read.</p>
]]></content:encoded></item><item><title><![CDATA[Control Flow in JavaScript: If, Else, and Switch]]></title><description><![CDATA[1. The if Statement
The if statement is the simplest way to make a decision in code. It basically says, "Check if this condition is true. If it is, run the code inside the block."
let age = 20;

if (a]]></description><link>https://jacked.dev/control-flow-in-javascript-if-else-and-switch</link><guid isPermaLink="true">https://jacked.dev/control-flow-in-javascript-if-else-and-switch</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Wed, 25 Feb 2026 18:45:15 GMT</pubDate><content:encoded><![CDATA[<h3>1. The if Statement</h3>
<p>The <code>if</code> statement is the simplest way to make a decision in code. It basically says, "Check if this condition is true. If it is, run the code inside the block."</p>
<pre><code class="language-typescript">let age = 20;

if (age &gt;= 18) {
  console.log("Welcome in!");
}
</code></pre>
<ol>
<li><p>It sees the variable <code>age</code> is set to 20.</p>
</li>
<li><p>It looks at the condition <code>(age &gt;= 18)</code>.</p>
</li>
<li><p>Because 20 is indeed greater than 18, the condition is "true".</p>
</li>
<li><p>Since it's true, it goes inside the curly braces <code>{}</code> and prints "Welcome in!".</p>
</li>
</ol>
<h3>2. The if-else Statement</h3>
<p>The <code>if</code> statement is great, but what if the condition is false and you still want something to happen? That’s where <code>else</code> comes in. It acts as a backup plan.</p>
<pre><code class="language-typescript">let marks = 35;

if (marks &gt;= 40) {
  console.log("You passed!");
} else {
  console.log("You failed. Better luck next time.");
}
</code></pre>
<p><strong>How this runs:</strong></p>
<ol>
<li><p>The marks variable is 35.</p>
</li>
<li><p>The computer checks <code>(marks &gt;= 40)</code>.</p>
</li>
<li><p>Because it's false, it skips the first block of code completely.</p>
</li>
<li><p>It sees the <code>else</code> block and automatically runs it, printing "You failed. Better luck next time."</p>
</li>
</ol>
<h3>3. The else if</h3>
<p>Sometimes a simple "yes or no" isn't enough. You might have multiple conditions to check. You can string these together using <code>else if</code>.</p>
<pre><code class="language-typescript">let score = 85;

if (score &gt;= 90) {
  console.log("Grade: A");
} else if (score &gt;= 80) {
  console.log("Grade: B");
} else if (score &gt;= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}
</code></pre>
<h3>4. The switch Statement</h3>
<p>If you have a lot of specific values to check, writing a massive <code>else if</code> ladder gets really messy and hard to read.</p>
<pre><code class="language-typescript">let trafficLight = "yellow";

switch (trafficLight) {
  case "green":
    console.log("Go!");
    break;
  case "yellow":
    console.log("Slow down!");
    break;
  case "red":
    console.log("Stop!");
    break;
  default:
    console.log("Invalid light color.");
}
</code></pre>
<h4>Why do we need break?</h4>
<p>I feel this is the biggest trap for beginners. If the computer finds a match, it will run that code. But if you don't include the word break, the code will "fall through" and automatically run the "red" and "default" console logs too, even though they don't match!</p>
<h3>When to use which?</h3>
<ul>
<li><p>Use if-else when <strong>-</strong> You are checking for ranges (like <code>age &gt; 18</code>) or comparing different variables. It's your most flexible, everyday tool.</p>
</li>
<li><p>Use switch when <strong>-</strong> You have one specific variable and you are checking it against a bunch of exact, fixed values. It keeps your code much easier to read.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Production-Grade Logging in Node.js with Winston]]></title><description><![CDATA[When you're building a side project, console.log is perfectly fine. But the moment you deploy a distributed system, where you have multiple instances of an app running behind a load balancer console.l]]></description><link>https://jacked.dev/production-grade-logging-in-node-js-with-winston</link><guid isPermaLink="true">https://jacked.dev/production-grade-logging-in-node-js-with-winston</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Backend Development]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Tue, 24 Feb 2026 19:33:22 GMT</pubDate><content:encoded><![CDATA[<p>When you're building a side project, <code>console.log</code> is perfectly fine. But the moment you deploy a distributed system, where you have multiple instances of an app running behind a load balancer <code>console.log</code> becomes an absolute liability.</p>
<p>In production, logs are not text files for humans to read. They are structured telemetry data meant to be indexed, searched, and aggregated by machines. I was re-exploring Winston today, and I want to break down how to actually set this up for a real-world Node.js environment.</p>
<h3>The Architecture of Winston</h3>
<p>Winston has survived this long in the Node ecosystem because it fundamentally gets the abstraction right. It separates what you are logging from where it is going. It does this using three concepts:</p>
<ol>
<li><p><strong>Levels -</strong> The severity of the log (e.g., <code>error</code>, <code>info</code>, <code>debug</code>).</p>
</li>
<li><p><strong>Formats -</strong> The shape of the log (e.g., raw text vs. structured JSON).</p>
</li>
<li><p><strong>Transports -</strong> The destination of the log (e.g., the console, a file, or an external API).</p>
</li>
</ol>
<p>By decoupling these, you can say, "Send all info logs to the console as text, but send all error logs to an external service as JSON."</p>
<h3>1. Setting Up the Baseline</h3>
<p>First, install the package: <code>npm install winston</code>.</p>
<p>When setting up your logger, the non-negotiable rule for production is <strong>JSON formatting</strong>. If your logs are JSON.</p>
<pre><code class="language-typescript">const winston = require('winston');
const { combine, timestamp, json, errors } = winston.format;

const logger = winston.createLogger({
  level: 'info', 
  format: combine(
    errors({ stack: true }), 
    timestamp(),             
    json()                   
  ),
 
  defaultMeta: { service: 'payment-service', env: process.env.NODE_ENV }, 
  transports: [
    
    new winston.transports.Console() 
  ]
});
</code></pre>
<p>By default, if you pass a JS <code>Error</code> object to a logger, it often just prints the message ("Database connection failed"). In an outage, you need the stack trace to find the exact file and line number. This format rule ensures the stack trace is preserved in the JSON output.</p>
<h3>2. The Real Power: Context via Child Loggers</h3>
<p>A log that says <code>logger.info("Fetching user cart")</code> is useless if you have 1,000 requests per second. Which user? Which request?</p>
<p>You need context. But passing <code>userId</code> and <code>requestId</code> to every single <code>logger.info()</code> call throughout your codebase is messy and prone to errors. Instead, you use Child Loggers.</p>
<pre><code class="language-typescript">
app.use((req, res, next) =&gt; {
  req.logger = logger.child({
    requestId: req.headers['x-request-id'] || generateId(),
    userId: req.user?.id || 'anonymous'
  });
  
  next();
});


function processPayment(req) {
  req.logger.info("Starting payment processing"); 
  
}
</code></pre>
<h3>3. Quick Profiling</h3>
<p>If you don't have a heavy Application Performance Monitoring (APM) tool set up yet, you can measure how long bottlenecks take directly through your logs.</p>
<pre><code class="language-typescript">const profiler = req.logger.startTimer();


await database.query('...');

profiler.done({ message: 'Database query executed', queryName: 'fetch_user_cart' });
</code></pre>
<p>Because your logs are in JSON, this outputs a key like <code>"durationMs": 342</code>. You can then go to your logging platform and write a query like <code>durationMs &gt; 500</code> to instantly find all slow database queries.</p>
<h3>4. Shipping Logs Off-Server</h3>
<p>If your application is running in a container, the local filesystem is ephemeral. If the app crashes and the container restarts, any <code>.log</code> files stored locally are permanently deleted—along with the exact error logs you need to figure out why it crashed.</p>
<pre><code class="language-typescript">const { Logtail } = require("@logtail/node");
const { LogtailTransport } = require("@logtail/winston");

const logtail = new Logtail(process.env.LOGTAIL_TOKEN);

logger.add(new LogtailTransport(logtail));
</code></pre>
<p>The logger just starts quietly streaming the data over the network in the background.</p>
]]></content:encoded></item><item><title><![CDATA[Building a Validation Layer with Zod]]></title><description><![CDATA[While building any backend API, you can never fully trust the data coming in from a client, a third-party webhook, or even a frontend application you wrote yourself. Every robust API needs a strict va]]></description><link>https://jacked.dev/building-a-validation-layer-with-zod</link><guid isPermaLink="true">https://jacked.dev/building-a-validation-layer-with-zod</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Backend Development]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Mon, 23 Feb 2026 19:36:59 GMT</pubDate><content:encoded><![CDATA[<p>While building any backend API, you can never fully trust the data coming in from a client, a third-party webhook, or even a frontend application you wrote yourself. Every robust API needs a strict validation layer to act as a bouncer, ensuring that incoming payloads match the exact shape your business logic expects. Even if we are writing typescript, we are not fully covered, coz, of course, typescript does not exist on runtime. When your Node server is running, it is executing plain JavaScript. All those interfaces and types are stripped away during the build step.</p>
<p>Historically, solving this meant writing massive, ugly manual validation blocks full of <code>if</code> statements to check <code>typeof</code> for every single field. This clutters your business logic and This is where Zod comes in.</p>
<h2>Zod: Your Single Source of Truth</h2>
<p><strong>Zod</strong> is a TypeScript-first schema declaration and validation library. It acts as the missing bridge between your runtime data and your compile time types. Instead of writing a TypeScript interface and a separate validation function, you define a Zod schema once.</p>
<pre><code class="language-typescript">import { z } from 'zod';


const userSchema = z.object({
  name: z.string().min(2, "Name is too short").max(50),
  email: z.string().email("Invalid email"),
  age: z.number().int().positive(),
  preferences: z.object({
    theme: z.enum(["light", "dark"]).default("light")
  }).optional()
});


type UserPayload = z.infer&lt;typeof userSchema&gt;;
</code></pre>
<h2>Implementing Zod in Express</h2>
<p>When raw JSON hits your Express server, you need to pass it through this schema. Zod gives you two primary ways to do this:</p>
<ol>
<li><p><code>.parse(data)</code>: Checks the data and throws an exception if it’s invalid.</p>
</li>
<li><p><code>.safeParse(data)</code>: Checks the data and <em>returns an object</em> telling you if it worked or failed, without throwing errors.</p>
</li>
</ol>
<p>Here is the pattern I highly recommend, a simple, reusable Express middleware that validates the body before it ever reaches your route handler -</p>
<pre><code class="language-typescript">import { Request, Response, NextFunction } from 'express';
import { AnyZodObject } from 'zod';

const validateBody = (schema: AnyZodObject) =&gt; {
  return (req: Request, res: Response, next: NextFunction) =&gt; {
    const result = schema.safeParse(req.body);
    
    if (!result.success) {
      
      return res.status(400).json({
        error: "Validation failed",
        details: result.error.errors.map(err =&gt; ({
          field: err.path.join('.'),
          message: err.message
        }))
      });
    }

    
    req.body = result.data;
    next();
  };
};
</code></pre>
<p>Now, the actual route handler becomes incredibly clean.</p>
<pre><code class="language-typescript">app.post('/users', validateBody(userSchema), (req, res) =&gt; {
  
  const userData = req.body; 
  res.status(201).json({ success: true });
});
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Javascript arrays 101]]></title><description><![CDATA[Imagine you are going grocery shopping. Instead of writing a separate sticky note for every single item you need to buy, one for apples, one for milk, one for bread, you write them all down on a singl]]></description><link>https://jacked.dev/javascript-arrays-101</link><guid isPermaLink="true">https://jacked.dev/javascript-arrays-101</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Sun, 22 Feb 2026 18:33:37 GMT</pubDate><content:encoded><![CDATA[<p>Imagine you are going grocery shopping. Instead of writing a separate sticky note for every single item you need to buy, one for apples, one for milk, one for bread, you write them all down on a single shopping list. arrays are that shopping list. They are a special type of variable that allows you to store a collection of values in a specific order, all under a single name.</p>
<h3>Why Do We Need Arrays?</h3>
<p>Imagine you are building a simple app to track your top three favorite fruits. Without arrays, you would have to store each fruit in its own separate variable.</p>
<pre><code class="language-javascript">let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";

// with array
let fruitArray = ["apple", "banana", "mango"]
</code></pre>
<h3>How to Create an Array</h3>
<p>Creating an array in JavaScript is incredibly straightforward. You use square brackets <code>[]</code> and separate your items with commas.</p>
<pre><code class="language-javascript">//  array of strings
let tasks = ["Wake up", "Drink water", "Learn JavaScript"];

// array of numbers
let testScores = [85, 92, 78, 99];
</code></pre>
<h3>Accessing Elements Using the Index</h3>
<p>How do you get a specific item out of your array? You use its index. The most important rule to remember about arrays is that counting starts at 0, not 1. This is known as zero-based indexing.</p>
<p>If we look at our <code>fruits</code> array:</p>
<ul>
<li><p><code>"Apple"</code> is at index 0</p>
</li>
<li><p><code>"Banana"</code> is at index 1</p>
</li>
<li><p><code>"Mango"</code> is at index 2</p>
</li>
</ul>
<pre><code class="language-javascript">let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); 
console.log(fruits[2]); 
</code></pre>
<h3>Updating Elements</h3>
<p>Arrays are flexible. You can easily change the value of an element after the array has been created by selecting its index and assigning a new value. Let's say we want to replace "Banana" with "Orange"</p>
<pre><code class="language-javascript">let fruits = ["Apple", "Banana", "Mango"];


fruits[1] = "Orange";

console.log(fruits); 
</code></pre>
<h3>Basic Looping Over Arrays</h3>
<p>If you want to print every item in your array, we can use a basic for loop to loop over the array.</p>
<pre><code class="language-javascript">let fruits = ["Apple", "Orange", "Mango"];

for (let i = 0; i &lt; fruits.length; i++) {
  console.log("I love eating " + fruits[i]);
}

/* Output:
I love eating Apple
I love eating Orange
I love eating Mango
*/
</code></pre>
<p><strong>Lets dry run it once -</strong></p>
<ol>
<li><p><code>let i = 0</code>: We start our counter (<code>i</code>) at 0, which perfectly matches our array's first index.</p>
</li>
<li><p><code>i &lt; fruits.length</code>: The loop keeps running as long as <code>i</code> is less than the total number of items (3).</p>
</li>
<li><p><code>i++</code>: After each loop, <code>i</code> increases by 1, allowing us to move to the next item in the array.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Call, Bind and Apply in Javascript]]></title><description><![CDATA[If you write JavaScript, you've fought this. The confusion happens because we bring mental models from languages like Java or C++, where this is tied to the class it was written in. JavaScript doesn’t]]></description><link>https://jacked.dev/call-bind-and-apply-in-javascript</link><guid isPermaLink="true">https://jacked.dev/call-bind-and-apply-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Sat, 21 Feb 2026 19:28:04 GMT</pubDate><content:encoded><![CDATA[<p>If you write JavaScript, you've fought <code>this</code>. The confusion happens because we bring mental models from languages like Java or C++, where <code>this</code> is tied to the class it was written in. JavaScript doesn’t care where you <em>wrote</em> the function. It only cares about who called the function at runtime. A mental model I can think of is, look at the left of the dot. Lets look at an example.</p>
<pre><code class="language-javascript">const service = {
  name: "Payment Gateway",
  start: function() {
    console.log(`Starting ${this.name}`);
  }
};

service.start(); 
</code></pre>
<p>Look at <code>service.start()</code>. Who is on the left of the dot? <code>service</code>. So, <code>this = service</code>.</p>
<pre><code class="language-javascript">const startService = service.start;
startService(); 
</code></pre>
<p>Look at <code>startService()</code>. There is nothing to the left of the dot. It’s just a raw function call. The context is lost, <code>this</code> defaults to undefined, and your app crashes. To fix this, JavaScript gives us three methods on the <code>Function.prototype</code> to manually force the <code>this</code> context <code>call</code>, <code>apply</code>, and <code>bind</code>.</p>
<h2>1. CALL</h2>
<p><code>call</code> immediately fires the function, forcing <code>this</code> to be the first argument you pass. Any remaining arguments are passed individually.</p>
<pre><code class="language-javascript">function logError(level, message) {
  console.log(`[\({this.service}] \){level}: ${message}`);
}

const context = { service: "Auth" };
logError.call(context, "CRITICAL", "connection lost"); 
</code></pre>
<h2>2. APPLY</h2>
<p><code>apply</code> is exactly the same as <code>call</code>, but it takes the function's arguments as a single array.</p>
<pre><code class="language-javascript">logError.apply(context, ["CRITICAL", "connection lost"]);
</code></pre>
<h2>3. BIND</h2>
<p><code>bind</code> doesn't execute the function immediately. Instead, it returns a new function with <code>this</code> permanently locked to the object you provided. This is how you fix the callback problem.</p>
<pre><code class="language-javascript">
const safeStart = service.start.bind(service);

setTimeout(safeStart, 1000); 
</code></pre>
<h3>writing the polyfills</h3>
<p>To truly understand a system, you build it yourself. If we were to write these methods from scratch, how would the engine actually do it?</p>
<h3>The call Polyfill</h3>
<p>trick is simple, temporarily attach the function to the target object as a property. Then call it. By doing this, the object is literally to the left of the dot.</p>
<pre><code class="language-javascript">Function.prototype.myCall = function(context = globalThis, ...args) {
  
  const fnKey = Symbol('fn');
  
  
  context[fnKey] = this;
  
  const result = context[fnKey](...args);
 
  delete context[fnKey];
  return result;
};
</code></pre>
<p><strong>The apply Polyfill</strong></p>
<p>Almost identical to <code>call</code>, but we spread an array.</p>
<pre><code class="language-javascript">Function.prototype.myApply = function(context = globalThis, argsArray = []) {
  const fnKey = Symbol('fn');
  context[fnKey] = this;
  
  const result = context[fnKey](...argsArray);
  
  delete context[fnKey];
  return result;
};
</code></pre>
<p><strong>The bind Polyfill</strong></p>
<p><code>bind</code> needs to return a closure. When that closure is eventually called, it uses <code>apply</code> internally to execute the original function with the locked context.</p>
<pre><code class="language-javascript">Function.prototype.myBind = function(context = globalThis, ...boundArgs) {
  const originalFn = this;
  
  return function(...executionArgs) {
    return originalFn.apply(context, [...boundArgs, ...executionArgs]);
  };
};
</code></pre>
<p>Mastering execution context moves you from randomly guessing why a callback broke, to deliberately architecting how your data flows through asynchronous boundaries.</p>
]]></content:encoded></item><item><title><![CDATA[What actually is the DOM?]]></title><description><![CDATA[I had a fundamental misunderstanding of how webpages worked. I used to think that when I wrote JavaScript to change a button's colour, my code was somehow reaching into my index.html file and rewritin]]></description><link>https://jacked.dev/what-actually-is-the-dom</link><guid isPermaLink="true">https://jacked.dev/what-actually-is-the-dom</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[DOM]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Fri, 20 Feb 2026 19:11:27 GMT</pubDate><content:encoded><![CDATA[<p>I had a fundamental misunderstanding of how webpages worked. I used to think that when I wrote JavaScript to change a button's colour, my code was somehow reaching into my index.html file and rewriting the text. (yes, really). Obviously, that’s not what happens. Once your server sends the HTML file over the network to the user's browser, that file is done.</p>
<p>If you’ve done any backend work, you know what happens when an API receives a JSON payload. It comes over the wire as a raw string. You can’t easily loop through a string to find a specific user ID. You convert that string into a native object loaded into the server's memory. The DOM is the exact same concept, just for the browser. The browser downloads your raw HTML string, parses it, and creates a massive, living data structure in its memory.</p>
<h2>Why a Tree?</h2>
<p>HTML is inherently nested. An <code>&lt;html&gt;</code> tag contains a <code>&lt;body&gt;</code>, which contains a <code>&lt;div&gt;</code>, which contains a <code>&lt;p&gt;</code>. The browser models this exact hierarchy using a Tree data structure. Every single HTML tag becomes a "node" in this tree. This tree is the DOM. It is a representation of your document, built out of objects, modelled as a tree.</p>
<p>The DOM is actually a Web API provided by the browser. In Chrome, the DOM is implemented in C++ under the hood. Browser give you a global object called <code>document</code><em>.</em> If you call methods on <code>document</code>, Browser lets you read or update the C++ tree.</p>
<pre><code class="language-javascript">const button = document.querySelector('.submit-btn');
button.style.backgroundColor = 'red';
</code></pre>
<p>You are writing JavaScript, but you are interacting with the browser's DOM API to change the state of a node in its memory tree.</p>
<h2>Why is the DOM slow?</h2>
<p>If you've been around frontend tooling for a while, you've probably heard the phrase, "The DOM is slow. That's why we need React and the Virtual DOM." That phrase is actually a half-truth. Updating a node in the DOM is incredibly fast. Remember, it's just updating an object in memory. If you change a button's color in the DOM, that memory update takes less than a fraction of a millisecond.</p>
<p><strong>The DOM isn't slow. Rendering is slow.</strong></p>
<p>When you change something in the DOM tree, the browser engine realizes the tree has mutated. It now has to figure out what that change means for the pixels on the screen.</p>
<ol>
<li><p>It has to recalculate the CSS.</p>
</li>
<li><p>It has to figure out the geometry of the page changing this text make the button wider? Did that push the image below it down? (This is called a <strong>Reflow</strong> or Layout).</p>
</li>
<li><p>Finally, it has to physically draw the new pixels on the screen (This is called a <strong>Repaint</strong>.</p>
</li>
</ol>
<p>Reflows and repaints are mathematically expensive. If you have a list of 1,000 items and you write a JavaScript for loop that updates them one by one, you trigger that expensive render pipeline 1,000 times in a row. The browser will freeze.</p>
<p>ools like React introduced the Virtual DOM to solve this. They do all the heavy calculations in a lightweight JavaScript copy of the tree, figure out the absolute bare minimum number of changes needed, and then update the real DOM in one big batch. They optimize the <em>writes</em> to avoid triggering the browser's slow render pipeline too many times.</p>
<h3>Wrapping up</h3>
<p>Whenever you are building for the web, keep the system architecture in your head -</p>
<ul>
<li><p><strong>HTML:</strong> The raw string payload sent over the wire.</p>
</li>
<li><p><strong>The DOM:</strong> The tree of objects the browser builds in memory from that string.</p>
</li>
<li><p><strong>JavaScript:</strong> The language we use to tell the browser how to update that tree.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Mastering Event-Driven Architecture in Node.js]]></title><description><![CDATA[Today, we are diving deep into a concept that will fundamentally change how you structure your Node.js and Express backends. Let's break down what EDA is, why you need it, and how to implement it nati]]></description><link>https://jacked.dev/mastering-event-driven-architecture-in-node-js</link><guid isPermaLink="true">https://jacked.dev/mastering-event-driven-architecture-in-node-js</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Backend Development]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Thu, 19 Feb 2026 19:19:38 GMT</pubDate><content:encoded><![CDATA[<p>Today, we are diving deep into a concept that will fundamentally change how you structure your Node.js and Express backends. Let's break down what EDA is, why you need it, and how to implement it natively in Node.js.</p>
<h2>The Problem: The Coupling Trap</h2>
<p>we first need to understand the problem. Let's use a classic e-commerce application as an example. Imagine a user places an order. The request hits our Express controller, which then calls an OrderService to handle the business logic. Inside the createOrder method, we don't just save the order to the database. We usually have a laundry list of side effects:</p>
<ol>
<li><p>Send an order confirmation email to the user.</p>
</li>
<li><p>Update the inventory stock.</p>
</li>
</ol>
<p>In a naive approach, our <code>OrderService</code> would import an <code>EmailService</code> and an <code>InventoryService</code>, calling their methods directly . Why is this bad? This introduces tight coupling . The <code>OrderService</code> is now fully dependent on the email and inventory modules. If the email service throws an error, it might crash the entire order creation process. This makes the code harder to maintain.</p>
<h2>The Solution - Event-Driven Architecture</h2>
<p>We want to decouple these services. The <code>OrderService</code> shouldn't care how an email is sent or how the inventory is updated. It should only care about creating the order. Think of Event-Driven Architecture like a public announcement system. Instead of the <code>OrderService</code> directly telling the <code>EmailService</code> what to do, it simply grabs a megaphone and shouts to the rest of the application - Hey everyone, an Order was just Created.</p>
<h2>Implementing EDA in Node.js</h2>
<p>Most of Node.js's core API are already built around an asynchronous, event-driven architecture. For our custom business logic, Node gives us a powerful tool, the EventEmitter class from the events module.</p>
<h3>Step 1: Extend the EventEmitter</h3>
<p>First, we make our OrderService a child of the EventEmitter class. By using the <mark class="bg-yellow-200 dark:bg-yellow-500/30">extends</mark> keyword, our service inherits the superpower to broadcast events.</p>
<pre><code class="language-javascript">import { EventEmitter } from 'events';

export class OrderService extends EventEmitter {
    createOrder(orderData) {
        // 1. Logic to save order to the database goes here
        const newOrder = { id: Date.now().toString(), ...orderData };

        // 2. Broadcast the event!
        this.emit('order:created', newOrder); 

        return newOrder;
    }
}
</code></pre>
<h4>Step 2: Emitting the Event</h4>
<p>Notice the <code>this.emit('order:created', newOrder)</code> line above. We give the event a descriptive name (order:created) and pass along the relevant data payload (newOrder). Our service's job is now done.</p>
<h4>Step 3: Registering the Subscribers</h4>
<p>Now, we need to wire up the listeners that will react to this event. We do this by calling the <code>.on()</code> method on the instance of our OrderService.</p>
<pre><code class="language-javascript">
const orderService = new OrderService();
const emailService = new EmailService();
const inventoryService = new InventoryService();


orderService.on('order:created', (data) =&gt; {
    emailService.sendEmail(data);
});

orderService.on('order:created', (data) =&gt; {
    inventoryService.updateInventory(data);
});
</code></pre>
<h3>A Crucial Gotcha</h3>
<p>Here is a massive misconception that trips up a lot of developers, they often assume the <code>EventEmitter</code> acts like an asynchronous message queue. <strong>It does not.</strong> When you call <code>this.emit()</code>, Node.js will execute all the registered listeners synchronously in the exact order they were registered . If you place a <code>console.log('After emit')</code> right beneath your emit function, it will only log after the email and inventory callbacks have finished running . If you want these listeners to not block the main execution thread, you need to handle them asynchronously, using async/await inside the callback or wrapping the logic in setImmediate.</p>
<p>Event-Driven Architecture is a phenomenal pattern for separating concerns and keeping your backend codebase modular. By utilizing Node's built-in EventEmitter.</p>
<p>HAPPY CODING.</p>
]]></content:encoded></item><item><title><![CDATA[WebSockets 101: How to Build Real-Time Apps]]></title><description><![CDATA[Today, we’re going to look at WebSockets. This is the tech that makes multiplayer games, chat apps, and live stock tickers actually work. We’ll also look at Socket.io, which is basically the cheat code for making WebSockets easy to use. We’ll keep th...]]></description><link>https://jacked.dev/how-to-build-real-time-apps</link><guid isPermaLink="true">https://jacked.dev/how-to-build-real-time-apps</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[websockets]]></category><category><![CDATA[Backend Development]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Wed, 18 Feb 2026 18:59:58 GMT</pubDate><content:encoded><![CDATA[<p>Today, we’re going to look at <strong>WebSockets</strong>. This is the tech that makes multiplayer games, chat apps, and live stock tickers actually work. We’ll also look at Socket.io, which is basically the cheat code for making WebSockets easy to use. We’ll keep the jargon to a minimum.</p>
<h2 id="heading-the-problem-the-mailman-model-http">The Problem: The "Mailman" Model (HTTP)</h2>
<p>To get why WebSockets are cool, you have to understand why standard websites are kind of annoying for real-time stuff. Think of standard HTTP like sending a letter via mail -</p>
<ol>
<li><p><strong>You -</strong> Send a letter asking "Do I have new messages?" (Request)</p>
</li>
<li><p><strong>Server -</strong> Reads letter, checks database, writes back "No." (Response)</p>
</li>
<li><p><strong>End of conversation.</strong></p>
</li>
</ol>
<p>If you want to check again 5 seconds later, you have to send a whole new letter. Basically http is stateless.</p>
<p>we used to solve this by making the browser ask the server every single second: <em>"</em>Any updates? Any updates? Any updates?<em>"</em> This is called <strong>Polling</strong>. It works, but it’s exhausting for your server and eats up your user’s data.</p>
<h2 id="heading-the-solution-the-phone-call-websockets">The Solution: The "Phone Call" (WebSockets)</h2>
<p>WebSockets change the rules. Instead of mailing letters back and forth, you open a phone line<strong>.</strong></p>
<ol>
<li><p><strong>You -</strong> Dial the server.</p>
</li>
<li><p><strong>Server -</strong> Picks up.</p>
</li>
<li><p><strong>The line stays open.</strong></p>
</li>
</ol>
<p>Now, nobody has to ask for updates. If the server has a message for you, it just speaks. If you have a message, you just speak. It’s a two way, persistent connection.</p>
<h2 id="heading-lets-build-something">Let’s Build Something</h2>
<p>Enough talk. Let's write some code. We’ll use Node.js for this.</p>
<p>If you want to follow along, create a folder, open your terminal, and run -</p>
<p><code>npm init -y. npm install express</code> <a target="_blank" href="http://socket.io"><code>socket.io</code></a></p>
<h3 id="heading-1-the-backend-indexjs">1. The Backend (index.js)</h3>
<p>Standard Express apps look one way, but when you add <a target="_blank" href="http://Socket.IO">Socket.IO</a>, you have to do a little "wrapping" of the server.</p>
<pre><code class="lang-javascript"><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> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); 
<span class="hljs-keyword">const</span> { Server } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"socket.io"</span>);

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

<span class="hljs-keyword">const</span> server = http.createServer(app);
<span class="hljs-keyword">const</span> io = <span class="hljs-keyword">new</span> Server(server);

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.sendFile(__dirname + <span class="hljs-string">'/index.html'</span>);
});

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A user connected! Socket ID:'</span>, socket.id);


  socket.on(<span class="hljs-string">'chat message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> {

    io.emit(<span class="hljs-string">'chat message'</span>, msg);
  });
});

server.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">'Server running on port 3000'</span>);
});
</code></pre>
<p><strong>The important bits:</strong></p>
<ul>
<li><p><code>io.on('connection')</code>: This runs every single time a new tab opens your site.</p>
</li>
<li><p><a target="_blank" href="http://socket.id"><code>socket.id</code></a>: Every user gets a random, unique ID. This is how you tell users apart.</p>
</li>
<li><p><code>io.emit</code>: This shouts the message to everyone. If you used <code>socket.emit</code>, you'd only be whispering back to the person who sent the message.</p>
</li>
</ul>
<h3 id="heading-2-the-frontend-indexhtml">2. The Frontend (index.html)</h3>
<p>This is the HTML file the server will send to the browser.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Simple Chat<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"input"</span> <span class="hljs-attr">autocomplete</span>=<span class="hljs-string">"off"</span> /&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"sendMsg()"</span>&gt;</span>Send<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"messages"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/socket.io/socket.io.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">

      <span class="hljs-keyword">const</span> socket = io();

      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendMsg</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">const</span> input = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'input'</span>);
        <span class="hljs-keyword">if</span> (input.value) {

          socket.emit(<span class="hljs-string">'chat message'</span>, input.value);
          input.value = <span class="hljs-string">''</span>;
        }
      }


      socket.on(<span class="hljs-string">'chat message'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">msg</span>) </span>{
        <span class="hljs-keyword">const</span> item = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>);
        item.textContent = msg;
        <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'messages'</span>).appendChild(item);
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h3 id="heading-is-this-the-only-way">Is this the only way?</h3>
<p>Short answer, NO. You don't always need WebSockets. WebSockets are heavy. They keep a connection open 24/7. Sometimes, that's overkill.</p>
<p>If you want to make your app feel realtime, we have 4 popular ways</p>
<ol>
<li><p>Short polling</p>
</li>
<li><p>Long polling</p>
</li>
<li><p>SSE (server side events)</p>
</li>
<li><p>Web sockets</p>
</li>
</ol>
<p>WebSockets feel like magic, but they are just a persistent phone call between your browser and the server. Socket.io just makes sure the call doesn't drop.</p>
]]></content:encoded></item><item><title><![CDATA[the Power of Worker Threads in Node.js]]></title><description><![CDATA[A while back, Node introduced the worker_threads module. It allows parallel execution, Real multi-tasking.
How you actually code it
It’s surprisingly simple. You just need two files.
The Bottleneck
Lets understand this with a very simple and realisti...]]></description><link>https://jacked.dev/worker-threads-in-nodejs</link><guid isPermaLink="true">https://jacked.dev/worker-threads-in-nodejs</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Backend Development]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Tue, 17 Feb 2026 19:11:14 GMT</pubDate><content:encoded><![CDATA[<p>A while back, Node introduced the <code>worker_threads</code> module. It allows parallel execution, Real multi-tasking.</p>
<h3 id="heading-how-you-actually-code-it">How you actually code it</h3>
<p>It’s surprisingly simple. You just need two files.</p>
<h2 id="heading-the-bottleneck">The Bottleneck</h2>
<p>Lets understand this with a very simple and realistic example.</p>
<ul>
<li><p>Take a folder of high-res nature photos.</p>
</li>
<li><p>Resize them, blur them, and grayscale them.</p>
</li>
<li><p>Set a timer on it</p>
</li>
</ul>
<p>I already did it on my machine and here are the results. Running this on the main thread took over 11 seconds for just 10 images. For those 11 seconds, the app was dead. WHEN I tried to ping the homepage, it timed out. In the real world, that’s unacceptable.</p>
<p>Now, lets see the worker way.</p>
<h2 id="heading-1-the-manager">1. The Manager</h2>
<pre><code class="lang-javascript"><span class="hljs-comment">// index.js</span>
<span class="hljs-keyword">const</span> { Worker } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processImageInBackground</span>(<span class="hljs-params">filePath</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {

    <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'./image-worker.js'</span>, {
      <span class="hljs-attr">workerData</span>: { filePath } 
    });

    worker.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Worker said: <span class="hljs-subst">${result}</span>`</span>);
      resolve(result);
    });

    worker.on(<span class="hljs-string">'error'</span>, reject);
  });
}

processImageInBackground(<span class="hljs-string">'./huge-photo.jpg'</span>);
</code></pre>
<h2 id="heading-2-the-worker">2. The Worker</h2>
<pre><code class="lang-javascript"><span class="hljs-comment">// image-worker.js</span>
<span class="hljs-keyword">const</span> { parentPort, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
<span class="hljs-keyword">const</span> jimp = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jimp'</span>); 


<span class="hljs-keyword">const</span> { filePath } = workerData;


<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> image = <span class="hljs-keyword">await</span> jimp.read(filePath);
  <span class="hljs-keyword">await</span> image.resize(<span class="hljs-number">100</span>, <span class="hljs-number">100</span>).writeAsync(<span class="hljs-string">`processed/output.jpg`</span>);

  parentPort.postMessage(<span class="hljs-string">'Done processing!'</span>);
}

run();
</code></pre>
<h2 id="heading-the-whoa-moment">The "Whoa" Moment 🤯</h2>
<p>I took that same 11-second task and refactored it to use Worker Threads. spun up a worker for each image so they all processed at the exact same time.</p>
<p><strong>The result? just took 4 seconds.</strong></p>
<p>That is a nearly <strong>3x speed improvement</strong>. But more importantly, the main thread wasn't blocked. The server stayed responsive the entire time.</p>
<h2 id="heading-tldr">TL;DR</h2>
<p>If you’re doing heavy CPU work in Node.js, stop blocking the event loop.</p>
<ol>
<li><p>Use <code>worker_threads</code>.</p>
</li>
<li><p>Offload the heavy math/image processing to a separate file.</p>
</li>
<li><p>Use a Pool to manage them so you don't fry your server.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Production Ready Auth with Better Auth]]></title><description><![CDATA[For a long time, we had to either pay a fortune for managed services (Clerk/Auth0) or wrestle with the absolute chaos that was maintaining your own auth sessions. But it’s 2026, and the ecosystem has finally matured.
The stack I’m opting for this one...]]></description><link>https://jacked.dev/production-ready-auth-with-better-auth</link><guid isPermaLink="true">https://jacked.dev/production-ready-auth-with-better-auth</guid><category><![CDATA[backend developments]]></category><category><![CDATA[authentication]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Mon, 16 Feb 2026 18:58:51 GMT</pubDate><content:encoded><![CDATA[<p>For a long time, we had to either pay a fortune for managed services (Clerk/Auth0) or wrestle with the absolute chaos that was maintaining your own auth sessions. But it’s 2026, and the ecosystem has finally matured.</p>
<p>The stack I’m opting for this one is Next.js. In this one I’m going to walk you through how I set this up in a production Next.js 15+ app. No fluff, just the code that actually works.</p>
<h2 id="heading-the-stack">The Stack</h2>
<p>I am keeping it simple here</p>
<ul>
<li><p><strong>Next.js 15+</strong> (App Router, obviously)</p>
</li>
<li><p><strong>Better Auth</strong></p>
</li>
<li><p><strong>MongoDB</strong> (Because I don’t want to write SQL, ugh)</p>
</li>
</ul>
<h2 id="heading-phase-1-the-setup">Phase 1: The Setup</h2>
<pre><code class="lang-bash">pnpm add better-auth mongodb
</code></pre>
<h3 id="heading-the-environment-variables">The Environment Variables</h3>
<p>You know the drill. Create a <code>.env</code> file. Do not skip the <code>BETTER_AUTH_SECRET</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// .ENV</span>
MONGODB_URI=mongodb+srv:
BETTER_AUTH_SECRET=
BETTER_AUTH_URL=


GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
</code></pre>
<h2 id="heading-phase-2-the-server-side-config">Phase 2: The Server-Side Config</h2>
<p>Here is where Better Auth shines. We need to create a central Auth instance. I usually throw this in <code>src/lib/auth.ts</code>. The beauty here is the adapters. We don't need to manually write Mongoose schemas for users, sessions, or accounts. Better Auth handles the collections automatically.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { betterAuth } <span class="hljs-keyword">from</span> <span class="hljs-string">"better-auth"</span>;
<span class="hljs-keyword">import</span> { mongodbAdapter } <span class="hljs-keyword">from</span> <span class="hljs-string">"better-auth/adapters/mongodb"</span>;
<span class="hljs-keyword">import</span> { MongoClient } <span class="hljs-keyword">from</span> <span class="hljs-string">"mongodb"</span>;


<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> MongoClient(process.env.MONGODB_URI!);
<span class="hljs-keyword">const</span> db = client.db(<span class="hljs-string">"my-production-app"</span>);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> auth = betterAuth({
    database: mongodbAdapter(db),

    emailAndPassword: {
        enabled: <span class="hljs-literal">true</span>,
    },

    socialProviders: {
        google: {
            clientId: process.env.GOOGLE_CLIENT_ID!,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
        },
        github: {
            clientId: process.env.GITHUB_CLIENT_ID!,
            clientSecret: process.env.GITHUB_CLIENT_SECRET!,
        } 
    }
});
</code></pre>
<h2 id="heading-phase-3-the-api-route">Phase 3: The API Route</h2>
<p>In older libraries, this part used to be a mess of callbacks and switch statements. Now? It’s basically two lines of code. We need a catch-all route so Better Auth can handle <code>/api/auth/sign-in</code>, <code>/sign-out</code>, etc etc</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { auth } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/lib/auth"</span>; 
<span class="hljs-keyword">import</span> { toNextJsHandler } <span class="hljs-keyword">from</span> <span class="hljs-string">"better-auth/next-js"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> { GET, POST } = toNextJsHandler(auth);
</code></pre>
<h2 id="heading-phase-4-the-client">Phase 4: The Client</h2>
<p>Next.js creates a strict boundary between Server and Client, we need a dedicated Auth Client to use in our React components. This gives us hooks like <code>useSession</code> and functions like <code>signIn</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { createAuthClient } <span class="hljs-keyword">from</span> <span class="hljs-string">"better-auth/react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> authClient = createAuthClient({
    baseURL: process.env.BETTER_AUTH_URL 
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> { signIn, signUp, signOut, useSession } = authClient;
</code></pre>
<h2 id="heading-phase-5-building-a-login-form">Phase 5: Building a Login Form</h2>
<p>Let's build a proper Sign-Up page. I’m going to use the signUp function we just exported. Note how we handle the callbackURL, this controls where the user lands after they register.</p>
<pre><code class="lang-typescript"><span class="hljs-string">"use client"</span>;

<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { signUp } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/lib/auth-client"</span>; 
<span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">"next/navigation"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SignUp</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">""</span>);
    <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">""</span>);
    <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">""</span>);
    <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">false</span>);
    <span class="hljs-keyword">const</span> router = useRouter();

    <span class="hljs-keyword">const</span> handleRegister = <span class="hljs-keyword">async</span> () =&gt; {
        setLoading(<span class="hljs-literal">true</span>);
        <span class="hljs-keyword">await</span> signUp.email({
            email,
            password,
            name,
            callbackURL: <span class="hljs-string">"/dashboard"</span>, 
        }, {
            onSuccess: <span class="hljs-function">() =&gt;</span> {

                router.push(<span class="hljs-string">"/dashboard"</span>);
            },
            onError: <span class="hljs-function">(<span class="hljs-params">ctx</span>) =&gt;</span> {
                alert(ctx.error.message); 
                setLoading(<span class="hljs-literal">false</span>);
            }
        });
    };

    <span class="hljs-keyword">return</span> (
        &lt;div className=<span class="hljs-string">"flex flex-col gap-4 p-10 max-w-sm mx-auto"</span>&gt;
            &lt;h1 className=<span class="hljs-string">"text-2xl font-bold"</span>&gt;Join the App&lt;/h1&gt;

            {<span class="hljs-comment">/* Social Auth is literally one function call */</span>}
            &lt;button 
                onClick={<span class="hljs-function">() =&gt;</span> signUp.social({ provider: <span class="hljs-string">"google"</span>, callbackURL: <span class="hljs-string">"/dashboard"</span> })}
                className=<span class="hljs-string">"bg-white border text-black p-2 rounded flex items-center justify-center gap-2"</span>
            &gt;
                Continue <span class="hljs-keyword">with</span> Google
            &lt;/button&gt;

            &lt;div className=<span class="hljs-string">"text-center text-gray-500"</span>&gt;or&lt;/div&gt;

            &lt;input className=<span class="hljs-string">"border p-2 rounded"</span> placeholder=<span class="hljs-string">"Name"</span> onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setName(e.target.value)} /&gt;
            &lt;input className=<span class="hljs-string">"border p-2 rounded"</span> placeholder=<span class="hljs-string">"Email"</span> onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setEmail(e.target.value)} /&gt;
            &lt;input className=<span class="hljs-string">"border p-2 rounded"</span> <span class="hljs-keyword">type</span>=<span class="hljs-string">"password"</span> placeholder=<span class="hljs-string">"Password"</span> onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setPassword(e.target.value)} /&gt;

            &lt;button 
                onClick={handleRegister} 
                disabled={loading}
                className=<span class="hljs-string">"bg-black text-white p-2 rounded hover:opacity-80 disabled:opacity-50"</span>
            &gt;
                {loading ? <span class="hljs-string">"Creating Account..."</span> : <span class="hljs-string">"Sign Up"</span>}
            &lt;/button&gt;
        &lt;/div&gt;
    );
}
</code></pre>
<h2 id="heading-phase-6-protecting-routes">Phase 6: Protecting Routes</h2>
<p>We need to protect our routes. In 2026, the best way to do this in the App Router isn't just client-side checking, it's Server Side Checking in a Layout.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { auth } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/lib/auth"</span>; 
<span class="hljs-keyword">import</span> { headers } <span class="hljs-keyword">from</span> <span class="hljs-string">"next/headers"</span>; 
<span class="hljs-keyword">import</span> { redirect } <span class="hljs-keyword">from</span> <span class="hljs-string">"next/navigation"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DashboardLayout</span>(<span class="hljs-params">{ children }: { children: React.ReactNode }</span>) </span>{

    <span class="hljs-keyword">const</span> session = <span class="hljs-keyword">await</span> auth.api.getSession({
        headers: <span class="hljs-keyword">await</span> headers() 
    });
    <span class="hljs-keyword">if</span> (!session) {
        redirect(<span class="hljs-string">"/sign-in"</span>);
    }

    <span class="hljs-keyword">return</span> (
        &lt;div&gt;
            &lt;header className=<span class="hljs-string">"p-4 border-b flex justify-between items-center"</span>&gt;
                &lt;h2 className=<span class="hljs-string">"font-bold"</span>&gt;Dashboard&lt;/h2&gt;
                &lt;div className=<span class="hljs-string">"flex gap-4 items-center"</span>&gt;
                    &lt;p&gt;Hello, {session.user.name}&lt;/p&gt;
                    {<span class="hljs-comment">/* Note: You'll need a Client Component for the Logout button */</span>}
                &lt;/div&gt;
            &lt;/header&gt;
            &lt;main className=<span class="hljs-string">"p-4"</span>&gt;
                {children}
            &lt;/main&gt;
        &lt;/div&gt;
    );
}
</code></pre>
<ol>
<li><p><strong>No Flash of Unauthenticated Content -</strong> Because we check in the layout (server-side), the user never sees the dashboard if they aren't allowed.</p>
</li>
<li><p><strong>Type Safety -</strong> session.user.name is typed. I didn't have to create a custom interface, Better Auth inferred it from my schema.</p>
</li>
<li><p><strong>Flexibility-</strong> If I want to add 2FA later? I just add <code>twoFactor: { enabled: true }</code> in the config. That's it.</p>
</li>
</ol>
<p>It’s genuinely the cleanest auth setup I’ve touched in a long time. If you want a visual walkthrough, definitely check the Coder's Gyan video <a target="_blank" href="https://youtu.be/2c-0_G3vpU8?si=IV3gqWiBLOalnDds">linked</a>, it was a huge help when I was figuring this out.</p>
]]></content:encoded></item><item><title><![CDATA[Building OAuth From Scratch]]></title><description><![CDATA[To truly understand how that magic works, we need to look under the hood. We are going to implement a basic OAuth flow using nothing but standard Node.js and Express. No NextAuth, no better-auth, nothing.
The Problem: Why Does OAuth Even Exist?
Imagi...]]></description><link>https://jacked.dev/building-oauth-from-scratch</link><guid isPermaLink="true">https://jacked.dev/building-oauth-from-scratch</guid><category><![CDATA[Backend Development]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Sat, 14 Feb 2026 18:42:03 GMT</pubDate><content:encoded><![CDATA[<p>To truly understand how that magic works, we need to look under the hood. We are going to implement a basic OAuth flow using nothing but standard Node.js and Express. No NextAuth, no better-auth, nothing.</p>
<h2 id="heading-the-problem-why-does-oauth-even-exist">The Problem: Why Does OAuth Even Exist?</h2>
<p>Imagine you use a budgeting app called "BudgetBuddy." BudgetBuddy needs to see your bank transaction history to help you save money.</p>
<h3 id="heading-the-old-bad-way">The Old (Bad) Way</h3>
<p>In the early days of the internet, BudgetBuddy might have asked you for your bank username and password.</p>
<p>This is bad for a few reasons:</p>
<ul>
<li><p><strong>Security:</strong> You just gave a third-party app the keys to your entire bank account.</p>
</li>
<li><p><strong>Trust:</strong> If BudgetBuddy gets hacked, <em>your</em> bank account gets hacked.</p>
</li>
<li><p><strong>Control:</strong> You can’t limit access. BudgetBuddy has full access to transfer money, change settings, etc., just like you do.</p>
</li>
</ul>
<h3 id="heading-the-oauth-way">The OAuth Way</h3>
<p>This is why <strong>"Login with Google"</strong> (and OAuth) exists.</p>
<p>OAuth solves the problem of <strong>Delegated Authorization</strong>. It’s like a valet key for your car. You give the valet a special key that only starts the ignition (so they can park it), but it doesn't open the glove box or the trunk.</p>
<p>With OAuth we get two benefits</p>
<ol>
<li><p><strong>No Password Sharing:</strong> You never give your password to the app. You give it to the Provider (like Google).</p>
</li>
<li><p><strong>Token-Based:</strong> The app gets a "token" that allows access to specific data for a limited time.</p>
</li>
</ol>
<h2 id="heading-the-flow-how-it-actually-works">The Flow: How It Actually Works</h2>
<p>The specific version of OAuth we see most often is called the <strong>Authorization Code Flow</strong>. It’s a bit of a dance between four main characters.</p>
<h3 id="heading-the-step-by-step-flow">The Step-by-Step Flow</h3>
<p>Here is what happens when you click that login button:</p>
<ol>
<li><p><strong>The Ask:</strong> You click "Login." The Client redirects you to the Authorization Server (Google).</p>
</li>
<li><p><strong>The Permission:</strong> Google asks you: <em>"</em>Do you want to let this app see your email?<em>"</em> You say Yes.</p>
</li>
<li><p><strong>The Code:</strong> Google redirects you <em>back</em> to your app with a temporary <strong>Authorization Code</strong> in the URL.</p>
</li>
<li><p><strong>The Exchange:</strong> Your app takes that code and whispers to Google (server-to-server): <em>"</em>Hey, I have this code from the user. Can I have a real Access Token now?"</p>
</li>
<li><p><strong>The Token:</strong> Google verifies the code and gives your app an <strong>Access Token</strong>.</p>
</li>
<li><p><strong>The Data:</strong> Your app uses that token to fetch your data from the API.</p>
</li>
</ol>
<h2 id="heading-minimal-implementation-nodejs-express">Minimal Implementation (Node.js + Express)</h2>
<p>Let's build this! We will assume we are connecting to a provider (GitHub or Google).</p>
<pre><code class="lang-javascript"><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> axios = <span class="hljs-built_in">require</span>(<span class="hljs-string">'axios'</span>); 
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// we usually get these from your provider's developer console</span>
<span class="hljs-keyword">const</span> CLIENT_ID = <span class="hljs-string">'your_client_id'</span>;
<span class="hljs-keyword">const</span> CLIENT_SECRET = <span class="hljs-string">'your_client_secret'</span>;
<span class="hljs-keyword">const</span> REDIRECT_URI = <span class="hljs-string">'http://localhost:3000/auth/callback'</span>;


<span class="hljs-keyword">const</span> AUTH_URL = <span class="hljs-string">'https://provider.com/oauth/authorize'</span>;
<span class="hljs-keyword">const</span> TOKEN_URL = <span class="hljs-string">'https://provider.com/oauth/token'</span>;
<span class="hljs-keyword">const</span> USER_INFO_URL = <span class="hljs-string">'https://api.provider.com/user'</span>;
</code></pre>
<h3 id="heading-step-1-the-redirect">Step 1: The Redirect</h3>
<pre><code class="lang-javascript">app.get(<span class="hljs-string">'/auth/login'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> URLSearchParams({
        <span class="hljs-attr">client_id</span>: CLIENT_ID,
        <span class="hljs-attr">redirect_uri</span>: REDIRECT_URI,
        <span class="hljs-attr">response_type</span>: <span class="hljs-string">'code'</span>,
        <span class="hljs-attr">scope</span>: <span class="hljs-string">'read:user'</span> 
    });

    res.redirect(<span class="hljs-string">`<span class="hljs-subst">${AUTH_URL}</span>?<span class="hljs-subst">${params.toString()}</span>`</span>);
});
</code></pre>
<p>Lets breakdown it line by line</p>
<ul>
<li><p><code>URLSearchParams</code>: This is a handy utility to build query strings safely.</p>
</li>
<li><p><code>client_id</code>: Identifies our app to the provider.</p>
</li>
<li><p><code>redirect_uri</code>: Tells the provider, "Once the user says yes, send them back here."</p>
</li>
<li><p><code>response_type: 'code'</code>: This is crucial. It tells the provider we are using the Authorization Code Flow. We want a code, not a token (yet).</p>
</li>
<li><p><code>res.redirect</code>: We physically move the user's browser from our site to the provider's site.</p>
</li>
</ul>
<h3 id="heading-step-2-the-callback">Step 2: The Callback</h3>
<p>The user has clicked "Allow." The provider sends them back to our <code>REDIRECT_URI</code> with a surprise attached to the URL - http://localhost:3000/auth/callback?code=abc12345.</p>
<pre><code class="lang-javascript">app.get(<span class="hljs-string">'/auth/callback'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> { code } = req.query;

    <span class="hljs-keyword">if</span> (!code) {
        <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">'Authorization code missing.'</span>);
    }

    <span class="hljs-keyword">try</span> {
        /
        <span class="hljs-keyword">const</span> tokenResponse = <span class="hljs-keyword">await</span> exchangeCodeForToken(code);

        <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> fetchUserProfile(tokenResponse.access_token);

        res.send(<span class="hljs-string">`Hello, <span class="hljs-subst">${userData.name}</span>! You are logged in.`</span>);
    } <span class="hljs-keyword">catch</span> (error) {
        res.status(<span class="hljs-number">500</span>).send(<span class="hljs-string">'Authentication failed'</span>);
    }
});
</code></pre>
<ul>
<li><p><strong>req.query</strong> - In Express, this is how we read the URL parameters. We extract the <code>code</code>.</p>
</li>
<li><p><strong>Error Handling -</strong> If there is no code, something went wrong (or the user said "No"), so we stop.</p>
</li>
<li><p><strong>The Async Flow -</strong> We pause to exchange the code for a token, then use the token to get user data.</p>
</li>
</ul>
<h3 id="heading-step-3-the-exchange">Step 3: The Exchange</h3>
<p>This is the most critical security step. We take the "temporary code" and swap it for the "permanent token." This happens on the server side, so the user never sees it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">exchangeCodeForToken</span>(<span class="hljs-params">code</span>) </span>{
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.post(TOKEN_URL, {
        <span class="hljs-attr">client_id</span>: CLIENT_ID,
        <span class="hljs-attr">client_secret</span>: CLIENT_SECRET,
        <span class="hljs-attr">code</span>: code,
        <span class="hljs-attr">redirect_uri</span>: REDIRECT_URI,
        <span class="hljs-attr">grant_type</span>: <span class="hljs-string">'authorization_code'</span>
    }, {
        <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Accept'</span>: <span class="hljs-string">'application/json'</span> }
    });

    <span class="hljs-keyword">return</span> response.data;
}
</code></pre>
<ul>
<li><p><a target="_blank" href="http://axios.post"><code>axios.post</code></a>: We are sending a POST request to the provider.</p>
</li>
<li><p><code>client_secret</code>: This is our app's password. We never share this on the frontend<strong>.</strong> This proves to the provider that we are the ones asking for the token, not a hacker.</p>
</li>
<li><p><code>grant_type: 'authorization_code'</code>: This tells the provider, "I am exchanging an auth code for a token."</p>
</li>
<li><p><a target="_blank" href="http://response.data"><code>response.data</code></a>: If successful, this object contains the <code>access_token</code> (and often a <code>refresh_token</code>).</p>
</li>
</ul>
<h3 id="heading-step-4-using-the-token">Step 4: Using the Token</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUserProfile</span>(<span class="hljs-params">accessToken</span>) </span>{
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(USER_INFO_URL, {
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-string">'Authorization'</span>: <span class="hljs-string">`Bearer <span class="hljs-subst">${accessToken}</span>`</span>
        }
    });

    <span class="hljs-keyword">return</span> response.data;
}
</code></pre>
<ul>
<li><p><code>Authorization</code> Header - This is the standard way to present a token.</p>
</li>
<li><p><code>Bearer</code> - Think of this like saying, "I am the bearer of this valid ticket."</p>
</li>
<li><p><a target="_blank" href="http://response.data"><code>response.data</code></a> - This will finally return the json data we wanted (e.g., <code>{ "name": "John Doe", "email": "</code><a target="_blank" href="mailto:john@example.com"><code>john@example.com</code></a><code>" }</code>) . Typical john doe.</p>
</li>
</ul>
<p><strong>Should you use this code in production?</strong></p>
<p>Probably not. Libraries handle edge cases, security vulnerabilities, and token rotation much better than a raw implementation. But now, when you’ll use libraries like NextAuth, better auth, you’re not just copy pasting code without understnding.</p>
]]></content:encoded></item><item><title><![CDATA[Building a Mini Express from Scratch]]></title><description><![CDATA[1. Why Build Express From Scratch?
Ever wondered what's actually happening under the hood when you type app.get()? Express feels like magic because it is abstraction done right. It hides the messy parts of handling HTTP requests so we can focus on sh...]]></description><link>https://jacked.dev/building-a-mini-express-from-scratch</link><guid isPermaLink="true">https://jacked.dev/building-a-mini-express-from-scratch</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Fri, 13 Feb 2026 17:50:40 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-1-why-build-express-from-scratch"><strong>1. Why Build Express From Scratch?</strong></h2>
<p>Ever wondered what's actually happening under the hood when you type <code>app.get()</code>? Express feels like magic because it is abstraction done right. It hides the messy parts of handling HTTP requests so we can focus on shipping.</p>
<p>Building a mini Express teaches what frameworks actually do. You'll understand routing, middleware chains, and why abstraction layers matter. Think of it this way a framework is just structured orchestration sitting on top of <code>http.createServer</code>.</p>
<h2 id="heading-2-designing-the-mini-framework-api">2<strong>. Designing the Mini Framework API</strong></h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> app = miniExpress();

app.get(<span class="hljs-string">"/users"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { res.send(<span class="hljs-string">"Users"</span>); });

app.listen(<span class="hljs-number">3000</span>);
</code></pre>
<p>We're building an abstraction layer that feels like Express, our own mini express.</p>
<h2 id="heading-3-routing-system"><strong>3. Routing System</strong></h2>
<p>The router is just a registry that matches incoming requests to handlers -</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> routes = [];

app.get = <span class="hljs-function">(<span class="hljs-params">path, handler</span>) =&gt;</span> {
  routes.push({ <span class="hljs-attr">method</span>: <span class="hljs-string">"GET"</span>, path, handler });
};

<span class="hljs-comment">// when the request comes in </span>

<span class="hljs-keyword">const</span> match = routes.find(
  <span class="hljs-function"><span class="hljs-params">r</span> =&gt;</span> r.method === req.method &amp;&amp; r.path === req.url
);
</code></pre>
<p>Simple O(n) lookup. Express uses fancy trie structures for speed. For learning purposes, a loop works fine. The concept match method and path, then execute is what matters.</p>
<h2 id="heading-4-middleware-system">4. Middleware System</h2>
<p>This is where things get interesting. Middleware is just a function that runs before your route handler, with the power to continue or stop the chain.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> middlewares = [];

app.use = <span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> {
  middlewares.push(fn);
};

<span class="hljs-comment">//</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//</span>

<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">next</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> middleware = middlewares[i++];
  <span class="hljs-keyword">if</span> (middleware) {
    middleware(req, res, next);
  }
}
</code></pre>
<p>Each middleware calls <code>next()</code> to pass control to the next one. This creates a linear execution chain where any middleware can modify the request, send a response early, or pass it along. It's control flow inversion, instead of you calling functions, the framework calls you and asks "what next?"</p>
<h2 id="heading-5-enhancing-responses-res"><strong>5. Enhancing responses (res)</strong></h2>
<pre><code class="lang-javascript">res.send = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
  res.end(<span class="hljs-built_in">JSON</span>.stringify(data));
};
</code></pre>
<p>Frameworks enhance primitives. We can add anything in our mini express. i.e. res.json, res.status, whatever solves our purpose.</p>
<h2 id="heading-6-order-of-execution"><strong>6. Order of Execution</strong></h2>
<pre><code class="lang-javascript">app.use(authMiddleware);
app.get(<span class="hljs-string">"/profile"</span>, handler);
</code></pre>
<p>The auth check runs first. If it fails, the profile handler never sees the request. Route matching typically happens after global middleware. That's a design decision Express made, and it affects how you structure apps. Order is architecture.</p>
<h2 id="heading-7-handling-404-and-fallback"><strong>7. Handling 404 and Fallback</strong></h2>
<p>What happens when no route matches? Lets see what can we do here</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!match) {
  res.statusCode = <span class="hljs-number">404</span>;
  res.end(<span class="hljs-string">"Not Found"</span>);
}
</code></pre>
<p>Express has a default 404 handler, but in production we usually override it. Defining fallback behavior is part of framework design.</p>
<h2 id="heading-8-handling-errors"><strong>8. Handling Errors</strong></h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (err) {
  errorHandler(err, req, res);
}
</code></pre>
<p>Error middleware takes four arguments <code>(err, req, res, next)</code> and centralizes failure handling. Instead of try-catch blocks scattered everywhere, you bring all errors to one place.</p>
<h2 id="heading-9-comparing-to-real-express-internals"><strong>9. Comparing to Real Express Internals</strong></h2>
<p>Oue mini express works, but real Express has more moving parts. It uses the <code>connect</code> middleware engine internally, with a <code>Layer</code> abstraction that wraps each middleware. The <code>Router</code> object handles nested routes and params.</p>
<h2 id="heading-10-production-limitations-of-your-mini-framework"><strong>10. Production Limitations of Your Mini Framework</strong></h2>
<p>Here are somethings that we did’nt really touch upon in this one, you try some of them on your own, it would be a fun ride</p>
<ul>
<li><p><strong>No async error handling</strong> try-catch won't catch errors in async middleware</p>
</li>
<li><p><strong>No route params</strong> <code>/users/:id</code> won't work, just exact matches</p>
</li>
<li><p><strong>No body parsing</strong> <code>req.body</code> is undefined; you'd need to stream and parse</p>
</li>
<li><p><strong>No query parsing</strong> <code>?foo=bar</code> stays a string</p>
</li>
<li><p><strong>No performance optimization</strong> that O(n) route lookup breaks at scale</p>
</li>
<li><p><strong>No security hardening</strong> no helmet, no cors, no protection</p>
</li>
</ul>
<p>My only goal with this one was to convey that frameworks aren’t magic, Its just someone’s organized code, and express has really organised our way of writing code.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Prototypes]]></title><description><![CDATA[Ever caught yourself typing something like [1,2,3].map() and suddenly wondered, where the hell does map actually live? You never defined it. It's not sitting there in your array. But it works anyway, every single time.
The Hidden Link Every Object Ca...]]></description><link>https://jacked.dev/javascript-prototypes</link><guid isPermaLink="true">https://jacked.dev/javascript-prototypes</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[oop]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Thu, 12 Feb 2026 19:07:18 GMT</pubDate><content:encoded><![CDATA[<p>Ever caught yourself typing something like <code>[1,2,3].map()</code> and suddenly wondered, where the hell does <code>map</code> actually live? You never defined it. It's not sitting there in your array. But it works anyway, every single time.</p>
<h2 id="heading-the-hidden-link-every-object-carries"><strong>The Hidden Link Every Object Carries</strong></h2>
<p>Here's the part they don't teach clearly every object in JavaScript has a secret connection to another object. Behind the scenes, there's an internal link called <code>[[Prototype]]</code>. You can't touch it directly, but you can peek at it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">"Chirag"</span> };
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(user));
</code></pre>
<p>There's also this old, informal way. The point is thi when JavaScript looks for a property on <code>user</code> and doesn't find it, it doesn't give up. It follows that hidden link upward. It checks the next object. And the next. This chain lookup is the engine that makes JavaScript inheritance work.</p>
<h2 id="heading-following-the-chain"><strong>Following the Chain</strong></h2>
<p>Let's trace what actually happens when you run <code>user.toString()</code>.</p>
<p>First, JavaScript checks <code>user</code> itself. No <code>toString</code> there. So it hops up to <code>user.__proto__</code>, which points to <code>Object.prototype</code>. <code>toString</code> lives there. If it hadn't found it? It would keep climbing. The chain goes: <code>user</code> - <code>Object.prototype</code> -<code>null</code>. <code>null</code> means stop. End of the road. If the property isn't found by then, you get <code>undefined</code>.</p>
<h2 id="heading-the-part-where-functions-get-weird"><strong>The Part Where Functions Get Weird</strong></h2>
<p>Okay, here's where people usually get lost. Functions in JavaScript have a <code>prototype</code> property. But that's <strong>not</strong> the same as <code>__proto__</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

User.prototype.sayHello = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>;
};

<span class="hljs-keyword">const</span> u1 = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"Arpit"</span>);
<span class="hljs-built_in">console</span>.log(u1.sayHello()); 

<span class="hljs-comment">// "Hello Arpit"</span>
</code></pre>
<p>What does <code>new</code> actually do? Four things creates an empty object, links its <code>__proto__</code> to <code>User.prototype</code>, binds <code>this</code> to that new object, and returns it. That's it. The <code>User.prototype</code> object becomes the prototype for every instance you create. So <code>u1</code> doesn't carry <code>sayHello</code> around in its pocket. It borrows it from <code>User.prototype</code>. One method, shared across every user. That's the memory efficiency people talk about.</p>
<p>ES6 gave us the <code>class</code> keyword, and it looks clean -</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }

  sayHello() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>;
  }
}
</code></pre>
<h2 id="heading-why-any-of-this-actually-matters"><strong>Why Any of This Actually Matters</strong></h2>
<p>In real systems, prototypes aren't academic trivia. They're practical tools with real consequences.</p>
<p><strong>Memory efficiency first -</strong> When you put methods on a prototype, every instance shares one function object. Put them in the constructor with <code>this.method</code> and you're duplicating that function for every single instance. At scale this is what matters(a lot )</p>
<p><strong>Performance next -</strong> Deep prototype chains slow down property lookup. If your object inherits from something that inherits from something else, JavaScript has to climb more links. Usually negligible, but worth knowing if you're optimizing hot paths.</p>
<h2 id="heading-the-takeaway"><strong>The Takeaway</strong></h2>
<p>Prototypes aren't some dusty JavaScript quirk. They're the living mechanism behind every method call, every inheritance chain, every <code>class</code> you write. Objects delegate upward. The chain ends at <code>null</code>. Functions have a <code>prototype</code> property that becomes the <code>__proto__</code> of their instances.</p>
]]></content:encoded></item><item><title><![CDATA[OOP in JavaScript?]]></title><description><![CDATA[First Things First: What Is OOP, Really?
Forget "paradigm" and "abstraction layers." Let's keep it real, OOP is just grouping related stuff together like how life actually works.
Your coffee mug? It has properties (colour, size) and does things (hold...]]></description><link>https://jacked.dev/oop-in-javascript</link><guid isPermaLink="true">https://jacked.dev/oop-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[OOPS]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Wed, 11 Feb 2026 18:06:49 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-first-things-first-what-is-oop-really"><strong>First Things First: What Is OOP, Really?</strong></h2>
<p>Forget "paradigm" and "abstraction layers." Let's keep it real, OOP is just grouping related stuff together like how life actually works.</p>
<p>Your coffee mug? It has properties (colour, size) and does things (holds coffee, gets warm). You don't store its colour in one drawer and its "hold-coffee" ability in another room. That'd be wild.</p>
<p>Code should feel the same.</p>
<h2 id="heading-the-four-pillars-of-oop"><strong>The "Four Pillars" of OOP</strong></h2>
<p><strong>Encapsulation = Keep Your Stuff in Your Lane</strong></p>
<p>Your bank account balance isn't scribbled on a sticky note everyone can grab. You deposit or withdraw through the bank. this is how it looks in code <em>-</em></p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BankAccount</span> </span>{
  #balance = <span class="hljs-number">0</span>;  

  deposit(amount) {
    <span class="hljs-keyword">if</span> (amount &gt; <span class="hljs-number">0</span>) <span class="hljs-built_in">this</span>.#balance += amount;
  }

  getBalance() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.#balance;
  }
}
</code></pre>
<p><strong>Abstraction = Don't Sweat the Small Stuff</strong></p>
<p>You drive a car. You press the gas pedal. You don't need to know about fuel injectors, piston timing, or transmission fluid. Thank goodness. Again lets see the code -</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentProcessor</span> </span>{
  process(amount) {
    <span class="hljs-built_in">this</span>.validate(amount);
    <span class="hljs-built_in">this</span>.chargeCard(amount);
    <span class="hljs-built_in">this</span>.sendReceipt();
  }


  validate(amount) { <span class="hljs-comment">/* ... */</span> }
  chargeCard(amount) { <span class="hljs-comment">/* ... */</span> }
}

<span class="hljs-comment">// Using it:</span>
processor.process(<span class="hljs-number">29.99</span>);
</code></pre>
<p>You call <code>process(29.99)</code>. Done. It just works.</p>
<p><strong>Inheritance = Stand on Shoulders, Don't Reinvent</strong></p>
<p>Your kid inherits your eye color and learns to ride a bike from you. They add their own flair.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }

  speak() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> makes a sound`</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
  speak() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> barks!`</span>);
  }
}

<span class="hljs-keyword">const</span> buddy = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">"Buddy"</span>);
buddy.speak(); 

 <span class="hljs-comment">// "Buddy barks!"</span>
</code></pre>
<p><strong>Polymorphism = Same Button, Different Magic</strong></p>
<p>Press "play" on Netflix, show starts. Press "play" on Spotify, music flows. Same button. Smart behavior.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Notification</span> </span>{
  send() {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Subclasses must implement send()"</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailNotification</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Notification</span> </span>{
  send() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sending email..."</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SMSNotification</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Notification</span> </span>{
  send() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sending text..."</span>);
  }
}


<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">trigger</span>(<span class="hljs-params">notification</span>) </span>{
  notification.send(); 
}

trigger(<span class="hljs-keyword">new</span> EmailNotification()); 
trigger(<span class="hljs-keyword">new</span> SMSNotification());
</code></pre>
<p>Add a new notification type tomorrow? Zero changes to <code>trigger()</code>. That's the flexibility it provides.</p>
<p>And the classic debate <strong>javascript isn’t really OOP,</strong> ahh . The truth is under the hood, prototypes are doing the heavy lifting. But since ES6, We get <code>class</code> syntax and it's quite readable.</p>
]]></content:encoded></item><item><title><![CDATA[Higher Order Functions in JavaScript]]></title><description><![CDATA[A higher-order function is just a function that plays with other functions. That's it.
Basically it either -

Take a function as input

returns a function


Most of the time, it does both. But even doing one of those things makes it "higher-order."
T...]]></description><link>https://jacked.dev/higher-order-functions-in-javascript</link><guid isPermaLink="true">https://jacked.dev/higher-order-functions-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Tue, 10 Feb 2026 18:57:47 GMT</pubDate><content:encoded><![CDATA[<p>A higher-order function is just a function that plays with other functions. That's it.</p>
<p>Basically it either -</p>
<ol>
<li><p>Take a function as input</p>
</li>
<li><p>returns a function</p>
</li>
</ol>
<p>Most of the time, it does both. But even doing one of those things makes it "higher-order."</p>
<p>Think of it like this: regular functions work with data numbers, strings, objects. Higher-order functions work with behavior. Here's the thing that makes JavaScript special, functions are first-class citizens.</p>
<p>In some languages, functions are these rigid, special things. In JavaScript, a function is just another piece of data you can move around. That's why higher-order functions are so natural here we're not fighting the language, we're using it the way it was designed.</p>
<h2 id="heading-lets-look-at-some-basic-examples"><strong>Let's Look at Some Basic Examples</strong></h2>
<h3 id="heading-passing-a-function-as-an-argument"><strong>Passing a Function as an Argument</strong></h3>
<p>This is probably the easiest place to start.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hey there, <span class="hljs-subst">${name}</span>!`</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formalGreet</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Good evening, <span class="hljs-subst">${name}</span>.`</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saySomething</span>(<span class="hljs-params">name, greetingFunction</span>) </span>{
  <span class="hljs-keyword">return</span> greetingFunction(name);
}


<span class="hljs-built_in">console</span>.log(saySomething(<span class="hljs-string">"Sam"</span>, greet));        <span class="hljs-comment">// "Hey there, Sam!"</span>
<span class="hljs-built_in">console</span>.log(saySomething(<span class="hljs-string">"Sam"</span>, formalGreet));  <span class="hljs-comment">// "Good evening, Sam."</span>
</code></pre>
<h3 id="heading-returning-a-function"><strong>Returning a Function</strong></h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makeMultiplier</span>(<span class="hljs-params">factor</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">number</span>) </span>{
    <span class="hljs-keyword">return</span> number * factor;
  };
}

<span class="hljs-keyword">const</span> triple = makeMultiplier(<span class="hljs-number">3</span>);
<span class="hljs-keyword">const</span> double = makeMultiplier(<span class="hljs-number">2</span>);

<span class="hljs-built_in">console</span>.log(triple(<span class="hljs-number">5</span>));   <span class="hljs-comment">// 15</span>
<span class="hljs-built_in">console</span>.log(double(<span class="hljs-number">5</span>));   <span class="hljs-comment">// 10</span>
</code></pre>
<p><code>makeMultiplier</code> is like a little factory. You tell it what factor you want, and it builds you a custom function that remembers that factor.</p>
<h2 id="heading-the-built-in-hof"><strong>The Built-In HOF</strong></h2>
<p>JavaScript gives us three classics that pretty much every developer uses daily. Map, Filter, Reduce.</p>
<h3 id="heading-lets-start-with-map">Lets start with MAP</h3>
<p>Use map when you have an array and want to turn every item into something else. Same number of items, different values.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> prices = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>];
<span class="hljs-keyword">const</span> withTax = prices.map(<span class="hljs-function"><span class="hljs-params">price</span> =&gt;</span> price * <span class="hljs-number">1.2</span>);

<span class="hljs-comment">// [12, 24, 36]</span>
</code></pre>
<h3 id="heading-next-is-filter">Next is FILTER</h3>
<p>Use <code>filter</code> when you want to remove stuff based on a condition. You might end up with fewer items than you started with.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ages = [<span class="hljs-number">15</span>, <span class="hljs-number">22</span>, <span class="hljs-number">18</span>, <span class="hljs-number">30</span>, <span class="hljs-number">12</span>];
<span class="hljs-keyword">const</span> adults = ages.filter(<span class="hljs-function"><span class="hljs-params">age</span> =&gt;</span> age &gt;= <span class="hljs-number">18</span>);

<span class="hljs-comment">// [22, 18, 30]</span>
</code></pre>
<h3 id="heading-reduce">REDUCE</h3>
<p>Use <code>reduce</code> when you want to take a whole array and collapse it into one value. Could be a sum, an object, whatever.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">total, num</span>) =&gt;</span> total + num, <span class="hljs-number">0</span>);

<span class="hljs-comment">// 10</span>
</code></pre>
<p><strong>The key thing:</strong> don't get hung up on memorizing syntax. Focus on intent. When you look at a problem, ask yourself: "Am I transforming, selecting, or aggregating?" That tells you which tool to grab.</p>
<h2 id="heading-closures-how-functions-remember-things"><strong>Closures: How Functions Remember Things</strong></h2>
<p>When a function is created inside another function, it keeps access to all the variables from its parent even after the parent finishes. It's like the inner function carries a backpack with all the stuff it needs.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;  

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">increment</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      count++;
      <span class="hljs-keyword">return</span> count;
    },
    <span class="hljs-attr">decrement</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      count--;
      <span class="hljs-keyword">return</span> count;
    },
    <span class="hljs-attr">getCount</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> count;
    }
  };
}

<span class="hljs-keyword">const</span> myCounter = createCounter();

<span class="hljs-built_in">console</span>.log(myCounter.increment());  <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(myCounter.increment());  <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(myCounter.getCount());   <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(myCounter.decrement());  <span class="hljs-comment">// 1</span>


<span class="hljs-built_in">console</span>.log(myCounter.count);        <span class="hljs-comment">// undefined (it's protected!)</span>
</code></pre>
<p>Nothing from the outside can touch it directly, but the functions we returned can still use it. This is a classic pattern for creating configurable, stateful behavior while keeping your data safe.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createLogger</span>(<span class="hljs-params">prefix</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">message</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`[<span class="hljs-subst">${prefix}</span>] <span class="hljs-subst">${message}</span>`</span>);
  };
}

<span class="hljs-keyword">const</span> apiLogger = createLogger(<span class="hljs-string">"API"</span>);
<span class="hljs-keyword">const</span> dbLogger = createLogger(<span class="hljs-string">"DATABASE"</span>);

apiLogger(<span class="hljs-string">"Request received"</span>);     
dbLogger(<span class="hljs-string">"Connection failed"</span>);
</code></pre>
<h2 id="heading-real-world-stuff-youll-actually-use"><strong>Real-World Stuff You'll Actually Use</strong></h2>
<h3 id="heading-logging-wrappers"><strong>Logging Wrappers</strong></h3>
<p>Want to log how long a function takes without cluttering your business logic? here is an example</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withTiming</span>(<span class="hljs-params">fn</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-keyword">const</span> start = <span class="hljs-built_in">Date</span>.now();
    <span class="hljs-keyword">const</span> result = fn(...args);
    <span class="hljs-keyword">const</span> end = <span class="hljs-built_in">Date</span>.now();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${fn.name}</span> took <span class="hljs-subst">${end - start}</span>ms`</span>);
    <span class="hljs-keyword">return</span> result;
  };
}

<span class="hljs-keyword">const</span> slowFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// ... some heavy work</span>
};

<span class="hljs-keyword">const</span> timedSlowFunction = withTiming(slowFunction);
timedSlowFunction();  <span class="hljs-comment">// Logs: "slowFunction took 45ms"</span>
</code></pre>
<h3 id="heading-retry-logic"><strong>Retry Logic</strong></h3>
<p>APIs fail sometimes. Let's make a wrapper that tries again -</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withRetry</span>(<span class="hljs-params">fn, maxAttempts = <span class="hljs-number">3</span></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= maxAttempts; i++) {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> fn(...args);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-keyword">if</span> (i === maxAttempts) <span class="hljs-keyword">throw</span> error;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Attempt <span class="hljs-subst">${i}</span> failed, retrying...`</span>);
      }
    }
  };
}

<span class="hljs-keyword">const</span> fetchWithRetry = withRetry(fetchUserData, <span class="hljs-number">3</span>);
</code></pre>
<p>Higher order functions aren't some academic CS concept they're just functions that work with other functions. JavaScript makes this easy because functions are just values we can pass around.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript’s Core Secrets - Everything is object]]></title><description><![CDATA[The Building Blocks (Primitives)
Think of primitives like the basic Lego pieces. They're simple, they're straight forward, and you can't break them down further.

Strings - “hello“

Numbers - 24

Booleans - True/False


these are the simplest ones, n...]]></description><link>https://jacked.dev/javascripts-core-secrets</link><guid isPermaLink="true">https://jacked.dev/javascripts-core-secrets</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Mon, 09 Feb 2026 19:01:50 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-the-building-blocks-primitives">The Building Blocks (Primitives)</h2>
<p>Think of primitives like the basic Lego pieces. They're simple, they're straight forward, and you can't break them down further.</p>
<ul>
<li><p>Strings - “hello“</p>
</li>
<li><p>Numbers - 24</p>
</li>
<li><p>Booleans - True/False</p>
</li>
</ul>
<p>these are the simplest ones, nothing fancy.</p>
<p><strong>Undefined -</strong> This is JavaScript saying "I've got nothing for you." It's what you get when something doesn't exist in memory yet. No box, no label, just... nothing.</p>
<p><strong>Null</strong> - This is intentional nothing. It's you saying, "This should be empty." Which brings us to the Weirdest Thing in JavaScript(one of many weird parts, haha).</p>
<p><code>typeof null === "object"</code></p>
<p>It's basically a bug from JavaScript's early days that they can't fix now because it would break the entire internet. Back in 1995, when Brendan Eich was creating JavaScript in about 10 days (seriously), values were stored with a type tag. The tag for objects was <code>0</code>, and <code>null</code> was represented as <code>0x00</code> in most platforms which made it look like an object. Oops. Now we're stuck with it.</p>
<h2 id="heading-reference-types">Reference Types</h2>
<p>Unlike primitives (which are just values), objects, arrays, and functions are references.Lets dig deep. Think of it like this, If I have a primitive, I'm holding the actual Lego piece. If I have an object, I'm holding a map to where the Lego castle is built. Two people can have the same map pointing to the same castle. If one person rearranges the castle, everyone with that map sees the changes.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alex'</span> }
<span class="hljs-keyword">let</span> anotherPerson = person
anotherPerson.name = <span class="hljs-string">'Jordan'</span>
<span class="hljs-built_in">console</span>.log(person.name) 

<span class="hljs-comment">// Output </span>
<span class="hljs-comment">// 'Jordan' - wait, what?!</span>
</code></pre>
<h3 id="heading-variables">Variables</h3>
<p><code>var</code>, <code>let</code>, <code>const</code>, why three ways to do the same thing?</p>
<p><code>var</code> <strong>-</strong> The old way. It's like that friend who shows up uninvited to parties. <code>var</code> doesn't respect boundaries (block scope, hehe), it gets hoisted to the top (more on that soon), and it's just generally messy. Don't use it unless you're maintaining ancient code.</p>
<p><code>let</code> &amp; <code>const</code>: They respect block scope (anything inside <code>{}</code>, is a block).</p>
<p>Here's the real talk about <code>const</code> - It doesn't mean "immutable." It means "this reference can't change." You can't reassign the variable, but if it points to an object? You can change that object all day long(typical javascript nvm).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArray = []
myArray.push(<span class="hljs-string">'surprise!'</span>) 
<span class="hljs-comment">// Totally fine</span>
myArray = [<span class="hljs-string">'new'</span>] 
<span class="hljs-comment">// Error! Can't reassign</span>
</code></pre>
<p><strong>Temporal Dead Zone -</strong> Fancy term for a simple concept. With <code>let</code> and <code>const</code>, you can't use them before they're declared. The space between the start of the scope and the declaration is the "dead zone."</p>
<p>Use <code>const</code> by default. Use <code>let</code> when you need to reassign. Use <code>var</code> never. and stay happy.</p>
<h2 id="heading-execution-context">Execution Context</h2>
<p>Every time a function runs, it gets its own little stage with its own props.</p>
<p><strong>Global Context:</strong> The main stage. When your script starts, this is created first.</p>
<p><strong>Function Context:</strong> Every function call gets its own mini-stage stacked on top.</p>
<p><strong>The Call Stack:</strong> Imagine stacking plates. Each function call is a plate. When it's done, the plate is removed. Last in, first out. This is why infinite recursion breaks things, you run out of plates (stack overflow).</p>
<p>Here's the secret sauce: JavaScript runs in <strong>two phases</strong>.</p>
<ol>
<li><p><strong>Memory Phase:</strong> JavaScript scans the code and says, "Okay, I see variables and functions. I'll set aside space for them."</p>
</li>
<li><p><strong>Execution Phase:</strong> Then it actually runs the code, line by line.</p>
</li>
</ol>
<h2 id="heading-hoisting">Hoisting</h2>
<p>During the memory phase, JavaScript sets aside space. <code>var</code> variables: Get hoisted and initialized with <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(name) <span class="hljs-comment">// undefined, not an error</span>
<span class="hljs-keyword">var</span> name = <span class="hljs-string">'Alex'</span>
</code></pre>
<p><code>let</code>/<code>const</code>: Get hoisted but <em>not</em> initialized. That's why you get a reference error instead of <code>undefined</code>. Temporal deadzone in action.</p>
<p><strong>Function declarations:</strong> Get fully hoisted. You can call them before they're defined.</p>
<pre><code class="lang-javascript">sayHi() <span class="hljs-comment">// Error!</span>
<span class="hljs-keyword">let</span> sayHi = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hi'</span>) }
</code></pre>
<p><strong>Function expressions:</strong> Don't get hoisted (they're just variables).</p>
<h2 id="heading-scope">SCOPE</h2>
<p>Scope is about who can see what. JavaScript has three types:</p>
<p><strong>Global:</strong> The outside world. Anything out here is visible everywhere</p>
<p><strong>Function:</strong> Variables inside a function are only visible there.</p>
<p><strong>Block:</strong> Anything inside <code>{}</code> when using <code>let</code>/<code>const</code>.</p>
<p><strong>Lexical Scoping:</strong> Fancy term meaning "where you write it matters." Inner functions can see outer variables, but not vice versa.</p>
<h3 id="heading-closures-the-magic-trick">Closures - The Magic Trick</h3>
<p>Here's where JavaScript becomes interesting. A closure is when a function remembers and accesses variables from outside its own scope, even after that outer function has finished.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span> 

  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    count++ 
    <span class="hljs-keyword">return</span> count
  }
}

<span class="hljs-keyword">const</span> counter = createCounter()
<span class="hljs-built_in">console</span>.log(counter()) <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(counter()) <span class="hljs-comment">// 2</span>
</code></pre>
<p><strong>Real uses:</strong> Private variables (like above), event handlers that need to remember stuff, callbacks.</p>
<p><strong>The catch:</strong> Closures keep memory alive. If you're not careful, you can create memory leaks. But 99% of the time, it's fine.</p>
<h2 id="heading-functions">Functions</h2>
<p>Functions in JS are first class citizens. They can be assigned, passed around, returned just like any other value. cool right !</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Declaration - hoisted</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">walk</span>(<span class="hljs-params"></span>) </span>{}

<span class="hljs-comment">// Expression - just a value</span>
<span class="hljs-keyword">const</span> run = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{}
</code></pre>
<p><strong>Arrow functions:</strong> Shorter syntax, no <code>this</code> of their own (they inherit it), no <code>arguments</code> object. Great for callbacks, not great for methods that need <code>this</code>.</p>
<p><strong>Parameters vs Arguments:</strong> Parameters are the recipe, arguments are the ingredients you actually use.</p>
<p><strong>Default parameters:</strong> Life-changing. <code>function greet(name = 'stranger') {}</code></p>
<p><strong>Rest parameters:</strong> When you want "the rest of them." <code>function sum(...numbers) {}</code></p>
<h3 id="heading-higher-order-functions">Higher-Order Functions</h3>
<p>A higher-order function is either -</p>
<ol>
<li><p>A function that takes another function as input</p>
</li>
<li><p>A function that returns a function</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-comment">// Instead of this:</span>
<span class="hljs-keyword">const</span> doubled = []
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) {
  doubled.push(numbers[i] * <span class="hljs-number">2</span>)
}

<span class="hljs-comment">// You write this:</span>
<span class="hljs-keyword">const</span> doubled = numbers.map(<span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> n * <span class="hljs-number">2</span>)
</code></pre>
<p><code>map</code> Transform each item in an array<br /><code>filter</code> Keep only what you want<br /><code>reduce</code> Boil it down to one value</p>
<p>I'm not saying you need to memorize all this. Hell, I still Google the weird parts sometimes, I did a lot of googling for this as well. But understanding these concepts is like having a map in a foreign city. You might still take wrong turns.</p>
]]></content:encoded></item><item><title><![CDATA[HTTP & Building a Server From Scratch (Using Core http)]]></title><description><![CDATA[if you really want to understand how servers work, you need to go one level lower. You need to touch the raw metal. You need to build a server using the core http module. That’s what this post is about.
In this we are gonna -

Understand what HTTP ac...]]></description><link>https://jacked.dev/http-and-building-a-server-from-scratch</link><guid isPermaLink="true">https://jacked.dev/http-and-building-a-server-from-scratch</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Backend Development]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Sun, 08 Feb 2026 18:05:01 GMT</pubDate><content:encoded><![CDATA[<p>if you really want to understand <strong>how servers work</strong>, you need to go one level lower. You need to touch the raw metal. You need to build a server using the <strong>core</strong> <code>http</code> module. That’s what this post is about.</p>
<p>In this we are gonna -</p>
<ul>
<li><p>Understand what HTTP actually is</p>
</li>
<li><p>Build a server from scratch</p>
</li>
<li><p>Parse routes manually</p>
</li>
<li><p>Read headers</p>
</li>
<li><p>Handle request bodies using streams</p>
</li>
<li><p>Send proper status codes</p>
</li>
</ul>
<h3 id="heading-what-is-http">what is HTTP ?</h3>
<p>Starting with the most important/basic thing, what http is actually ? HTTP is just a <strong>conversation protocol</strong>.</p>
<p>Every HTTP request has:</p>
<ul>
<li><p><strong>Method</strong> (GET, POST, PUT, etc etc)</p>
</li>
<li><p><strong>URL</strong></p>
</li>
<li><p><strong>Headers</strong></p>
</li>
<li><p><strong>Body</strong> (optional)</p>
</li>
</ul>
<p>Every HTTP response has:</p>
<ul>
<li><p><strong>Status code</strong> (200, 404, 500…)</p>
</li>
<li><p><strong>Headers</strong></p>
</li>
<li><p><strong>Body</strong></p>
</li>
</ul>
<h3 id="heading-creating-the-smallest-possible-http-server">Creating the smallest possible HTTP server</h3>
<p>starting with most basic one</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">"http"</span>);

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.end(<span class="hljs-string">"Hello World"</span>);
});

server.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">"Server running on port 3000"</span>);
});
</code></pre>
<h2 id="heading-understanding-req-and-res">Understanding <code>req</code> and <code>res</code></h2>
<h3 id="heading-req-incoming-message"><code>req</code> (Incoming Message)</h3>
<p>And it mostly contains -</p>
<ul>
<li><p><code>req.method</code></p>
</li>
<li><p><code>req.url</code></p>
</li>
<li><p><code>req.headers</code></p>
</li>
<li><p>request body as a stream</p>
</li>
</ul>
<h3 id="heading-res-server-response"><code>res</code> (Server response)</h3>
<p>It is Used to -</p>
<ul>
<li><p>set status codes</p>
</li>
<li><p>set headers</p>
</li>
<li><p>send response body</p>
</li>
</ul>
<h3 id="heading-routing-in-nodejs">Routing in nodejs</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">"GET"</span> &amp;&amp; req.url === <span class="hljs-string">"/"</span>) {
    res.end(<span class="hljs-string">"Home page"</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">"GET"</span> &amp;&amp; req.url === <span class="hljs-string">"/health"</span>) {
    res.end(<span class="hljs-string">"OK"</span>);
    <span class="hljs-keyword">return</span>;
  }

  res.statusCode = <span class="hljs-number">404</span>;
  res.end(<span class="hljs-string">"Not Found"</span>);
});
</code></pre>
<p>Routing is just if-else on method and path(i love this analogy, got it from a cohort and still carry with me). Every framework eventually does this just in a cleaner way.</p>
<h2 id="heading-reading-request-headers">Reading request headers</h2>
<p>Headers are metadata.</p>
<p>Auth tokens, content type, user agent all comes through headers.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(req.headers);

  res.end(<span class="hljs-string">"Check your terminal"</span>);
});
<span class="hljs-comment">/* output you'll see in terminal. it might differ a bit
content-type
authorization
user-agent
content-length
*/</span>
</code></pre>
<h3 id="heading-handling-request-body">Handling request body</h3>
<p>Request body is a stream. The body does not come all at once. It arrives in chunks.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> body = <span class="hljs-string">""</span>;

  req.on(<span class="hljs-string">"data"</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> {
    body += chunk;
  });

  req.on(<span class="hljs-string">"end"</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(body);
    res.end(<span class="hljs-string">"Body received"</span>);
  });
});
</code></pre>
<p>This pattern matters a lot in real systems. Because -</p>
<ul>
<li><p>Requests can be huge</p>
</li>
<li><p>Streaming avoids loading everything in memory</p>
</li>
<li><p>This scales better</p>
</li>
</ul>
<h3 id="heading-parsing-json-request-body">Parsing JSON request body</h3>
<pre><code class="lang-javascript">req.on(<span class="hljs-string">"end"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(body);
    <span class="hljs-built_in">console</span>.log(data);
    res.end(<span class="hljs-string">"JSON parsed"</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    res.statusCode = <span class="hljs-number">400</span>;
    res.end(<span class="hljs-string">"Invalid JSON"</span>);
  }
});
</code></pre>
<p>On eimportant thing to notice here is that you are responsible for validations here, frameworks just hide these from us.</p>
<h3 id="heading-sending-proper-status-codes">Sending proper status codes</h3>
<pre><code class="lang-javascript">res.statusCode = <span class="hljs-number">201</span>;
res.end(<span class="hljs-string">"User created"</span>);
</code></pre>
<p>Some common status codes with meaning</p>
<ul>
<li><p><code>200</code> – OK</p>
</li>
<li><p><code>201</code> – Created</p>
</li>
<li><p><code>400</code> – Bad request</p>
</li>
<li><p><code>401</code> – Unauthorized</p>
</li>
<li><p><code>404</code> – Not found</p>
</li>
<li><p><code>500</code> – Server error</p>
</li>
</ul>
<h3 id="heading-setting-response-headers">Setting response headers</h3>
<p>Headers go out before body</p>
<pre><code class="lang-javascript">res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
res.statusCode = <span class="hljs-number">200</span>;
res.end(<span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Hello"</span> }));
</code></pre>
<p>Order doesn’t matter in code that much. Node sends them correctly under the hood.</p>
<h3 id="heading-a-tiny-but-complete-server">A tiny but complete server</h3>
<p>Putting everything together</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">"http"</span>);

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">"POST"</span> &amp;&amp; req.url === <span class="hljs-string">"/echo"</span>) {
    <span class="hljs-keyword">let</span> body = <span class="hljs-string">""</span>;

    req.on(<span class="hljs-string">"data"</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> {
      body += chunk;
    });

    req.on(<span class="hljs-string">"end"</span>, <span class="hljs-function">() =&gt;</span> {
      res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);
      res.statusCode = <span class="hljs-number">200</span>;
      res.end(body);
    });

    <span class="hljs-keyword">return</span>;
  }

  res.statusCode = <span class="hljs-number">404</span>;
  res.end(<span class="hljs-string">"Route not found"</span>);
});

server.listen(<span class="hljs-number">3000</span>);
</code></pre>
<p>Once we understand these foundations of a server Frameworks stop feeling magical. Debugging becomes easier. Performance issues make sense.</p>
]]></content:encoded></item><item><title><![CDATA[The Event Loop]]></title><description><![CDATA[well well well, I love this stuff, my eyes lit up when I understood the concept. I hope I can do justice to this amazing engineering.
before getting started, two important questions to answer.
1. Is nodejs single-threaded ?YES
2. Node.js is also non-...]]></description><link>https://jacked.dev/the-event-loop</link><guid isPermaLink="true">https://jacked.dev/the-event-loop</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Backend Development]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Chirag Bhugra]]></dc:creator><pubDate>Sat, 07 Feb 2026 19:05:46 GMT</pubDate><content:encoded><![CDATA[<p>well well well, I love this stuff, my eyes lit up when I understood the concept. I hope I can do justice to this amazing engineering.</p>
<p>before getting started, two important questions to answer.</p>
<p><strong>1. Is nodejs single-threaded ?</strong><br />YES</p>
<p><strong>2. Node.js is also non-blocking.</strong><br />YES</p>
<h2 id="heading-what-the-event-loop-really-is">What the Event Loop really is</h2>
<p>Think of the Event Loop as:</p>
<blockquote>
<p>A disciplined scheduler that decides <strong>what code runs next</strong> and <strong>when</strong></p>
</blockquote>
<p>It repeatedly does this:</p>
<ol>
<li><p>Take one task</p>
</li>
<li><p>Run it to completion</p>
</li>
<li><p>Pick the next task based on strict rules</p>
</li>
<li><p>Repeat forever</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1770485766862/19deb2aa-38e7-4af0-9b2f-99cf4126b4a5.png" alt class="image--center mx-auto" /></p>
<p>The event loop is like a <strong>conductor</strong> in an orchestra it doesn't play instruments itself, but it coordinates when each section (or phase) gets to perform. Every time the event loop completes one full cycle through all phases, we call that a <strong>tick.</strong></p>
<h2 id="heading-the-six-phases"><strong>The Six Phases</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1770488558925/d9fecc37-97cd-4d6a-92cf-afcc8f03a901.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-phase-1-timers-phase"><strong>Phase 1: Timers Phase</strong></h3>
<p><strong>What happens here -</strong> This phase executes callbacks scheduled by <code>setTimeout()</code> and <code>setInterval()</code> once their timer expires.</p>
<p><strong>Key details:</strong></p>
<ul>
<li><p>If you set <code>setTimeout(callback, 0)</code>, it doesn't mean "run immediately." It means "run in the next tick's timers phase."</p>
</li>
<li><p>The event loop checks if the timer's time has elapsed, and if so, executes those callbacks.</p>
</li>
<li><p>If one or more timers are ready, the event loop will wrap back to this phase to execute those timers' callbacks.</p>
</li>
</ul>
<h3 id="heading-phase-2-pending-callbacks-phase"><strong>Phase 2: Pending Callbacks Phase</strong></h3>
<p><strong>What happens here:</strong> Executes I/O callbacks that were deferred to the next loop iteration. Think of this as your "pending mail" folder. Some I/O operations (like TCP errors, certain file system operations) couldn't be handled immediately in the poll phase, so they're queued here for the next cycle.</p>
<p><strong>Key details:</strong></p>
<ul>
<li><p>This phase handles callbacks that couldn't be processed in the previous poll phase.</p>
</li>
<li><p>Examples include certain types of TCP errors or operations that the system couldn't complete right away.</p>
</li>
<li><p>It's essentially a "catch-up" phase for I/O that needs attention but wasn't ready during the last poll.</p>
</li>
</ul>
<h3 id="heading-phase-3-idle-prepare-phase"><strong>Phase 3: Idle, Prepare Phase</strong></h3>
<p><strong>What happens here:</strong> This phase is used internally by Node.js and libuv. This is like the orchestra's tuning phase musicians adjust their instruments before the main performance. You don't see it, but it's essential for everything to work smoothly.</p>
<p><strong>Key details:</strong></p>
<ul>
<li><p><strong>Idle phase:</strong> Used internally by libuv for housekeeping tasks.</p>
</li>
<li><p><strong>Prepare phase:</strong> Also internal, used to prepare for the upcoming poll phase.</p>
</li>
<li><p>As a developer, you typically don't interact with this phase directly it's all behind the scenes magic.</p>
</li>
</ul>
<h3 id="heading-phase-4-poll-phase-most-important-one"><strong>Phase 4: Poll Phase <mark>Most important one</mark></strong></h3>
<p><strong>What happens here:</strong> This is the <strong>core phase</strong> where Node.js retrieves new I/O events and executes their callbacks.</p>
<p><strong>Key details:</strong></p>
<p><strong>It has two main responsibilities:</strong></p>
<ol>
<li><p><strong>Calculate how long it should block and poll for I/O:</strong> The event loop figures out how long to wait for new events.</p>
</li>
<li><p><strong>Process I/O events in the poll queue:</strong> When I/O events are ready, their callbacks get executed here.</p>
</li>
</ol>
<p>Also, it has a special behviour as well. f there are <code>setImmediate()</code> callbacks waiting AND the poll queue is empty, Node.js will immediately exit the poll phase and move to the check phase.<br />If timers are ready to fire, Node.js will wrap back to the timers phase after the poll phase completes. It can be made predictible. We’ll see that through code snippets.</p>
<h3 id="heading-phase-5-check-phase"><strong>Phase 5: Check Phase</strong></h3>
<p><strong>What happens here:</strong> Executes callbacks scheduled by <code>setImmediate()</code>. <strong>Key details:</strong></p>
<ul>
<li><p><code>setImmediate()</code> callbacks are designed to execute <strong>after</strong> I/O callbacks but <strong>before</strong> the next tick's timers.</p>
</li>
<li><p>This phase exists specifically to allow developers to schedule callbacks that run right after the poll phase.</p>
</li>
<li><p>If you have both <code>setTimeout(callback, 0)</code> and <code>setImmediate(callback)</code>, the order depends on context—usually <code>setTimeout</code> fires first when called from the main module, but <code>setImmediate</code> can win inside I/O callbacks.</p>
</li>
</ul>
<h3 id="heading-phase-6-close-callbacks-phase">Phase 6: Close Callbacks Phase</h3>
<p><strong>What happens here:</strong> Handles "close" events and cleanup operations. For instance, a connection being terminated or a <code>socket.close</code> event.</p>
<p><strong>Lets look at the complete cycle in action -</strong></p>
<p>And the best way to understand this is to play classic “guess the output“ game</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">' Start'</span>);

<span class="hljs-comment">// Timers phase</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">' setTimeout (timers phase)'</span>), <span class="hljs-number">0</span>);

<span class="hljs-comment">// Check phase</span>
setImmediate(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'setImmediate (check phase)'</span>));

<span class="hljs-comment">// Poll phase (I/O callback)</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>).readFile(__filename, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'readFile callback (poll phase)'</span>);
    setImmediate(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">' Nested setImmediate'</span>));
});

<span class="hljs-comment">// Close callbacks phase</span>
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'net'</span>);
<span class="hljs-keyword">const</span> server = net.createServer();
server.listen(<span class="hljs-number">0</span>, <span class="hljs-function">() =&gt;</span> {
    server.close(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'🚪 Close callback (close callbacks phase)'</span>);
    });
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'End'</span>);

<span class="hljs-comment">/// * Output </span>
 Start
 End
 readFile callback (poll phase)
 setImmediate (check phase)
 Close callback (close callbacks phase)
 <span class="hljs-built_in">setTimeout</span> (timers phase)
 Nested setImmediate
 <span class="hljs-comment">/// *</span>
</code></pre>
<h2 id="heading-the-takeaway"><strong>The Takeaway</strong></h2>
<p>it's a very well-organized system with six distinct phases:</p>
<ol>
<li><p><strong>Timers</strong> - Scheduled timeouts and intervals</p>
</li>
<li><p><strong>Pending Callbacks</strong> -Deferred I/O callbacks</p>
</li>
<li><p><strong>Idle/Prepare</strong> - Internal housekeeping</p>
</li>
<li><p><strong>Poll</strong> - The heart of I/O processing (where Node spends most time!)</p>
</li>
<li><p><strong>Check</strong> - <code>setImmediate()</code> callbacks</p>
</li>
<li><p><strong>Close Callbacks</strong> - Cleanup and resource destruction.</p>
</li>
</ol>
<p>he event loop is powered by <strong>libuv</strong> a C library that handles all the low-level I/O operations and threading. Node.js sits on top of libuv, providing the JavaScript interface we all love. The Node.js official documentation has amazing diagrams of the event loop. Check it out if you want to go even deeper, I took a lot of inspiration from there and some other great blogs out there.</p>
]]></content:encoded></item></channel></rss>