<?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[Abdul Rahman ]]></title><description><![CDATA[Full stack development, explained the way I understood it. Backend, frontend and everything between. CS student · ChaiCode Web Dev Cohort 2026.]]></description><link>https://blog.abdulrdeveloper.me</link><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 01:23:52 GMT</lastBuildDate><atom:link href="https://blog.abdulrdeveloper.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How “Sign in with Google” Really Works: OIDC and OAuth 2.0 Explained]]></title><description><![CDATA[How Sign in with Google really works: shared secrets, public keys, OIDC, client_id and the Authorization Code flow, explained step by step.]]></description><link>https://blog.abdulrdeveloper.me/why-google-trusts-your-app-oidc-oauth2</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/why-google-trusts-your-app-oidc-oauth2</guid><category><![CDATA[oauth]]></category><category><![CDATA[OpenID Connect]]></category><category><![CDATA[authentication]]></category><category><![CDATA[backend]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Tue, 03 Nov 2026 12:49:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/5e905f94-5d88-4dce-8912-2641f789ef8a.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You have clicked "Sign in with Google" many times. One click and you are inside.</p>
<p>Most of us just install a library, paste a <code>client_id</code> and a <code>client_secret</code>, and it works. But that is the easiest part of the whole story.</p>
<p>The real engineering is what happens behind that button. In this blog I will explain it as a story. Every problem will lead to the next idea, so you never have to memorize anything.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/edbc7f11-355b-4c4b-ac6b-8571c27f5024.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Step 1: The Server Is a Proxy</h2>
<p>A user never talks to the database directly. The server stands in the middle.</p>
<p>It checks who the user is, and then it talks to the database for them.</p>
<p>So the first question for every server is: <strong>how do I remember who this user is?</strong></p>
<p>There are two ways:</p>
<ul>
<li><strong>Sessions (stateful):</strong> the server saves the login information and gives the user a session id. On every request, the server looks it up.</li>
<li><strong>Tokens (stateless):</strong> the server saves nothing. The user carries a signed token, and sends it with every request.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/746d217a-03e3-427f-ab49-25ac0ed809e6.png" alt="" style="display:block;margin:0 auto" />

<p>Tokens are very popular. But they bring a new problem.</p>
<hr />
<h2>Step 2: The Problem With One Shared Key</h2>
<p>To sign a token, the simplest way is <strong>symmetric</strong> signing (for example HS256).</p>
<p>Symmetric means <strong>one key for everything</strong>. The same key creates the signature and also checks it.</p>
<pre><code class="language-js">const token = jwt.sign(payload, SECRET);   // create
const data  = jwt.verify(token, SECRET);   // verify with the same secret
</code></pre>
<p>This is fast and simple, and it is perfect for one server.</p>
<p>But big companies do not run one server. To understand why, we need to know two ways of building an application.</p>
<hr />
<h2>Monolith &amp; Microservices</h2>
<h3><strong>Monolith</strong></h3>
<p>A <strong>monolith</strong> is <strong>one big application</strong>. Everything lives in one codebase and runs on one server.</p>
<p>Think of a small online course website. Login, courses, payments and videos are all written in one project, and they all run together as one app.</p>
<p>Because everything is in one place, one secret is enough. The whole app knows it, and nothing else does.</p>
<h3><strong>Microservices</strong></h3>
<p>When a company grows, one big app becomes hard to manage. If the payment code breaks, the whole site can go down. So the company breaks the app into <strong>many small applications</strong>. Each one does only one job and runs on its own server. These are called <strong>microservices</strong>.</p>
<p>Now the same course website looks like this:</p>
<ul>
<li>a login service</li>
<li>a courses service</li>
<li>a payment service</li>
<li>a video service</li>
</ul>
<p>Each service is a separate application. They talk to each other through API calls.</p>
<p>Google is a big example of this idea. YouTube, Gmail, Drive, Play Store and Maps are different products, run by different teams, on different servers. But a user logs in only once, and every one of these needs to know who that user is.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/59ed6652-cfa3-4c19-92e7-7dde9375e803.png" alt="" style="display:block;margin:0 auto" />

<h4>So Where Is the Problem?</h4>
<p>Every service must check the user’s token. If the token is signed with one shared secret, every service needs to know that secret. That brings two problems:</p>
<ol>
<li><strong>Security.</strong> A secret that lives in many places will leak one day. Think about it: a new employee joins the YouTube team. Should they get the secret that signs every Google user’s token? Of course not. That is far too risky. But with a shared secret, every team must have it.</li>
<li><strong>Network hop.</strong> The other option is to keep the secret in one auth service only. Then every other service asks it, “Is this token real?” Every request needs <strong>one extra call</strong> to the auth service before it can continue. That is slow, and if the auth service goes down, everything stops. It also becomes a bottleneck, because every service depends on it.</li>
</ol>
<p>So we need a way to check a token <strong>without knowing the secret</strong>, and <strong>without calling anyone</strong>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/a94f10fc-6735-49d4-b1d9-4bdf172c0331.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Step 3: Asymmetric Keys</h2>
<p>The solution is two keys instead of one:</p>
<ul>
<li><strong>Private key:</strong> only the auth server has it. It <strong>signs</strong> the token.</li>
<li><strong>Public key:</strong> everyone can have it. It <strong>verifies</strong> the token.</li>
</ul>
<pre><code class="language-js">// Auth server (only place with the private key)
const token = jwt.sign(payload, PRIVATE_KEY, { algorithm: "RS256" });

// Any other service (only needs the public key)
const data = jwt.verify(token, PUBLIC_KEY);
</code></pre>
<p>This is called <strong>asymmetric</strong> because the two keys are different.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/e95fc7bf-4f79-4884-ab6b-cc9b208f7589.png" alt="" style="display:block;margin:0 auto" />

<p>Now, no other service knows the private key. They only know the public key, and the public key can only <strong>verify</strong>. It cannot create or change a token.</p>
<p>That is why a company like Google can show its public key to the whole world. You can even open it yourself.</p>
<p>(In JWT this is called signing and verifying. The token is not hidden, but nobody can change it.)</p>
<hr />
<h2>Step 4: How Do We Share the Public Key?</h2>
<p>A new problem. If the company changes its private key, there is a new public key too. Now it must tell every service (like if it`s google it will tell youtube , map , drive etc all that), "please take the fresh key." Copying keys by hand does not work.</p>
<p>So the companies made a simple solution: <strong>publish the key on a URL</strong>. Services fetch it when they start, or when it expires (10 minutes, one month, anything).</p>
<p>Everyone liked this idea. Google, Microsoft and others all built it. But everyone built it in their own way:</p>
<ul>
<li>One used <code>GET /publish-key</code> and returned JSON.</li>
<li>Another used <code>GET /pk</code> and sent a file.</li>
<li>Another used <code>GET /keys/publish-key</code> and streamed JSON.</li>
</ul>
<p>If you wanted to trust three companies, you had to write three different codes. That is a mess.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/ae82a8cf-39d4-4f5d-9b68-af71c1a96700.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Step 5: OIDC Brings the Standard</h2>
<p>So the big companies sat together and said, "Let's make one standard way for all systems to share user information."</p>
<p>From that came</p>
<ul>
<li><strong>SAML</strong></li>
<li><strong>OIDC</strong></li>
</ul>
<p>SAML is older. <strong>OIDC is the modern and most common one.</strong></p>
<p>OIDC`s first rule is <strong>service discovery</strong>. Every provider must have this one fixed address:</p>
<pre><code class="language-plaintext">GET /.well-known/openid-configuration
</code></pre>
<p>It returns a JSON that tells you everything. For example, you can open this in your browser:</p>
<pre><code class="language-plaintext">https://accounts.google.com/.well-known/openid-configuration
</code></pre>
<p>Other companies like OpenAI also follow the same structure. That is what a standard means.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/47cd7c68-0996-4456-9e0f-ebfdfeca0673.png" alt="" style="display:block;margin:0 auto" />

<h3>What Is Inside?</h3>
<p>Here is a small example:</p>
<pre><code class="language-json">{
  "issuer": "https://auth.example.com",
  "authorization_endpoint": "https://auth.example.com/authorize",
  "token_endpoint": "https://auth.example.com/oauth/token",
  "userinfo_endpoint": "https://auth.example.com/oauth/userinfo",
  "jwks_uri": "https://auth.example.com/.well-known/jwks.json",
  "scopes_supported": ["openid", "profile", "email"],
  "response_types_supported": ["code"],
  "id_token_signing_alg_values_supported": ["RS256"]
}
</code></pre>
<p>What each one does:</p>
<ul>
<li><strong>issuer:</strong> who is this provider. Every token carries this name.</li>
<li><strong>authorization_endpoint:</strong> the login page. You send the user here. You can call it sign in or login, the name does not matter.</li>
<li><strong>token_endpoint:</strong> where your backend exchanges a short code for the real tokens.</li>
<li><strong>userinfo_endpoint:</strong> gives you the user's profile.</li>
<li><strong>jwks_uri:</strong> where the public keys are.</li>
<li><strong>scopes_supported:</strong> what you are allowed to ask for (<code>openid</code>, <code>profile</code>, <code>email</code>).</li>
<li><strong>response_types_supported:</strong> <code>code</code> means the Authorization Code flow, which we will see soon.</li>
<li><strong>id_token_signing_alg_values_supported:</strong> <code>RS256</code> means the token is signed with asymmetric keys.</li>
</ul>
<p>The token itself is also standard. It always has the same fields, like <code>sub</code> (user id), <code>email</code>, <code>name</code> and <code>exp</code> (expiry), so every service reads it the same way.</p>
<hr />
<h2>JWK vs JWKS</h2>
<p>You will see both names, and the difference is small.</p>
<ul>
<li><strong>JWK</strong> is <strong>one</strong> key.</li>
<li><strong>JWKS</strong> is a <strong>set</strong> of keys, an array.</li>
</ul>
<p>Open the <code>jwks_uri</code> and you will see the public keys:</p>
<pre><code class="language-json">{
  "keys": [
    { "kid": "key-new", "kty": "RSA", "alg": "RS256" },
    { "kid": "key-old", "kty": "RSA", "alg": "RS256" }
  ]
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/1e7dede4-1274-4ccc-8f61-2ab06b83df72.png" alt="" style="display:block;margin:0 auto" />

<h3>Why Is It an Array?</h3>
<p>Because companies change their private key sometimes. When they do, they do <strong>not</strong> delete the old public key. They keep it in the array.</p>
<p>Each token has a <code>kid</code> (key id) in its header. The service uses it to find the matching key. That way, old tokens still work, new tokens also work, and nothing breaks.</p>
<h3>What Happens Inside a Request?</h3>
<p>When you open YouTube while logged in:</p>
<ol>
<li>The service takes your token.</li>
<li>It goes to <code>/.well-known/openid-configuration</code> and finds the <code>jwks_uri</code>.</li>
<li>It downloads the public keys with a simple GET request.</li>
<li>It picks the key that matches the <code>kid</code>.</li>
<li>It checks the signature by itself.</li>
</ol>
<p>This is the whole point. The service does not ask the auth server again and again. No secret is shared, and no extra network hop is needed.</p>
<hr />
<h2>Step 6: Why Can't We Open the Authorization Endpoint?</h2>
<p>Try this. Copy the <code>authorization_endpoint</code> of a big company and open it. You will get an "invalid request" error.</p>
<p>But if you open YouTube, Maps or Drive, login works fine. Why?</p>
<p>Because OIDC is <strong>secure by default</strong>. Google's own apps are known and trusted. A stranger is not.</p>
<p>Your request fails because Google does not know who you are. It does not have your app registered, and it does not know where to send the user afterwards. It will not authenticate people for an unknown website.</p>
<p>It is the same with ChaiCode. If you log in once, you can move between MasterJi, TimeArena, SQL Labs and the courses without logging in again. They are all known to the provider. Outsiders are not.</p>
<p>That is great for security. But it creates a new question.</p>
<hr />
<h2>Step 7: What About Third-Party Apps?</h2>
<p>Let's say you are building an app called <a href="http://jingalala.com"><strong>jingalala.com</strong></a>.</p>
<p>Your first job is authentication. But building a really secure auth is hard. You have to save passwords safely, handle leaks, add two-factor, and stop bots. Usually it is not a good idea to do all this yourself.</p>
<p>Google already has a huge and secure auth system. So you think, "Why not take it from Google?"</p>
<ul>
<li>It is more secure than what I can build.</li>
<li>The user does not enter details again, because Google already has them.</li>
<li>The user does not need another password.</li>
</ul>
<p>This is called <strong>Single Sign-On (SSO)</strong>. One sign in, and you are signed in everywhere.</p>
<p>So <a href="http://jingalala.com">jingalala.com</a> wants to use Google's OIDC. But we just saw the problem. Google does not trust strangers, and <a href="http://jingalala.com">jingalala.com</a> is a stranger.</p>
<p>Google also wanted that other external services can use their auth for work. It wanted its auth to be a <strong>service</strong> for other apps. Other also want it to give as a service like Microsoft, LinkedIn and GitHub.</p>
<p>They needed a way to say, "This third-party app is trusted." That way is <strong>OAuth 2.0</strong>.</p>
<hr />
<h2>Step 8: OAuth 2.0 Makes a Stranger Trusted</h2>
<p><strong>1. Register your app.</strong> <a href="http://jingalala.com">jingalala.com</a> goes to the developer console and fills a form:</p>
<ul>
<li>application name</li>
<li>website URL</li>
<li>privacy policy and terms</li>
<li>what user data it needs</li>
<li>where it is hosted</li>
<li><strong>redirect URI:</strong> where to send the user after login, for example <code>https://jingalala.com/api/redirect-uri</code></li>
</ul>
<p><strong>2. Get your keys.</strong> Google checks the form and gives two things:</p>
<ul>
<li><strong>client_id:</strong> your app's public id.</li>
<li><strong>client_secret:</strong> your app's private password. Only your backend knows it.</li>
</ul>
<p>Now Google knows <a href="http://jingalala.com">jingalala.com</a>. It is a trusted source.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/7d9aa0cb-fa3c-40ac-bb9f-bbed0a5e6110.png" alt="" style="display:block;margin:0 auto" />

<p><strong>3. Use client_id in every request.</strong></p>
<pre><code class="language-plaintext">https://auth.example.com/authorize
  ?client_id=JINGALALA_CLIENT_ID
  &amp;redirect_uri=https://jingalala.com/api/redirect-uri
  &amp;response_type=code
  &amp;scope=openid email profile
</code></pre>
<p>Google uses the <code>client_id</code> to find your registered details. And that is how the user sees the familiar screen: <strong>"Do you want to continue with</strong> <a href="http://jingalala.com"><strong>jingalala.com</strong></a><strong>?"</strong> That text comes from the form you filled in.</p>
<p>A small correction people often miss: <code>client_id</code> is <strong>one per application</strong>, not per user. All users of <a href="http://jingalala.com">jingalala.com</a> use the same <code>client_id</code>, but another app has a different one.</p>
<p>If you remove the <code>client_id</code> from the URL, the request fails.</p>
<p><strong>What if the client_id leaks?</strong> It is not a secret, so no big problem. Google will only send users back to the redirect URI you registered. Nobody can use your <code>client_id</code> to send users to their own website.</p>
<hr />
<h2>Step 9: Never Send the Token Through the Browser</h2>
<p>After login, Google has to send the user back to <a href="http://jingalala.com">jingalala.com</a>. What if it sends the token in that redirect?</p>
<p>That is dangerous. The browser can show the token in the network tab, save it in history, or leak it through an extension. Anyone who gets it can act as the user.</p>
<p>So Google gives a <strong>short code</strong> instead. It lives for a very short time (usually 1min), and it is useless on its own.</p>
<hr />
<h2>Step 10: The Complete Flow, From Click to Logged In</h2>
<p>Now we put everything together. Let's follow one real login on <a href="http://jingalala.com">jingalala.com</a>, step by step. We will see which URL is called, who calls it, and what comes back.</p>
<hr />
<h3>1. Find the Addresses (done once)</h3>
<p><a href="http://jingalala.com">jingalala.com</a>'s backend does not know where Google's login page or token page is. So it asks the discovery address, which every OIDC provider has:</p>
<pre><code class="language-plaintext">GET https://accounts.google.com/.well-known/openid-configuration
</code></pre>
<p>Google replies with the JSON we saw earlier. The backend picks out the four addresses it needs:</p>
<ul>
<li><code>authorization_endpoint</code>: where to send the user to log in</li>
<li><code>token_endpoint</code>: where to exchange the code</li>
<li><code>userinfo_endpoint</code>: where to ask for the profile</li>
<li><code>jwks_uri</code>: where the public keys are</li>
</ul>
<p>The backend saves these and does not ask again every time. Normally this happens once, when the server starts.</p>
<hr />
<h3>2. The User Clicks the Button</h3>
<p>The user clicks <strong>"Login with Google"</strong> on <a href="http://jingalala.com">jingalala.com</a>.</p>
<hr />
<h3>3. Redirect to Google's Login Page</h3>
<p><a href="http://jingalala.com">jingalala.com</a> sends the user's browser to the <code>authorization_endpoint</code> from point 1, with its details in the URL:</p>
<pre><code class="language-plaintext">https://accounts.google.com/o/oauth2/v2/auth
  ?client_id=JINGALALA_CLIENT_ID                          (who is asking)
  &amp;redirect_uri=https://jingalala.com/api/redirect-uri    (where to come back)
  &amp;response_type=code                                     (give me a short code)
  &amp;scope=openid email profile                             (what data I want)
  &amp;state=RANDOM_STRING                                    (protects against fake requests)
</code></pre>
<p>The <code>scope</code> is important. It decides what user data we are allowed to receive:</p>
<ul>
<li><code>openid</code>: required. It tells the provider "this is a login, give me an ID Token".</li>
<li><code>profile</code>: name, picture and similar details.</li>
<li><code>email</code>: email address and whether it is verified.</li>
</ul>
<hr />
<h3>4. The User Logs In on Google</h3>
<p>Google checks the <code>client_id</code> and the <code>redirect_uri</code> against what <a href="http://jingalala.com">jingalala.com</a> registered. If they match, it shows its own login page. Then it shows the screen: <strong>"Continue with</strong> <a href="http://jingalala.com"><strong>jingalala.com</strong></a><strong>? It will see your name, email and picture."</strong></p>
<p>The user types the password <strong>on Google's page</strong>. <a href="http://jingalala.com">jingalala.com</a> never sees it.</p>
<hr />
<h3>5. Google Sends the User Back With a Code</h3>
<p>Google redirects the browser to the <code>redirect_uri</code>, with a short code in the URL:</p>
<pre><code class="language-plaintext">https://jingalala.com/api/redirect-uri?code=SHORT_CODE&amp;state=RANDOM_STRING
</code></pre>
<p>Our backend first checks that <code>state</code> is the same value it sent in point 3. Then it takes the code.</p>
<p>The code is not the token. It lives for a very short time (usually a minute or less), can be used only once, and is useless without the client secret.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/aaabca6e-4212-4ea9-828a-8db3359e4d25.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>6. The Backend Exchanges the Code (Server to Server)</h3>
<p>Now <a href="http://jingalala.com">jingalala.com</a>'s <strong>backend</strong> calls Google's <code>token_endpoint</code> directly. The browser is not part of this call:</p>
<pre><code class="language-plaintext">POST https://oauth2.googleapis.com/token

grant_type    = authorization_code
code          = SHORT_CODE
client_id     = JINGALALA_CLIENT_ID
client_secret = JINGALALA_CLIENT_SECRET     (only the backend knows this)
redirect_uri  = https://jingalala.com/api/redirect-uri
</code></pre>
<p>Google checks the code and the secret. If everything is correct, it replies:</p>
<pre><code class="language-plaintext">id_token      = eyJhbGciOi...    (who the user is)
access_token  = ya29.a0Af...     (to call Google's APIs for the user)
expires_in    = 3600
</code></pre>
<hr />
<h3>7. The Backend Verifies the ID Token</h3>
<p>The <code>id_token</code> is a JWT, signed by Google with its <strong>private key</strong>. Our backend must not trust it blindly. It checks:</p>
<ol>
<li>It calls the <code>jwks_uri</code> from point 1 and downloads Google's <strong>public keys</strong>.</li>
<li>It picks the key that matches the <code>kid</code> in the token header.</li>
<li>It verifies the <strong>signature</strong>. This proves the token was really made by Google and nobody changed it.</li>
<li>It checks <code>iss</code>: was it issued by Google?</li>
<li>It checks <code>aud</code>: is it meant for <strong>our</strong> <code>client_id</code>?</li>
<li>It checks <code>exp</code>: is it still not expired?</li>
</ol>
<p>If any check fails, the login is rejected.</p>
<hr />
<h3>8. Read the User's Details</h3>
<p>After verification, the data inside the ID Token can be trusted. The payload looks like this:</p>
<pre><code class="language-json">{
  "iss": "https://accounts.google.com",
  "aud": "JINGALALA_CLIENT_ID",
  "sub": "110169484474386276334",
  "name": "Abdul Rahman",
  "given_name": "Abdul",
  "family_name": "Rahman",
  "email": "abdul@gmail.com",
  "email_verified": true,
  "picture": "https://lh3.googleusercontent.com/...",
  "iat": 1790000000,
  "exp": 1790003600
}
</code></pre>
<p>What each one means:</p>
<ul>
<li><code>sub</code>: the user's unique id at Google. It never changes, so this is the safest id to save in your database.</li>
<li><code>name</code>, <code>given_name</code>, <code>family_name</code>, <code>picture</code>: come from the <code>profile</code> scope.</li>
<li><code>email</code>, <code>email_verified</code>: come from the <code>email</code> scope.</li>
<li><code>iss</code>, <code>aud</code>, <code>iat</code>, <code>exp</code>: who issued it, who it is for, when it was issued, and when it expires.</li>
</ul>
<p>If you need more details than the token has, the backend can call the <code>userinfo_endpoint</code> and send the <code>access_token</code> with it. Google replies with the user's profile.</p>
<hr />
<h3>9. Create Your Own Session</h3>
<p>Now Google's job is done. <a href="http://jingalala.com">jingalala.com</a> does its own work:</p>
<ol>
<li>It looks in its database for a user with this <code>sub</code> (or email).</li>
<li>If there is no user, it creates one with the name, email and picture.</li>
<li>It creates <strong>its own</strong> session or JWT and sends it to the browser in a secure cookie.</li>
</ol>
<p>From now on, the user talks to <a href="http://jingalala.com">jingalala.com</a> with jingalala's own cookie. Google is not needed for every request.</p>
<p>The user is logged in, and <a href="http://jingalala.com">jingalala.com</a> never saw or stored a password.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/8564388d-7dad-4dfb-a8a8-8b21d07dd0e5.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>So What Is the Difference?</h2>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/fa366d3c-612e-4c0c-bf2c-521589896422.png" alt="" style="display:block;margin:0 auto" />

<ul>
<li><strong>OIDC = Authentication.</strong> It answers: "Who is this user?" For example: "This is Abdul Rahman, and this is his email." It gives us the discovery document, the ID Token and the keys.</li>
<li><strong>OAuth 2.0 = Authorization and trust.</strong> It answers: "What is this app allowed to do?" It lets outside apps be trusted to use the OIDC endpoints, with <code>client_id</code>, <code>client_secret</code> and the code exchange.</li>
</ul>
<p>(In real history OAuth 2.0 came first and OIDC was built on top of it. But this is how the two ideas fit together in practice.)</p>
<p>The three players in every login:</p>
<ul>
<li><strong>Identity Provider:</strong> Google, GitHub, Auth0. It authenticates the user.</li>
<li><strong>Relying Party:</strong> your backend. It trusts the provider.</li>
<li><strong>End User:</strong> the person using your app.</li>
</ul>
<hr />
<h2>Why It Is Worth It</h2>
<ul>
<li><strong>No passwords to store.</strong> You do not hash or save them, so a leak on your side is much less dangerous.</li>
<li><strong>Same profile format.</strong> Every provider gives user data in the same claim format.</li>
<li><strong>Single Sign-On.</strong> One login works across many apps.</li>
<li><strong>Security is handled for you.</strong> Two-factor and bot protection are done by the provider.</li>
</ul>
<hr />
<h2>What Your Library Does for You</h2>
<p>When you use Auth.js, Clerk, Auth0 or Okta, you only paste a <code>client_id</code> and a <code>client_secret</code>. Now you know what they do behind the scenes:</p>
<ul>
<li>read the discovery document</li>
<li>redirect the user to the login page</li>
<li>take the code and exchange it with the secret</li>
<li>fetch the public keys and verify the ID Token</li>
<li>create a session Pasting the id and secret is the last and easiest part. The real engineering is everything above.</li>
</ul>
<p>Next time you see "Sign in with Google", you will know what really happens behind the button.</p>
<p>If you read this and understood it, you are already ahead of those who just skipped the article. Thanks for Reading .</p>
<hr />
<p><strong>About the author</strong></p>
<p>I'm Abdul Rahman, a full stack developer and CS student. I write about software engineering.</p>
<ul>
<li>Portfolio: <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a></li>
<li>Blog: <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></li>
<li>GitHub: <a href="https://github.com/abdulrdeveloper">abdulrdeveloper</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[From Bytes to the Cloud: How Node.js Reads, Validates and Uploads Files]]></title><description><![CDATA[Learn how Node.js handles files: fs module, Buffer, magic bytes, Multer validation and cloud storage with Cloudinary and ImageKit.]]></description><link>https://blog.abdulrdeveloper.me/nodejs-file-upload-fs-buffer-multer</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/nodejs-file-upload-fs-buffer-multer</guid><category><![CDATA[Node.js]]></category><category><![CDATA[backend]]></category><category><![CDATA[multer]]></category><category><![CDATA[filesystem]]></category><category><![CDATA[abdulrdeveloper]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Sat, 31 Oct 2026 11:13:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/be3e0790-7d9c-44bd-be99-a29e2165ba4a.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Almost every real application works with files. A user uploads a profile picture, an app saves a PDF, a server reads a config file, a report is written to the disk.</p>
<p>But what is a file for a backend? How does Node.js read it? How do we know that an uploaded file is really an image? And where should we keep it after the upload?</p>
<p>In this blog, we will follow the journey of a file step by step: the <code>fs</code> module, <code>Buffer</code>, Multer, file validation, and cloud storage.</p>
<hr />
<h2>What is a File?</h2>
<p>For a computer, every file is just a long list of <strong>bytes</strong>. A text file, a photo, a PDF and a video are all bytes. The only difference is how those bytes are arranged.</p>
<p>That`s why Node.js needs a way to hold raw bytes in memory. That tool is called a <strong>Buffer</strong>.We will discuss about buffer but first, let`s see how Node.js reads and writes files.</p>
<hr />
<h2>The <code>fs</code> Module</h2>
<p><code>fs</code> stands for <strong>file system</strong>. It is built into Node.js, so we do not need to install anything.</p>
<pre><code class="language-javascript">import fs from 'node:fs';
</code></pre>
<p>It can create, read, update, rename, copy and delete files and folders. Every operation comes in three styles: <strong>synchronous</strong>, <strong>callback</strong> and <strong>promise</strong>.</p>
<table>
<thead>
<tr>
<th>Action</th>
<th>Sync</th>
<th>Promise</th>
</tr>
</thead>
<tbody><tr>
<td>Write a file</td>
<td><code>writeFileSync</code></td>
<td><code>writeFile</code></td>
</tr>
<tr>
<td>Read a file</td>
<td><code>readFileSync</code></td>
<td><code>readFile</code></td>
</tr>
<tr>
<td>Add to a file</td>
<td><code>appendFileSync</code></td>
<td><code>appendFile</code></td>
</tr>
<tr>
<td>Create a folder</td>
<td><code>mkdirSync</code></td>
<td><code>mkdir</code></td>
</tr>
<tr>
<td>Rename</td>
<td><code>renameSync</code></td>
<td><code>rename</code></td>
</tr>
<tr>
<td>Copy</td>
<td><code>cpSync</code></td>
<td><code>cp</code></td>
</tr>
<tr>
<td>Delete a file</td>
<td><code>unlinkSync</code></td>
<td><code>unlink</code></td>
</tr>
<tr>
<td>Delete a file or a folder</td>
<td><code>rmSync</code></td>
<td><code>rm</code></td>
</tr>
</tbody></table>
<hr />
<h3><strong>1. Synchronous</strong></h3>
<pre><code class="language-javascript">import fs from 'node:fs';

fs.writeFileSync('test.txt', 'Hello');

const data = fs.readFileSync('test.txt', 'utf-8');
console.log(data); // Hello

fs.mkdirSync('myFolder/innerFolder', { recursive: true }); // creates the parent folders too
fs.rmSync('myFolder', { recursive: true, force: true });   // deletes a folder with everything inside
</code></pre>
<p>Synchronous functions <strong>block</strong> the program. Node.js waits until the work is finished, and nothing else can run in that time. This is fine for small scripts and for work at the start of a program. But on a server, one slow file read can freeze the requests of all other users.</p>
<hr />
<h3>2. Callbacks</h3>
<p>The asynchronous version does not block. We give it a function, and Node.js calls it when the work is finished.</p>
<pre><code class="language-javascript">import fs from 'node:fs';

fs.readFile('b.txt', 'utf-8', (err, data) =&gt; {
  if (err) return console.log(err);

  fs.writeFile('c.txt', data, (err) =&gt; {
    if (err) return console.log(err);

    fs.appendFile('c.txt', '\nDone', (err) =&gt; {
      if (err) return console.log(err);

      fs.unlink('b.txt', (err) =&gt; {
        if (err) return console.log(err);
        console.log('b.txt deleted');
      });
    });
  });
});
</code></pre>
<p>This works, but look at the shape of the code. Every next step goes one level deeper, and error handling is repeated at every level. This pyramid is known as <strong>callback hell</strong>.</p>
<hr />
<h3>3. Promises</h3>
<p>The same work with <code>node:fs/promises</code> and <code>async/await</code>:</p>
<pre><code class="language-javascript">import fs from 'node:fs/promises';

try {
  const data = await fs.readFile('b.txt', 'utf-8');
  await fs.writeFile('c.txt', data);
  await fs.appendFile('c.txt', '\nDone');
  await fs.unlink('b.txt');
  console.log('b.txt deleted');
} catch (err) {
  console.log('Something went wrong:', err.message);
}
</code></pre>
<p>The code is flat, it reads from top to bottom, and one <code>try/catch</code> handles all errors. It is also non-blocking. This is the style we use in modern projects. (Top-level <code>await</code> works in ES modules, so set <code>"type": "module"</code> in your <code>package.json</code>.)</p>
<p><strong>Which one to use?</strong> Use the promise style inside servers and request handlers. Use the sync style only in small scripts or at startup, never while handling requests.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/fd9556f9-f34f-4fdf-8691-f4713667f5c7.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Buffer</h2>
<p>A <strong>Buffer</strong> is a fixed-size block of memory that holds raw bytes. In Node.js, it is a special kind of <code>Uint8Array</code>, and it is stored outside the normal JavaScript heap.</p>
<p>Why do we need it? Strings are for text. But files, network data and streams are made of bytes, and many of them are not text at all (like a photo). A Buffer is the way to hold and work with them.</p>
<pre><code class="language-javascript">const buf = Buffer.from('Hi');

console.log(buf);            // &lt;Buffer 48 69&gt;
console.log(buf.toString()); // Hi
</code></pre>
<p><code>48</code> and <code>69</code> are the bytes for the letters <code>H</code> and <code>i</code>, written in hexadecimal.</p>
<p>We can also decide how bytes are shown as text. This is called an <strong>encoding</strong>:</p>
<pre><code class="language-javascript">const text = Buffer.from('Hello');

console.log(text.toString('hex'));    // 48656c6c6f
console.log(text.toString('base64')); // SGVsbG8=
</code></pre>
<h3>Reading a File Gives a Buffer</h3>
<p>If we do not give an encoding, <code>readFile</code> returns a Buffer:</p>
<pre><code class="language-javascript">import fs from 'node:fs/promises';

const data = await fs.readFile('photo.png'); // no encoding

console.log(data);        // &lt;Buffer 89 50 4e 47 ...&gt;
console.log(data.length); // size of the file in bytes
</code></pre>
<p>If we give <code>'utf-8'</code>, Node.js converts the bytes to a string. That is right for text files, but wrong for images.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/b13fcd7f-ff35-4207-8db8-ec1c9024bb73.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Buffers and Memory</h3>
<p>When we read a whole file with <code>readFile</code>, all of its bytes go into memory at once. For a small file, it is fine. For a file of 2 GB, it is a problem.</p>
<p>The solution is a <strong>stream</strong>. A stream reads the file in small pieces (chunks). Every chunk is a Buffer, and we can process it and move on:</p>
<pre><code class="language-javascript">import fs from 'node:fs';

const stream = fs.createReadStream('big-video.mp4');

stream.on('data', (chunk) =&gt; {
  console.log('Got a chunk of', chunk.length, 'bytes');
});
</code></pre>
<p>Streams are used when a file is uploaded to cloud storage, so the whole file never sits in memory.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/4dcc5131-c167-431b-b32d-20525af2b77c.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Magic Bytes: What a File Really Is</h2>
<p>A user uploads <code>avatar.png</code>. Is it really a PNG image? The file name can be changed by anyone. The <code>mimetype</code> is also sent by the client, so it can be faked.</p>
<p>The real answer is inside the file. Most file types start with a few special bytes called a <strong>file signature</strong> or <strong>magic bytes</strong>.</p>
<table>
<thead>
<tr>
<th>Type</th>
<th>First bytes (hex)</th>
</tr>
</thead>
<tbody><tr>
<td>PNG</td>
<td><code>89 50 4E 47</code></td>
</tr>
<tr>
<td>JPEG</td>
<td><code>FF D8 FF</code></td>
</tr>
<tr>
<td>GIF</td>
<td><code>47 49 46 38</code></td>
</tr>
<tr>
<td>PDF</td>
<td><code>25 50 44 46</code></td>
</tr>
</tbody></table>
<p>Now we use a Buffer to read just the first bytes of a file and compare them:</p>
<pre><code class="language-javascript">import { open } from 'node:fs/promises';

async function startsWith(filePath, signature) {
  const file = await open(filePath, 'r');

  try {
    const buffer = Buffer.alloc(signature.length);
    await file.read(buffer, 0, signature.length, 0); // read from position 0

    return signature.every((byte, i) =&gt; buffer[i] === byte);
  } finally {
    await file.close();
  }
}

const isPng = await startsWith('avatar.png', [0x89, 0x50, 0x4e, 0x47]);
console.log(isPng); // true only if the content is really a PNG
</code></pre>
<p>We read only a few bytes, not the whole file. Note that some formats need more bytes to be sure. For example, a WebP file starts with <code>RIFF</code>, but other formats start the same way, so its name <code>WEBP</code> at bytes 8 to 11 must be checked too.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/3d5b8ed8-d0a4-48dc-bebf-96c30d9060d0.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Multer</h2>
<p>When a user uploads a file from a form or an app, the browser sends it in a special format called <code>multipart/form-data</code>. Express cannot read this by default: <code>express.json()</code> and <code>express.urlencoded()</code> do not understand files.</p>
<p><strong>Multer</strong> is a middleware that reads <code>multipart/form-data</code>, saves the file, and gives us the file's details in <code>req.file</code>.</p>
<pre><code class="language-plaintext">npm install multer
</code></pre>
<hr />
<h3>Disk Storage vs Memory Storage</h3>
<p>Multer can keep the uploaded file in two places:</p>
<ul>
<li><code>diskStorage</code><strong>:</strong> Multer saves the file on the disk in a temporary folder. We get its location in <code>req.file.path</code>.</li>
<li><code>memoryStorage</code><strong>:</strong> Multer keeps the file in RAM. We get it as a Buffer in <code>req.file.buffer</code>.</li>
</ul>
<p>Memory storage is quick, but all uploads sit in RAM, so it is only good for small files. For bigger files, disk storage is safer.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/280c6e0c-5d1a-4d76-8f39-a123e8dc0b75.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Configuring Multer</h3>
<pre><code class="language-javascript">import multer from 'multer';
import path from 'node:path';

const storage = multer.diskStorage({
  destination: (req, file, cb) =&gt; cb(null, 'public/uploads'),
  filename: (req, file, cb) =&gt; {
    const unique = Date.now() + '-' + Math.round(Math.random() * 1e9);
    cb(null, file.fieldname + '-' + unique + path.extname(file.originalname));
  },
});

const fileFilter = (req, file, cb) =&gt; {
  const allowed = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];

  if (allowed.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('File type not supported'), false);
  }
};

export const upload = multer({
  storage,
  fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB
});
</code></pre>
<p>Let's understand each part:</p>
<ul>
<li><code>destination</code><strong>:</strong> the folder where the file is saved. When we write it as a function, the folder must already exist.</li>
<li><code>filename</code><strong>:</strong> the name of the saved file. We add the time and a random number, so two users who upload <code>photo.png</code> never overwrite each other. <code>path.extname</code> keeps the original extension.</li>
<li><code>fileFilter</code><strong>:</strong> decides whether a file is accepted or rejected.</li>
<li><code>limits</code><strong>:</strong> stops files that are too large.</li>
</ul>
<p>Now we use it in a route:</p>
<pre><code class="language-javascript">app.post('/upload', upload.single('avatar'), (req, res) =&gt; {
  // req.file has the details of the uploaded file
  res.status(201).json({ filename: req.file.filename, size: req.file.size });
});
</code></pre>
<p><code>upload.single('avatar')</code> accepts one file, and <code>'avatar'</code> must match the field name sent by the client. For many files, we use <code>upload.array('photos', 5)</code>.</p>
<p><code>req.file</code> has useful properties: <code>originalname</code>, <code>filename</code>, <code>path</code>, <code>mimetype</code> and <code>size</code> (in bytes).</p>
<hr />
<h2>Validate in Layers</h2>
<p>No single check is enough. A safe upload uses all of these layers:</p>
<ol>
<li><strong>File size limit</strong> (<code>limits</code>): stops very large files.</li>
<li><code>fileFilter</code><strong>:</strong> checks the declared <code>mimetype</code>. It is quick, but the client sends it, so it can be faked.</li>
<li><strong>Magic bytes:</strong> checks the real content of the file, as we did above.</li>
</ol>
<p>The first two layers reject obvious problems early, and the third layer checks what the file really is.</p>
<h2>Serving Files from the Server</h2>
<p>Files saved in <code>public/uploads</code> can be served with Express's static middleware:</p>
<pre><code class="language-javascript">app.use('/uploads', express.static('public/uploads'));
</code></pre>
<p>Now a file saved as <code>public/uploads/avatar-123.png</code> is available at <a href="http://localhost:3000/uploads/avatar-123.png"><code>http://localhost:3000/uploads/avatar-123.png</code></a>. We do not write any route for it.</p>
<p>This is fine while learning. In production, we usually do not keep files on the server's disk. Let's see why.</p>
<hr />
<h2>Cloud Storage: Cloudinary and ImageKit</h2>
<p>Keeping uploads on the server's own disk has real problems:</p>
<ul>
<li>On many hosting platforms, the disk is <strong>temporary</strong>. Files disappear when the server restarts or is redeployed.</li>
<li>If you run more than one server, each has its own disk, so a file uploaded to one is missing on the others.</li>
<li>The disk can get full, and serving big files makes your server slower.</li>
</ul>
<p>Services like <strong>Cloudinary</strong> and <strong>ImageKit</strong> solve this. They give us:</p>
<ul>
<li><strong>Storage:</strong> your files are saved safely outside your server.</li>
<li><strong>CDN:</strong> files are delivered from a location close to the user, so they load fast.</li>
<li><strong>Transformations:</strong> resize, compress or convert an image just by changing the URL, without saving many versions.</li>
</ul>
<p>The idea is the same in both. Our server sends the file to the service, either from the temporary file as a stream or from a Buffer in memory. The service saves it and sends back:</p>
<ul>
<li>a <strong>URL</strong> to show the file, and</li>
<li>a unique <strong>ID</strong> (<code>public_id</code> in Cloudinary, <code>fileId</code> in ImageKit).</li>
</ul>
<p>We must save both. The URL is for showing the file, and the ID is needed later to <strong>delete or replace</strong> it.</p>
<hr />
<h2>Saving File Details in the Database</h2>
<p>The cloud keeps the file, and our database keeps the <strong>details</strong> about it. A good record has:</p>
<ul>
<li><code>originalName</code>: the name the user uploaded</li>
<li><code>filename</code>: the saved name</li>
<li><code>url</code>: where to find it</li>
<li><code>size</code>: in bytes, as a number</li>
<li><code>mimetype</code></li>
<li><code>storageType</code>: local or cloud</li>
<li><code>fileId</code>: the ID from the cloud service</li>
</ul>
<hr />
<h2>Cleaning Up Temporary Files</h2>
<p>When Multer saves a file on the disk, that is only a <strong>temporary</strong> copy. After the file is uploaded to the cloud, we must delete it. And we must delete it even when something fails, otherwise the disk fills with unused files.</p>
<p>The <code>finally</code> block is perfect for this:</p>
<pre><code class="language-javascript">import { unlink } from 'node:fs/promises';

app.post('/upload-cloud', upload.single('avatar'), async (req, res, next) =&gt; {
  try {
    // check the magic bytes of req.file.path
    // upload the temporary file to the cloud storage
    // save the url and the ID in the database
    res.status(201).json({ message: 'File uploaded' });
  } catch (error) {
    next(error);
  } finally {
    await unlink(req.file.path).catch(() =&gt; {}); // always delete the temporary file
  }
});
</code></pre>
<p>The same rule is true for deleting. When a file record is deleted, we also delete the real file: from the disk with <code>unlink</code>, or from the cloud using its saved ID. Otherwise, the file stays in storage forever with nothing pointing to it.</p>
<hr />
<h2>The Complete Flow</h2>
<ol>
<li>The client sends the file in a <code>multipart/form-data</code> request.</li>
<li>Multer checks the size and the type, and saves a temporary file.</li>
<li>We check the magic bytes of the file.</li>
<li>We upload the file to the cloud storage.</li>
<li>The cloud storage returns the URL and the ID.</li>
<li>We save the details in the database.</li>
<li>We delete the temporary file.</li>
<li>We send the response to the client.</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/6cf43c79-f284-4553-a806-320ee623fea3.png" alt="" style="display:block;margin:0 auto" />

<h2>Common Mistakes</h2>
<ul>
<li><strong>Using sync functions inside request handlers.</strong> They block the server for everyone.</li>
<li><strong>Trusting the file name or</strong> <code>mimetype</code><strong>.</strong> Both can be faked. Check the magic bytes too.</li>
<li><strong>No file size limit.</strong> Anyone can upload a huge file.</li>
<li><strong>Reading big files with</strong> <code>readFile</code><strong>.</strong> Use streams for large files.</li>
<li><strong>Forgetting to delete temporary files.</strong> Use <code>finally</code> so cleanup always happens.</li>
<li><strong>Saving only the URL.</strong> Save the cloud ID too, or you cannot delete the file later.</li>
<li><strong>Keeping uploads on the server's disk in production.</strong> Use cloud storage.</li>
</ul>
<hr />
<p>The complete project of this blog is on GitHub: <a href="https://github.com/abdulrdeveloper/FullStackHub/tree/main/backend%20best%20collection/chai-aur-filesystem">chai-aur-filesystem</a></p>
<p>You can find more of my work at <a href="http://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="http://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Authentication vs Authorization: Who Are You, and What Can You Do?]]></title><description><![CDATA[Learn the difference between authentication and authorization in backend development with practical Node.js and Express.js middleware examples.]]></description><link>https://blog.abdulrdeveloper.me/authentication-vs-authorization-in-nodejs-express</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/authentication-vs-authorization-in-nodejs-express</guid><category><![CDATA[authentication]]></category><category><![CDATA[authorization]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[abdulrdeveloper]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Fri, 23 Oct 2026 10:55:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/307c7bc6-0c3f-4795-8974-451fcd56aa2e.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Many beginners ask this question: "Should I learn Node.js first, or should I learn authentication first?"</p>
<p>The answer is that <strong>authentication and authorization are not Node.js things</strong>. They are backend concepts, like routing or databases. The same ideas work in Node.js, Python, Java, PHP and every other backend language. Node.js and Express are just tools that we use to build them.</p>
<p>So first we understand the concept, and then we can build it in any language. In this blog, we will understand what authentication and authorization mean, how they are different, and how they work together in a real backend, using a simple example: a <strong>school result card</strong>.</p>
<hr />
<h2>Two Questions Every Backend Asks</h2>
<p>Every time a request comes to a protected part of your backend, the server asks two questions:</p>
<ol>
<li><strong>Who are you?</strong> This is <strong>authentication</strong>.</li>
<li><strong>What can you do?</strong> This is <strong>authorization</strong>.</li>
</ol>
<p>The order is always the same. First we find out who the user is, and only then we decide what that user is allowed to do.</p>
<hr />
<h2>What is Authentication?</h2>
<p><strong>Authentication</strong> means proving who you are. The server must be sure that you are really that user.</p>
<p>The most common proof is a password. In general, there are three kinds of proof:</p>
<ul>
<li><strong>Something you know:</strong> a password or a PIN.</li>
<li><strong>Something you have:</strong> a phone that receives an OTP, or an ID card.</li>
<li><strong>Something you are:</strong> a fingerprint or a face scan.</li>
</ul>
<p>When we use two of these together (for example, a password and an OTP), it is called <strong>multi-factor authentication (MFA)</strong>, and it is much safer.</p>
<p>There are many ways to build login in a backend: passwords with sessions, JWT tokens, or login with Google. We covered JWT in the last blog. In this blog, we only need to know one thing: after authentication, the server knows <strong>who the user is</strong>.</p>
<hr />
<h2>What is Authorization?</h2>
<p><strong>Authorization</strong> means deciding what an authenticated user is allowed to do.</p>
<p>Logging in does not mean you can do everything. A student and a teacher can both log in to the same school system, but they are not allowed to do the same things.</p>
<p>Authorization usually works in two ways:</p>
<ul>
<li><strong>Roles:</strong> the user has a role like <code>student</code>, <code>teacher</code> or <code>admin</code>, and each role has its own permissions.</li>
<li><strong>Ownership:</strong> the user can only access <strong>their own</strong> data. A student can see only their own result.</li>
</ul>
<hr />
<h2>Example: The Result Card</h2>
<p>Let`s use a school system with three users: a student, a teacher and an admin. They all log in, so all of them are authenticated. But they are authorized differently:</p>
<table>
<thead>
<tr>
<th>Action</th>
<th>Student</th>
<th>Teacher</th>
<th>Admin</th>
</tr>
</thead>
<tbody><tr>
<td>View own result</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>View other students' results</td>
<td>No</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Edit marks</td>
<td>No</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Delete a result</td>
<td>No</td>
<td>No</td>
<td>Yes</td>
</tr>
</tbody></table>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/5af02f0a-6312-4828-ac45-4fea9e959540.png" alt="" style="display:block;margin:0 auto" />

<p>All three users prove who they are in the same way. The difference comes after that, in what each of them is allowed to do.</p>
<hr />
<h2>Authentication vs Authorization</h2>
<p>Remember the status codes: <code>401</code> means "we do not know who you are", and <code>403</code> means "we know who you are, but you are not allowed".</p>
<hr />
<h2>How They Work Together in a Request</h2>
<p>In a real backend, every protected request passes through these steps:</p>
<ol>
<li>The request comes in with a token.</li>
<li><strong>Authenticate:</strong> the server verifies the token and finds out who the user is. If this fails, the answer is <code>401</code>.</li>
<li><strong>Authorize:</strong> the server checks the user's role or ownership. If this fails, the answer is <code>403</code>.</li>
<li>The route handler runs and sends the response.</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/f15299a1-93f3-4ef5-9a90-9fc289237090.png" alt="" style="display:block;margin:0 auto" />

<p>This is exactly a pipeline of middlewares, and each step does one small job.</p>
<hr />
<h2>Building It in Express</h2>
<p>Let's build the result card rules. First, we need an authentication middleware. Its job is to find out who the user is and save it in <code>req.user</code>, so every next step can use it.</p>
<pre><code class="language-javascript">function verifyToken(req, res, next) {
  // read the token from the request
  // verify the token (for example, with a JWT library)
  // if the token is missing or invalid:
  // return res.status(401).json({ error: 'You are not logged in' });

  req.user = { id: 12, role: 'student' }; // data taken from the token
  next();
}
</code></pre>
<p>After this middleware, <code>req.user</code> holds the user`s <code>id</code> and <code>role</code>. Now we can build authorization as the next step of it.</p>
<hr />
<h3>Authorization by Role</h3>
<p>We create a middleware that returns a middleware, so we can reuse it for any role:</p>
<pre><code class="language-javascript">function requireRole(...roles) {
  return (req, res, next) =&gt; {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ error: 'You do not have permission' });
    }
    next();
  };
}
</code></pre>
<p>Now we protect the routes:</p>
<pre><code class="language-javascript">// Teacher or admin can edit marks
app.put('/results/:id', verifyToken, requireRole('teacher', 'admin'), (req, res) =&gt; {
  // update the marks in the database
  res.status(200).json({ message: 'Marks updated' });
});

// Only admin can delete a result
app.delete('/results/:id', verifyToken, requireRole('admin'), (req, res) =&gt; {
  // delete the result from the database
  res.status(204).end();
});
</code></pre>
<p>The order is important , <code>verifyToken</code> runs first and sets <code>req.user</code>, then <code>requireRole</code> reads it.</p>
<h3>Authorization by Ownership</h3>
<p>A role is not enough for viewing a result. A student can view a result, but only <strong>their own</strong>. So we also check who owns the result:</p>
<pre><code class="language-javascript">app.get('/results/:id', verifyToken, (req, res) =&gt; {
  // get the result from the database using req.params.id
  const result = { id: req.params.id, studentId: 12 }; // imagine this came from the database

  const isOwner = result.studentId === req.user.id;
  const isStaff = req.user.role === 'teacher' || req.user.role === 'admin';

  if (!isOwner &amp;&amp; !isStaff) {
    return res.status(403).json({ error: 'You can only view your own result' });
  }

  res.status(200).json(result);
});
</code></pre>
<p>Here, a student with id <code>12</code> can open their own result. If the student changes the id in the URL to see someone else's result, the server returns <code>403</code>.</p>
<h2>Things to avoide as a best practice:</h2>
<ul>
<li><strong>Mixing :</strong> a user who is logged in is not automatically allowed to do everything. Always check authorization after authentication.</li>
<li><strong>Hiding buttons only on the frontend:</strong> if the edit button is hidden, the API is still open. Anyone can send the request with Postman. Always check on the server.</li>
<li><strong>Trusting the user id from the request body or the URL:</strong> take the user`s identity from the verified token (<code>req.user</code>), not from what the client sends.</li>
<li><strong>Skipping the ownership check:</strong> if a user can change an id in the URL and see another person`s data, it is a serious security bug. It is known as <strong>broken access control</strong>.</li>
<li><strong>Storing plain passwords:</strong> always hash passwords before saving them in the database so that in case of db leak, the hacker or any attacker still can`t get the password .</li>
<li><strong>Giving too much power by default:</strong> give every user the lowest role, and give more permissions only when needed.</li>
</ul>
<hr />
<h2>Some Points to note down :</h2>
<ul>
<li>Authentication and authorization are backend concepts. They are not limited to Node.js.</li>
<li>Authentication answers "Who are you?". Authorization answers "What can you do?".</li>
<li>Authentication always comes first, and authorization comes after it.</li>
<li>Authentication fails with <code>401</code>, authorization fails with <code>403</code>.</li>
<li>Authorization works through roles and ownership.</li>
<li>In Express, both are middlewares: <code>verifyToken</code> for authentication, <code>requireRole</code> and an ownership check for authorization.</li>
<li>Always check on the server. Never trust the frontend.</li>
</ul>
<p><strong>logging in proves who you are, but it does not give you permission to do everything.</strong></p>
<hr />
<p>You can find more of my work at <a href="http://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="http://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Your Server Has Amnesia. JWT Is the Cure.]]></title><description><![CDATA[Learn JWT authentication in Node.js: token structure, login flow, protecting routes with middleware, and access and refresh tokens, explained simply.]]></description><link>https://blog.abdulrdeveloper.me/jwt-authentication-nodejs-access-refresh-tokens</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/jwt-authentication-nodejs-access-refresh-tokens</guid><category><![CDATA[JWT]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Express.js]]></category><category><![CDATA[authentication]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[abdulrdeveloper]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Thu, 22 Oct 2026 08:30:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/1b3bcdfe-42e0-4b8d-a3ca-1216726d9e56.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>You log in to a website. You click on your profile. Then you click on your orders. And the website still knows who you are. It never asks for your password again.</p>
<p>It looks very normal, but it is not. By default, <strong>a server forgets you after every request</strong>. HTTP is stateless, so every request reaches the server like it is the first one, and the server has no memory of the last one.</p>
<p>So how does the server remember you? In this blog, we will understand what authentication means, what JWT is, how a token is built, and how to log in a user and protect routes in Node.js and Express.</p>
<hr />
<h2>What is Authentication?</h2>
<p><strong>Authentication</strong> means proving who you are. It answers one question: <em>"Who are you?"</em></p>
<p>A login form with an email and a password is the most common example. If the details are correct, the server accepts you as that user.</p>
<blockquote>
<p><em>Authentication is "who are you?". Authorization is "what are you allowed to do?". In this blog, we only focus on authentication.</em></p>
</blockquote>
<hr />
<h2>The Problem: Stateless Servers</h2>
<p>Let's say you log in successfully. Now you send a second request to <code>/profile</code>. The server has already forgotten the first one, so it has no idea that you just logged in.</p>
<p>We need a way for the client to <strong>prove itself on every request</strong>, without sending the password again and again. This is where a token comes in.</p>
<hr />
<h2>What is a JWT?</h2>
<p><strong>JWT</strong> stands for <strong>JSON Web Token</strong>. It is a small piece of text that the server gives you after login. You send it back with every request, and the server uses it to know who you are.</p>
<p>A JWT looks like this:</p>
<pre><code class="language-plaintext">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYyNDI2MjJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
</code></pre>
<p>It looks like random text, but it has a clear structure.</p>
<hr />
<h3>Stateless Authentication</h3>
<p>The most important idea of JWT is that the <strong>server does not need to store anything</strong>. All the information is inside the token, and the server only checks if the token is valid.</p>
<p>Think of it like an entry pass. The guard does not need to remember your face. He only checks if your pass is real.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/f9fa122f-923c-426b-ac65-eeb704169103.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Structure of a JWT</h2>
<p>A JWT has <strong>three parts</strong>, separated by dots:</p>
<pre><code class="language-plaintext">header.payload.signature
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/66de9fd0-ef2d-44e3-80f2-667feb906126.png" alt="" style="display:block;margin:0 auto" />

<h3>1. Header</h3>
<p>The header tells which algorithm is used to create the signature, and the type of token.</p>
<pre><code class="language-json">{
  "alg": "HS256",
  "typ": "JWT"
}
</code></pre>
<h3>2. Payload</h3>
<p>The payload holds the data, which are called <strong>claims</strong>. This is where we put things like the user's id.</p>
<pre><code class="language-json">{
  "id": 1,
  "iat": 1760000000,
  "exp": 1760000900
}
</code></pre>
<ul>
<li><code>id</code>: our own data, who the user is</li>
<li><code>iat</code>: issued at, when the token was created</li>
<li><code>exp</code>: expiry, when the token stops working</li>
</ul>
<hr />
<h3>3. Signature</h3>
<p>The signature is created from the header, the payload and a <strong>secret key</strong> that only the server knows. It makes sure that nobody has changed the token.</p>
<pre><code class="language-javascript">// jsonwebtoken does this for us automatically, we never write it ourselves
HMAC-SHA256( base64url(header) + "." + base64url(payload), secret )
</code></pre>
<ul>
<li><code>header</code> and <code>payload</code>: the first two parts of the token</li>
<li><code>secret</code>: a key that only the server knows</li>
<li><code>HMAC-SHA256</code>: the method that mixes them into one signature</li>
</ul>
<p>On every request, the server creates this signature again and compares it with the one in the token. If both are the same, the token is valid.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/ea3a4978-f389-4dbb-b0b4-b30fafa22519.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Encoded, Not Encrypted</h3>
<p>The header and payload of a JWT are only <strong>encoded</strong>. Encoding can be reversed, so anyone can decode them and read the data inside.</p>
<pre><code class="language-javascript">// encode
const encoded = Buffer.from('{"id":1}').toString('base64url');
console.log(encoded); // eyJpZCI6MX0

// decode: we get the same data back
const decoded = Buffer.from(encoded, 'base64url').toString();
console.log(decoded); // {"id":1}
</code></pre>
<ul>
<li>Encoding works in <strong>both directions</strong>.</li>
<li>No secret is needed to decode.</li>
<li>That is why we never put passwords or secrets in a JWT.</li>
</ul>
<h3>Why Nobody Can Fake It</h3>
<p>The signature is different. It is a <strong>hash</strong>, and a hash only works in <strong>one direction</strong>. We cannot go back from the signature to the original data.</p>
<pre><code class="language-javascript">HMAC-SHA256({"id":1}, secret)  →  a3f9c2...   // example value
HMAC-SHA256({"id":1}, secret)  →  a3f9c2...   // same input, same secret, same result
HMAC-SHA256({"id":2}, secret)  →  7be104...   // one change, a completely new result
</code></pre>
<ul>
<li>A hash <strong>cannot be reversed</strong>.</li>
<li>The same data and the same secret <strong>always give the same signature</strong>, so the server can check it easily.</li>
<li>If someone changes even one character in the payload, the signature no longer matches, and the server rejects the token.</li>
<li>Without the secret, nobody can create a valid signature.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/3ce639cd-bd81-4569-9375-be071944f09d.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Login Flow using JWT</h2>
<p>The complete flow has four steps:</p>
<ol>
<li>The user sends an email and a password to <code>/login</code>.</li>
<li>The server checks the details. If they are correct, it creates a JWT with <code>jwt.sign()</code>.</li>
<li>The server sends the token back to the client.</li>
<li>The client sends this token with every next request, and the server verifies it. Let's build it. First, install the packages:</li>
</ol>
<pre><code class="language-plaintext">npm install express jsonwebtoken
</code></pre>
<p>Keep the secret in a <code>.env</code> file. It should be a long random string, and it must never be pushed to GitHub:</p>
<pre><code class="language-javascript">JWT_SECRET=put_a_long_random_string_here

// As a good practice never generate secret key through websites , generate it from your terminal with command

node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
</code></pre>
<blockquote>
<p>Now the login route:</p>
</blockquote>
<pre><code class="language-javascript">import express from 'express';
import jwt from 'jsonwebtoken';
 
const app = express();
app.use(express.json());
 
app.post('/login', (req, res) =&gt; {
  const { email, password } = req.body;
 
  // find the user in the database using the email
  // compare the password with the hashed password in the database
  // if the user is not found or the password is wrong:
  // return res.status(401).json({ error: 'Invalid email or password' });
 
  const user = { id: 1, email }; // imagine this came from the database
 
  const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '15m' });
 
  res.status(200).json({ token });
});
</code></pre>
<p><code>jwt.sign()</code> takes three things: the payload, the secret and the options. Here, the token expires after 15 minutes.</p>
<hr />
<h2>Sending the Token with Requests</h2>
<p>After login, the client has the token. Now it must send this token with <strong>every request</strong>, so the server can know who is calling. There are two common ways.</p>
<h3>1. In the Authorization Header</h3>
<p>The client sends the token in the <code>Authorization</code> header. The standard format is <code>Bearer</code>, then a space, then the token:</p>
<pre><code class="language-plaintext">Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
</code></pre>
<p>From the frontend, it looks like this:</p>
<pre><code class="language-javascript">fetch('http://localhost:3000/profile', {
  headers: { Authorization: `Bearer ${token}` },
});
</code></pre>
<p>We send the token ourselves with every request. This way works for web apps, mobile apps and other servers, and it is easy to test in Postman. In this blog, we use this way.</p>
<h3><strong>2. In a Cookie</strong></h3>
<p>For <strong>web apps</strong>, the recommended way is a <strong>cookie</strong>. The server sets it after login, and the browser sends it automatically with every request:</p>
<pre><code class="language-javascript">res.cookie('token', token, {
  httpOnly: true,     // JavaScript in the browser cannot read it
  secure: true,       // sent only over HTTPS
  sameSite: 'strict', // helps to protect against CSRF
});
</code></pre>
<ul>
<li>The browser sends the cookie for us.</li>
<li>With <code>httpOnly</code>, JavaScript cannot read it, so a stolen script cannot steal the token.</li>
</ul>
<p>Mobile apps do not use the browser's cookies in the same way, so they use the header and keep the token in the device's secure storage.</p>
<p>Both ways have their own good and bad sides.</p>
<hr />
<h2>Protecting Routes using Tokens</h2>
<p>Now we need a guard in front of our private routes. This is a perfect job for a <strong>middleware</strong>, which we already learned in the middleware blog.</p>
<pre><code class="language-javascript">function verifyToken(req, res, next) {
  const authHeader = req.headers.authorization; // "Bearer &lt;token&gt;"
  const token = authHeader?.split(' ')[1];
 
  if (!token) {
    return res.status(401).json({ error: 'No token provided' });
  }
 
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET);
    req.user = payload; // now every next step can use req.user
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid or expired token' });
  }
}
</code></pre>
<p><code>jwt.verify()</code> checks the signature and the expiry for us. If anything is wrong, it throws an error, and we return <code>401</code>.</p>
<p>Now we put it before the private route:</p>
<pre><code class="language-javascript">app.get('/profile', verifyToken, (req, res) =&gt; {
  // get the user from the database using req.user.id
  res.json({ message: `Hello user ${req.user.id}` });
});
 
app.listen(3000, () =&gt; console.log('Server running on port 3000'));
</code></pre>
<p>If the token is valid, the request reaches the route handler. If not, it stops at the middleware.</p>
<hr />
<h2>Token Validation Lifecycle</h2>
<p>Every time a request comes to a protected route, the token goes through these checks:</p>
<ol>
<li><strong>Is there a token?</strong> If not, <code>401</code>.</li>
<li><strong>Is the signature valid?</strong> If someone changed the token, <code>401</code>.</li>
<li><strong>Is it expired?</strong> If the <code>exp</code> time has passed, <code>401</code>.</li>
<li><strong>All good:</strong> the payload is saved in <code>req.user</code>, and the request moves forward.</li>
</ol>
<hr />
<h2>What if the Token is Stolen?</h2>
<p>A JWT works like a pass: whoever holds it is treated as the user. If someone steals the token, they can use it until it expires. And the server cannot cancel a token before its expiry, because it does not store anything.</p>
<p>We can keep the token's life very short, like 15 minutes. But then the user would have to log in again every 15 minutes. The solution is to use <strong>two tokens</strong>.</p>
<h3>Access Token and Refresh Token</h3>
<ul>
<li><strong>Access token:</strong> short life (for example, 15 minutes). It is sent with every request.</li>
<li><strong>Refresh token:</strong> long life (for example, 7 days). It is saved in the database, and it is used only to get a new access token when the old one expires.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/537ece54-2ae0-4a55-9c0f-8ad3b55f68e5.png" alt="" style="display:block;margin:0 auto" />

<blockquote>
<p>Here is how the flow works:</p>
</blockquote>
<ol>
<li>The user logs in, and the server sends <strong>both</strong> tokens.</li>
<li>The client sends the access token with every request.</li>
<li>After 15 minutes, the access token expires, and the server returns <code>401</code>.</li>
<li>The client sends the refresh token to <code>/refresh</code>.</li>
<li>The server checks that the refresh token is valid and exists in the database, and sends a <strong>new access token</strong>.</li>
<li>When the user logs out, the server deletes the refresh token from the database.</li>
</ol>
<p>From now on, we use two secrets in <code>.env</code>:</p>
<ul>
<li><code>ACCESS_SECRET</code></li>
<li><code>REFRESH_SECRET</code>.</li>
</ul>
<p>The <code>verifyToken</code> middleware stays the same, but it now uses <code>ACCESS_SECRET</code>.</p>
<blockquote>
<p>At login, we create both tokens:</p>
</blockquote>
<pre><code class="language-javascript">const accessToken = jwt.sign({ id: user.id }, process.env.ACCESS_SECRET, { expiresIn: '15m' });
const refreshToken = jwt.sign({ id: user.id }, process.env.REFRESH_SECRET, { expiresIn: '7d' });

// save the refreshToken in the database

res.status(200).json({ accessToken, refreshToken });
</code></pre>
<p>The <code>/refresh</code> route gives a new access token:</p>
<pre><code class="language-javascript">app.post('/refresh', (req, res) =&gt; {
  const { refreshToken } = req.body;

  if (!refreshToken) {
    return res.status(401).json({ error: 'No refresh token provided' });
  }

  try {
    const payload = jwt.verify(refreshToken, process.env.REFRESH_SECRET);

    // check that this refresh token exists in the database
    // if it does not exist: return res.status(401).json({ error: 'Refresh token is not valid' });

    const accessToken = jwt.sign({ id: payload.id },          process.env.ACCESS_SECRET, { expiresIn: '15m' });
    res.status(200).json({ accessToken });
  } catch (err) {
    return res.status(401).json({ error: 'Invalid or expired refresh token' });
  }
});
</code></pre>
<p>And logout:</p>
<pre><code class="language-javascript">app.post('/logout', (req, res) =&gt; {
  // delete the refresh token from the database
  res.status(204).end();
});
</code></pre>
<p>Now if an access token is stolen, it works only for a few minutes. And if something goes wrong, the server can delete the refresh token from the database, so the user's session ends. This is how we cancel a session, even though a JWT itself cannot be cancelled.</p>
<hr />
<h3>Does the user have to log in again after 15 minutes?</h3>
<p>No. Only the access token expires after 15 minutes. The refresh token stays alive for 7 days, so the app uses it quietly to get a new access token. The user does not even notice it.</p>
<p>The refresh token ends only in three cases:</p>
<ul>
<li>The user <strong>logs out</strong>, and the server deletes it from the database.</li>
<li>The server <strong>revokes</strong> it, for example if it thinks the token was stolen.</li>
<li>The <strong>7 days are over</strong>, and the user has to log in again.</li>
</ul>
<p>This is why you stay logged in to many apps for days or weeks, for example your Google account. If you come back within the refresh token's life (24 hours, 7 days or whatever the app sets), you do not have to log in again. The app gets a new access token in the background, and you continue where you left off.</p>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Think Like a Factory: JavaScript Fundamentals That Actually Stick]]></title><description><![CDATA[Learn JavaScript fundamentals with a factory analogy: functions, if-else, loops, arrays, hoisting, map and forEach, explained in simple words.]]></description><link>https://blog.abdulrdeveloper.me/javascript-fundamentals-functions-loops-arrays</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/javascript-fundamentals-functions-loops-arrays</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[js]]></category><category><![CDATA[abdulrdeveloper]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Wed, 21 Oct 2026 07:46:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/ccfc1f40-c0e1-42cd-af98-7537f4d433e4.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let’s Go in deep dive of JS :</p>
<hr />
<p><strong>Main work in programming languages is this:</strong></p>
<ol>
<li><p><strong>What to do</strong> (identify the problem)</p>
</li>
<li><p><strong>How to do</strong> (implement the solution)</p>
</li>
</ol>
<hr />
<p>JavaScript is like a factory, in a factory :</p>
<ul>
<li><p>Some <strong>input</strong> is given and that input gets <strong>process</strong></p>
</li>
<li><p>There are some <strong>functions</strong> which are like rooms - input goes there, get process and come back to the <strong>main hall</strong>.</p>
</li>
</ul>
<hr />
<h2><strong>Example - Wood Factory :</strong></h2>
<p>There is a factory in which woods are coming:</p>
<ol>
<li><p>First of all the woods are <strong>cut</strong></p>
</li>
<li><p>Then they are <strong>polish</strong></p>
</li>
<li><p>Then <strong>cushion</strong> and <strong>carve</strong> is done</p>
</li>
<li><p>Every step is happening in a proper flow</p>
</li>
</ol>
<p>This complete process is handled by the factory <strong>manager</strong> :</p>
<ul>
<li><p>He receive the order</p>
</li>
<li><p>First he show it on the <strong>globally board</strong> (so everyone know about it)</p>
</li>
<li><p>Then manager send the work in a flow to every room of factory</p>
</li>
<li><p>First wood go to <strong>cutting room</strong> → then <strong>polish room</strong> → then <strong>carving room</strong></p>
</li>
<li><p>In this way the complete flow is running</p>
</li>
</ul>
<hr />
<h3><strong>Wood factory workflow diagram:</strong></h3>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1770538520070/36406531-0f26-47c0-89a6-a5423d13df91.png" alt="" />

<hr />
<h2><strong>JavaScript Also Work Exactly Like This :</strong></h2>
<ol>
<li><p>First of all we check the <strong>data types</strong></p>
</li>
<li><p>We save them on <strong>globally board</strong> (in variables) so we can use them later</p>
</li>
<li><p>We make small small <strong>functions</strong> (we can also call them rooms)</p>
<ul>
<li><p>They help us</p>
</li>
<li><p>Code is not <strong>overwrite</strong> (every function do its own work)</p>
</li>
<li><p>can be reuse, same as room we can send anything in any room and it come back after process</p>
</li>
<li><p>They help in processing every input</p>
</li>
</ul>
</li>
</ol>
<p>All this flow is managed by <strong>Call Stack</strong> (factory manager) - it decide which function will run when and in which order.</p>
<hr />
<h3><strong>JS Factory WorkFlow diagram:</strong></h3>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1770538709876/e8f9cc5a-79cb-4c0b-b896-688669d591c2.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Important Devtools in inspect:</h3>
<p>elements: for html/css</p>
<p>console : for js (can write any kind of valid js)</p>
<p>sources : for watching what is loading and from where</p>
<p>Network tab : for seeing if your browser is calling external APIs</p>
<p>performance tab : for measuring website performance.</p>
<hr />
<h2>Learn Function Here :</h2>
<p>A function does not care from where and what the data is coming, user, hard-coded, API, anything , it only knows that how to proceed the given input and return a result.</p>
<pre><code class="language-javascript">     let num1 = Number(prompt("Enter First Number: "));
       let num2 = Number(prompt("Enter Second Number: "));
        function sayhello(a,b){
            return a * b;
        }
        /* we give 2 numbers in function (those numbers are given by the user) */
        let finaloutput = sayhello(num1,num2);
        console.log(`Hello Dear , Your calculation is: ${finaloutput}`);

        /* it`s reuse of function, we give 2 numbers to the function by ourself */

        let userinput = sayhello(5,8);
        console.log(userinput);
</code></pre>
<hr />
<h2><strong>Ways to write Function:</strong></h2>
<h3>Function Declaration</h3>
<pre><code class="language-javascript">function sayhello() {
    return "Hello!";
}
let result = sayhello();
console.log(result);
</code></pre>
<h3><strong>Important Points:</strong></h3>
<ul>
<li><p>It <strong>start</strong> with <code>function</code> keyword</p>
</li>
<li><p>Function <strong>must have</strong> a name</p>
</li>
<li><p>We can call it directly</p>
</li>
<li><p><strong>Hoisting</strong> happen (means we can call it first, and define it later)</p>
</li>
</ul>
<hr />
<h3>Function Expression:</h3>
<pre><code class="language-javascript">const greet = function() {
    return "Hello!";
};
let result = greet();
console.log(result);
</code></pre>
<h3><strong>Important Points:</strong></h3>
<ul>
<li><p>We <strong>store the function in a variable</strong></p>
</li>
<li><p>Function has <strong>no name of its own</strong> (anonymous)</p>
</li>
<li><p>We call it using the variable name</p>
</li>
<li><p><strong>Semicolon</strong> (<code>;</code>) is recommended at the end</p>
</li>
<li><p>We use <code>const</code> or <code>let</code></p>
</li>
<li><p><strong>No hoisting</strong> (first we define it, then we call it)</p>
</li>
</ul>
<h3>Arrow Function :</h3>
<pre><code class="language-javascript">const greet = () =&gt; {     //just =&gt; added at the place of function
    return "Hello!";
};

// Short form (single line):
const greet = () =&gt; "Hello!";

let result = greet();
console.log(result);
</code></pre>
<p><strong>Arrow function</strong> is same as <strong>Function expression.</strong> It just replaced function into =&gt; this</p>
<h3>Important Points:</h3>
<ul>
<li><p><code>=&gt;</code> is used in place of <code>function</code> keyword</p>
</li>
<li><p>Everything else is same like Function Expression</p>
</li>
<li><p>Short form: if there is only one line return then remove <code>{}</code> and <code>return</code> .</p>
</li>
</ul>
<hr />
<h2>Learn If-else :</h2>
<pre><code class="language-javascript">let userage = Number(prompt(`Enter Your Age`));
    if(userage &lt;= 10){
        console.log(`you are a child`);
   }
    else if(18 &gt;= userage &amp;&amp; userage &gt; 10 ){
         console.log(`you are a teen`);
    }
    else if(20 &gt;= userage &amp;&amp; userage &gt; 18){
        console.log(`you are an adault`);
    }
    else if(40 &gt;= userage &amp;&amp; userage &gt; 20 ){
        console.log(`you are mature man .`);
    }
    else{
        console.log(`Best of luck , dear senior dev. `);
    }
</code></pre>
<hr />
<h2>For-Loop :</h2>
<pre><code class="language-javascript">let firstnumber = Number(prompt(`Enter Starting Number: `));
let lastnum = Number(prompt(`Enter Last Number: `));

for (let i = firstnumber; i &lt;= lastnum; i++) {
    console.log(i);
}
</code></pre>
<p>Always remember this, <code>i = 0 or i = firstnumber</code> it means here we add the exact starting number of the loop, from where it should start ,</p>
<ul>
<li><p>and in <code>i &lt;= 10 or i &lt;= lastnum</code> we have to enter the last number where the loop go and stop .</p>
</li>
<li><p>i++ increase 1 every time in code, here we can also write i += 2 or i += 3 then it will add 2 or 3 every time in code</p>
</li>
</ul>
<p>Use for loop when you already know exactly how many iteration needed . exactly how many lines to print .</p>
<h2><strong>Real-world use case For Loop:</strong></h2>
<h3>Printing a table</h3>
<ul>
<li>table is from <strong>1 to 10</strong>, we have to print it</li>
</ul>
<h3><strong>Students list</strong></h3>
<ul>
<li>there are <strong>30 students</strong> in the class, we have to print them</li>
</ul>
<h3>Array / list data</h3>
<ul>
<li>we know the size of the items inside the array</li>
</ul>
<h3>Game levels</h3>
<ul>
<li>Game has 10 levels</li>
</ul>
<hr />
<h2>While Loop:</h2>
<p><strong>when we don't know how many times the work will repeat</strong></p>
<p>while loop iterate the code until the code is complete . We don't know in exactly how many iteration it will complete but it will keep running until code is complete .</p>
<p><strong>Example :</strong></p>
<p>We are downloading a file from server but we don't know in exactly how many iteration the file will download, because sometime file come 1MB per second and sometime 10MB per second.</p>
<pre><code class="language-javascript">let filesize = 1024 ;            // Just suppose the file size is 1024MB 
let currentfiledownload = 0;     
// current download MB of the file eg (100MB , 200MB , 500MB)
while (filesize &gt; currentfiledownload){
    console.log("increase the mb after every iterate");
    currentfiledownload = currentfiledownload + 40;   
/* data comes in chunk from the server so it can be 10,20,30 etc everytime) */
}
</code></pre>
<hr />
<h3><strong>Real-World use case While loop:</strong></h3>
<h3>File download</h3>
<ul>
<li>don't know how much time it will take</li>
</ul>
<h3>Login system</h3>
<ul>
<li>until the password is wrong</li>
</ul>
<h3>Game life</h3>
<ul>
<li>until life &gt; 0</li>
</ul>
<h3>Loading Screen</h3>
<ul>
<li>until the data is not loaded</li>
</ul>
<hr />
<h2>do-while loop:</h2>
<p>It is same like while loop but it run the code at least one time even if the statement is false, still it will run at least 1 time ;</p>
<pre><code class="language-javascript">let filesize = 1024 ;
let currentfiledownload = 3000;
do{
    console.log("increase the mb after every iterate");
    currentfiledownload = currentfiledownload + 40;  
}
while (filesize &gt; currentfiledownload);
</code></pre>
<ul>
<li><p>Just suppose the file size is 1024MB</p>
</li>
<li><p>We wrote current download 3000MB of the file means statement is false , so the loop will not work,</p>
</li>
<li><p>but it will run code atleast 1 time because of <code>do-while</code></p>
</li>
<li><p>then it checks the statement.</p>
</li>
</ul>
<hr />
<h2>Real world use case Do-while loop :</h2>
<h3>Menu system (ATM / Calculator)</h3>
<ul>
<li>Menu is always show first</li>
</ul>
<h3>Login form</h3>
<ul>
<li><p>User have to enter the password at least 1 time, whether password is wrong or right,</p>
<p>prompt will run one time for sure .</p>
</li>
</ul>
<h3>Game start</h3>
<ul>
<li>Game start screen always come one time</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/dbea4a80-3289-4cab-a50c-9bc7d44668ef.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Ternary Operator:</h2>
<p>It is the shortest version of if else statements . Use it in simpler codes/tasks , it is not suitable for big projects because we can get confused.</p>
<h2>Example of ternary</h2>
<pre><code class="language-javascript">let age = 18;

let result = age &gt;= 18 ? "Adult" : "Minor";
console.log(result);
</code></pre>
<p><strong>How it works:</strong></p>
<ul>
<li><p><code>age &gt;= 18</code> → condition</p>
</li>
<li><p><code>"Adult"</code> → runs if condition is true</p>
</li>
<li><p><code>"Minor"</code> → runs if condition is false</p>
</li>
</ul>
<hr />
<h2>Switch Statement:</h2>
<pre><code class="language-javascript">let day = prompt("Enter day of the week");

switch(day) {
    case "Monday":
        console.log("Start of the week");
        break;
    case "Friday":
        console.log("Almost weekend");
        break;
    case "Saturday":
    case "Sunday":
        console.log("Weekend!");
        break;
    default:
        console.log("Midweek day");
}
</code></pre>
<p>Always remember this:</p>
<ul>
<li><p>in <code>switch(expression)</code> expression = <strong>the variable we want to check</strong></p>
</li>
<li><p><code>case value:</code> → it check if the value of variable is equal to case or not</p>
</li>
<li><p><code>break</code> → it make sure that after match, <strong>come out of the switch</strong></p>
</li>
<li><p><code>default</code> → if no case match, then this run</p>
</li>
</ul>
<p>Use switch when: <strong>we need different action for multiple exact values of one variable</strong></p>
<hr />
<h3>Real-world use case Switch Statement:</h3>
<ul>
<li><p><strong>Calculator operator:</strong><br />User enters <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> → different calculation for every operator</p>
</li>
<li><p><strong>Menu systems:</strong><br />ATM / Game menu / App menu → user select 1,2,3,4 → different action</p>
</li>
<li><p><strong>Day scheduler / Calendar apps:</strong><br />Variable = <code>"Monday"</code>, <code>"Saturday"</code> etc → show message or activity</p>
</li>
<li><p><strong>Game levels:</strong><br />Level number = 1,2,3 → different difficulty or enemies</p>
</li>
<li><p><strong>Payment method selection:</strong><br />Credit Card, PayPal, Bank Transfer → take different action</p>
</li>
</ul>
<hr />
<h2><strong>Arrays (List of items)</strong></h2>
<ul>
<li><p>Array is a <strong>container</strong> in which we can store <strong>multiple values together</strong>.</p>
</li>
<li><p>Every item has an <strong>index</strong>, start from 0.</p>
</li>
</ul>
<pre><code class="language-javascript">let colors = ["red", "green", "blue"];
// index        0       1       2
</code></pre>
<ul>
<li><p><code>colors[0]</code> → "red"</p>
</li>
<li><p><code>colors[1]</code> → "green"</p>
</li>
<li><p><code>colors[2]</code> → "blue"</p>
</li>
</ul>
<p><strong>Real-world examples:</strong></p>
<table>
<thead>
<tr>
<th>Use Case</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td>Student list</td>
<td>Storing the names of 30 students in class</td>
</tr>
<tr>
<td>Shopping cart</td>
<td>Storing items in the cart of user</td>
</tr>
<tr>
<td>Game scores</td>
<td>Storing scores of players in game</td>
</tr>
<tr>
<td>Colors / Settings</td>
<td>Storing theme colors of website</td>
</tr>
</tbody></table>
<p><strong>Use with Loop:</strong></p>
<ul>
<li>It help us to access every element of array one by one.</li>
</ul>
<pre><code class="language-javascript">for (let i = 0; i &lt; colors.length; i++) {
  console.log(colors[i]); // prints red, green, blue
}
</code></pre>
<hr />
<h2><strong>Nested Loops (Loops inside loops)</strong></h2>
<ul>
<li><p>When <strong>one loop run inside another loop</strong>, we call it <strong>nested loop</strong>.</p>
</li>
<li><p>It is used when we have to process <strong>2D data or grid</strong>.</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<ul>
<li><p>Printing 3×3 grid</p>
</li>
<li><p>Printing the combination of Row and Column</p>
</li>
</ul>
<pre><code class="language-javascript">for (let row = 1; row &lt;= 3; row++) {
  for (let col = 1; col &lt;= 3; col++) {
    console.log(`Row ${row} Col ${col}`);
  }
}
</code></pre>
<p><strong>Real-world use cases:</strong></p>
<table>
<thead>
<tr>
<th>Situation</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Classroom seating</strong></td>
<td>Assigning number to students in rows and columns</td>
</tr>
<tr>
<td><strong>Game boards</strong></td>
<td>Chess, Tic-Tac-Toe, 2D map grid</td>
</tr>
<tr>
<td><strong>Website table</strong></td>
<td>Showing data in row and column</td>
</tr>
<tr>
<td><strong>Calendar / Schedule</strong></td>
<td>Making the grid of Weekdays × Hours</td>
</tr>
<tr>
<td><strong>Image / Pixels</strong></td>
<td>Processing every pixel (photo editing)</td>
</tr>
</tbody></table>
<hr />
<h2><strong>Hoisting :</strong></h2>
<p><strong>Hoisting</strong> means:</p>
<blockquote>
<p>In JavaScript, <strong>variable and function declarations are automatically taken to the top</strong> before execution.</p>
</blockquote>
<ul>
<li><p>Only <strong>declaration</strong> go up, <strong>not the value assignment</strong>.</p>
</li>
<li><p>In <code>var</code> variables we get undefined if we use it before.</p>
</li>
<li><p>In <code>let</code> and <code>const</code> there is <strong>Temporal Dead Zone (TDZ)</strong> → if we access it before then we get <strong>error</strong>.</p>
</li>
</ul>
<hr />
<ol>
<li><p><strong>var</strong></p>
<ul>
<li><p>Declaration get hoisted.</p>
</li>
<li><p>Default value = <code>undefined</code>.</p>
</li>
<li><p>If we access it before, no error, we just get <code>undefined</code>.</p>
</li>
</ul>
<pre><code class="language-javascript">console.log(x); // undefined
var x = 5;
</code></pre>
<hr />
</li>
<li><p><strong>let / const</strong></p>
<ul>
<li><p>Declaration technically get hoisted.</p>
</li>
<li><p>It stay in <strong>TDZ</strong> → access before = <strong>ReferenceError</strong>.</p>
</li>
<li><p>We can use it after initialize.</p>
</li>
</ul>
<pre><code class="language-javascript">console.log(y); // ReferenceError
let y = 10;
</code></pre>
</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/d734b72b-45f2-46bf-b412-9ba0a8ca7270.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3><strong>Finding a specific item in Array:</strong></h3>
<p>We can find a specific item data in an array using its index number.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
console.log(students[0], students[2]);
// Output: Abdul Ahmad (Abdul is on 0 index and Ahmad is on 2 index)
</code></pre>
<hr />
<h2><strong>Check item by Name (Available or Not) in Array:</strong></h2>
<p>We can check if a specific item exists in the array using <code>includes()</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
console.log(students.includes("Anas"));
// Output: true

console.log(students.includes("Zain"));
// Output: false
</code></pre>
<hr />
<h2><strong>Get a slice of items from the Array:</strong></h2>
<p>We can extract a portion of array using <code>slice(start, end)</code>. End index is <strong>not included</strong>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
console.log(students.slice(2, 5));
// Output: ['Ahmad', 'Hamza', 'Sohail']
// (index 2, 3, 4      index 5 not included)
</code></pre>
<hr />
<h2><strong>Add item at the Start in Array:</strong></h2>
<p>We can add item at the beginning using <code>unshift()</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
students.unshift("Rahul");
console.log(students);

/* Output:
   ['Rahul', 'Abdul', 'Ali', 'Ahmad', 'Hamza', 'Sohail', 'Anas'] */
</code></pre>
<hr />
<h2><strong>Add item at the End in Array:</strong></h2>
<p>We can add item at the end using <code>push()</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
students.push("Adam");
console.log(students);

/* Output:
   ['Abdul', 'Ali', 'Ahmad', 'Hamza', 'Sohail', 'Anas', 'Adam'] */
</code></pre>
<hr />
<h2><strong>Remove item from the Start in Array:</strong></h2>
<p>We can remove the first item using <code>shift()</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
students.shift();
console.log(students);

/* Output:
   ['Ali', 'Ahmad', 'Hamza', 'Sohail', 'Anas'] */
</code></pre>
<hr />
<h2><strong>Remove item from the End in Array:</strong></h2>
<p>We can remove the last item using <code>pop()</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
students.pop();
console.log(students);

/* Output:
   ['Abdul', 'Ali', 'Ahmad', 'Hamza', 'Sohail'] */
</code></pre>
<hr />
<h2><strong>Check length of the Array:</strong></h2>
<p>We can check the total number of items in the array using <code>length</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
console.log(students.length);
// Output: 6
</code></pre>
<hr />
<h2><strong>Find index of an item:</strong></h2>
<p>We can find the position (index) of an item using <code>indexOf()</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
console.log(students.indexOf("Ahmad"));
// Output: 2

console.log(students.indexOf("Zain"));
// Output: -1 (not found)
</code></pre>
<hr />
<h2><strong>Reverse the Array:</strong></h2>
<p>We can reverse the order of items using <code>reverse()</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
students.reverse();
console.log(students);

/* Output:
   ['Anas', 'Sohail', 'Hamza', 'Ahmad', 'Ali', 'Abdul'] */
</code></pre>
<hr />
<h2><strong>Join Array items into a String:</strong></h2>
<p>We can combine all items into one string using <code>join()</code>.</p>
<pre><code class="language-javascript">let students = ["Abdul","Ali","Ahmad","Hamza","Sohail","Anas"];
console.log(students.join(", "));
// Output: "Abdul, Ali, Ahmad, Hamza, Sohail, Anas"

console.log(students.join(" - "));
// Output: "Abdul - Ali - Ahmad - Hamza - Sohail - Anas"
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/93dc0279-68d1-425c-8a6b-3b7898fc0d93.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2><strong>Quick Reference Table:</strong></h2>
<table>
<thead>
<tr>
<th>Method</th>
<th>Action</th>
<th>Position</th>
<th>Returns</th>
</tr>
</thead>
<tbody><tr>
<td><code>push()</code></td>
<td>Add</td>
<td>End</td>
<td>New length</td>
</tr>
<tr>
<td><code>pop()</code></td>
<td>Remove</td>
<td>End</td>
<td>Removed item</td>
</tr>
<tr>
<td><code>unshift()</code></td>
<td>Add</td>
<td>Start</td>
<td>New length</td>
</tr>
<tr>
<td><code>shift()</code></td>
<td>Remove</td>
<td>Start</td>
<td>Removed item</td>
</tr>
<tr>
<td><code>slice(start, end)</code></td>
<td>Extract</td>
<td>Any</td>
<td>New array</td>
</tr>
<tr>
<td><code>includes(item)</code></td>
<td>Check</td>
<td>-</td>
<td>true/false</td>
</tr>
<tr>
<td><code>indexOf(item)</code></td>
<td>Find index</td>
<td>-</td>
<td>Index or -1</td>
</tr>
<tr>
<td><code>reverse()</code></td>
<td>Reverse</td>
<td>-</td>
<td>Reversed array</td>
</tr>
<tr>
<td><code>join(separator)</code></td>
<td>Convert</td>
<td>-</td>
<td>String</td>
</tr>
<tr>
<td><code>length</code></td>
<td>Count</td>
<td>-</td>
<td>Number</td>
</tr>
</tbody></table>
<hr />
<h2>Higher Order Functions :</h2>
<p>A function which:</p>
<ol>
<li><p>Take another function as argument (input)</p>
</li>
<li><p>Or return a function (output)</p>
</li>
</ol>
<h3><strong>Without Higher Order Function (Repetition):</strong></h3>
<pre><code class="language-javascript">function makeBiryani() {
    return "Biryani";
}

function makePizza() {
    return "Pizza";
}

function makeBurger() {
    return "Burger";
}

// Every time we have to write the SAME pattern
console.log("Order liya");
console.log("Bana raha hoon...");
console.log(makeBiryani());
console.log("Serve kiya!");
console.log("---");

console.log("Order liya");
console.log("Bana raha hoon...");
console.log(makePizza());
console.log("Serve kiya!");
console.log("---");

console.log("Order liya");
console.log("Bana raha hoon...");
console.log(makeBurger());
console.log("Serve kiya!");
</code></pre>
<p><strong>Problem:</strong> Every time the <strong>same things repeat</strong> !</p>
<hr />
<h3><strong>With Higher Order Function (Smart Way):</strong></h3>
<pre><code class="language-javascript">function makeBiryani() {
    return "Biryani";
}

function makePizza() {
    return "Pizza";
}

function makeBurger() {
    return "Burger";
}

// WRITTEN ONE TIME (reusable!)
function cook(recipeFunction) {
    console.log("Order liya");
    console.log("Bana raha hoon...");
    return recipeFunction();
}

// Now just do this
console.log(cook(makeBiryani));    // it will print, you can print others also
cook(makePizza);
cook(makeBurger);
</code></pre>
<p><strong>Benefit:</strong> We write <code>cook</code> one time, now we can <strong>use</strong> it as many times as we want !</p>
<hr />
<h2>For Each :</h2>
<p><code>forEach()</code> is a <strong>Higher Order Function</strong> which run a function on <strong>every element</strong> of the array.</p>
<pre><code class="language-javascript">let students = ["Abdul", "Ali", "Ahmad", "Hamza"];

students.forEach(function(student) {
    console.log(student);
});

/* Output:
Abdul
Ali
Ahmad
Hamza
*/
</code></pre>
<hr />
<pre><code class="language-javascript">let names = ["Abdul", "Ali", "Ahmad"];

const greet = name =&gt; {
    console.log(`Hello ${name}! Welcome to the class!`);
};

names.forEach(greet);

/* Output:
Hello Abdul! Welcome to the class!
Hello Ali! Welcome to the class!
Hello Ahmad! Welcome to the class!
*/
</code></pre>
<hr />
<h2>Map Method :</h2>
<p>Map always return a new array</p>
<ul>
<li><p>on whichever array we apply map, map make a new array,</p>
</li>
<li><p>and it apply on all items of the real array,</p>
</li>
<li><p>but it don't touch the real array, all the output is saved in the new array .</p>
</li>
<li><p>in this way it make a new array without touching the old/real array and save the output in it.</p>
</li>
</ul>
<pre><code class="language-javascript">let students = [1, 2, 3, 4, 5, 6];

function double(numberinside){
  return (numberinside * 2);
}

let numbersDouble = students.map(double);
console.log(numbersDouble);  // output: [2, 4, 6, 8, 10, 12]

/* or short version 

let numbersDouble = students.map(numberinside =&gt; numberinside * 2);
console.log(numbersDouble);  
output : [2, 4, 6, 8, 10, 12] */
</code></pre>
<hr />
<h2><strong>Map() vs For-each function :</strong></h2>
<p><code>map()</code> - Return a new array:</p>
<pre><code class="language-javascript">let numbers = [1, 2, 3];
let doubled = numbers.map(num =&gt; num * 2);
console.log(doubled);  // [2, 4, 6]
</code></pre>
<p><code>forEach()</code> - Return nothing (undefined):</p>
<pre><code class="language-javascript">let numbers = [1, 2, 3];
let doubled = numbers.forEach(num =&gt; num * 2);
console.log(doubled);  // undefined
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/b28e0eb9-4e46-43be-9157-5482bbc5115c.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2><strong>Use Case (When to Use)</strong></h2>
<h3>map function:</h3>
<p><code>map()</code> - When we need a new array:</p>
<pre><code class="language-javascript">let students = ["Abdul", "Ali", "Ahmad"];

// We need every name in uppercase
let upperNames = students.map(name =&gt; name.toUpperCase());
console.log(upperNames);  // ["ABDUL", "ALI", "AHMAD"]
</code></pre>
<h3>For-each Function:</h3>
<p><code>forEach()</code> - When we only want to do some action (display, save, etc):</p>
<pre><code class="language-javascript">let students = ["Abdul", "Ali", "Ahmad"];

// Just want to print
students.forEach(name =&gt; console.log(name));
// Abdul
// Ali
// Ahmad
</code></pre>
<hr />
<p>If you did not find a topic you were looking for, please check my notes. I hope you will find it there: <a href="https://github.com/abdulrdeveloper/FullStackHub/tree/main/Learn%20JavaScript">FullStackHub / Learn JavaScript</a></p>
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[The Guard at Your API’s Gate : Middleware in Express, explained simply]]></title><description><![CDATA[Learn how Express middleware works: next(), execution order, router-level, built-in and error-handling types, plus auth, validation and role checks.]]></description><link>https://blog.abdulrdeveloper.me/express-middleware-explained</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/express-middleware-explained</guid><category><![CDATA[Middleware]]></category><category><![CDATA[Express]]></category><category><![CDATA[backend]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[abdulrdeveloper]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Mon, 12 Oct 2026 11:46:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/027142b7-cec3-439a-98ba-b45520773021.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>In a real application, a lot of work happens before the route runs like logging the request, reading the JSON body, checking if the user is logged in and validating the input.</p>
<p>If we write all of this inside every route, the code becomes repetitive very fast. Express solves this with middleware.</p>
<p>In this blog, we will understand what middleware is, how <code>next()</code> works, why order matters, and how to use the different types of middleware in real projects.</p>
<hr />
<h2>What is Middleware?</h2>
<p>A middleware is a function that runs between the request and the response. It receives three things:</p>
<ul>
<li><p><code>req</code>: the request</p>
</li>
<li><p><code>res</code>: the response</p>
</li>
<li><p><code>next</code>: a function that passes control to the next step</p>
</li>
</ul>
<pre><code class="language-javascript">function myMiddleware(req, res, next) {
  // do something with req or res
  next(); // move to the next step
}
</code></pre>
<p>A middleware can do four things:</p>
<ol>
<li><p>Run any code.</p>
</li>
<li><p>Change <code>req</code> and <code>res</code> (for example, add <code>req.user</code>).</p>
</li>
<li><p>End the request by sending a response.</p>
</li>
<li><p>Pass the request forward by calling <code>next()</code>.</p>
</li>
</ol>
<p>Think of it as a security check at an airport. Before you reach the gate (the route handler), you pass through a few checks: ticket, ID, baggage. If any check fails, you are stopped there. If all pass, you reach the gate.</p>
<h3>Two Forms of Middleware</h3>
<p>Express has two forms of middleware. Express tells them apart by the <strong>number of parameters</strong>.</p>
<pre><code class="language-javascript">// Normal middleware: 3 parameters
function myMiddleware(req, res, next) {
  next();
}

// Error-handling middleware: 4 parameters
function myErrorHandler(err, req, res, next) {
  res.status(500).json({ error: 'Something went wrong' });
}
</code></pre>
<ul>
<li><p><strong>Normal middleware</strong> has 3 parameters: <code>req</code>, <code>res</code>, <code>next</code>.</p>
</li>
<li><p><strong>Error-handling middleware</strong> has 4 parameters: <code>err</code>, <code>req</code>, <code>res</code>, <code>next</code>. The first one is always <code>err</code>.</p>
</li>
</ul>
<p>All four parameters must be written, even if you do not use <code>err</code> inside the function. If you remove <code>err</code>, only three parameters are left, and Express treats it as a normal middleware.</p>
<p>Many beginners never write an error handler, because Express has a default one built in. But writing your own gives you control: you decide the response, the status code and what gets logged. We will see how in the Error-handling section.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/ab528503-14b4-437c-a493-c39951eed6a0.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Your First Middleware</h2>
<blockquote>
<p><strong>Let`s say we want to log every request: its method and URL. Without middleware, we would write the log in every route:</strong></p>
</blockquote>
<pre><code class="language-javascript">app.get('/', (req, res) =&gt; {
  console.log(`${req.method} ${req.url}`); // repeated
  res.send('Home page');
});

app.get('/about', (req, res) =&gt; {
  console.log(`${req.method} ${req.url}`); // repeated
  res.send('About page');
});

app.get('/users', (req, res) =&gt; {
  console.log(`${req.method} ${req.url}`); // repeated
  res.json('Users page');
});
</code></pre>
<p>The same line is copied three times. With 50 routes, it will be copied 50 times, and if we want to change the log, we must change it in 50 places. Even worse, if we forget it in one route, that request is never logged.</p>
<blockquote>
<p><strong>Middleware solves this. We write the logic once, and it runs for every request:</strong></p>
</blockquote>
<pre><code class="language-javascript">import express from 'express';

const app = express();

// Middleware: runs for every request
app.use((req, res, next) =&gt; {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.get('/', (req, res) =&gt; res.send('Home page'));
app.get('/about', (req, res) =&gt; res.send('About page'));
app.get('/users', (req, res) =&gt; res.json('Users page'));

app.listen(3000, () =&gt; console.log('Server running on port 3000'));
</code></pre>
<p>Now open <code>/</code>, <code>/about</code> and <code>/users</code> in the browser and look at your terminal:</p>
<pre><code class="language-plaintext">GET /
GET /about
GET /users
</code></pre>
<p>Notice that the middleware is written before the routes. Express reads from top to bottom, so it must come first.</p>
<p>All three routes are logged, and our routes did not change at all. They stay clean and only do their own job.</p>
<p><code>app.use()</code> registers the middleware for every request. After it prints the log, <code>next()</code> passes the request to the next step, which is the route. Any new route we add later is logged automatically.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/2558c59c-17a8-4d85-8e2e-f35848f6d223.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2><code>next()</code> Explained</h2>
<p><code>next()</code> is what keeps the request moving. There are only two possible endings for a middleware:</p>
<ul>
<li><p><strong>Call</strong> <code>next()</code>: the request continues to the next middleware or route.</p>
</li>
<li><p><strong>Send a response</strong>: the request ends here, and nothing after it runs.</p>
</li>
</ul>
<p>If you do neither, the request is stuck, and the client waits until it times out.</p>
<pre><code class="language-javascript">// Wrong: no next() and no response, the request hangs
app.use((req, res, next) =&gt; {
  console.log('Request came');
});

// Correct
app.use((req, res, next) =&gt; {
  console.log('Request came');
  next();
});
</code></pre>
<p>Always call <code>next()</code> if you want the request to continue. It passes control to the next middleware or route handler. Without <code>next()</code> or a response, the request gets stuck, and the client keeps waiting.</p>
<pre><code class="language-javascript">if (!token) {
  return res.status(401).json({ error: 'No token provided' });
}
next();
</code></pre>
<hr />
<h2>Middleware Execution Order</h2>
<p>Middleware runs <strong>in the order you write it</strong>, from top to bottom. This is the same rule as route order from part 1.</p>
<pre><code class="language-javascript">app.use((req, res, next) =&gt; {
  console.log('First');
  next();
});

app.use((req, res, next) =&gt; {
  console.log('Second');
  next();
});

app.get('/', (req, res) =&gt; {
  console.log('Route handler');
  res.send('Done');
});
</code></pre>
<p>A request to <code>/</code> prints:</p>
<pre><code class="language-plaintext">First
Second
Route handler
</code></pre>
<p>Because of this, <strong>placement matters</strong>. Always put middleware before the routes that need it. Otherwise, it may not run for those requests, and things like <code>express.json()</code> won't be able to parse the request body before the route handler uses it.</p>
<hr />
<h2>Types of Middleware</h2>
<h3>1. Application-level Middleware</h3>
<p>This is what we have used so far. It is attached to the whole app with <code>app.use()</code>.</p>
<pre><code class="language-javascript">app.use(logger);              // runs for every request
app.use('/api', apiLogger);   // runs only for URLs starting with /api
</code></pre>
<p>We can also attach a middleware to <strong>one route only</strong>. Just place it before the handler:</p>
<pre><code class="language-javascript">app.get('/profile', auth, (req, res) =&gt; {
  res.json({ message: 'Your profile' });
});
</code></pre>
<p>You can pass many middlewares in a row. They run left to right:</p>
<pre><code class="language-javascript">app.post('/users', auth, validateUser, (req, res) =&gt; {
  // runs only if auth and validateUser both called next()
});
</code></pre>
<hr />
<h3>2. Router-level Middleware</h3>
<p>Imagine your app has 10 admin routes. Instead of adding the same middleware to all 10 routes, we can group them together using <code>express.Router()</code>.</p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

const admin = express.Router();

// Runs before every admin route
admin.use((req, res, next) =&gt; {
  console.log('Checking admin access...');
  next();
});

admin.get('/', (req, res) =&gt; {
  res.send('Admin Dashboard');
});

admin.get('/settings', (req, res) =&gt; {
  res.send('Admin Settings');
});

// All admin routes start with /admin
app.use('/admin', admin);
</code></pre>
<h3>Working:</h3>
<ul>
<li><p><code>express.Router()</code> creates a separate router to keep admin routes together.</p>
</li>
<li><p><code>admin.use()</code> adds middleware that runs before the admin routes.</p>
</li>
<li><p><code>admin.get('/')</code> handles the admin dashboard.</p>
</li>
<li><p><code>admin.get('/settings')</code> handles the settings page.</p>
</li>
<li><p><code>app.use('/admin', admin)</code> connects this router to the main app. Every route inside it starts with <code>/admin</code>.</p>
</li>
<li><p>So <code>/</code> becomes <code>/admin/</code>, and <code>/settings</code> becomes <code>/admin/settings</code>.</p>
</li>
</ul>
<p>That`s how you can also keep group related routes together, add middleware once, and connect the group to your main app.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/44351c11-2dc0-47eb-962a-0940eb321fac.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>3. Built-in Middleware</h3>
<p>Express comes with a few ready-made middlewares.</p>
<table>
<thead>
<tr>
<th>Middleware</th>
<th>What it does</th>
</tr>
</thead>
<tbody><tr>
<td><code>express.json()</code></td>
<td>Reads a JSON body and puts it in <code>req.body</code></td>
</tr>
<tr>
<td><code>express.urlencoded({ extended: true })</code></td>
<td>Reads HTML form data and puts it in <code>req.body</code></td>
</tr>
<tr>
<td><code>express.static('public')</code></td>
<td>Serves files from a folder (images, CSS, JS)</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
</code></pre>
<p><strong>Serving static files:</strong> with <code>express.static('public')</code>, a file at <code>public/style.css</code> is available at <a href="http://localhost:3000/style.css"><code>http://localhost:3000/style.css</code></a>. We do not write any route for it. The middleware checks if the file exists, sends it, and ends the request. If the file does not exist, it calls <code>next()</code> and the request continues to your routes.</p>
<p>We can also add a prefix:</p>
<pre><code class="language-javascript">app.use('/assets', express.static('public'));
// public/logo.png is now available at /assets/logo.png
</code></pre>
<hr />
<h3>4. Error-handling Middleware</h3>
<p>This one is special. It has <strong>four</strong> parameters, and the first one is <code>err</code>. We will see it in detail below.</p>
<hr />
<h3>Third-party Middleware</h3>
<p>Many packages from npm are middleware too. For example, <code>cors</code> (cross-origin requests), <code>helmet</code> (security headers), and <code>morgan</code> (request logging). You install them and use them with <code>app.use()</code>.</p>
<hr />
<h2>Error-handling Middleware</h2>
<p>Errors will happen: a database fails, a value is missing, some code throws. Instead of handling errors in every route, we handle them in <strong>one place</strong>.</p>
<p>An error-handling middleware has <strong>four parameters</strong>. Express knows it is an error handler because of the <code>err</code> first parameter, so all four must be written, even if you do not use <code>next</code>.</p>
<p>javascript</p>
<pre><code class="language-javascript">app.use((err, req, res, next) =&gt; {
  console.error(err.message);
  res.status(err.status || 500).json({ error: 'Something went wrong' });
});
</code></pre>
<p>It must be placed <strong>after all routes and other middleware</strong>.</p>
<p>To send an error to it, pass the error to <code>next()</code>:</p>
<pre><code class="language-javascript">app.get('/users/:id', (req, res, next) =&gt; {
  const user = null; // imagine the database found nothing

  if (!user) {
    const error = new Error('User not found');
    error.status = 404;
    return next(error); // skips all normal middleware, goes to the error handler
  }

  res.json(user);
});
</code></pre>
<p>In Express 5, if an <code>async</code> route throws an error or a promise is rejected, Express passes it to the error handler automatically. In Express 4 you had to catch it and call <code>next(err)</code> yourself.</p>
<pre><code class="language-javascript">app.use((req, res) =&gt; {
  res.status(404).json({ error: `Cannot ${req.method} ${req.originalUrl}` });
});
</code></pre>
<hr />
<h2>The Middleware Chain</h2>
<p>Now let's put it together. This is a request to delete a user:</p>
<pre><code class="language-javascript">app.use(express.json());
app.use(logger);

app.delete('/users/:id', auth, requireRole('admin'), (req, res) =&gt; {
  // delete the user from the database
  res.status(204).end();
});

app.use(notFound);
app.use(errorHandler);
</code></pre>
<p>The request passes through:</p>
<ol>
<li><p><code>express.json()</code>: reads the body</p>
</li>
<li><p><code>logger</code>: prints the request</p>
</li>
<li><p><code>auth</code>: checks the token (stops with <code>401</code> if it fails)</p>
</li>
<li><p><code>requireRole('admin')</code>: checks the role (stops with <code>403</code> if it fails)</p>
</li>
<li><p>Route handler: does the real work and sends the response</p>
</li>
</ol>
<p>If any step fails, the request ends there, and the later steps never run. Each middleware does <strong>one small job</strong>, and together they form a pipeline.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/06175d46-81b8-480a-a67f-8c4d011ed2f3.png" alt="" style="display:block;margin:0 auto" />

<hr />
<p>You can find more of my work at <a href="http://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="http://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[The Era of Express: Routes, Params and the Art of Handling Requests]]></title><description><![CDATA[Learn how Express handles requests: routes, GET and POST, responses, URL params vs query strings, and why route order matters.]]></description><link>https://blog.abdulrdeveloper.me/express-routes-params-and-query-explained</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/express-routes-params-and-query-explained</guid><category><![CDATA[Express]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[backend]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[abdulrdeveloper]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Sun, 11 Oct 2026 11:47:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/09803697-4a02-4a1c-8d40-7ba0fe2494b9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Every backend does one job again and again: a request comes in, some logic runs, a response goes out. Node.js can do this on its own, but the code becomes long and repetitive very fast. Express exists to remove that pain.</p>
<p>In this blog, we will clearly understand how Express handles requests, like routes, handlers, responses, URL params and query strings.</p>
<hr />
<h2>What is Express and Why Do We Need It?</h2>
<p>Express is a minimal web framework built on top of node.js. We can write node.js code without Express, but it becomes too repetitive and hard to manage when the project grows. That`s why TJ Holowaychuk took the <code>http</code> module of Node.js and built Express separately on top of it. With Express, we can create servers, write code efficiently, and handle routes easily, and keep our code organized as the project grows.</p>
<blockquote>
<p><strong>Let`s see a small server with raw Node.js (without express):</strong></p>
</blockquote>
<pre><code class="language-javascript">import http from 'http';
 
const server = http.createServer((req, res) =&gt; {
  if (req.method === 'GET' &amp;&amp; req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Home page');
  } else if (req.method === 'GET' &amp;&amp; req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('About page');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not found');
  }
});
 
server.listen(3000);
</code></pre>
<p>Two routes, and it already looks heavy. Now imagine 40 routes, JSON bodies, URL parameters and query strings.</p>
<blockquote>
<p><strong>Now let`s see the same server in Express:</strong></p>
</blockquote>
<pre><code class="language-javascript">import express from 'express';
 
const app = express();
 
app.get('/', (req, res) =&gt; res.send('Home page'));
app.get('/about', (req, res) =&gt; res.send('About page'));
 
app.listen(3000, () =&gt; console.log('Server running on port 3000'));
</code></pre>
<p>As we can see, our code now looks much cleaner compared to the raw node.js server.Express gives a clear structure to our code, so it stays clean even when the project grows.</p>
<blockquote>
<p><strong>Comparing Raw Node.js and Express</strong></p>
</blockquote>
<table>
<thead>
<tr>
<th>Responsibility</th>
<th>Raw Node.js <code>http</code></th>
<th>Express</th>
</tr>
</thead>
<tbody><tr>
<td>Routing</td>
<td>Manual <code>if/else</code> on <code>req.url</code></td>
<td><code>app.get()</code>, <code>app.post()</code> etc.</td>
</tr>
<tr>
<td>Parsing URL params</td>
<td>Manual</td>
<td><code>req.params</code></td>
</tr>
<tr>
<td>Parsing query string</td>
<td>Manual</td>
<td><code>req.query</code></td>
</tr>
<tr>
<td>Sending JSON</td>
<td>Set header + <code>JSON.stringify</code> yourself</td>
<td><code>res.json()</code></td>
</tr>
<tr>
<td>Status codes</td>
<td><code>res.writeHead()</code></td>
<td><code>res.status()</code></td>
</tr>
</tbody></table>
<p>Raw HTTP is manual, while Express makes it simple and fast.Express removes the boilerplate and makes routing easy.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/343809f9-5c67-459c-bad9-441896bf3ef8.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Your First Express Server</h2>
<pre><code class="language-bash">npm init -y
npm install express
</code></pre>
<pre><code class="language-javascript">// server.js
import express from 'express';
 
const app = express();
const PORT = 3000;
 
app.get('/', (req, res) =&gt; {
  res.send('Hello from Express');
});
 
app.listen(PORT, () =&gt; {
  console.log(`Server running on http://localhost:${PORT}`);
});
</code></pre>
<p>Run it with <code>node server.js</code> and open <code>http://localhost:3000</code>.</p>
<p>Three things are happening here:</p>
<ol>
<li><p><code>express()</code> creates the application object, <code>app</code>.</p>
</li>
<li><p><code>app.get(...)</code> registers a <strong>route</strong>.</p>
</li>
<li><p><code>app.listen(...)</code> starts the server and waits for requests.</p>
</li>
</ol>
<hr />
<h2>The Request Lifecycle</h2>
<p>Before writing more routes, understand the path a request takes:</p>
<ol>
<li><p>The client sends a request (method + URL).</p>
</li>
<li><p>Express looks at its list of routes, <strong>from top to bottom</strong>.</p>
</li>
<li><p>The first route that matches both the <strong>method</strong> and the <strong>path</strong> runs its handler.</p>
</li>
<li><p>The handler sends a response, and the request ends.</p>
</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/ccdb2be0-17d0-475d-8f51-d35ff38206c3.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Routing Basics</h2>
<pre><code class="language-javascript">app.METHOD(PATH, HANDLER);
</code></pre>
<ul>
<li><p><code>METHOD</code>: the HTTP method (<code>get</code>, <code>post</code>, <code>put</code>, <code>patch</code>, <code>delete</code>).</p>
</li>
<li><p><code>PATH</code>: the URL pattern to match.</p>
</li>
<li><p><code>HANDLER</code>: the function that runs when both match. It receives <code>req</code> (request) and <code>res</code> (response).</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/97caa36f-d779-4072-9b05-5fb58fe7f44b.png" alt="" style="display:block;margin:0 auto" /></li>
</ul>
<hr />
<h3>Handling POST Requests</h3>
<p>POST is used to <strong>create</strong> data. The data comes in the request body, and Express does not read a JSON body by default. We must enable it with the built-in <code>express.json()</code> middleware.</p>
<pre><code class="language-javascript">app.use(express.json());

app.post('/users', (req, res) =&gt; {
  const name = req.body.name;

  if (!name) {
    return res.status(400).json({ error: 'name is required' });
  }

  // save the user in the database

  res.status(201).json({ message: 'User created', name: name });
});
</code></pre>
<p>Notice three good habits here:</p>
<ul>
<li><p>Validate the input, and return <code>400</code> if it is wrong.</p>
</li>
<li><p>Return <code>201 Created</code> when something new is created.</p>
</li>
<li><p>Take only the fields you need (like <code>name</code>) from <code>req.body</code>. Don’t save the whole <code>req.body</code> directly, because the client can send extra fields.</p>
</li>
</ul>
<hr />
<h3>PUT, PATCH and DELETE</h3>
<pre><code class="language-javascript">//replace the whole resource
app.put('/users/:id', (req, res) =&gt; {
  const id = req.params.id;

  // find the user in the database
  // replace the whole user with the new data from req.body

  res.json({ message: `User ${id} replaced` });
});

// PATCH: update only some fields
app.patch('/users/:id', (req, res) =&gt; {
  const id = req.params.id;

  // find the user in the database
  // update only the fields sent in req.body

  res.json({ message: `User ${id} updated` });
});

// DELETE
app.delete('/users/:id', (req, res) =&gt; {
  const id = req.params.id;

  // find the user in the database
  // delete the user

  res.status(204).end(); // 204 = success, nothing to send back
});
</code></pre>
<p>Every handler must <strong>send a response</strong>. A handler that never responds leaves the client hanging until it times out.</p>
<hr />
<h3>Wildcard Routes</h3>
<p>A wildcard route matches <strong>many URLs</strong> with one route. In Express 5, a wildcard must have a name, and we write it with a <code>*</code>.</p>
<pre><code class="language-javascript">app.get('/files/*filepath', (req, res) =&gt; {
  res.json({ filepath: req.params.filepath });
});
</code></pre>
<p>This one route matches all of these URLs:</p>
<ul>
<li><p><code>/files/readme.txt</code></p>
</li>
<li><p><code>/files/docs/readme.txt</code></p>
</li>
<li><p><code>/files/images/2024/photo.png</code></p>
</li>
</ul>
<p>Whatever comes after <code>/files/</code> is saved in <code>req.params.filepath</code>.</p>
<p>We can also use a wildcard to catch <strong>every</strong> URL that did not match any route above:</p>
<pre><code class="language-javascript">app.get('/*splat', (req, res) =&gt; {
  res.send('This page does not exist');
});
</code></pre>
<p><strong>Note:</strong> Express 4 used <code>'*'</code> without a name. Express 5 requires a name, like <code>*filepath</code> or <code>*splat</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/a48d2d5a-f680-4fb8-ab26-d1768e7b9701.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Sending Responses</h2>
<p><code>res</code> gives us many ways to reply. These are the ones you will use daily:</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>What it does</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td><code>res.send()</code></td>
<td>Sends text, HTML, or an object/buffer</td>
<td><code>res.send('Hello')</code></td>
</tr>
<tr>
<td><code>res.json()</code></td>
<td>Sends JSON with the right <code>Content-Type</code></td>
<td><code>res.json({ ok: true })</code></td>
</tr>
<tr>
<td><code>res.status()</code></td>
<td>Sets the status code (chainable)</td>
<td><code>res.status(404).json({...})</code></td>
</tr>
<tr>
<td><code>res.sendStatus()</code></td>
<td>Sets the status and sends its text</td>
<td><code>res.sendStatus(200)</code> sends <code>OK</code></td>
</tr>
<tr>
<td><code>res.redirect()</code></td>
<td>Redirects to another URL</td>
<td><code>res.redirect(301, '/new')</code></td>
</tr>
<tr>
<td><code>res.type()</code></td>
<td>Sets the <code>Content-Type</code></td>
<td><code>res.type('application/xml')</code></td>
</tr>
<tr>
<td><code>res.set()</code></td>
<td>Sets a response header</td>
<td><code>res.set('Request-Id', 'abc')</code></td>
</tr>
<tr>
<td><code>res.end()</code></td>
<td>Ends the response without data</td>
<td><code>res.status(204).end()</code></td>
</tr>
</tbody></table>
<p><strong>Rule:</strong> send only <strong>one</strong> response per request. Calling <code>res.send()</code> or <code>res.json()</code> twice throws the error <em>"Cannot set headers after they are sent to the client"</em>. This usually happens when you forget a <code>return</code>:</p>
<pre><code class="language-javascript">// Wrong: both lines try to respond
if (!user) res.status(404).json({ error: 'Not found' });
res.json(user);
 
// Correct: return stops the function
if (!user) return res.status(404).json({ error: 'Not found' });
res.json(user);
</code></pre>
<h3>Common Status Codes</h3>
<table>
<thead>
<tr>
<th>Code</th>
<th>Meaning</th>
<th>Use it when</th>
</tr>
</thead>
<tbody><tr>
<td><code>200</code></td>
<td>OK</td>
<td>Normal success</td>
</tr>
<tr>
<td><code>201</code></td>
<td>Created</td>
<td>A new resource was created (POST)</td>
</tr>
<tr>
<td><code>204</code></td>
<td>No Content</td>
<td>Success, nothing to return (DELETE)</td>
</tr>
<tr>
<td><code>400</code></td>
<td>Bad Request</td>
<td>Invalid input</td>
</tr>
<tr>
<td><code>404</code></td>
<td>Not Found</td>
<td>Resource or route does not exist</td>
</tr>
<tr>
<td><code>500</code></td>
<td>Server Error</td>
<td>Something broke on the server</td>
</tr>
</tbody></table>
<hr />
<h2>URL Params vs Query Strings</h2>
<pre><code class="language-plaintext">https://api.example.com/users/42/orders?status=pending&amp;limit=10&amp;page=2
</code></pre>
<p>It has three useful parts:</p>
<ul>
<li><p><strong>Path:</strong> <code>/users/42/orders</code></p>
</li>
<li><p><strong>URL param:</strong> <code>42</code> (a value inside the path)</p>
</li>
<li><p><strong>Query string:</strong> <code>?status=pending&amp;limit=10&amp;page=2</code> (key-value pairs after the <code>?</code>) Both carry data from the client to the server. But they carry <strong>different kinds</strong> of data.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/fd906dbe-015b-4ab0-8326-25c194f26725.png" alt="" style="display:block;margin:0 auto" />

<h3>URL Parameters (<code>req.params</code>)</h3>
<p>A URL param is a <strong>dynamic part of the path</strong>. We define it with a colon (<code>:</code>) in the route.</p>
<pre><code class="language-javascript">app.get('/users/:id', (req, res) =&gt; {
  const id = Number(req.params.id);
 
  if (!Number.isInteger(id)) {
    return res.status(400).json({ error: 'id must be an integer' });
  }
 
  const user = users.find((u) =&gt; u.id === id);
  if (!user) return res.status(404).json({ error: 'User not found' });
 
  res.json(user);
});
</code></pre>
<p>A request to <code>/users/1</code> gives <code>req.params</code> the value <code>{ id: '1' }</code>.</p>
<p>You can have more than one param:</p>
<pre><code class="language-javascript">app.get('/users/:userId/orders/:orderId', (req, res) =&gt; {
  res.json(req.params); // { userId: '5', orderId: '9' }
});
</code></pre>
<p>Params <strong>identify a specific resource</strong>. <code>/users/42</code> means <em>"the user whose id is 42"</em>.</p>
<hr />
<h3>Query Strings (<code>req.query</code>)</h3>
<p>A query string is everything after the <code>?</code>. It is <strong>not</strong> part of the route definition. Express reads it for you and puts it in <code>req.query</code>.</p>
<pre><code class="language-javascript">app.get('/users', (req, res) =&gt; {
  const { role, city, limit = '10', page = '1' } = req.query;
 
  let result = users;
  if (role) result = result.filter((u) =&gt; u.role === role);
  if (city) result = result.filter((u) =&gt; u.city === city);
 
  const l = Number(limit);
  const p = Number(page);
 
  res.json({
    count: result.length,
    page: p,
    data: result.slice((p - 1) * l, p * l),
  });
});
</code></pre>
<p>A request to <code>/users?role=student&amp;limit=5</code> gives <code>req.query</code> the value <code>{ role: 'student', limit: '5' }</code>.</p>
<p>Query strings <strong>filter, sort or paginate</strong> a collection. They are usually optional.</p>
<hr />
<h3>A Very Common Mistake: Everything is a String</h3>
<p>Both <code>req.params</code> and <code>req.query</code> always give you <strong>strings</strong>. Even <code>?limit=5</code> gives <code>'5'</code>, not <code>5</code>. Convert it yourself:</p>
<pre><code class="language-javascript">const limit = Number(req.query.limit);
</code></pre>
<p>And always validate the result. <code>Number('abc')</code> is <code>NaN</code>, and that should become a <code>400</code>, not a crash.</p>
<h3>Key Differences</h3>
<table>
<thead>
<tr>
<th></th>
<th>URL Params</th>
<th>Query String</th>
</tr>
</thead>
<tbody><tr>
<td>Example</td>
<td><code>/users/42</code></td>
<td><code>/users?role=admin</code></td>
</tr>
<tr>
<td>Defined in route</td>
<td>Yes (<code>:id</code>)</td>
<td>No</td>
</tr>
<tr>
<td>Access with</td>
<td><code>req.params</code></td>
<td><code>req.query</code></td>
</tr>
<tr>
<td>Purpose</td>
<td><strong>Identify</strong> one resource</td>
<td><strong>Filter, sort, paginate</strong></td>
</tr>
<tr>
<td>Required?</td>
<td>Yes, route will not match without it</td>
<td>Usually optional</td>
</tr>
<tr>
<td>Position</td>
<td>Inside the path</td>
<td>After the <code>?</code></td>
</tr>
</tbody></table>
<h3>When to Use Which</h3>
<p>A simple rule that works almost always:</p>
<ul>
<li><p><strong>Which resource?</strong> Use a param. <code>GET /users/42</code></p>
</li>
<li><p><strong>How should I see the list?</strong> Use a query. <code>GET /users?role=admin&amp;page=2</code> You can combine both:</p>
</li>
</ul>
<pre><code class="language-plaintext">GET /users/42/orders?status=pending
</code></pre>
<p><em>The Code is saying:</em> <code>"Give me the orders of user 42, but only the pending ones."</code></p>
<p>The param picks the user, and the query filters the orders.</p>
<p><strong>How to decide:</strong></p>
<ul>
<li><p>Use a <strong>param</strong> when the value tells you <em>which</em> resource you want. Example: <code>/users/42</code></p>
</li>
<li><p>Use a <strong>query</strong> when the value tells you <em>how</em> you want the result. Example: <code>/users?role=admin</code></p>
</li>
</ul>
<hr />
<h2>Route Order Matters</h2>
<p>Express checks your routes <strong>one by one, from top to bottom</strong>. As soon as one route matches, it runs that route and stops. It does not check the rest.</p>
<p>This can create a bug when a fixed route and a dynamic route look similar.</p>
<pre><code class="language-javascript">// Wrong order
app.get('/users/:id', (req, res) =&gt; res.json({ route: 'by id' }));
app.get('/users/search', (req, res) =&gt; res.json({ route: 'search' }));
</code></pre>
<p>Here, a request to <code>/users/search</code> reaches <code>/users/:id</code> first. Express treats the word <code>search</code> as the <code>id</code>, so the second route never runs.</p>
<p>This is how you can fix it: put the fixed route <strong>before</strong> the dynamic route.</p>
<pre><code class="language-javascript">// Correct order
app.get('/users/search', (req, res) =&gt; res.json({ route: 'search' }));
app.get('/users/:id', (req, res) =&gt; res.json({ route: 'by id' }));
</code></pre>
<p>Now <code>/users/search</code> matches the first route and stops. Any other value, like <code>/users/42</code>, moves down and matches <code>/users/:id</code>.</p>
<p><strong>Rule:</strong> put fixed routes first, and dynamic routes (<code>:id</code>) after them.</p>
<hr />
<p><strong>Express Class Github Link:</strong> <a href="https://github.com/abdulrdeveloper/FullStackHub/tree/main/Learn%20Backend/Intro%20to%20Express/express-class">https://github.com/abdulrdeveloper/FullStackHub/tree/main/Learn%20Backend/Intro%20to%20Express/express-class</a></p>
<hr />
<p>You can find more of my work at <a href="http://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="http://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Behind the Gate: What Node.js Really Does When You Run node app.js]]></title><description><![CDATA[Learn how Node.js works inside: V8, libuv, the Event Loop phases and the Thread Pool, with simple examples and exercises you can run yourself.]]></description><link>https://blog.abdulrdeveloper.me/nodejs-internals-event-loop-thread-pool</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/nodejs-internals-event-loop-thread-pool</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[backend]]></category><category><![CDATA[Event Loop]]></category><category><![CDATA[abdulrdeveloper]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Wed, 07 Oct 2026 09:53:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/3fc6f282-7f19-4a02-8ad0-20aa3f72894b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>We use Node.js every day. We write <code>node app.js</code> and our code runs. But if somebody asks "what is happening behind the scene?", very few developers know the answer. For most of us, Node.js is a <strong>black box</strong>.</p>
<p>In this blog, we will open this box and look inside: V8, libuv, Event Loop and Thread Pool. We will also run small experiments, so we can see everything working with our own eyes.</p>
<hr />
<h2>Node.js Formula</h2>
<p>Node.js is not one single thing. It is a mixture of 3 big parts:</p>
<ul>
<li><p><strong>V8 Engine:</strong> made by Google, written in C++. It converts our JavaScript into machine code, very fast.</p>
</li>
<li><p><strong>libuv:</strong> a C library which handles async work (files, network, timers). It manages the <strong>Event Loop</strong> and the <strong>Thread Pool</strong>.</p>
</li>
<li><p><strong>C++ Bindings:</strong> the bridge between our JavaScript and the C/C++ parts.</p>
</li>
</ul>
<blockquote>
<p><strong>Formula:</strong> V8 + libuv + CPP + Bindings = Node.js</p>
</blockquote>
<p>Simple way to remember:</p>
<ul>
<li><p><strong>V8</strong> = the brain (understands JavaScript)</p>
</li>
<li><p><strong>libuv</strong> = the hands and legs (does the work in background)</p>
</li>
<li><p><strong>C++ Bindings</strong> = the nerves (connect brain and hands)</p>
</li>
</ul>
<p><strong>Important:</strong> V8 only understands JavaScript. It does not know how to read a file or make a network call. For that, it needs libuv.</p>
<hr />
<h2>The Life Cycle of <code>node app.js</code></h2>
<p>When we run <code>node app.js</code> in terminal, this happens on the <strong>main thread</strong>:</p>
<ol>
<li><p><strong>Init project:</strong> Node sets up its environment.</p>
</li>
<li><p><strong>Top level code:</strong> all the code outside callbacks runs first, and imports are loaded.</p>
</li>
<li><p><strong>Register callbacks:</strong> async work (timers, file reading) is registered, to run later.</p>
</li>
<li><p><strong>Start the Event Loop.</strong></p>
</li>
</ol>
<p>That is why top level code always prints first. Callbacks wait for their turn.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/6fc16b3c-8bdd-4ccf-891f-002c4f94e3d2.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>The Event Loop</h2>
<p>Event Loop is like a <code>while</code> loop which keeps running as long as there is some work to do. Think of it like a <strong>traffic signal</strong>: it decides which callback goes next.</p>
<pre><code class="language-javascript">while True {
  ExpiredCallbacks()   // run setTimeout / setInterval callbacks whose time is finished
  IO Polling()         // run callbacks of finished I/O work (file reading, network)
  setImmediate()       // run setImmediate callbacks
  close callbacks()    // run cleanup callbacks (like closing a connection)

  check if anything pending?
  No = Exit                    // nothing left: loop stops, program ends
  Yes = Continue               // work left: start the next round
}
</code></pre>
<p>After every round, Node checks: is anything still pending? If <strong>yes</strong>, the loop goes again. If <strong>no</strong>, the loop stops and the program exits.</p>
<p>That is why a simple script ends by itself after the last callback, and a server keeps running (because it is always waiting for new requests).</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/96a3cfd6-3138-436f-a185-2c72cc0821da.png" alt="" style="display:block;margin:0 auto" />

<hr />
<hr />
<h2>Exercises: Guess the Output First</h2>
<p>Now let's test the phases with small experiments. (Your project needs <code>"type": "module"</code> in <code>package.json</code>, because we use <code>import</code>.)</p>
<h3>Exercise 1: Timer vs Top Level Code</h3>
<pre><code class="language-javascript">import fs from 'fs';

setTimeout(() =&gt; console.log('Hello from Timer'), 0);

console.log('Hello from Top Level Code');
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello from Top Level Code
Hello from Timer
</code></pre>
<p>Even with <code>0</code> ms, the timer callback waits. First the top level code finishes, then the Event Loop starts and runs the timer.</p>
<hr />
<h3>Exercise 2: Timer vs Immediate</h3>
<pre><code class="language-javascript">import fs from 'fs';

setTimeout(() =&gt; console.log('Hello from Timer'), 0);
setImmediate(() =&gt; console.log('Hello from Immediate'));

console.log('Hello from Top Level Code');
</code></pre>
<p>Top level code is always first. But the order of Timer and Immediate is <strong>not guaranteed</strong> here. Why?</p>
<p><code>setTimeout(fn, 0)</code> is not really "zero". Node treats it as <strong>1 ms</strong>. When the loop starts, it checks the Timers phase first:</p>
<ul>
<li><p>If 1 ms has already passed, Timer runs first, then Immediate.</p>
</li>
<li><p>If 1 ms has not passed, Timer is skipped, and Immediate (Check phase) runs first.</p>
</li>
</ul>
<p>It depends on your machine speed, so run it 5-6 times. On some machines you will see Timer first, on some Immediate first.</p>
<hr />
<h3>Exercise 3: Adding File Reading</h3>
<pre><code class="language-javascript">import fs from 'fs';

setTimeout(() =&gt; console.log('Hello from Timer'), 0);
setImmediate(() =&gt; console.log('Hello from Immediate'));

fs.readFile('sample.txt', 'utf-8', function (err, data) {
  console.log('File Reading Complete...');
});

console.log('Hello from Top Level Code');
</code></pre>
<p>Output (usually):</p>
<pre><code class="language-plaintext">Hello from Top Level Code
Hello from Timer
Hello from Immediate
File Reading Complete...
</code></pre>
<p>Reading a file takes time, because it is done in the background (thread pool). So its callback comes in the <strong>Poll phase of a later round</strong>, after Timer and Immediate.</p>
<hr />
<h2>Thread Pool: The Helpers</h2>
<p>Event Loop runs on the main thread. But slow work like file reading or hashing cannot be done on the main thread, otherwise everything will freeze. So libuv has a <strong>Thread Pool</strong>: a group of helper threads (<strong>4 by default</strong>).</p>
<p><strong>What goes to the Thread Pool:</strong></p>
<ul>
<li><p><code>fs</code> (file system operations, like <code>readFile</code>)</p>
</li>
<li><p><code>crypto</code> (heavy functions like <code>pbkdf2</code>, <code>scrypt</code>, <code>randomBytes</code>)</p>
</li>
<li><p><code>zlib</code> (compression)</p>
</li>
<li><p><code>dns.lookup</code></p>
</li>
</ul>
<p><strong>What does NOT go to the Thread Pool:</strong></p>
<ul>
<li><p><strong>Your own JavaScript code.</strong> A heavy <code>for</code> loop with 1 billion iterations runs on the main thread, and it blocks everything.</p>
</li>
<li><p><strong>Network work</strong> (HTTP, TCP). It is handled by the operating system, without thread pool.</p>
</li>
<li><p><strong>Timers</strong> (<code>setTimeout</code>, <code>setInterval</code>).</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/6948051e-347a-4835-81a7-2c7913c8eb64.png" alt="" style="display:block;margin:0 auto" /></li>
</ul>
<hr />
<h3>Exercise 5 and 6: <em>5 Tasks with 4 Threads</em></h3>
<p>Inside the <code>readFile</code> callback, we start 5 <code>crypto.pbkdf2</code> hashing tasks (heavy work, so it goes to the thread pool):</p>
<pre><code class="language-javascript">import crypto from 'crypto';

const start = Date.now();

for (let i = 1; i &lt;= 5; i++) {
  crypto.pbkdf2('password', 'salt', 300000, 1024, 'sha256', () =&gt; {
    console.log(`Password ${i} has been hashed`, Date.now() - start);
  });
}
</code></pre>
<p>The thread pool has only 4 threads, but we have 5 tasks. So <strong>4 tasks start together</strong>, and the 5th task waits until one thread is free. That is why the first 4 finish at almost the same time, and the 5th finishes later.</p>
<p>Now run the same code with 8 threads:</p>
<pre><code class="language-bash"># Mac / Linux
UV_THREADPOOL_SIZE=8

# Windows (PowerShell)
$env:UV_THREADPOOL_SIZE=8;
</code></pre>
<p>Now all 5 tasks can start together. In our file, Password 4 has 10 times more iterations (1,000,000), so it finishes last.</p>
<p><strong>Note:</strong> more threads does not always mean more speed. Real parallel work also depends on your <strong>CPU cores</strong>. If you have 4 cores and 8 threads, the threads share the cores. Also, set <code>UV_THREADPOOL_SIZE</code> from the terminal, because setting it inside the script does not work on every system.</p>
<hr />
<h2>Blocking the Main Thread</h2>
<p>Now the most important lesson. See this code:</p>
<pre><code class="language-javascript">const start = Date.now();

setTimeout(() =&gt; {
  console.log('Timer fired after', Date.now() - start, 'ms');
}, 100);

// Blocking code: main thread is busy for 3 seconds
while (Date.now() - start &lt; 3000) {}
</code></pre>
<p>We asked for 100 ms, but the timer fires after about <strong>3000 ms</strong>. Why? The main thread was busy in our <code>while</code> loop, so the Event Loop could not move ahead.</p>
<p>This is why we say: <strong>never block the main thread.</strong> One heavy loop can freeze your whole server for all users. In real projects, heavy work should go to the thread pool, a worker, or another service.</p>
<hr />
<h2>Is Node.js Single-Threaded?</h2>
<p>The honest answer: <strong>your JavaScript code runs on a single main thread.</strong> But Node.js itself uses more threads in the background (libuv thread pool, and some helper threads of V8).</p>
<ul>
<li><p>Your JS code: <strong>single thread</strong></p>
</li>
<li><p>libuv thread pool: <strong>4 helper threads by default</strong></p>
</li>
<li><p>Network work: handled by the <strong>operating system</strong></p>
</li>
</ul>
<p>Think of a restaurant: <strong>one waiter</strong> (main thread), and <strong>many cooks</strong> in the kitchen (thread pool).</p>
<hr />
<h2>Interview Questions</h2>
<p><strong>1. Is Node.js single-threaded?</strong> Your JavaScript runs on one main thread, but Node uses libuv threads in the background.</p>
<p><strong>2. What is the Event Loop?</strong> A loop which keeps checking if the call stack is free and runs ready callbacks in phases (Timers, Poll, Check, Close).</p>
<p><strong>3. What goes in the Thread Pool, and what does not?</strong><code>fs</code>, <code>crypto</code>, <code>zlib</code> and <code>dns.lookup</code> go. Our own JavaScript code and network work do not.</p>
<p><strong>4.</strong> <code>setTimeout(0)</code> <strong>vs</strong> <code>setImmediate</code><strong>: which runs first?</strong> From the main module, no guarantee. Inside an I/O callback, <code>setImmediate</code> always runs first.</p>
<p>If you remember one line, remember this: <strong>JavaScript runs on one thread, but Node.js works with many.</strong></p>
<hr />
<blockquote>
<p>Try the exercises yourself here: <a href="https://github.com/abdulrdeveloper/FullStackHub/tree/main/Learn%20Backend/intro%20to%20NODE%20JS/nodejs-internals">https://github.com/abdulrdeveloper/FullStackHub/tree/main/Learn%20Backend/intro%20to%20NODE%20JS/nodejs-internals</a><br />first guess the output of every file, then run it.</p>
</blockquote>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[What is Node.js? JavaScript on the Server Explained]]></title><description><![CDATA[Learn what Node.js is: a JavaScript runtime built on V8. Understand how it runs JS on servers, the event loop, and real-world use cases.]]></description><link>https://blog.abdulrdeveloper.me/nodejs-javascript-on-the-server</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/nodejs-javascript-on-the-server</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[nodejs-internals]]></category><category><![CDATA[abdulrdeveloper]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Thu, 01 Oct 2026 11:38:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/76106640-28ba-4929-869a-d0757fb0ae91.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>What is Node.js?</h2>
<p>Node.js is not a programming language. It is also not a framework. Actually, Node.js is a <strong>JavaScript Runtime Environment</strong>.</p>
<p>Runtime means: a place where JavaScript code can run. With Node.js, we can run JavaScript on our laptop or on a server, without any browser.</p>
<pre><code class="language-bash">node app.js
</code></pre>
<p>Just write this one command in terminal, and your JavaScript file will run.</p>
<hr />
<h3>Language vs Runtime</h3>
<ul>
<li><p><strong>Language</strong> = the rules of code. Like <code>let</code>, <code>function</code>, <code>if</code>.</p>
</li>
<li><p><strong>Runtime</strong> = the place where that code runs, and it gives some extra tools to us.</p>
</li>
</ul>
<p>JavaScript is the same language everywhere, but the tools are different in different places:</p>
<table>
<thead>
<tr>
<th></th>
<th>Browser</th>
<th>Node.js</th>
</tr>
</thead>
<tbody><tr>
<td>Language</td>
<td>JavaScript</td>
<td>JavaScript</td>
</tr>
<tr>
<td>Extra tools</td>
<td><code>window</code>, <code>document</code>, DOM</td>
<td><code>fs</code>, <code>http</code>, <code>path</code>, <code>process</code></td>
</tr>
</tbody></table>
<hr />
<h2>Why JavaScript Was Browser-Only</h2>
<p>JavaScript was made in 1995 for the browser. It`s only job was small things on a webpage, like button click, form validation, or changing some text.</p>
<p>The problem was: JavaScript code could only run <strong>inside the browser</strong>, because only the browser had a JavaScript engine. If you wanted a backend (database, files, login), you had to use another language like PHP or Java. So developers needed to learn two languages: one for frontend, one for backend.</p>
<hr />
<h2>How Node.js Made JavaScript Run on Servers</h2>
<p>In 2009, <strong>Ryan Dahl</strong> had a simple idea: Chrome's JavaScript engine (<strong>V8</strong>) is very fast. Why not take it out of the browser and use it on the server also?</p>
<p>So he took V8, added some extra things around it (like file system, network, etc.), and made <strong>Node.js</strong>.</p>
<p>Now JavaScript can do backend work too: read files, talk to database, create servers. Same language on frontend and backend.</p>
<hr />
<h2>V8 Engine (High Level)</h2>
<p>Computer cannot understand JavaScript directly. It only understands machine code (0 and 1). <strong>V8</strong> is the engine which converts our JavaScript code into machine code, and it does this very fast.</p>
<p>V8 is written in C++ and made by Google. Chrome uses it, and Node.js uses it also. That`s why Node.js is fast.</p>
<p><strong>Important:</strong> V8 only runs JavaScript. It don`t know how to read a file or make a server. For that, Node.js adds other parts.</p>
<hr />
<h2>Node.js Runtime Architecture</h2>
<p>Node.js is made of 3 main parts:</p>
<ul>
<li><p><strong>V8:</strong> runs our JavaScript code.</p>
</li>
<li><p><strong>libuv:</strong> a C++ library which handles background work like files and network. It manages the <strong>Event Loop</strong> also.</p>
</li>
<li><p><strong>C++ Bindings:</strong> the bridge between our JavaScript and C++.</p>
</li>
</ul>
<p><strong>Formula:</strong> V8 + libuv + CPP + Bindings = Node.js</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/f654bf00-d34a-4c1d-be64-2f745fbbc591.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Browser JS vs Server JS</h2>
<p>Same language, but different roles:</p>
<ul>
<li><p><strong>Browser JS:</strong> works with the user's screen. It changes the page using <code>document</code> and <code>window</code>.</p>
</li>
<li><p><strong>Server JS (Node.js):</strong> works behind the scene. It reads files, talks to database, and sends response using <code>fs</code>, <code>http</code>, <code>process</code>.</p>
</li>
</ul>
<p>Just suppose JavaScript is an <strong>actor</strong>. In browser, he works on the stage in front of the audience. In Node.js, he works behind the camera. Actor is same, but the role is different.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/77709487-87e6-446c-8304-11604a925375.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Node.js vs PHP / Java</h2>
<table>
<thead>
<tr>
<th></th>
<th>Traditional (PHP / Java)</th>
<th>Node.js</th>
</tr>
</thead>
<tbody><tr>
<td>Language</td>
<td>PHP or Java</td>
<td>JavaScript</td>
</tr>
<tr>
<td>Request handling</td>
<td>Traditionally, one thread for each request</td>
<td>One main thread with event loop</td>
</tr>
<tr>
<td>Waiting for file/DB</td>
<td>Thread waits</td>
<td>Does not wait, moves to next work</td>
</tr>
<tr>
<td>Frontend + backend</td>
<td>Two languages</td>
<td>One language</td>
</tr>
</tbody></table>
<p>In the traditional way, when 1000 users come, the server makes many threads, and each thread waits for its own work. It takes more memory. Node.js handles many requests on one main thread, and it does not wait. That is why Node.js is very good for apps with many users.</p>
<p><em>(Note: modern PHP and Java also have async options now, but this is how they were traditionally used.)</em></p>
<hr />
<h2>Event-Driven Architecture</h2>
<p>Event-driven means: <strong>do the work when an event happens</strong>, don't sit and wait.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/b09efa7d-8b31-4c91-9da2-49caca954f49.png" alt="" style="display:block;margin:0 auto" />

<p>Think of a restaurant with <strong>one waiter</strong>:</p>
<ul>
<li><p>He takes order from table 1, gives it to the kitchen, and <strong>does not stand there waiting</strong>.</p>
</li>
<li><p>He goes to table 2, takes the order.</p>
</li>
<li><p>When the kitchen says "order ready" (event), he serves the food.</p>
</li>
</ul>
<p>One waiter handles many tables, because he never waits. Node.js works exactly like this.</p>
<pre><code class="language-javascript">console.log("Order 1 taken");

setTimeout(() =&gt; {
    console.log("Order 1 ready");
}, 2000);

console.log("Order 2 taken");

// Output:
// Order 1 taken
// Order 2 taken
// Order 1 ready  (after 2 seconds)
</code></pre>
<p>Node did not wait for 2 seconds. It moved ahead, and came back when the timer was done. The part which manages this is called the <strong>Event Loop</strong>.</p>
<hr />
<h2>Real-World Use Cases</h2>
<p>Node.js is used when many users are connected and lots of input/output is happening:</p>
<ul>
<li><p><strong>REST APIs and backends:</strong> most common use.</p>
</li>
<li><p><strong>Chat apps:</strong> real-time messages (with WebSockets).</p>
</li>
<li><p><strong>Streaming:</strong> video and audio streaming.</p>
</li>
<li><p><strong>Developer tools:</strong> tools like Vite and many build tools run on Node.js.</p>
</li>
<li><p><strong>Server-side rendering:</strong> frameworks like Next.js.</p>
</li>
</ul>
<p><strong>Where not to use:</strong> heavy CPU work (like video editing or big calculations), because it blocks the main thread.</p>
<hr />
<h2>Why Developers Adopted Node.js</h2>
<ul>
<li><p><strong>One language:</strong> JavaScript for frontend and backend.</p>
</li>
<li><p><strong>Fast:</strong> V8 engine and non-blocking work.</p>
</li>
<li><p><strong>npm:</strong> a huge collection of ready-made packages.</p>
</li>
<li><p><strong>Big community:</strong> easy to find help.</p>
</li>
</ul>
<hr />
<h2>Quick Note:</h2>
<ul>
<li><p>Node.js is a <strong>JavaScript runtime</strong>, not a language.</p>
</li>
<li><p>JavaScript was browser-only, until Node.js took <strong>V8</strong> out of the browser.</p>
</li>
<li><p>Node.js = <strong>V8 + libuv + CPP + Bindings</strong>.</p>
</li>
<li><p>It is <strong>event-driven</strong>: one waiter, many tables, no waiting.</p>
</li>
<li><p>Best for APIs, chat apps, streaming and tools.</p>
</li>
</ul>
<p><strong>Node.js lets JavaScript run outside the browser.</strong></p>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[this in JavaScript: The Actor Who Changes Roles]]></title><description><![CDATA[Learn the JavaScript this keyword with a simple actor analogy: global context, objects, functions, and how the caller changes this.]]></description><link>https://blog.abdulrdeveloper.me/this-in-javascript-the-actor-who-changes-roles</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/this-in-javascript-the-actor-who-changes-roles</guid><category><![CDATA[this keyword]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[abdulrdeveloper]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[this keyword in javascript]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Thu, 01 Oct 2026 07:56:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/0034d554-d667-48ff-8cea-d5ee3037a182.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>What is <code>this</code> in JavaScript ?</h2>
<p>In almost all other languages, <code>conditionals, loops, functions</code> and these basic things are almost the same. But in JavaScript, <code>this</code> is a keyword that makes JavaScript different.</p>
<p><code>this</code> also exists in other languages, but in JavaScript it is used at a very high level. And after learning <code>this</code> , we can easily understand <code>call</code>, <code>apply</code>, <code>bind</code> and <code>new</code> later.</p>
<hr />
<h3><code>this</code> in Real World:</h3>
<p>Just suppose <code>this</code> is an <strong>actor</strong>. The same actor plays different roles in different movies. Actor is same, but the role depends on the movie.</p>
<p>In the same way, the value of <code>this</code> is not fixed. It depends on where and how the code is run.</p>
<p>Or understand it like this: every person behaves different in his own area. At home different, in office different. <code>this</code> also changes according to its environment.</p>
<hr />
<h3><code>this</code> in the Global Context</h3>
<p>Global context means: no function, no object, just <code>this</code> is written.</p>
<pre><code class="language-javascript">console.log(this);
</code></pre>
<ul>
<li><p><strong>In Browser console:</strong> we get the <code>Window</code> object</p>
</li>
<li><p><strong>In Node.js:</strong> we get an empty object <code>{}</code></p>
</li>
</ul>
<p>Code is same, but environment is different, that`s why <code>this</code> is different.</p>
<p><strong>Small Update for Node.js:</strong></p>
<ul>
<li><p>The <code>{}</code> result comes when your file is a CommonJS module (the one which uses <code>require</code>).</p>
</li>
<li><p>But if you use ES Modules (the one which uses <code>import</code>), then <code>this</code> will be <code>undefined</code> there.</p>
</li>
</ul>
<pre><code class="language-javascript">// CommonJS file (require)
console.log(this); // {}

// ES Module file (import)
console.log(this); // undefined
</code></pre>
<p>As we can see visually in the diagram below:</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/d832b9e1-059d-4ea4-84f3-6f5a70146c56.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2><code>this</code> Inside Objects</h2>
<p>Inside an object, <code>this</code> points to <strong>that same object</strong>. It is like the object is saying "my own properties". So with <code>this</code>, we can easily access other properties of the same object from inside its method.</p>
<pre><code class="language-javascript">const bollywoodFilm = {
    name: "Bajirao Mastani",
    lead: "Ranveer",
    introduce() {
        return `${this.lead} performs in ${this.name}`;
    },
};

console.log(bollywoodFilm.introduce());
// Output: Ranveer performs in Bajirao Mastani
</code></pre>
<p>Here <code>introduce()</code> is called by <code>bollywoodFilm</code>, so <code>this</code> = <code>bollywoodFilm</code>. That is why <code>this.lead</code> gives "Ranveer" and <a href="http://this.name"><code>this.name</code></a> gives "Bajirao Mastani".</p>
<p><strong>Easy way to Remember:</strong> Look at the left side of the dot. <code>this</code> is calling the method.</p>
<pre><code class="language-javascript">bollywoodFilm.introduce();
// ↑ left of the dot = bollywoodFilm = this
</code></pre>
<p>That`s how we can easily use this anywhere <strong>inside the object's methods</strong>, but remember, it works properly with <strong>regular methods</strong>. Arrow functions are different.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/9490b057-38fa-4967-a268-e2b181c97cc6.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2><code>this</code> <strong>Inside Functions</strong></h2>
<p>Now let's see <code>this</code> inside a normal function, which is not inside any object.</p>
<pre><code class="language-javascript">function showThis() {
    return typeof this;
}

console.log(showThis());
// Output: object
</code></pre>
<p>Here nobody is calling the function with a dot, so <code>this</code> becomes the <strong>global object</strong>.</p>
<ul>
<li><p>In Browser: <code>Window</code> object</p>
</li>
<li><p>In Node.js: Nodejs <code>global</code> object</p>
</li>
</ul>
<h4><strong>But using Strict Mode :</strong></h4>
<p>If we write <code>"use strict"</code> inside the function, the result will be different.</p>
<pre><code class="language-javascript">function showThisStrict() {
    "use strict";
    return typeof this;
}

console.log(showThisStrict());
// Output: undefined
</code></pre>
<p>In strict mode, JavaScript does not give the global object. <code>this</code> is just <code>undefined</code>.</p>
<p>Strict mode is safer, because we don't accidentally touch the global object.</p>
<h4><strong>Quick Summary</strong></h4>
<table>
<thead>
<tr>
<th><strong>Function type</strong></th>
<th><strong>Value of</strong> <code>this</code></th>
</tr>
</thead>
<tbody><tr>
<td>Normal function (no strict)</td>
<td>Global object</td>
</tr>
<tr>
<td>Normal function (strict mode)</td>
<td><code>undefined</code></td>
</tr>
</tbody></table>
<p>In a function, always check who is calling it. If nobody is calling it with a dot, then <code>this</code> is global object (or <code>undefined</code> in strict mode).</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/ef36c1d4-52f2-456c-9c84-86d9682b3b6f.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>How Calling Context Changes <code>this</code></h2>
<p>The most important point: <code>this</code> does not depend on where the function is <strong>written</strong>. It depends on <strong>who is calling it</strong>.</p>
<p>javascript</p>
<pre><code class="language-javascript">const actor = {
    name: "Ranveer",
    bow() {
        return `${this.name} takes a bow`;
    },
};

console.log(actor.bow());
// Output: Ranveer takes a bow

const detachedBow = actor.bow;
console.log(detachedBow());
// Output: undefined takes a bow
</code></pre>
<p>In the first call, <code>actor</code> is calling <code>bow()</code>, so <code>this</code> = <code>actor</code>.</p>
<p>In the second call, we took the method out of the object and called it alone. Now nobody is on the left of the dot, so <code>this</code> is lost. This is called a <strong>detached method</strong>: the method loses its context.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/24b55546-59b3-4d36-8a41-84e2a92c42ed.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Can We Set <code>this</code> Ourselves?</h2>
<p>In the last example, <code>detachedBow()</code> lost its <code>this</code>. Normally JavaScript decides <code>this</code> by itself, depending on who is calling the function.</p>
<p>But JavaScript also gives us three methods to <strong>set</strong> <code>this</code> <strong>manually</strong>: <code>call()</code>, <code>apply()</code> and <code>bind()</code>.</p>
<hr />
<h2><code>call()</code></h2>
<p><code>call()</code> runs the function <strong>immediately</strong>, and we decide what <code>this</code> will be. The first value we pass is <code>this</code>.</p>
<p>We can borrow a method from one object and use it for another object. Here we use <code>introduce()</code> from <code>bollywoodFilm</code> for a different film:</p>
<pre><code class="language-javascript">const bollywoodFilm = {
    name: "Bajirao Mastani",
    lead: "Ranveer",
    introduce() {
        return `${this.lead} performs in ${this.name}`;
    },
};

const anotherFilm = {
    name: "Pathaan",
    lead: "Shah Rukh",
};

console.log(bollywoodFilm.introduce.call(anotherFilm));
// Output: Shah Rukh performs in Pathaan
</code></pre>
<p>Let's understand how this works:</p>
<ol>
<li><p><code>bollywoodFilm.introduce</code> gives us the function. It does not run yet.</p>
</li>
<li><p><code>.call(anotherFilm)</code> runs that function immediately and sets <code>this</code> = <code>anotherFilm</code>.</p>
</li>
<li><p>Inside the function, <code>this.lead</code> is now "Shah Rukh" and <code>this.name</code> is "Pathaan".</p>
</li>
</ol>
<p>So the method belongs to <code>bollywoodFilm</code>, but <code>anotherFilm</code> <strong>borrowed</strong> it without writing it again. This is called <strong>method borrowing</strong>.</p>
<p>If the function needs arguments, we pass them <strong>one by one</strong> after <code>this</code>:</p>
<pre><code class="language-javascript">function announce(city, day) {
    return `${this.name} releases in ${city} on ${day}`;
}

console.log(announce.call(anotherFilm, "Lahore", "Friday"));
// Output: Pathaan releases in Lahore on Friday
</code></pre>
<hr />
<h2><code>apply()</code></h2>
<p><code>apply()</code> does the same work as <code>call()</code>. The only difference is how we send the arguments: in <strong>one array</strong>.</p>
<pre><code class="language-javascript">console.log(announce.apply(anotherFilm, ["Lahore", "Friday"]));
// Output: Pathaan releases in Lahore on Friday
</code></pre>
<p>Use <code>apply()</code> when your arguments are already inside an array.</p>
<hr />
<h2><code>bind()</code></h2>
<p><code>bind()</code> does <strong>not run</strong> the function. It returns a <strong>new function</strong> in which <code>this</code> is locked.</p>
<p>This is the fix for our detached method problem:</p>
<pre><code class="language-javascript">const actor = {
    name: "Ranveer",
    bow() {
        return `${this.name} takes a bow`;
    },
};

const detachedBow = actor.bow;
console.log(detachedBow());
// this is lost here (the output depends on the environment, as we saw above)

const boundBow = actor.bow.bind(actor);

console.log(boundBow());
// Output: Ranveer takes a bow
</code></pre>
<p>Let's understand how this works:</p>
<ol>
<li><p><code>actor.bow.bind(actor)</code> does <strong>not</strong> run the function. It gives us a <strong>new function</strong>.</p>
</li>
<li><p>In this new function, <code>this</code> is locked to <code>actor</code>.</p>
</li>
<li><p>We store it in <code>boundBow</code>, so now we can call it any time, and it will always say "Ranveer takes a bow".</p>
</li>
</ol>
<p>That is why <code>bind()</code> is useful when a method is passed alone as a callback, for example in a timer or an event handler. Without <code>bind()</code>, the method loses its <code>this</code>, as we saw in <code>detachedBow</code>.</p>
<hr />
<h2><code>call()</code> vs <code>apply()</code> vs <code>bind()</code></h2>
<table>
<thead>
<tr>
<th></th>
<th><code>call()</code></th>
<th><code>apply()</code></th>
<th><code>bind()</code></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Runs the function?</strong></td>
<td>Yes, immediately</td>
<td>Yes, immediately</td>
<td>No, returns a new function</td>
</tr>
<tr>
<td><strong>Arguments</strong></td>
<td>One by one</td>
<td>In an array</td>
<td>One by one</td>
</tr>
<tr>
<td><strong>Returns</strong></td>
<td>Result of the function</td>
<td>Result of the function</td>
<td>A new function</td>
</tr>
<tr>
<td><code>this</code></td>
<td>Set for this call only</td>
<td>Set for this call only</td>
<td>Locked inside the new function</td>
</tr>
</tbody></table>
<p><strong>Easy way to Remember:</strong></p>
<ul>
<li><p><strong>C</strong>all = <strong>C</strong>omma (arguments separated by commas)</p>
</li>
<li><p><strong>A</strong>pply = <strong>A</strong>rray (arguments in an array)</p>
</li>
<li><p><strong>B</strong>ind = <strong>B</strong>aad mein (runs later, it gives a new function)</p>
</li>
</ul>
<hr />
<h2>What About Arrow Functions?</h2>
<p>Arrow functions are different. They do not have their own <code>this</code>. They take <code>this</code> from the place where they are written, so <code>call()</code>, <code>apply()</code> and <code>bind()</code> cannot change it.</p>
<p>That is why we use normal functions when we want <code>this</code> to depend on the caller.</p>
<hr />
<h3>Quick Note:</h3>
<ul>
<li><p><strong>Global context:</strong> <code>Window</code> in browser, <code>{}</code> in Node.js (CommonJS)</p>
</li>
<li><p><strong>Inside object method:</strong> <code>this</code> = the object itself</p>
</li>
<li><p><strong>Inside normal function:</strong> global object, or <code>undefined</code> in strict mode</p>
</li>
<li><p><strong>Calling context:</strong> always check who is calling the function</p>
</li>
<li><p><code>call()</code><strong>:</strong> runs now, arguments one by one</p>
</li>
<li><p><code>apply()</code><strong>:</strong> runs now, arguments in an array</p>
</li>
<li><p><code>bind()</code><strong>:</strong> runs later, returns a new function with locked <code>this</code></p>
</li>
</ul>
<hr />
<p>If you did not find a topic you were looking for, please check my notes. I hope you will find it there: <a href="https://github.com/abdulrdeveloper/FullStackHub/tree/main/Learn%20JavaScript">FullStackHub / Learn JavaScript</a></p>
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a></p>
<p>Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Git & GitHub | oriantation class + cohort 3 + tea class 1]]></title><description><![CDATA[Sab se pehle question aata hai ke hum Git & GitHub hi kyun Study karna chahte hain? Git ke bina bhi to work ho raha tha, fir kya wajah thi ke Git & GitHub…]]></description><link>https://blog.abdulrdeveloper.me/git-github-oriantation-class-cohort-3-tea-class-1</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/git-github-oriantation-class-cohort-3-tea-class-1</guid><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Tue, 04 Aug 2026 15:57:52 GMT</pubDate><content:encoded><![CDATA[<hr />
<h1>01_Git_And_GitHub_Why_Learning_Matters</h1>
<h3><strong>Question</strong> :: &gt;</h3>
<p>Sab se pehle question aata hai ke hum Git &amp; GitHub hi kyun Study karna chahte hain? Git ke bina bhi to work ho raha tha, fir kya wajah thi ke Git &amp; GitHub ko create/build/introduce karna pada?</p>
<h3><strong>Ans with Example :: &gt;</strong></h3>
<ol>
<li><p>Man lo ke ek developer hai Ahmad jo apni local machine par code run karta hai. Vo apna code ek pen drive mein save karke apne teammate ke saath share karta hai taake vo bhi uska use kar sake.</p>
</li>
<li><p>Jab teammate vo code dekhta hai to khud se bhi kuch changes kar deta hai aur phir se Ahmad ko updated code ki pen drive de deta hai.</p>
</li>
<li><p>Ab Ahmad ko nahi pata ke code mein kya ho raha hai, kaun se changes hue hain, kahan-kahan changes hue hain.</p>
</li>
<li><p>Kuch der baad teammate ko realize hota hai ke uske code mein issue tha to vo unko fix karta hai. Phir se Ahmad ko pen drive dena parta hai. Yeh cycle aisi hi chalti rahi...</p>
</li>
</ol>
<h3><strong>Problems They Face :: &gt;</strong></h3>
<ol>
<li><p>Agar teammate changes karta to Ahmad ko pata nahi chalta tha ke code mein kya change hua -</p>
</li>
<li><p>Agar Ahmad changes karta to teammate ko pata nahi chalta tha ke code mein kya change hua -</p>
</li>
<li><p>Kaunsi files change hui, kaunsi delete hui - iska pata nahi chalta tha -</p>
</li>
<li><p>Jab bhi koi changes karta to har baar pen drive share karna parta tha - Dono ek saath kaam nahi kar sakte the (collaboration bohat mushkil tha) -</p>
</li>
<li><p>Code ke changes ka koi history/record nahi rehta tha - purana version nahi mil sakta tha</p>
</li>
</ol>
<h3>Solution - Part 1 : Git ( Local Version Control ) :: &gt;</h3>
<p>Now... jab unho ne problem find kiya to unho ne ek CODE TRACKER banaya jise "Git" ka naam diya. Actually, "Git" ek Version Control System (VCS) hai. Market mein doosre VCS bhi hain jaise Mercurial, Apache Subversion (SVN) etc, lekin Git most popular hai.</p>
<p><strong>Ab Git yeh kaam karta hai</strong> …</p>
<ol>
<li><p>Unke code ke sab changes track karta hai -</p>
</li>
<li><p>Batata hai ke code mein kisne, kab aur kya changes kiye -</p>
</li>
<li><p>Modified/changed files ki history dikhaata hai -</p>
</li>
<li><p>1 developer bhi use kar sakta hai (local mein) -</p>
</li>
<li><p>Iss tarah se unho ne ek problem solve kar liya.</p>
<hr />
</li>
</ol>
<p><strong>Lekin abhi bhi ek BADA PROBLEM tha …</strong></p>
<ol>
<li><p>Pen drive har baar share karna padta tha -</p>
</li>
<li><p>Kaunsa version latest/updated tha iska confusion hota tha -</p>
</li>
<li><p>Ek central backup nahi tha -</p>
</li>
<li><p>Sirf local machine par code tha - jiske paas pen drive hoti, sirf vo hi code kar sakta tha , Yeh collaboration ka bohat bada problem tha.</p>
</li>
</ol>
<h3><strong>Solution - Part 2 : Remote Repository (GitHub) :: &gt;</strong></h3>
<p>To unho ne mil kar ek single source SOLUTION banaya taake sab developers apna updated code ek central server par push kar saken, jise "GitHub" ka naam diya. Actually, jise ham "server" boltay hain, us concept ko "Remote Repository" kehte hain. GitHub sirf ek example hai. Doosre remote services bhi hain jaise GitLab, Bitbucket etc.</p>
<p><strong>Ab GitHub (Remote) yeh kaam karta hai ::&gt;</strong></p>
<ol>
<li><p>Ek central server hai (cloud mein) jahan par collaboration ho sakti hai developers ki -</p>
</li>
<li><p>Jitne bhi developers hain, sab GitHub par connect ho jate hain -</p>
</li>
<li><p>Jab koi developer code update karta hai, vo GitHub par "Push" kar deta hai - Baaki sab developers easily latest code dekh sakte hain aur use "Pull" kar lete hain -</p>
</li>
<li><p>Har kisi ko instantly pata chal jata hai ke code mein kya change hua -</p>
</li>
<li><p>Code ka complete backup safely reh jaata hai cloud par Is tarah se collaboration ki problem bhi completely solve ho gaya!</p>
<hr />
<h3><strong>Important Note - Git is Independent :: &gt;</strong></h3>
<p>Git ka use 1 developer bhi kar sakta hai apni local machine par:</p>
<ul>
<li><p>Apne code ke changes dekh sakta hai</p>
</li>
<li><p>kal kya changes kiye the, aaj kya changes kiye hain</p>
</li>
<li><p>Agar code mein koi issue ho jaye to purane code mein easily ja sakte hain -</p>
</li>
<li><p>Git ko internet ya server ki zaroorat nahi - yeh LOCAL software hai Jab Git bana tha to sirf local use ke liye bana tha taake aap apne projects ko track kar sako.</p>
</li>
</ul>
<p>Baad mein jab collaboration ki zaroorat padi, tab GitHub jaisi remote services bani jo Git ko cloud par host karti hain.</p>
<p>Simple Words Mein:</p>
<ul>
<li><p>Git = Local Version Control System (Apke computer par)</p>
</li>
<li><p>GitHub = Remote Repository Hosting (Internet par, collaboration ke liye)</p>
</li>
<li><p>GitLab = GitHub jaisa ek aur remote option</p>
</li>
</ul>
</li>
</ol>
<h3>Who Built Git :: &gt;</h3>
<p>Git ko "Linus Torvalds" ne 2005 mein banaya tha. Vo Linux Operating System par kaam kar rahe the aur us time Linux bohat tezi se grow ho raha tha. Hazaron developers ek saath kaam kar rahe the aur code ko track karna bohat mushkil ho gaya tha.</p>
<p>Pehle vo doosre version control systems use kar rahe the (jaise SVN) lekin vo slow aur limited the. To Linus ne socha ke khud ka version control system banana chahiye jo: - Bohat fast ho - Distributed ho (har developer ke paas poora code ho) - Reliable ho Unhone sirf kuch hafton mein Git bana diya as a side project! Aaj Git duniya ka sabse popular version control system hai.</p>
<p><strong>Fun Fact :</strong> "Git" ka matlab English mein "annoying ya foolish person" hota hai. Linus ne mazak mein yeh naam rakha tha kyunke Git version control kaafi strict aur complicated tha! Waise bhi, Linux ke baad Git ek aur "Linus creation" hai jo duniya badal gaya!</p>
<h3><strong>Important Clarification Git vs GitHub :</strong></h3>
<p>Aaj kal bohat se log resume likhtay hain "GitHub seekha" lekin TECHNICALLY GALAT HAI! Sach yeh hai:</p>
<ul>
<li><p>❌ "GitHub seekha" = GALAT</p>
</li>
<li><p>✅ "Git seekha" = SAHI Kyun?</p>
</li>
</ul>
<p>GitHub sirf ek HOSTING SERVICE hai jahan par code store karta hai. GitHub seekhna matlab sirf button click karna aur repository banalo. Git ek COMPLETE VERSION CONTROL SYSTEM hai jo seekhna padta hai and ham jald hi seekhe gay.</p>
<ol>
<li><p>Commands samajhna (init, add, commit, push, pull, branch, merge, etc.) -</p>
</li>
<li><p>Concepts samajhna (staging, commits, history, etc.) - Workflows seekhna (how to collaborate properly) -</p>
</li>
<li><p>Problem solving (conflicts resolve karna, etc.)</p>
</li>
</ol>
<h3><strong>Git aur GitHub mai kya Difference hai ?</strong></h3>
<ul>
<li><p>"Git = Version Control System (tool/language)</p>
</li>
<li><p>GitHub = Git ke liye hosting service (platform)"</p>
</li>
<li><p>Most students GitHub account banate hain but Git properly nahi seekhte. To GitHub repository banate hain par actually kaam nahi aata Git ka! Isliye jab interview mein puchche, to proper answer dena!</p>
</li>
</ul>
<hr />
<h1><strong>02_Git_Complete_Guide_A_to_Z</strong></h1>
<h3>Let's Learn Git :: &gt;</h3>
<p>Ok, sab se pehle question aata hai ke Git internally code/project ko track kaise karta hai? Vo kaise hamara complete code ke changes ko track karta hai aur hum to kuch bhi see nahi karte, fir Git ko kaise pata chal jaata hai ke code mein kya change hua?</p>
<p><strong>Ans ::&gt;</strong> Jab Linus Torvalds ne Git banana shuru kiya to usne socha: "Mujhe code ke changes track to krne hain, par inhe store kahan karu?" , Database (MongoDB, MySQL, PostgreSQL) mein store kar sakta tha, lekin database separate server par rehta hai - portable nahi hota (move/shift mushkil). To usne ek CLEVER SOLUTION nikala: Project ke andar hi ek ".git" folder banaya (hidden folder), Is folder mein ek special "database" hota hai (actually complex file structure hain), Jo har single change ko record karta hai.</p>
<p><strong>Now, jab koi code likhta hai aur Git se commit karte hain to:</strong></p>
<ol>
<li><p>Git automatically uski sab files ko scan karta hai</p>
</li>
<li><p>Dekhta hai ke kya changes hue.</p>
</li>
<li><p>Har change ko + aur - mein show karta hai :</p>
<p>+ = Nai line add hui - = Line remove/delete hui</p>
</li>
<li><p>Un changes ke liye ek unique ID (hash) generate karta hai, Taake future mein is unique ID se specific change dekh saken.</p>
</li>
<li><p>Sab kuch .git folder mein save kar deta hai , Future mein jab purane changes dekhne ho ya purana code chahiye, vo commands se dekh sakta hai</p>
<h3>Simple Example :</h3>
<p><strong>Ahmad :</strong> "file.js mein 5 nai lines add kiye"</p>
<p>↓</p>
<p><strong>Git :</strong> ".git folder mein record save kiya (+ 5 lines)"</p>
<p>↓</p>
<p><strong>Ahmad :</strong> "git log command chalata hai"</p>
<p>↓</p>
<p><strong>Git :</strong> ".git folder se data nikaal kar Ahmad ko show karta hai"</p>
<p><strong>IMPORTANT Point ::</strong></p>
<p>.git Folder Hidden Hota Hai, Isliye Linus ne .git folder ko "hidden" banaya Taake user accidentally usse touch ya delete na kar de Windows/Mac/Linux mein hidden files/folders hote hain, Jisse .git folder safe aur protected rehta hai.</p>
</li>
</ol>
<h2>GIT COMMANDS :</h2>
<hr />
<h3><strong>Command 1 : git init</strong></h3>
<p>Ab samjho, agar hum apna khud ka Git system banana chahte hain (like Linus ne banaya tha), to terminal mein git ke commands likhnay partay hain.</p>
<pre><code class="language-powershell">git init           # git init command : 1
</code></pre>
<p><strong>Git kehta hai:</strong> "Tum git init command do, main ek .git folder banao dun ga jo hidden rhay ga tumhay usmay kuh nai krna "</p>
<p><strong>What Happens:</strong></p>
<p>Tum: "git init" command terminal mein likho aur Enter press karo</p>
<p>↓</p>
<p><strong>Git:</strong> Automatically ek hidden ".git" folder banata hai jisme apko kuch nai krna</p>
<p><strong>Example:</strong></p>
<p>$ git init</p>
<p><strong>Output:</strong> "Initialized empty Git repository in /path/to/your/project/.git/"</p>
<p>(Means: .git folder successfully created!)</p>
<p>For Verification (Check karna ke .git folder ban gaya):</p>
<p><strong>$ ls -a</strong></p>
<p><strong>Output:</strong> . .. .git file.js index.html</p>
<p>(Dekho! .git folder dikh raha hai hidden files ke sath)</p>
<p><strong>Note:</strong></p>
<p><strong>ls = List files</strong> (sirf visible files dikhata hai)</p>
<p><strong>ls -a = List ALL files</strong> (hidden files bhi dikhata hai)</p>
<p>.git folder hidden hota hai isliye "ls -a" use karna padta hai.</p>
<hr />
<h3><strong>Command 2 : git add . or git add</strong></h3>
<p>Ab hmare paas .git folder ready hai. Lekin Git abhi tak hmare code ko track nahi kar raha.</p>
<pre><code class="language-powershell">git add &lt;filename&gt;    #  It will add specific file  . you will use it in 5% cases
</code></pre>
<p><strong>or</strong></p>
<pre><code class="language-powershell">git add .     # It will add all files  . you will use it in 95% cases
</code></pre>
<p>Git bolta hai: "Tumne code likha hai, par mujhe bataya nahi ke kaunsi files ko track karu!"</p>
<p>To Git kehta hai: "Tum .git add command do. Main us file ko "staging area" mein daal deta hun. Abhi track nahi, bas commit karne ke liye ready kar dunga".</p>
<p>What Happens:</p>
<p><strong>Tum</strong> : "git add file.js" (ya "git add ." sab files ke liye)</p>
<p>↓</p>
<p><strong>Git :</strong> "Ok, maine file.js ko track list mein daal diya"</p>
<p>↓</p>
<p>Ab ye file "staging area" mein chali gai (ose pta chl gya he ke kis file ko track krna he)</p>
<p><strong>Example:</strong></p>
<p><strong>$ git add file.js</strong></p>
<p>(Koi output nahi - silently uss file ko track kar leta hai)</p>
<p>or</p>
<p><strong>$ git add .</strong></p>
<p>(Sab files track ko track kr leta he )</p>
<p>ab Git ko complete pta he ke konsi file ko track krna he and usne file complete ready kr di he but track nai kia.</p>
<hr />
<h3><strong>Command 3 : git commit</strong></h3>
<p>Ab Git ko pata chal gaya ke kaunsi files track karni hain aur sab kuch staging area mein ready hai. Lekin abhi tak Git ne files ko .git folder mein SAVE nahi kiya.</p>
<pre><code class="language-powershell">git commit -m "I update readme file"      # you can type any message,use it professionally
</code></pre>
<p><strong>Git bolta hai:</strong> "Ab git commit command do. Main in files ko .git folder mein permanently save kar dunga aur ek unique ID (hash) dunga".</p>
<p><strong>What Happens:</strong></p>
<p>Tum: git commit -m " your message "</p>
<p>↓</p>
<p>Git: ".git folder mein files permanently save kar deta hai"</p>
<p>↓</p>
<p>Har commit ko ek unique hash (ID) generate karta hai</p>
<p>↓</p>
<p>Ab changes .git folder mein permanently record ho gayi</p>
<p><strong>Example:</strong></p>
<p><strong>$ git commit -m "Added login feature"</strong></p>
<p><strong>Output :</strong> "[master abc123d] Added login feature 1 file changed, 50 insertions(+)"</p>
<p>(Dekho! Unique ID "abc123d" diya - and iss ID se commit ko future mein identify kar sakte ho)</p>
<hr />
<p>COMPLETE WORKFLOW:</p>
<ol>
<li><p>git init [ .git folder banao (first time only) , Code likho / changes karo ]</p>
</li>
<li><p>git add . [ → Git ko batao: "Inn files ko track karna hai!" ]</p>
</li>
<li><p>git commit -m "message" [ → Git ko kahao: "Ab save kar do unn files ko!" ]</p>
</li>
</ol>
<p><strong>REPEAT:</strong></p>
<p>Step 2,3 and 4 har baar jab code mai koi new changes kro to repeat kro!</p>
<hr />
<h3><strong>Command 4 : git log</strong></h3>
<p>Poori history dekh sakte ho jab chahiye.</p>
<pre><code class="language-powershell">git log
</code></pre>
<p>(<strong>Output:</strong> Sab commits with hash, author, date, aur message dikhega)</p>
<p>Short Version (Easy View):</p>
<pre><code class="language-powershell">git log --oneline   # oneline view short and easy view
</code></pre>
<p>(<strong>Output:</strong> Sirf hash aur message dikhega - ek line per ek commit)</p>
<p><strong>Example:</strong></p>
<p>$ git log --oneline</p>
<p>def456f third commit</p>
<p>xyz789e second commit</p>
<p>abc123d first commit</p>
<p>(Bilkul short aur clean!)</p>
<hr />
<h3><strong>Command 5 : git status</strong></h3>
<p>Current situation dekh sakte ho - kaunsi files change hui, kaunsi staged hain, kaunsi untracked hain.</p>
<pre><code class="language-powershell">git status
</code></pre>
<p>(<strong>Output:</strong> file.js aur index.html change hui, new-file.js abhi track nahi hui etc)</p>
<hr />
<h3><strong>Command 6: git diff</strong></h3>
<p>Do commits ke beech changes dekh sakte ho.</p>
<pre><code class="language-powershell">git diff 840c9bd 9b17369                # use this flow --&gt;  &lt;old commit&gt; &lt;latest commit&gt;
</code></pre>
<p>(840c9bd se 9b17369 tak kya badla)</p>
<p><strong>Important:</strong> Order matter karta hai!</p>
<ul>
<li><p>Pehla hash = Old (start)</p>
</li>
<li><p>Doosra hash = New (end)</p>
</li>
<li><p>Agar Reverse (new commit pehle and old hash baad mai) karo gay to code kay changes bhi reverse show honge iss liay ise nai krna</p>
</li>
</ul>
<hr />
<h3><strong>Command 7: git commit -am "message"</strong></h3>
<p><strong>Git add aur commit ek saath (shortcut).</strong></p>
<pre><code class="language-powershell">git commit -am "I added a login form"            # don`t try this in Professional work
</code></pre>
<p><strong>Note:</strong></p>
<p>Sirf modified files par kaam karta hai - New files add nahi hoti - Professional work mein git add + git commit alag alag use karo.</p>
<p>(Brief rakhna - zyada detail nahi chahiye)</p>
<hr />
<h3>⭐⭐⭐ IMPORTANT CONCEPT: HEAD ⭐⭐⭐</h3>
<p><strong>HEAD Kya Hota Hai?</strong></p>
<p>→ Git mein latest/newest commit ko "HEAD" bola jata hai</p>
<p>→ HEAD = Current position jahan Git abhi khara hai</p>
<p>→ Jab naya commit karte ho, HEAD automatically us naye commit par move ho jata hai</p>
<p><strong>Example:</strong></p>
<p>Commit 1: abc123d (1st commit)</p>
<p>Commit 2: xyz789e (2nd commit) ← <strong>HEAD yahan hai</strong> (latest)</p>
<p>Ab agar tum naya commit karo:</p>
<p><strong>$ git commit -m " I Update Code "</strong> ←- (3rd Commit)</p>
<p><strong>Now:</strong></p>
<p>Commit 1: abc123d (1st commit)</p>
<p>Commit 2: xyz789e (2nd commit)</p>
<p>Commit 3: def456f (3rd commit) ← HEAD ab yahan move ho gaya (NEW LATEST)</p>
<p><strong>— Simple Rule: HEAD hamesha latest commit ko point karta hai! —</strong></p>
<p><strong>Git log mein dekho ge to :</strong></p>
<p>$ git log</p>
<p>commit def456f (HEAD -&gt; main) ← Ye latest hai Author: Abdul Date: Dec 31 2025 third commit</p>
<p>commit xyz789e Author: Abdul Date: Dec 30 2025 second commit</p>
<p>commit abc123d Author: Abdul Date: Dec 29 2025 first commit</p>
<hr />
<h3>Command 8: git revert &lt;commit_hash&gt;</h3>
<p>Ek purane commit ko SAFELY undo karna (naya commit banake).</p>
<pre><code class="language-powershell">git revert &lt;commit_hash&gt;         # git revert def456f
#Remember: yaha per vo hash id enter krna jise revert krna he vo add nai krna jissper jana he.
</code></pre>
<p>(Commit 3 ke changes ko undo kar deta hai, par history preserve rehti hai)</p>
<p><strong>How it works:</strong></p>
<p>Commit 1: "Added login"</p>
<p>Commit 2: "Added dashboard"</p>
<p>Commit 3: "Added payment" ❌ (galat tha)</p>
<p>$ git revert def456f</p>
<p>Commit 1: "Added login"</p>
<p>Commit 2: "Added dashboard"</p>
<p>Commit 3: "Added payment" (still in history)</p>
<p>Commit 4: "Revert: Added payment" ← Naya commit (commit 3 payment code removed)</p>
<p><strong>Important Points:</strong></p>
<ol>
<li><p>History preserve rehti hai (git reset nahi karte)</p>
</li>
<li><p>Ek naya commit banata hai -</p>
</li>
<li><p>Professional teams mein use karte hain</p>
</li>
<li><p>Safe aur trackable hota hai</p>
</li>
</ol>
<hr />
<h3><strong>Command 9: git reset --hard &lt;commit_hash&gt;</strong></h3>
<p>Ek commit ke baad sab kuch DELETE karna (history se bhi).</p>
<pre><code class="language-powershell">git reset --hard abc123d        #professional work mai use nai krna
</code></pre>
<p>(Commit 2 aur 3 completely remove ho jayengi)</p>
<p><strong>How it works:</strong></p>
<p><strong>Before:</strong></p>
<p>Commit 1: "login"</p>
<p>Commit 2: "dashboard"</p>
<p>Commit 3: "payment" ❌</p>
<p><strong>You type command :</strong> $ git reset --hard abc123d</p>
<p><strong>After:</strong></p>
<p>Commit 1: "login" ← HEAD yahan (Commit 2 aur 3 delete!)</p>
<p>⚠️ IMPORTANT - DANGEROUS:</p>
<ol>
<li><p>History completely delete hoti hai (no backup or view of changes)</p>
</li>
<li><p>Team mein problem aata hai - Professional work mein git revert prefer karo!</p>
</li>
<li><p>Khud ke projects mein only use karo</p>
</li>
<li><p>Recovery mushkil hota hai</p>
</li>
</ol>
<p><strong>Professionally : git revert use karo, git reset --hard avoid karo!</strong></p>
<hr />
<h2><strong>03_What`s_Inside_Git :</strong></h2>
<p><strong>Sab se pehle question ::&gt;</strong></p>
<p>" .git folder ke andar kya hai aur Git sab kuch manage kaise karta hai? "</p>
<p>Ab ham finally ye dekhte hain ke .git folder ke inside kya hai - akhir ye sab work aur files ko manage kaisay kr raha hai aur hamay commands se data kaise de raha hai.</p>
<hr />
<ol>
<li><p><strong>STEP 1:</strong> Check karo ke .git folder exist karta hai ya nahi</p>
<pre><code class="language-powershell">ls -a           # Output:  .   ..   .git   file.js   index.html
</code></pre>
<p><strong>Notice :</strong></p>
<ul>
<li>.git folder likha hai (hidden folder)</li>
</ul>
<p><strong>Matlab :</strong></p>
<ul>
<li><p>.git folder hidden hai hamary code mai jo hum normally nahi dekh sakte,</p>
</li>
<li><p>lekin "ls -a" se dekh sakte hain.</p>
</li>
</ul>
<hr />
</li>
<li><p><strong>STEP 2:</strong> Check karo ham kis branch par hain</p>
<pre><code class="language-powershell">git branch          # Output: * main
</code></pre>
<p><strong>Notice :</strong> Piyush (*) main branch par likha hai</p>
<p><strong>Matlab :</strong> Ham main branch par hain (ye mostly default case hai).</p>
</li>
</ol>
<hr />
<p><strong>STEP 3:</strong> HEAD file dekho</p>
<pre><code class="language-powershell">cat .git/HEAD          # Output:  ref: refs/heads/main
</code></pre>
<p>Notice: Ye likha hai "ref: refs/heads/main"</p>
<p>Matlab:</p>
<ul>
<li><p>HEAD pointing kar raha hai refs/heads/main file ki taraf</p>
</li>
<li><p>Ye .git folder ke andar ka ek structure hai</p>
</li>
<li><p>HEAD batata hai: "Tum main branch par ho"</p>
</li>
</ul>
<hr />
<ol>
<li><strong>STEP 4: Main branch ka latest commit dekho</strong></li>
</ol>
<pre><code class="language-powershell">cat .git/refs/heads/main      # Output: abc123def456xyz789abc123def456xyz789abc123
</code></pre>
<p><strong>Notice:</strong></p>
<ul>
<li>Ye ek long hash likha hai</li>
</ul>
<p><strong>Matlab:</strong></p>
<ul>
<li><p>Ye main branch ka latest commit hai</p>
</li>
<li><p>Ye hash hai jo hamara HEAD currently point kar raha hai</p>
</li>
<li><p>YE SAME HASH HAI JO GIT LOG MEIN SHOW HOTA HAI!</p>
</li>
</ul>
<p><strong>Connection Samajho Yaha Per :</strong></p>
<p>.git/refs/heads/main file</p>
<p>↓</p>
<p>abc123def456... (HASH STORE HAI YAHAN)</p>
<p>↓</p>
<p>Jab tum "git log" karte ho</p>
<p>↓</p>
<p>Git yahi se hash le kar show karta hai!</p>
<p>↓</p>
<p>git log --oneline or (git log)</p>
<p>↓</p>
<p>abc123def (HEAD -&gt; main) Your message</p>
<p>↓</p>
<p>SAME HASH! ✅</p>
<p>Matlab: Git yaha .git/refs/heads/main file se hash ID nikaal kar agay output deta hai!</p>
<hr />
<ol>
<li><p><strong>STEP 5: Objects folder mein dekho - jahan actual data rehta hai</strong></p>
<pre><code class="language-powershell">ls .git/objects/      # Output: ab/ cd/ ef/ pack/
</code></pre>
<p><strong>Notice:</strong></p>
<ul>
<li>Har commit ko yaha per only 2-letter se save kia jata he (ab, cd, ef)</li>
</ul>
<p><strong>Matlab:</strong></p>
<ul>
<li><p>Ye folders commit hashes ke first 2 letters se bane hain</p>
</li>
<li><p>Har commit ke data ko organize karne ke liye ye structure use hota hai</p>
</li>
<li><p>Jab tum "git log" ya "git diff" karte ho, Git yahan se data nikal kar deta hai</p>
</li>
</ul>
</li>
</ol>
<hr />
<p><strong>STEP 6 : Samajho ke data kahan rakha hota hai, Jab tum "git log" command dete ho:</strong></p>
<p>$ git log --oneline</p>
<ul>
<li>ham yay likh kr enter krtay hain</li>
</ul>
<p>To Git ka system ye 4 process follow karta hai:</p>
<ul>
<li><p>.git/HEAD file padhta he: ref: refs/heads/main (Git ko Pata chala: Tum main branch par ho)</p>
</li>
<li><p>.git/refs/heads/main file padhta he: abc123def456... (Ose Pata chala: Latest commit ye hai)</p>
</li>
<li><p>.git/objects/ walay folder mein gaya: waha se usne (Actual commit data nikala)</p>
</li>
<li><p>Display kiya hamay</p>
</li>
</ul>
<p>Iska matlab:</p>
<ul>
<li>Git .git/objects/ walay folder se hi sab data nikal kar hamay show karta hai jab ham log diff krtay hain!</li>
</ul>
<hr />
<ul>
<li><p><strong>STEP 7 : Advanced - Commit ka complete detail dekho</strong></p>
<pre><code class="language-powershell">     git cat-file -p abc123def456     # for complete data of any hash id
</code></pre>
<p>Output:</p>
<p>tree 096b74c23d...</p>
<p>parent xyz789e...</p>
<p>author Ahmad <a href="mailto:ahmad@email.com">ahmad@email.com</a></p>
<p>date Dec 31 2025 message:</p>
<p>Added login feature</p>
<p>Notice:</p>
<ul>
<li>Ye full commit details likhe hain</li>
</ul>
<p>Matlab:</p>
<ul>
<li><p>Tree: File structure ka snapshot</p>
</li>
<li><p>Parent: Pichla commit (linked list)</p>
</li>
<li><p>Author: Kisne likha</p>
</li>
<li><p>Date: Kab likha</p>
</li>
<li><p>Message: Kya likha</p>
</li>
</ul>
<p><strong>Iska matlab: .git/objects/ mein sab kuch data hota hai !</strong></p>
</li>
</ul>
<hr />
<p>Remember it Always:</p>
<ul>
<li><p>ls = Folder ka content dekhnay ke liay (list files/folders inside)</p>
</li>
<li><p>cat = File ka content dekhnay ke liay (read file content)</p>
</li>
</ul>
<hr />
<h3><strong>GIT KI COMPLETE KAHANI:</strong></h3>
<ol>
<li><p>.git folder hidden rakha gaya (.git folder hidden hota hai)</p>
</li>
<li><p>.git folder ke andar:</p>
<ul>
<li><p>HEAD file : Current branch pointer</p>
</li>
<li><p>refs/heads/main : Latest commit hash store karta hai ← YE IMPORTANT HAI!</p>
</li>
<li><p>objects/ : Actual commit data store karta hai</p>
</li>
</ul>
</li>
<li><p>Jab tum git log karte ho but git yay krta he:</p>
</li>
</ol>
<ul>
<li><p>HEAD file dekha</p>
</li>
<li><p>refs/heads/main dekha</p>
</li>
<li><p>objects/ folder se data nikala</p>
</li>
<li><p>Data Show kiya</p>
</li>
</ul>
<p>4. Jab tum git diff karte ho: Ye direct objects/ folder se sab files se data nikal kar show karta hai</p>
<p>5. Jab tum git revert karte ho: Git .git/objects/ folder se purana commit la kar naya commit banata hai (purane changes ko undo karte hue).</p>
<p>6. Verification ke liye tum kar sakte ho:</p>
<ul>
<li><p>cat .git/HEAD (check: kis branch par ho)</p>
</li>
<li><p>cat .git/refs/heads/main (get: latest commit hash id - ye wahi hash id hay jo Git log mein show hota hai!)</p>
</li>
<li><p>git log --oneline (compare: same hash dikhega?)</p>
</li>
<li><p>Agar sab match ho = Synchronized! ✅</p>
</li>
</ul>
<hr />
<h3><strong>Complete Structure of .git Folder :</strong></h3>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769340293732/7fc51226-5b33-42ec-90f7-c64ac96f049e.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769340603474/98d0a889-602b-48ab-b279-d49c0d3b1bda.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769340848823/47fd3587-8dfc-44ab-8f15-a154df5c426a.png" alt="" style="display:block;margin:0 auto" />

<p>Sari kahani ko ham ese bi bol saktay hain ek line mai:</p>
<ul>
<li><p>Git .git/refs/heads/main se latest commit hash le kar,</p>
</li>
<li><p>.git/objects/ folder se data show karta hai!</p>
</li>
</ul>
<hr />
<h2>Some more Commands :</h2>
<h3><strong>For Cloning a Repository:</strong></h3>
<ul>
<li>If You want to clone any repository from GitHub then use</li>
</ul>
<pre><code class="language-powershell">git clone https://github.com/user/repo

# Ex :: git clone https://github.com/jhonspro/my-public-repo
</code></pre>
<ul>
<li>Or for Private Repository, you need owner repository token</li>
</ul>
<pre><code class="language-powershell">git clone https://user:TOKEN@github.com/user/repo

# Ex: git clone https://johnspro:ghp_AbC123XyZ753ds2fdMnO678@github.com/johnspro/my-private-repo
</code></pre>
<hr />
<h3><strong>For GitHub Remote</strong> :</h3>
<ul>
<li><p>For Checking Git Remote, use this command in Powershell or CMD:</p>
<pre><code class="language-powershell">git remote -v    # It will show you current remote
</code></pre>
</li>
<li><p>For Updating Git Remote, use this Command,</p>
<pre><code class="language-powershell">git remote set-url origin &lt;repo-url&gt;   # It will update remote
</code></pre>
</li>
</ul>
<hr />
<ol>
<li><p>For Pushing Code in a Repository, use this command :</p>
<pre><code class="language-powershell">git push -u origin main      # It will push complete local code in remote repository
</code></pre>
</li>
</ol>
<hr />
<h2>Let`s Learn Git Branch :</h2>
<p>ham kafi dfa dekhte hain</p>
<ul>
<li>git branch is main</li>
</ul>
<p>but yay kia he ? technically branch ko pehle master bola jata tha but ab main bola jata he</p>
<p>Hamara commit hash id jo he vo ek track ke oper hota he and ham bi osi per work krtay hain one by one agay ki taraf jatay hain to osi linkdlist ko main kaha jata he</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769346523233/c4c42c98-34fd-4448-ba14-2f5629842633.png" alt="" style="display:block;margin:0 auto" />

<p>ham main ke ilawa ek new branch bi bna sakta hain and uska kuch bi name rakh saktay hain .</p>
<p>new branch ki zroorat tab prti he jab hamne kisi website per work krna ho like</p>
<p>hmaray paas ek website he ali,ahmad and umar . yay 3 log iss website per work kr rhay hain and mil kr website build kr di he .</p>
<p>ab ali bolta he ke mojay ek new feature add krna he but agar vo osi branch mai work kray to agar code khraab hoa to whole website khraab ho sakti he . iss situation mai vo new branch ke HEAD (jo ke latest commit he waha se ) se alag se work kr sakta he.</p>
<h3><strong>2 commands se ham new branch bna saktay hain :</strong></h3>
<pre><code class="language-powershell"># Step 1: Branch banao
git branch feature/login

# Step 2: Uspar switch karo
git checkout feature/login
</code></pre>
<p><strong>Lekin easier yeh hai (1 command):</strong></p>
<pre><code class="language-powershell">git checkout -b feature/login    # create + switched to new branch
</code></pre>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769348238330/7a442ab2-62e3-43ee-8112-9507170be12c.png" alt="" style="display:block;margin:0 auto" />

<p>and jab hmara complete feature build ho jaiy test krkay to ham osay again main branch mai add kr saktay hain . main branch mai ek new commit bna kr usmay ham apna jo hmari feature branch ka latest and working commit he vo add krday gay.</p>
<hr />
<h3><strong>New Branch Ka Data Main branch Mein Add Karna :</strong></h3>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769348499677/7d6fce94-f00e-4e0d-b657-98ac817a4778.png" alt="" />

<p><strong>Command 1: Main branch par jao</strong></p>
<pre><code class="language-powershell">git checkout main     # output : Switched to branch 'main'
</code></pre>
<p><strong>Command 2: Feature branch ka data add karo</strong></p>
<pre><code class="language-powershell"># whole data main branch per with all commits add hogya  
git merge feature/a  

# Whole 2nd branch ka data , main branch per with only 1 commit add hoga 
git merge --squash feature/login
</code></pre>
<hr />
<h3><strong>Normal Marge vs Squash Marge :</strong></h3>
<ul>
<li><p>Normal merge may feature branch ke <strong>sab commits separately</strong> main branch mein add hote hain and commit bi automatically kr deta he. (Don`t use in Professional work)</p>
</li>
<li><p><strong>Squash merge</strong> may feature branch ke <strong>sab commits ek single commit</strong> mein compress ho jate hai but commit automatically nai hota vo khud krna prta he. **(**Clean only 1 commit <strong>Recomanded)</strong></p>
</li>
<li><p>but yay owerright bi kr deta he code ke chnges</p>
</li>
</ul>
<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/019adaaf-080e-79e5-9938-0870d1df90e4/1769350745028-019bf584-fc1b-7b80-9e08-87347f65d5cb.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260125%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260125T141905Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=332b05f6adbf09ca5bb378d90aa20379ede7d83d68b64c7dba8703d2fb8cca90&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="" />

<hr />
<h3><strong>Code Collaboration: Pushing Feature Branches to Remote Repository :</strong></h3>
<p>Ab jab complete code update ho jaiy and new feature add kr lia jaiy to ose merge —squash krkay new commit bna kr commit -m krkay add krdia jaiy .</p>
<p>ab yay code apkay pc per offline hay , and apnay main branch mai sab add krdia he to ise GitHub per push kr day, lakin push krtay time kabhi bi directly main branch mai push nai kray (not good for professionals)</p>
<p>hamesha apni branch mai hi push kray like agar apnay feature/login name se branch bnai thi to osi branch per,</p>
<p>git push -u origin feature/login</p>
<p>krkay push krday iss trha se GitHub per uss repository ka owner apki pull request and code changes easily dekh kr request pull or cancel kr sakta he ( Always Recomanded for Professionals ).</p>
<p>agar unho ne commited kr di remot repository ke inner , to fir aap again</p>
<p>git pull origin main</p>
<p>try kro takay all new commits sync ho skay apki machine ke saath.</p>
<hr />
<h3><strong>Rebase in Git :</strong></h3>
<p>Just suppose ke aap feature branch par kaam kar rahe ho, lekin main branch ahead ho gaya (kisi ne naye commits add kiye).</p>
<ul>
<li><p>Main:</p>
<p>A → B → E</p>
</li>
<li><p>Feature: C → D</p>
</li>
</ul>
<p>Conflict ho sakta hai kyunke main branch aage nikal gaya.</p>
<h3><strong>Step 1: Feature branch par ho</strong></h3>
<ul>
<li>git checkout feature/login</li>
</ul>
<h3><strong>Step 2: Main ke latest changes par rebase karo</strong></h3>
<pre><code class="language-powershell">git rebase main
</code></pre>
<p>ab new yay hoga:</p>
<p>Main: A → B → E</p>
<p>Feature ke commits C, D ko E ke top par replay karega</p>
<p>Result: A → B → E → C → D</p>
<img src="https://cms-assets.tutsplus.com/uploads/users/585/posts/23191/preview_image/preview.png" alt="Rewriting History With Git Rebase | Envato Tuts+" />

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769362789326/5cba49e0-aff3-4403-a636-a08599cba9e4.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>All commands Cheatsheet :</h2>
<h3>Basic / Local Git</h3>
<pre><code class="language-css">git init
git add .
git add &lt;filename&gt;
git commit -m "message"
git commit -am "message"
git status
git log
git log --oneline
git diff &lt;old-commit&gt; &lt;new-commit&gt;
git revert &lt;commit-hash&gt;
git reset --hard &lt;commit-hash&gt;
</code></pre>
<hr />
<h3>🔹 Git Internals / Verification</h3>
<pre><code class="language-css">ls -a
git branch
cat .git/HEAD
cat .git/refs/heads/main
ls .git/objects/
git cat-file -p &lt;commit-hash&gt;
</code></pre>
<hr />
<h3>Remote / GitHub</h3>
<pre><code class="language-css">git clone &lt;repo-url&gt;
git clone https://user:TOKEN@github.com/user/repo
git remote remove &lt;name&gt;
git remote -v
git remote add origin &lt;repo-url&gt;
git remote set-url origin &lt;repo-url&gt;
git push -u origin main
git pull origin main
</code></pre>
<hr />
<h3>Branching</h3>
<pre><code class="language-javascript">git branch feature/login
git checkout feature/login
git checkout -b feature/login
git checkout main      // switch branch

git merge master --allow-unrelated-histories 
// complete code ek branch se dosri branch mai laanay mai hep krta he like aap master branch se main branch mai switch krkay aa gaiy hain to yaya apply krday code main branch mai aa jaiy ga , last wala --allow-unrelated-histories  yay tab use kray jab iske bgair na ho code marge

git branch -d &lt;branch-name&gt; // it will delete branch
</code></pre>
<hr />
<h3>Merging</h3>
<pre><code class="language-css">git merge feature/a
git merge --squash feature/login
</code></pre>
<hr />
<h3>Collaboration (Professional Flow)</h3>
<pre><code class="language-css">git push -u origin feature/login
</code></pre>
<hr />
<h3>Rebase</h3>
<pre><code class="language-css">git rebase main
</code></pre>
<hr />
]]></content:encoded></item><item><title><![CDATA[How to Fix React (Vite) & Next.js Auto-Refresh Not Working on Windows]]></title><description><![CDATA[Browser not auto-refreshing on Windows? Learn how to fix Hot Module Replacement (HMR) in React, Vite, and Next.js by enabling active file polling.]]></description><link>https://blog.abdulrdeveloper.me/how-to-fix-react-vite-next-js-auto-refresh-not-working-on-windows</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/how-to-fix-react-vite-next-js-auto-refresh-not-working-on-windows</guid><category><![CDATA[Next.js]]></category><category><![CDATA[React]]></category><category><![CDATA[HMR]]></category><category><![CDATA[web dev]]></category><category><![CDATA[Windows]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Thu, 11 Jun 2026 02:09:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/3769c10a-2165-4399-acd4-a472f6ea0817.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever saved a file in your React or Next.js project and... nothing happened? You go to the browser, manually refresh it, and only <em>then</em> the change shows up. Or maybe you have to kill the dev server and start it again just to see your new code.</p>
<p>Most beginners think this is a bug in their code. But let me tell you, it is actually one of the most common issues you will face if you are coding on Windows.</p>
<h2>Why Does This Happen Behind the Scene??</h2>
<p>When we run our dev server, Vite and Next.js use a "file watcher" to detect changes and trigger Hot Module Replacement (HMR). On macOS or Linux, this file watcher works perfectly and instantly. But on Windows, these file system events often fail to fire.</p>
<p>Because the watcher misses the change, HMR never triggers, and you are stuck manually refreshing.</p>
<p>The fix? We just need to tell our server to actively check for changes every single second instead of waiting to be notified. In programming, this is called <strong>polling</strong>.</p>
<h2>Fix for React (Vite)</h2>
<p>If you are building with Vite, the fix is super simple. Open your <code>vite.config.ts</code> and just add this <code>server</code> option:</p>
<p><strong>TypeScript</strong></p>
<pre><code class="language-plaintext">export default defineConfig({
  plugins: [react()],
  server: {
    watch: {
      usePolling: true,
    },
    hmr: {
      host: 'localhost',
    },
  },
})
</code></pre>
<h2>Fix for Next.js</h2>
<p>Next.js is a bit tricky here. Next.js 16 uses Turbopack by default, but our polling fix only works with <strong>Webpack</strong>. So, first, we need to disable Turbopack.</p>
<p>Go to your <code>package.json</code> and update your dev script to this:</p>
<p><strong>JSON</strong></p>
<pre><code class="language-plaintext">"scripts": {
  "dev": "next dev --webpack"
}
</code></pre>
<p>Then, open your <code>next.config.ts</code> and add this configuration:</p>
<p><strong>TypeScript (or if you are on JS)</strong></p>
<pre><code class="language-plaintext">import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  webpack: (config) =&gt; {
    config.watchOptions = {
      poll: 1000,
      aggregateTimeout: 300,
    };
    return config;
  },
};

export default nextConfig;
</code></pre>
<p><strong>What is happening here?</strong> <code>poll: 1000</code> means Webpack will check for file changes every 1000 milliseconds (1 second). <code>aggregateTimeout: 300</code> adds a tiny delay so that if you mash <code>Ctrl+S</code> rapidly, it doesn't trigger multiple rebuilds at the same time. Restart your dev server, and auto-refresh will finally work!</p>
<hr />
<h3>⚠️ <strong>Important: Disable this configuration before deploying</strong></h3>
<p>This Webpack polling fix is strictly for local development on Windows. Production platforms like Vercel run on Linux—where file-watching works natively—and build using Next.js 16's default Turbopack engine. Leaving this custom Webpack configuration active in your repository will cause your production build to fail.</p>
<p><strong>How to handle it:</strong></p>
<ul>
<li><p><strong>Locally:</strong> Keep this config active to ensure a smooth development workflow.</p>
</li>
<li><p><strong>Production:</strong> Comment out or remove the custom Webpack config and the <code>--webpack</code> flag before pushing your changes to GitHub or Vercel.</p>
</li>
</ul>
<p>You can easily re-enable it whenever you need to work locally again.</p>
<h2>What if you are using WSL2?</h2>
<p>If you are running WSL2 and still facing this, the problem is likely where your project is stored.</p>
<p>Your project needs to live <strong>inside the WSL filesystem</strong> — at a path like <code>/home/yourname/projects/</code>. If your project is sitting on your Windows drive (like <code>/mnt/c/Users/...</code>), file events will not work properly and polling alone might not save you. Move the project inside <code>/home/</code> and the issue goes away.</p>
<p>This Next.js issue tripped me up for a while — just adding <code>watchOptions</code> does not work until you switch back to Webpack first. Once I figured that out, everything clicked.</p>
<hr />
<p>You can find more of my work at <a href="http://abdulrdeveloper.me"><strong>abdulrdeveloper.me</strong></a></p>
<p>Read more posts at <a href="http://blog.abdulrdeveloper.me"><strong>blog.abdulrdeveloper.me</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Next.js Middleware — Route Protection Without Any Library]]></title><description><![CDATA[Learn how to protect routes globally in Next.js App Router using pure cookies and native middleware. No npm install required. Copy and ship fast!]]></description><link>https://blog.abdulrdeveloper.me/next-js-middleware-route-protection-without-any-library</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/next-js-middleware-route-protection-without-any-library</guid><category><![CDATA[authentication]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Middleware]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Tue, 02 Jun 2026 16:27:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/618adf06-a666-4ae0-abff-df0ecea6437f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most beginners think route protection means installing NextAuth or Clerk. It does not always have to be that.</p>
<p>For a small project, a hackathon prototype, or just something you are building to learn — a simple cookie check in middleware is enough to get the job done.</p>
<p>This is exactly that.</p>
<hr />
<h2>How the Logic Works</h2>
<p>Next.js middleware runs before a request reaches any page. That makes it the perfect place to check if someone is allowed to visit a route.</p>
<p>Here is what we are doing:</p>
<ul>
<li><p>If someone tries to open <code>/dashboard</code> without being logged in, they get kicked back to <code>/</code></p>
</li>
<li><p>If someone is already logged in and visits <code>/</code>, they get skipped straight to <code>/dashboard</code></p>
</li>
<li><p>The check is based on one cookie: <code>isLoggedIn</code></p>
</li>
</ul>
<p>That is it. No library. No JWT verification. Just a cookie presence check.</p>
<hr />
<h2>Step 1: Create <code>middleware.ts</code> (or <code>middleware.js</code>)</h2>
<p>Put this file in your root directory <code>/</code> — or inside <code>src/</code> if you use that structure.</p>
<p><strong>TypeScript (</strong><code>middleware.ts</code><strong>):</strong></p>
<pre><code class="language-typescript">import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const isLoggedIn = request.cookies.has('isLoggedIn');
  const { pathname } = request.nextUrl;

  const protectedRoutes = ['/dashboard'];
  const isProtectedRoute = protectedRoutes.some(route =&gt; pathname.startsWith(route));

  if (isProtectedRoute &amp;&amp; !isLoggedIn) {
    return NextResponse.redirect(new URL('/', request.url));
  }

  if (pathname === '/' &amp;&amp; isLoggedIn) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/', '/dashboard/:path*'],
};
</code></pre>
<p><strong>or if you are using JavaScript (</strong><code>middleware.js</code><strong>) — same logic, no types:</strong></p>
<pre><code class="language-javascript">import { NextResponse } from 'next/server';

export function middleware(request) {
  const isLoggedIn = request.cookies.has('isLoggedIn');
  const { pathname } = request.nextUrl;

  const protectedRoutes = ['/dashboard'];
  const isProtectedRoute = protectedRoutes.some(route =&gt; pathname.startsWith(route));

  if (isProtectedRoute &amp;&amp; !isLoggedIn) {
    return NextResponse.redirect(new URL('/', request.url));
  }

  if (pathname === '/' &amp;&amp; isLoggedIn) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/', '/dashboard/:path*'],
};
</code></pre>
<p>The <code>matcher</code> at the bottom is important. Without it, the middleware runs on every single request — including <code>_next/static</code> files, images, API routes. That slows things down for no reason. The matcher makes sure it only fires where it actually matters.</p>
<hr />
<h2>Step 2: Wire It Up to Your Forms</h2>
<p>You do not need to change your layout or UI. Just drop these lines into the right places.</p>
<p><strong>On Login — inside your login page's submit handler:</strong></p>
<p>Most people have a login form on their landing page or <code>/login</code>. Find the function that runs when the form is submitted — after your validation passes, add this:</p>
<pre><code class="language-javascript">document.cookie = "isLoggedIn=true; path=/; max-age=86400";
router.push('/dashboard');
</code></pre>
<p><code>max-age=86400</code> means the cookie lives for exactly one day — 86400 seconds. After that it disappears on its own.</p>
<p><strong>On Logout — inside your dashboard's logout button:</strong></p>
<p>You do not need a separate logout page or file. Just find your logout button — it is usually sitting in your dashboard's navbar or sidebar — and add this to its <code>onClick</code> handler:</p>
<pre><code class="language-jsx">&lt;button onClick={() =&gt; {
  document.cookie = "isLoggedIn=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  router.push('/');
  router.refresh();  // It will Clear Next.js client-side cache     and force a fresh server state reload (prevents browser back-button bypass)

}}&gt;
  Logout
&lt;/button&gt;
</code></pre>
<p>Setting <code>expires</code> to a past date is how you delete a cookie. The browser sees it as already expired and removes it.</p>
<hr />
<h2>What This Does Not Do</h2>
<p>This setup only checks if the cookie <em>exists</em>. It does not verify a signature or validate who the user actually is.</p>
<p>That means someone could open DevTools, go to Application → Cookies, manually add <code>isLoggedIn=true</code>, and get past the middleware. The lock is real but the key is easy to duplicate.</p>
<p>For a hackathon or a personal project — totally fine. For something handling real user data or payments — replace the boolean cookie with a signed JWT and verify the signature server-side.</p>
<p>But for getting something working fast? This does the job.</p>
<hr />
<p>No <code>npm install</code> needed. Copy, paste, ship.</p>
<p>You can find more of my work at <a href="http://abdulrdeveloper.me"><strong>abdulrdeveloper.me</strong></a><br />Read more posts at <a href="http://blog.abdulrdeveloper.me"><strong>blog.abdulrdeveloper.me</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Chai aur SQL — A Beginner's Journey into Databases]]></title><description><![CDATA[Learn SQL from scratch — how databases live on servers, write your first queries, use Docker for PostgreSQL, and understand ACID transactions.]]></description><link>https://blog.abdulrdeveloper.me/chai-aur-sql-a-beginner-s-journey-into-databases</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/chai-aur-sql-a-beginner-s-journey-into-databases</guid><category><![CDATA[SQL]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Sat, 23 May 2026 15:15:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/22579757-8ee8-4029-9bee-129561c42cad.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>SQL stands for Structured Query Language. It is the language we use to talk to relational databases like MySQL, PostgreSQL, and SQLite.</p>
<h2>What is a Server and Where Does the Database Live?</h2>
<p>Most beginners think the database is somewhere floating in the "cloud." It is not.</p>
<p>A database is software running on a server. A server is just a powerful computer that runs 24/7 inside a data center — like Amazon AWS, Google Cloud, or DigitalOcean. When that software saves your data, it writes it to actual files on the server's SSD or hard drive.</p>
<p>MySQL and PostgreSQL save data as <code>.ibd</code> files or WAL (Write-Ahead Log) files. MongoDB saves as <code>.bson</code> files. These files sit on disk just like any file on your laptop.</p>
<p>When you write this in your backend code:</p>
<pre><code class="language-javascript">const pool = new Pool({ host: 'localhost', port: 5432 })
</code></pre>
<p>You are telling your backend to open a connection to the port where the database is listening. That is it. It is a TCP connection — like a phone call between your application and the database.</p>
<hr />
<h2>Why Docker for PostgreSQL?</h2>
<p>Instead of installing PostgreSQL directly on my system, I used Docker. Docker creates an isolated environment (called a container) so I do not mess up my laptop's setup.</p>
<p>Here is the command I used to create a PostgreSQL container with persistent data:</p>
<p><strong>Mac / Linux / WSL:</strong></p>
<pre><code class="language-bash">docker run -d --name sql_class \
  -e POSTGRES_PASSWORD=postgres \
  -e POSTGRES_DB=sql_class_01_db \
  -p 5433:5432 \
  -v "$(pwd)/pgdata:/var/lib/postgresql/data" \
  postgres
</code></pre>
<p><strong>Windows (PowerShell):</strong></p>
<pre><code class="language-powershell">docker run -d --name sql_class -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=sql_class_01_db -p 5433:5432 -v "${PWD}/pgdata:/var/lib/postgresql/data" postgres
</code></pre>
<p>The <code>-v</code> flag maps a <code>pgdata</code> folder inside your current directory to the container's storage. So even if the container is deleted, your data stays on your laptop.</p>
<p>To check if the container is running:</p>
<pre><code class="language-bash">docker ps
</code></pre>
<p>To remove the container:</p>
<pre><code class="language-bash">docker rm -f sql_class
</code></pre>
<hr />
<h2>Why Learn Raw SQL When We Have Prisma and Drizzle?</h2>
<p>This was my first question. Why learn raw SQL when Prisma can generate the queries for me?</p>
<p>Here is what I found out:</p>
<p>ORMs like Prisma and Drizzle translate your JavaScript/TypeScript code into SQL strings and send them to the database. If you do not know SQL, you do not know what Prisma is actually doing behind the scene.</p>
<p>The N+1 problem is a real thing. ORMs sometimes generate 100 queries instead of 1 optimized query. You will only catch this if you understand SQL.</p>
<p>For complex queries — joining 6 tables, generating financial reports — ORM syntax breaks down. Developers fall back to raw SQL.</p>
<p>And SQL has not changed in 50 years. Sequelize came and went. Prisma came. Drizzle came. SQL is still the same.</p>
<hr />
<h2>DDL — How You Create Tables</h2>
<p>DDL stands for Data Definition Language. These are the commands that define the structure of your database — not the data, just the structure.</p>
<p>The four main DDL commands are <code>CREATE</code>, <code>ALTER</code>, <code>DROP</code>, and <code>TRUNCATE</code>.</p>
<p>Here is a real table I created while practicing:</p>
<pre><code class="language-sql">CREATE TABLE students (
    student_id SERIAL PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50),
    email VARCHAR(100) UNIQUE NOT NULL,
    phone_number CHAR(10) UNIQUE,
    age INT CHECK (age &gt; 12),
    current_status VARCHAR(20) DEFAULT 'active'
        CHECK (current_status IN ('active', 'graduated', 'dropped_out', 'on_leave')),
    has_joined_masterji BOOLEAN DEFAULT FALSE,
    current_score NUMERIC(5, 2) CHECK (current_score &gt;= 0 AND current_score &lt;= 100),
    enrollment_date DATE DEFAULT CURRENT_DATE
);
</code></pre>
<p><code>SERIAL</code> means auto-incrementing integer — PostgreSQL handles the ID for you. <code>NOT NULL</code> means the column cannot be empty. <code>UNIQUE</code> means no two rows can have the same value. <code>CHECK</code> is a custom condition — here age must be greater than 12. <code>DEFAULT</code> sets a value automatically if nothing is provided.</p>
<p>To add a new column to an existing table later:</p>
<pre><code class="language-sql">ALTER TABLE students ADD COLUMN batch_name VARCHAR(50) DEFAULT 'Web Dev 2026';
</code></pre>
<hr />
<h2>SELECT Queries — Reading Your Data</h2>
<p>SELECT is the command to read data from a table.</p>
<pre><code class="language-sql">-- Get everything
SELECT * FROM ipl_players;

-- Get specific columns
SELECT name, team, auction_price_crores FROM ipl_players;
</code></pre>
<p><strong>Filtering with WHERE:</strong></p>
<pre><code class="language-sql">-- Basic condition
SELECT * FROM ipl_players WHERE team = 'Mumbai Indians';

-- Multiple conditions
SELECT * FROM ipl_players WHERE role = 'All-Rounder' AND wickets_taken &gt; 10;

-- Either condition
SELECT * FROM ipl_players WHERE team = 'CSK' OR team = 'RCB';

-- Range
SELECT * FROM ipl_players WHERE auction_price_crores BETWEEN 5 AND 12;

-- From a list
SELECT * FROM ipl_players WHERE team NOT IN ('Mumbai Indians', 'CSK', 'RCB');

-- Pattern matching — names starting with R
SELECT * FROM ipl_players WHERE name LIKE 'R%';

-- Check for empty values
SELECT * FROM ipl_players WHERE team IS NULL;
</code></pre>
<p><code>%</code> means zero or more characters. <code>_</code> means exactly one character. <code>LIKE</code> is case-sensitive. <code>ILIKE</code> is case-insensitive (PostgreSQL only).</p>
<p><strong>Sorting and limiting:</strong></p>
<pre><code class="language-sql">-- Sort by price, highest first
SELECT name, auction_price_crores FROM ipl_players ORDER BY auction_price_crores DESC;

-- Top 3 results
SELECT name, auction_price_crores FROM ipl_players ORDER BY auction_price_crores DESC LIMIT 3;

-- Skip first 3, get next 3 (pagination)
SELECT name, auction_price_crores FROM ipl_players ORDER BY auction_price_crores DESC LIMIT 3 OFFSET 3;
</code></pre>
<hr />
<h2>DML — Insert, Update, Delete</h2>
<p>DML stands for Data Manipulation Language. This is how you actually work with the data inside the tables.</p>
<p><strong>INSERT:</strong></p>
<pre><code class="language-sql">-- Single row
INSERT INTO canteen_menu (item_name, category, price)
VALUES ('Vada Pav', 'Snacks', 15);

-- Multiple rows at once
INSERT INTO canteen_menu (item_name, category, price) VALUES
('Masala Chai', 'Beverages', 10),
('Samosa', 'Snacks', 12),
('Maggi', 'Snacks', 25);
</code></pre>
<p><strong>UPDATE:</strong></p>
<pre><code class="language-sql">UPDATE canteen_menu
SET price = 20
WHERE item_name = 'Vada Pav';
</code></pre>
<p><strong>DELETE:</strong></p>
<pre><code class="language-sql">DELETE FROM canteen_menu WHERE item_name = 'Cold Coffee';
</code></pre>
<p>Always use <code>WHERE</code> with UPDATE and DELETE. If you forget the WHERE clause, SQL will update or delete every single row in the table. I learned this the hard way in practice.</p>
<hr />
<h2>Aggregate Functions — COUNT, SUM, AVG, MAX, MIN</h2>
<p>Aggregate functions take a whole column and return one number.</p>
<pre><code class="language-sql">-- How many rows?
SELECT COUNT(*) FROM smart_watch_sales;

-- Total revenue
SELECT SUM(units_sold * price_per_unit) AS total_revenue FROM smart_watch_sales;

-- Average price
SELECT AVG(price_per_unit) AS avg_price FROM smart_watch_sales;

-- Cheapest and most expensive
SELECT MIN(price_per_unit) AS cheapest, MAX(price_per_unit) AS costliest FROM smart_watch_sales;
</code></pre>
<p><strong>GROUP BY</strong> lets you split these calculations by category:</p>
<pre><code class="language-sql">-- Total units sold per brand
SELECT brand, SUM(units_sold) AS total_units_sold
FROM smart_watch_sales
GROUP BY brand
ORDER BY total_units_sold DESC;
</code></pre>
<p><strong>HAVING</strong> filters the groups after they are created. WHERE cannot do this because WHERE runs before grouping:</p>
<pre><code class="language-sql">-- Only show brands that sold more than 20 units total
SELECT brand, SUM(units_sold) AS total_units
FROM smart_watch_sales
GROUP BY brand
HAVING SUM(units_sold) &gt; 20;
</code></pre>
<hr />
<h2>Joins — Connecting Multiple Tables</h2>
<p>This is where relational databases get powerful.</p>
<p>We keep data in separate tables to avoid duplication. Students in one table, internships in another. Joins let you combine them in one query.</p>
<p><strong>Foreign Key</strong> is what connects the tables. The internships table has a <code>student_id</code> column that references the <code>student_id</code> in the students table:</p>
<pre><code class="language-sql">CREATE TABLE internships (
    internship_id SERIAL PRIMARY KEY,
    student_id INT REFERENCES students(student_id) ON DELETE SET NULL,
    company_name VARCHAR(100),
    role VARCHAR(50),
    stipend INT,
    status VARCHAR(20)
);
</code></pre>
<p><code>ON DELETE SET NULL</code> means if a student is deleted, the internship record stays but <code>student_id</code> becomes NULL. <code>ON DELETE CASCADE</code> would delete the internship too.</p>
<p><strong>INNER JOIN — only matching rows:</strong></p>
<pre><code class="language-sql">SELECT s.name, s.branch, i.company_name, i.role
FROM students s
INNER JOIN internships i ON s.student_id = i.student_id;
</code></pre>
<p>Students without internships will not show up here.</p>
<p><strong>LEFT JOIN — all students, matched or not:</strong></p>
<pre><code class="language-sql">SELECT
    s.name,
    s.branch,
    COALESCE(i.company_name, 'No Internship') AS company_name,
    COALESCE(i.stipend, 0) AS stipend
FROM students s
LEFT JOIN internships i ON s.student_id = i.student_id;
</code></pre>
<p><code>COALESCE</code> replaces NULL with a default value. Students without internships will appear with 'No Internship' instead of NULL.</p>
<p>To find students who have NOT applied anywhere:</p>
<pre><code class="language-sql">SELECT s.name, s.email
FROM students s
LEFT JOIN internships i ON s.student_id = i.student_id
WHERE i.internship_id IS NULL;
</code></pre>
<p><strong>RIGHT JOIN</strong> returns all rows from the right table. In practice, developers rarely use RIGHT JOIN — they just flip the table order and use LEFT JOIN instead. It reads more naturally.</p>
<p><strong>FULL OUTER JOIN — everything from both tables:</strong></p>
<pre><code class="language-sql">SELECT s.name AS student_name, i.company_name
FROM students s
FULL OUTER JOIN internships i ON s.student_id = i.student_id;
</code></pre>
<p>This shows all students and all internships. Where there is no match on either side, you get NULL.</p>
<hr />
<h2>Indexes — Making Queries Fast</h2>
<p>I inserted 1,000,000 rows into a table to test this.</p>
<p>Without an index, when you search by name, PostgreSQL scans every single row from top to bottom. This is called a Sequential Scan.</p>
<pre><code class="language-sql">EXPLAIN ANALYZE SELECT marks FROM marks WHERE name = '809E15792322';
</code></pre>
<p><code>EXPLAIN ANALYZE</code> shows you the query plan and execution time. Before adding an index, my query took around 40-50 milliseconds on 1 million rows.</p>
<p>After creating an index:</p>
<pre><code class="language-sql">CREATE INDEX idx_name ON marks (name);
</code></pre>
<p>The same query dropped to under 1 millisecond. PostgreSQL now uses a B-Tree structure to find the row directly instead of scanning everything.</p>
<p>A <strong>covering index</strong> goes one step further. If your query asks for <code>marks</code> along with <code>name</code>, you can store both in the index itself:</p>
<pre><code class="language-sql">CREATE INDEX idx_name ON marks (name) INCLUDE (marks);
</code></pre>
<p>Now PostgreSQL does not even need to visit the main table. It gets everything from the index directly. This is called an Index Only Scan.</p>
<hr />
<h2>Transactions and ACID</h2>
<p>A transaction is a way to group multiple SQL operations into one unit of work. Either all of them succeed, or none of them do.</p>
<p>The classic example is a bank transfer:</p>
<pre><code class="language-sql">BEGIN;

    UPDATE accounts SET balance = balance - 500 WHERE owner = 'Shubham';
    UPDATE accounts SET balance = balance + 500 WHERE owner = 'Hitesh';

COMMIT;
</code></pre>
<p>If the server crashes between the two UPDATE statements, the database will rollback both changes. The money will not disappear from Shubham's account and fail to reach Hitesh.</p>
<p>If something goes wrong, you can manually undo everything:</p>
<pre><code class="language-sql">BEGIN;
    UPDATE accounts SET balance = balance - 5000 WHERE owner = 'Shubham';
ROLLBACK;
</code></pre>
<p><strong>ACID</strong> is the set of guarantees that make this work:</p>
<p><strong>Atomicity</strong> — All or nothing. If Step 2 fails, Step 1 is also undone. I tested this by putting <code>SELECT 1/0</code> (division by zero error) in the middle of a transaction. The whole thing rolled back.</p>
<p><strong>Consistency</strong> — The database only moves from one valid state to another. I set <code>CHECK (balance &gt;= 0)</code> on the accounts table. When I tried to deduct 5000 from an account with 1000, PostgreSQL threw an error and refused the operation completely.</p>
<p><strong>Isolation</strong> — Uncommitted transactions are invisible to other connections. I opened two terminal windows to test this. Terminal 1 started a transaction and updated a balance but did not COMMIT. Terminal 2 could still see the old balance. Only after Terminal 1 ran <code>COMMIT</code> did Terminal 2 see the new number.</p>
<p><strong>Durability</strong> — Once committed, data is permanent. PostgreSQL writes committed transactions to the Write-Ahead Log (WAL) on disk before returning a success response. Even if the server crashes one second after the COMMIT, the data will be there when the server restarts.</p>
<hr />
<p>All the code from this blog is in my GitHub repo: <a href="https://github.com/abdulrdeveloper/Learn-SQL">github.com/abdulrdeveloper/Learn-SQL</a></p>
<p><a href="https://github.com/abdulrdeveloper/Learn-SQL/tree/main/Real%20World%20DBs%20Collection">Real World Database Collections ↗</a></p>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a><br />Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Chai aur CSS]]></title><description><![CDATA[Learn CSS from scratch — specificity, box model, flexbox, grid, animations & modern features explained simply with practical examples.]]></description><link>https://blog.abdulrdeveloper.me/chai-aur-css</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/chai-aur-css</guid><category><![CDATA[CSS]]></category><category><![CDATA[CSS Animation]]></category><category><![CDATA[css flexbox]]></category><category><![CDATA[CSS Grid]]></category><category><![CDATA[webdevelopment]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Sun, 01 Feb 2026 14:12:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/1250cf42-e4e3-43af-abe8-fa4465f9b031.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>CSS stands for <strong>Cascading Stylesheet</strong>.</p>
<ul>
<li><p>Cascading is a word that is meant by overwriting.</p>
</li>
<li><p>The stylesheet is just for styling.</p>
</li>
</ul>
<p>While overwriting the style of an element , Cascading first checks the (specificity + line).</p>
<hr />
<h2>Specificity and Priority Toppic in CSS :</h2>
<p>The style will only apply for highest priority of specificity , if both element are at same priority then 2nd element will overwrite 1st element style .</p>
<ol>
<li><p>p { color: blue; } &lt;—- lowest priority (tag name)</p>
</li>
<li><p>.class { color: blue; } &lt;—- medium priority</p>
</li>
<li><p>#class { color: blue; } ←—- high priority</p>
</li>
<li><p>inline style directly in html tag &lt;—— highest priority</p>
</li>
</ol>
<hr />
<p><strong>Same element, same specificity → last rule wins</strong></p>
<pre><code class="language-css">/* CSS rules flow from UP to Down. When second rule target in
the same element, then the bottom rule override the first rule. */
p {
  color: red;
}

p {
  color: blue;             /* This style will applied */
}
</code></pre>
<pre><code class="language-xml">&lt;p&gt;Hello world&lt;/p&gt;
</code></pre>
<hr />
<p><strong>Same element, → higher‑priority selector wins</strong></p>
<pre><code class="language-css">p {
  color: red;        /* element selector (lowest) */
}

.highlight {
  color: green;      /* class selector (higher) */
}

#special {
  color: blue;       /* ID selector (highest because there is no inline style) */
}
</code></pre>
<pre><code class="language-xml">&lt;p id="special" class="highlight"&gt;Hello world&lt;/p&gt;
</code></pre>
<hr />
<h2>CSS CheatSheet :</h2>
<h2><strong>Font :</strong></h2>
<pre><code class="language-css">font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Sets prioritized fonts for text */
font-size: 1rem; /* Sets text size, responsive with rem */
font-weight: bold; /* or 100–900 for thickness control */
font-style: italic;  /* Makes text italic */
</code></pre>
<hr />
<h2>Responsive Font :</h2>
<pre><code class="language-css">font-size: clamp(16px, 4vw, 24px);
</code></pre>
<p>It keeps responsive font on screen size.</p>
<ul>
<li><p>Minimum: 16px → Font will never be less then 16px.</p>
</li>
<li><p>Preferred: 4vw (4% of viewport width) → Normally use the 4% of screen width.</p>
<ul>
<li><p>If Screen size will be large, then font will be also large.</p>
</li>
<li><p>If Screen size will be small, then font will be also small.</p>
</li>
</ul>
</li>
<li><p>Maximum: 24px → Font size will never be less then 24px.</p>
</li>
<li><p>You can set these according to your specifications.</p>
</li>
</ul>
<hr />
<h2><strong>Text</strong></h2>
<pre><code class="language-css">text-align: center; /* Aligns text in the center of the line */
letter-spacing: 0.15em; /* Adjusts space between characters */
text-decoration: underline; /* Adds decoration like underline/overline/line-through */
word-spacing: 0.25em; /* Sets spacing between words */
line-height: 1.5; /* Sets vertical spacing between lines */
text-transform: uppercase; /* Converts text to uppercase */
</code></pre>
<hr />
<h2><strong>Background</strong></h2>
<pre><code class="language-css">background: linear-gradient(...);  /* Adds gradient */
background-image: url("path"); /* Adds image */
background-position: center; /* Positions background image */
background-size: cover; /* Scales image to cover element */
background-blend-mode: multiply; /* Blends background layers */
background-clip: text; /* Clips background to text */
</code></pre>
<h2><strong>Border &amp; Outline</strong></h2>
<pre><code class="language-css">border: 2px solid #000; /* Adds border with size, style, color */
border-radius: 15px; /* Rounds corners */
outline: 2px dashed red; /* Adds outline outside element box */
border-image: url(border.png) 30 round; /* Uses image as border */
</code></pre>
<hr />
<h2><strong>Box Model</strong></h2>
<pre><code class="language-css">margin: 10px 20px 10px 20px; /* Outer spacing */
padding: 5px 10px 5px 10px; /* Inner spacing */
width: 100%; /* Element width */
height: fit-content; /* Height based on content */
</code></pre>
<hr />
<h2>Box-Sizing</h2>
<pre><code class="language-css">box-sizing: border-box; /* Includes padding/border in total size */
overflow: hidden; /* Hides overflow */
overflow-x: scroll; /* Scroll horizontally */
overflow-y: auto; /* Scroll vertically as needed */
aspect-ratio: 16/9; /* Keeps width:height ratio */
object-fit: cover; /* Scales image/video to fill box */
</code></pre>
<h2><strong>Colors</strong></h2>
<pre><code class="language-css">color: #333; /* Text color */
opacity: 0.8; /* Element transparency */
color: hsl(200, 80%, 40%); /* HSL color format */
</code></pre>
<h2><strong>Positioning</strong></h2>
<pre><code class="language-css">position: relative; /* Sets positioning context */
z-index: 10; /* Stacking order */
</code></pre>
<hr />
<h2>FlexBox :</h2>
<p><strong>Container-axis:</strong><br />In a Container, there are 2 axis.</p>
<ul>
<li><p>First is Main Axis , It goes from left (main start) to right (main end) . And it is controlled by <code>justify-content: ;</code></p>
</li>
<li><p>Second is Cross-axis , It goes from Top (cross main) to bottom (cross end). Ad It is controlled by <code>Align-Items: ;</code></p>
</li>
</ul>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769913304686/64f263b9-1bc0-4344-8893-837f1b063531.png" alt="" style="display:block;margin:0 auto" />

<p>And when we apply <code>Display: flex;</code> on this container, then the whole items inside the container will be come on main axis start.</p>
<h3><strong>Flex Direction :</strong></h3>
<ul>
<li><p><code>flex-direction : row;</code> is used to add all items in a row (mostly default)</p>
</li>
<li><p><code>flex-direction:column;</code> is used to add all items in a column.</p>
</li>
</ul>
<h3><strong>Properties for Child in Flexbox :</strong></h3>
<ul>
<li><p>You can also add some properties on a specific item in a container, and you can control it.</p>
</li>
<li><p><code>flex-1</code> is used to add on a specific item , and it`s means that give all the extra width to this specific item.</p>
</li>
<li><p><code>flex-2</code> is also used to add a specific item but it will take double space of the extra space .<br />It works like this :<br />If you have 5 items in a container, and you added <code>flex:1;</code> on item 1 and <code>flex:2;</code> on item 2 , then first of all all items will take his width and the extra remaining width will be divided into 3 parts . 2 parts will be of item 2 and 1 part will be of item 1 .</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769915430661/9b1cf5d9-0c64-48e2-90e9-d44ff075fe94.png" alt="" style="display:block;margin:0 auto" /></li>
</ul>
<h3><strong>Order in Flexbox :</strong></h3>
<p>Using order property , you can adjust/change any item place.<br />If you write <code>order:1;</code> on item 1 then it`s priority will be higher then all other items because all items have the default priority of 0 . And if you added 1 on a specific item then it will shift at the end , and it will come after all lowest orders .</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769926898557/6db304dc-196e-4a14-bfc9-486a7f24e2e3.png" alt="" style="display:block;margin:0 auto" />

<h3><strong>Wrap property in Flexbox:</strong></h3>
<ul>
<li><p><code>flex:wrap;</code> will keep default position and place.</p>
</li>
<li><p><code>flex:wrap-reverse</code> will do opposite of default position and place.</p>
</li>
</ul>
<h3><strong>Flexbox all Properties :</strong></h3>
<pre><code class="language-css">/* Parent (Container) */

display: flex; /* Activates flex layout */
flex-direction: row; /* Row direction */
justify-content: space-between; /* Distributes space */
align-items: center; /* Aligns items vertically */
gap: 1rem; /* Space between flex items */

/* Child (items) */

flex: 1; /* Flexible width */
align-self: center; /* Individual alignment */
order: 2; /* Changes visual order */
</code></pre>
<hr />
<h2>Set Primary/Secondary Color in CSS :</h2>
<p>You can define colors in the <code>:root</code> using css variables and you can reuse them anywhere in the stylesheet just by giving the color reference. It`s easy and widely used in modern CSS.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769953103903/730cc4da-de4b-47d6-a7b0-04c0a2ddfb23.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>CSS Grid :</h2>
<h3><strong>Control Whole Container coloumn`s:</strong></h3>
<p>You can control whole container , and you can decide that how many coloumns it should take.</p>
<p>1fr is used to add 1 coloumn and this is how you can add coloumns according to your need.</p>
<pre><code class="language-css">display: grid;
grid-template-columns: 1fr 1fr 1fr;
</code></pre>
<hr />
<h3><strong>Control Whole Container Row`s:</strong></h3>
<p>Grid-row is used to create rows with their different rows height. like in this it will create three rows with their 3 different rows height.</p>
<pre><code class="language-html"> .grid-container {
 display: grid;
 grid-template-rows: 80px 100px 100px;
</code></pre>
<hr />
<h3><strong>Control specific item width:</strong></h3>
<pre><code class="language-css">  grid-column: 1 / 4; /* It will cover ( colomn 1,2 and 3 ) width. */
  grid-column: 2 / 4; /* It will cover ( colomn 2 and 3 ) width. 
And if you make 3 box, the lines will be 4.
     | 1 | 2 | 3 |
     ^   ^   ^   ^
     1   2   3   4   ← lines */
</code></pre>
<p>And remember that always apply this on a specfic box not on the whole container.</p>
<hr />
<h3><strong>Control specific item height:</strong></h3>
<p>You can control , stretch , minimize, or adjust any row item height in a container.</p>
<pre><code class="language-css">  grid-row: 1 / 4; /* It will cover ( row 1,2 and 3 ) height. */
  grid-row: 2 / 4; /* It will cover ( rows 2 and 3 ) height. 
And remember that always apply this on a specfic box not on the whole container.
And if you make 3 box, the lines will be 4.
     | 1 | 2 | 3 |
     ^   ^   ^   ^
     1   2   3   4   ← lines */
</code></pre>
<hr />
<h2><strong>Media Queries:</strong></h2>
<pre><code class="language-css">@media (max-width: 768px) {
  body { 
      font-size: 14px; /* Applies styles on small screens */ 
       }
 }
</code></pre>
<hr />
<h2><strong>Animations &amp; Transitions</strong></h2>
<h3><strong>Animation</strong></h3>
<pre><code class="language-css">@keyframes slide {
from {
      transform: translateX(-100%); 
     }
  to {
      transform: translateX(0); 
     }
}
.element {
  animation: slide 1s ease-in-out infinite alternate; /* Animates element */
}

transition: all 0.3s ease-in-out;    /* Smoothly animates property changes */
transform: scale(1.1) rotate(10deg); /* Moves, rotates, scales elements */
transform:  translate(10px,20px);    /* use to move element in X-axis,Y-axis direction*/
</code></pre>
<hr />
<h2><strong>Modern Features in CSS :</strong></h2>
<pre><code class="language-css">scroll-snap-type: x mandatory; /* Creates snap scrolling */
backdrop-filter: blur(10px); /* Adds blur behind element */
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-thumb { background: #888; border-radius: 4px; } /* Styles scrollbar */
font-size: clamp(1rem, 2vw, 1.5rem); /* Responsive font size */
</code></pre>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a><br />Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Browser working]]></title><description><![CDATA[when we opened a website on browser, what happened behind the scene ?? we only write code, then how the browser loads everything and show the complete…]]></description><link>https://blog.abdulrdeveloper.me/browser-working</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/browser-working</guid><category><![CDATA[Browsers]]></category><category><![CDATA[rendering engine]]></category><category><![CDATA[BROWSER ENGINE AND WEB BROWSER]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Thu, 29 Jan 2026 07:06:01 GMT</pubDate><content:encoded><![CDATA[<p>when we opened a website on browser, what happened behind the scene ??</p>
<p>we only write code, then how the browser loads everything and show the complete webpage to the client.</p>
<p>This all happened through Browser.</p>
<h2>Basics of a Browser :</h2>
<p>So let’s try to understand the browser.</p>
<ul>
<li><p>Basic knowledge of the browser is enough if you don’t want to build your own browser.</p>
</li>
<li><p>Deep knowledge will help when you want to build your own browser.</p>
</li>
</ul>
<hr />
<h2>Browser`s Most Important Part :</h2>
<p>The most important part of a browser is the Search URL (where we search everything).</p>
<h2>Browser structure :</h2>
<p>Browser seems like this:</p>
<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/019c056b-ba7e-71d9-8218-b9644164b0d3/1769617660715-019c056d-b082-7b30-abee-dc2936ec5fa8.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260129%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260129T065444Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=f38d65be8a4405c4f682ac535877954a687ad15190b261cf71b292076a3efa03&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="019c056b-ba7e-71d9-8218-b9644164b0d3/1769617660715-019c056d-b082-7b30-abee-dc2936ec5fa8.png" />

<hr />
<h2>User Interface :</h2>
<ul>
<li>It is the frontend view of the browser which the user/client see while visiting the browser. It contains UI/UX like search bar, buttons (back, forward, refresh), webpages , tabs , page content.</li>
</ul>
<hr />
<h2>Browser Engine :</h2>
<p>It manage whole user requests and give instructions to the rendering engine. Think of it like a coordinator who gives instructions , organise and manage them.</p>
<ul>
<li><p>Browser Engine recieves all the users input.</p>
</li>
<li><p>It Gives instructions to rendering Engine.</p>
</li>
<li><p>It gives js code to javascript interpreter.</p>
</li>
<li><p>It gives network requests to networking.</p>
</li>
</ul>
<hr />
<h2>Rendoring Engine :</h2>
<p>It is the most interesting and magical part of the browser . It is divided into 3 main parts,</p>
<ul>
<li><p>Networking</p>
</li>
<li><p>JS interpreter</p>
</li>
<li><p>UI Backend</p>
</li>
</ul>
<h3><strong>Networking :</strong></h3>
<p>When the user types "chicode.com", the user sees the website but behind the scene</p>
<ul>
<li><p>Network Engine goes to chaicode server and brings all HTML, CSS and JS files and images.</p>
</li>
<li><p>It gives the complete code files to Browser Engine.</p>
</li>
</ul>
<hr />
<h3>JS-Interpreter :</h3>
<p>It controls all functions on the website , if the user enter a button on the website then behind the scene</p>
<ul>
<li><p>JS interpreter loads all the JS files, manages them and update the page quickly infront of the user</p>
</li>
<li><p>It executes functions and perform specific actions.</p>
</li>
</ul>
<hr />
<h3>UI Backend :</h3>
<p>It is the most important part of the rendering engine. It fatches data from HTML and CSS files, create DOM and CSSOM , and finally create a paints of them and show the user on browser screen. Fist of all it takes HTML and CSS code files by Network Engine.</p>
<p><strong>HTML DOM Tree :</strong></p>
<ul>
<li><p>It converts HTML into DOM like this,</p>
<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/6c17eb9e-3623-4351-8fdf-ef2a02745e13/1769669554839-019c0885-bc87-75af-9f10-d03b1ac33bee.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260129%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260129T065235Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=c3a909cce0655b20743f0e1ea88f8255177a328ee9d668b4567a109295bba49a&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="" />

<hr />
<h3>CSS CSSOM Tree :</h3>
</li>
<li><p>It converts CSS code into CSSOM like this ,</p>
<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/6c17eb9e-3623-4351-8fdf-ef2a02745e13/1769664795029-019c083c-f7b0-794b-a095-78f59cd8020d.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260129%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260129T053315Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=95bd6b0f1ed74ecf4c9ecbaff30230871cf2fab8a3443686846bda904b1ad8f2&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="" />

<hr />
<h3>Render Tree ( Combine of DOM + CSSOM ):</h3>
</li>
<li><p>After Creating DOM and CSSOM Tree, The UI Backend combines these both and make a Render Tree.</p>
<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/6c17eb9e-3623-4351-8fdf-ef2a02745e13/1769667790758-019c086a-ea65-7246-8440-b10af98b6506.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260129%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260129T062310Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=ab48ad81cdae5dffaa21d0b7c71f6bafa98a35b6a5268f843864e7440520a494&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="" />

<hr />
<h3>Final Output on The Browser Screen :</h3>
</li>
<li><p>And after Creating Render Tree, It finally make layout and paint it for showing on the screen .</p>
<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/6c17eb9e-3623-4351-8fdf-ef2a02745e13/1769668718408-019c0879-0810-74ce-bad0-9e0e93ee5e86.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260129%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260129T063838Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=ab2ecee5f67aed3bffbab1bbeb084fd5a4ce697735de98fcbb4d608eaf522611&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="" />

<p>It have a connection directly with User interface because It shows the webpage(paint) .</p>
</li>
</ul>
<hr />
<h2>Disk API :</h2>
<p>It communicate with <strong>Operating System</strong>.</p>
<ul>
<li><p>It reads Hard drive files and saves cache data/files , it saves permanently</p>
</li>
<li><p>It store/retrieve user's data.</p>
</li>
<li><p>It access system resources.</p>
</li>
</ul>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a><br />Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Chai aur HTML]]></title><description><![CDATA[Learn HTML from scratch — boilerplate, tags, forms, tables, media & semantic elements explained simply with real examples and practical tips.]]></description><link>https://blog.abdulrdeveloper.me/chai-aur-html</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/chai-aur-html</guid><category><![CDATA[HTML5]]></category><category><![CDATA[HTML]]></category><category><![CDATA[webdevelopment]]></category><category><![CDATA[beginnersguide]]></category><category><![CDATA[cheatsheet]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Tue, 27 Jan 2026 17:45:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/299dcc41-d1ba-4e56-9499-ae9c21e0223e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Web Servers:</strong></p>
<ul>
<li>A web server is a program/machine that serves files (HTML, CSS, JS, images, etc.) in response to a browser's request.</li>
</ul>
<p>HTML stands for "<strong>Hyper Text Markup Language".</strong></p>
<h2><strong>Boilerplate:</strong></h2>
<pre><code class="language-xml">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;!-- Content goes here --&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<ul>
<li><p>Very Useful for Beginners ,</p>
</li>
<li><p>Just write, " ! " and it will auto generate boilerplate.</p>
</li>
<li><p>It saves time and increases speed in Coding.</p>
</li>
</ul>
<h2><strong>Headings :</strong></h2>
<p>There are six levels of headings. <code>&lt;h1&gt;</code> <code>&lt;h2&gt;</code> and <code>&lt;h3&gt;</code> are most important headings, and <code>&lt;h4&gt; &lt;h5&gt; &lt;h6&gt;</code> are not widely used now, less important.</p>
<pre><code class="language-xml">&lt;h1&gt;Heading 1&lt;/h1&gt;      &lt;!-- Most Important --&gt;
&lt;h2&gt;Heading 2&lt;/h2&gt;      &lt;!-- Most Important --&gt;
&lt;h3&gt;Heading 3&lt;/h3&gt;      &lt;!-- Important --&gt;
&lt;h4&gt;Heading 4&lt;/h4&gt;
&lt;h5&gt;Heading 5&lt;/h5&gt;
&lt;h6&gt;Heading 6&lt;/h6&gt;
</code></pre>
<hr />
<h2><strong>Containers :</strong></h2>
<pre><code class="language-xml">&lt;div&gt;This is a block container (div)&lt;/div&gt;         &lt;!-- Most Important --&gt;
&lt;span&gt;This is an inline container (span)&lt;/span&gt;    &lt;!-- Important --&gt;
&lt;p&gt;This is a paragraph&lt;/p&gt;                         &lt;!-- Most Important --&gt;
&lt;pre&gt;Preserves formatting and spaces&lt;/pre&gt;
&lt;code&gt;console.log("Code snippet")&lt;/code&gt;
&lt;blockquote&gt;A block quotation of text&lt;/blockquote&gt;
</code></pre>
<h2><strong>Text Formatting :</strong></h2>
<pre><code class="language-xml">&lt;b&gt;Bold text&lt;/b&gt;                               &lt;!-- Important --&gt; 
&lt;strong&gt;Important text (semantic)&lt;/strong&gt;     &lt;!-- Most Important --&gt;
&lt;i&gt;Italic text&lt;/i&gt;                             &lt;!-- Stylish Font --&gt;
&lt;em&gt;Emphasized text (semantic)&lt;/em&gt;            &lt;!-- Stylish Font --&gt;
&lt;u&gt;Underlined text&lt;/u&gt;                         &lt;!-- Most Important --&gt;
&lt;mark&gt;Highlighted text&lt;/mark&gt;
&lt;small&gt;Smaller text&lt;/small&gt;
&lt;time datetime="2026-01-27"&gt;Published on January 27, 2026&lt;/time&gt;      &lt;!-- Good Practice for SEO, 
you can use div and p also but use it to represent specific date on blogs,articles etc --&gt;
&lt;del&gt;Deleted text&lt;/del&gt;
&lt;ins&gt;Inserted text&lt;/ins&gt;
&lt;sub&gt;Subscript&lt;/sub&gt;                            &lt;!-- H₂O, CO₂ --&gt;
&lt;sup&gt;Superscript&lt;/sup&gt;                          &lt;!-- x², E=mc² --&gt;
</code></pre>
<hr />
<h2><strong>Lists :</strong></h2>
<h3><strong>Ordered List :</strong></h3>
<pre><code class="language-xml">&lt;ol&gt;
  &lt;li&gt;First&lt;/li&gt;                    &lt;!-- display output : 1,2,3 in order --&gt;
  &lt;li&gt;Second&lt;/li&gt;
&lt;/ol&gt;
</code></pre>
<ul>
<li><p>Use <code>type</code> and <code>start</code> attributes inside the <code>&lt;ol&gt;</code> tag.</p>
</li>
<li><p><code>type="A"</code> gives uppercase letters, (A, B, C...)</p>
</li>
<li><p><code>&lt;ol type="A" start="5"&gt;</code> Both can be used at same time.</p>
<ul>
<li><p><code>type="1"</code> → 1, 2, 3 (default)</p>
</li>
<li><p><code>type="A"</code> → A, B, C (uppercase letters)</p>
</li>
<li><p><code>type="a"</code> → a, b, c (lowercase letters)</p>
</li>
<li><p><code>type="I"</code> → I, II, III (Roman numerals uppercase)</p>
</li>
<li><p><code>type="i"</code> → i, ii, iii (Roman numerals lowercase)</p>
</li>
</ul>
</li>
<li><p><code>start="5"</code> means It will start by 5th letter (E, F, G...)</p>
<ul>
<li><p><code>start="5"</code> → 5 se start hoga</p>
</li>
<li><p><code>start="10"</code> → 10 se start hoga etc.</p>
</li>
</ul>
</li>
</ul>
<h3><strong>Unordered List :</strong></h3>
<pre><code class="language-xml">&lt;ul&gt;
  &lt;li&gt;First Item&lt;/li&gt;                    &lt;!-- display output : •  •  •  without any order --&gt;
  &lt;li&gt;Second Item&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<h3><strong>Definition List :</strong></h3>
<pre><code class="language-xml">&lt;dl&gt;
  &lt;dt&gt;What is HTML&lt;/dt&gt;
  &lt;dd&gt;HTML is a HyperText Markup Language. It is Known as the skeleton of the website.&lt;/dd&gt;
&lt;/dl&gt;
</code></pre>
<hr />
<h2>Media :</h2>
<pre><code class="language-xml">&lt;img src="image.jpg" alt="Description" width="300" height="200"&gt;      
&lt;!-- Always use alt with images, (and width and height can be adjusted by using CSS also) --&gt;

&lt;audio controls&gt;
  &lt;source src="audio.mp3" type="audio/mpeg"&gt;
&lt;/audio&gt;
 
&lt;video width="480" height="320" controls&gt;
  &lt;source src="video.mp4" type="video/mp4"&gt;
&lt;track src="captions.vtt"&gt;&lt;/track&gt;      &lt;!-- Use track tag to add captions in video --&gt;
&lt;/video&gt;
 
&lt;iframe src="https://www.example.com" width="600" height="400"&gt;&lt;/iframe&gt;
&lt;!-- Get video iframe: Share → Embed → Copy code --&gt;

&lt;iframe src="https://drive.google.com/file/d/1KasLwUTg39qp54-ZH3sZ/preview"&gt;&lt;/iframe&gt;
&lt;!-- or you can use embed | But always use preview word at the end of the pdf link --&gt;
&lt;embed src="https://drive.google.com/file/d/1EV-MO8TuJhHCfpmfvfD0/preview" &gt;&lt;/embed&gt;
&lt;!-- Use embed or iframe for PDFs to show them on the webpage --&gt;
</code></pre>
<h2><strong>Tables :</strong></h2>
<p>There are three Parts of Table in HTML ,</p>
<ul>
<li><p><code>&lt;thead&gt;&lt;/thead&gt;</code> Here we give the top heading inside the table like student marks, grade etc.</p>
</li>
<li><p><code>&lt;tbody&gt;&lt;/tbody&gt;</code> Here we add Real data like 99 marks,83 marks ,C grade ,B grade etc.</p>
</li>
<li><p><code>&lt;tfoot&gt;&lt;/tfoot&gt;</code> Here we add a final display colomn like Total Marks, CGPA, etc</p>
</li>
<li><p><code>&lt;td colspan = "2"&gt;</code> use colspan to control and increase specific colomns width.</p>
</li>
<li><p><code>&lt;td rowspan = "2"&gt;</code> use rowspan to control and increase specific row’s height.</p>
</li>
</ul>
<pre><code class="language-xml">    &lt;table border="1"&gt;         &lt;!-- use border = "1", it will add border directly on table --&gt;

&lt;colgroup&gt;
      &lt;col style="background-color: skyblue;"&gt;
      &lt;col style="background-color: lightblue; color:white;"&gt;
      &lt;col style="background-color: aquamarine;"&gt;
&lt;/colgroup&gt;
&lt;!-- With the help of colspan, we can change the background colors of
our columns. But remember that colspan only changes the background 
colors, not the actual structure of the columns.--&gt;

  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Column 1&lt;/th&gt;
      &lt;th colspan="2"&gt;Column 2&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;

  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td rowspan="2"&gt;Rowspan&lt;/td&gt;
      &lt;td&gt;Data A&lt;/td&gt;
      &lt;td&gt;Data B&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Data C&lt;/td&gt;
      &lt;td&gt;Data D&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;

  &lt;tfoot&gt;
    &lt;tr&gt;
      &lt;td&gt;Total&lt;/td&gt;
      &lt;td colspan="2"&gt;100&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tfoot&gt;

&lt;/table&gt;
</code></pre>
<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/7d7ee137-9aad-4fec-80ee-a7920603dac4/1769459184709-019bfbfb-a799-722b-a98d-d4265a5c5cc4.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260126%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260126T202624Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=6e49c47e3324b6f75a3b1bbd3411618f6f247e396154eb5ba294e4961a3802ce&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="" />

<hr />
<h2>Links :</h2>
<pre><code class="language-xml">&lt;a href="https://www.chaicode.com" target="_blank" rel="noopener"&gt;Visit CodeWithHarry&lt;/a&gt;
&lt;!-- Google Drive direct download pattern:
     https://drive.google.com/uc?export=download&amp;id=FILE_ID --&gt;

&lt;a href="mailto:support@chaicode.com"&gt;Send Email&lt;/a&gt;    &lt;!-- Use maitro:  and then email --&gt;

&lt;a href="#section1"&gt;Jump to Section&lt;/a&gt;   
&lt;!-- also add jump section id like this →  &lt;h1 id="section"&gt;Learn Coding &lt;/h1&gt;   --&gt;
</code></pre>
<hr />
<h2>Forms :</h2>
<pre><code class="language-xml">&lt;form action="/action.php" method="post"&gt;
  &lt;label for="username"&gt;Username:&lt;/label&gt;
  &lt;input type="text" id="username" name="username"&gt;&lt;br&gt;

  &lt;input type="password" name="password" placeholder="Enter Password"&gt;&lt;br&gt;

  &lt;input type="checkbox" name="subscribe" value="yes"&gt; Subscribe&lt;br&gt;

  &lt;input type="radio" name="gender" value="male"&gt; Male
  &lt;input type="radio" name="gender" value="female"&gt; Female&lt;br&gt;

  &lt;select name="country"&gt;
    &lt;option value="us"&gt;USA&lt;/option&gt;
    &lt;option value="ca"&gt;Canada&lt;/option&gt;
  &lt;/select&gt;&lt;br&gt;

  &lt;textarea name="comments" rows="4" cols="30"&gt;&lt;/textarea&gt;&lt;br&gt;

  &lt;input type="file" name="resume" multiple accept=".pdf,.doc,.docx,.jpg,.png"&gt;&lt;br&gt;

&lt;!-- type="file" → File upload input
multiple → can select multiple files
accept=".pdf,.jpg" → only .pdf files allow , can adjust by own choice  --&gt;

  &lt;input type="number" name="age" min="18" max="100"&gt;&lt;br&gt;
  &lt;input type="range" name="volume" min="0" max="100"&gt;&lt;br&gt;
  &lt;input type="date" name="dob"&gt;&lt;br&gt;
  &lt;input type="email" name="email"&gt;&lt;br&gt;
  &lt;input type="url" name="website"&gt;&lt;br&gt;
  &lt;input type="search" name="query"&gt;&lt;br&gt;



  &lt;button type="submit"&gt;Submit&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<h3><strong>HTML all input Types Image Preview:</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/c87a4b9e-fd91-4ed3-b6b9-a61e70ac0cb4.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h3>Auto Suggestion Search System Using HTML :</h3>
<pre><code class="language-xml">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Datalist Autocomplete&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;Search Fruit&lt;/h1&gt;
    
    &lt;input type="text" list="fruits" placeholder="Type fruit name"&gt;
    
    &lt;datalist id="fruits"&gt;
      &lt;option value="Apple"&gt;
      &lt;option value="Banana"&gt;
      &lt;option value="Mango"&gt;
      &lt;option value="Orange"&gt;
      &lt;option value="Grapes"&gt;
      &lt;option value="Strawberry"&gt;
      &lt;option value="Pineapple"&gt;
    &lt;/datalist&gt;
    
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2>Output :</h2>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769505092515/341cd3b8-1706-4860-8303-2b38a7db4670.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2><strong>Semantic Elements :</strong></h2>
<pre><code class="language-xml">&lt;header&gt;Page header&lt;/header&gt;
&lt;main&gt;Main content&lt;/main&gt;
&lt;footer&gt;Page footer&lt;/footer&gt;
&lt;nav&gt;Navigation links&lt;/nav&gt;
&lt;section&gt;Section of content&lt;/section&gt;
&lt;article&gt;Independent article&lt;/article&gt;
&lt;aside&gt;Sidebar content&lt;/aside&gt;
</code></pre>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a><br />Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Understanding DNS and Name Resolution]]></title><description><![CDATA[What is DNS? DNS stands for Domain Name System. It is a system that converts website names (like google.com) into IP addresses that computers can…]]></description><link>https://blog.abdulrdeveloper.me/understanding-dns-and-name-resolution</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/understanding-dns-and-name-resolution</guid><category><![CDATA[dig command]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Tue, 27 Jan 2026 07:08:12 GMT</pubDate><content:encoded><![CDATA[<p><strong>What is DNS?</strong></p>
<p>DNS stands for Domain Name System. It is a system that converts website names (like <a href="http://google.com">google.com</a>) into IP addresses that computers can understand. When you type <a href="http://google.com">google.com</a> in your browser, your computer does not know where <a href="http://google.com">google.com</a> is located. So DNS helps to find the IP address of <a href="http://google.com">google.com</a> and connect you to the correct server.</p>
<p><strong>Why Name Resolution Exists?</strong></p>
<p>Computers communicate with each other using IP addresses (like 142.251.41.14), but humans cannot remember all these long numbers. So DNS was created to convert easy-to-remember domain names (like <a href="http://google.com">google.com</a>) into their corresponding IP addresses. This process is called name resolution. Without DNS, you would have to type IP addresses instead of domain names every time you want to visit a website.</p>
<p><strong>What is the dig Command?</strong></p>
<p>dig stands for Domain Information Groper. It is a command-line tool that is used to query DNS servers and get information about domain names. Dig command helps us to understand how DNS works and troubleshoot DNS-related problems. When you run dig command, it shows you the complete DNS resolution process - from the root server all the way to the authoritative name server.</p>
<p><strong>When is dig Command Used?</strong></p>
<p>Dig command is used when:</p>
<ul>
<li><p>You want to find the IP address of a website</p>
</li>
<li><p>You want to check if a domain name is working properly</p>
</li>
<li><p>You want to troubleshoot DNS issues</p>
</li>
<li><p>You want to understand the DNS resolution process step by step</p>
</li>
<li><p>Network administrators want to debug DNS problems</p>
</li>
</ul>
<p><strong>Understanding dig . NS and Root Name Servers:</strong></p>
<p><strong>What is the Root Name Server?</strong></p>
<p>The root name server is the first step in DNS resolution. When you request <a href="http://google.com">google.com</a>, your computer first asks the root name server "Where should I go to find <a href="http://google.com">google.com</a>?" The root name server does not know the IP address of <a href="http://google.com">google.com</a> directly. Instead, it tells you which server can help you find <a href="http://google.com">google.com</a>.</p>
<p><strong>What Does dig . NS Show?</strong></p>
<p>When you run the command <code>dig . NS</code>, it shows all the root name servers in the world. These are 13 root name servers (<a href="http://a.root-servers.net">a.root-servers.net</a>, <a href="http://b.root-servers.net">b.root-servers.net</a>, <a href="http://c.root-servers.net">c.root-servers.net</a>, etc.). Although there are only 13 official root servers concept-wise, they have 1600+ copies (instances) distributed across the world to handle trillions of DNS queries every day. This is similar to how banks have one main office but thousands of branches.</p>
<p><strong>How Root Name Servers Work:</strong></p>
<p>Your Computer sends request → Root Name Server receives it (dig . NS)<br />Root Name Server checks the domain extension (.com, .org, .edu)<br />Root Name Server responds with the address of the TLD (Top Level Domain) name server<br />Your Computer then knows where to go next</p>
<p><strong>Understanding dig com NS and TLD Name Servers:</strong></p>
<p><strong>What is a TLD Name Server?</strong></p>
<p>TLD stands for Top Level Domain. Common TLDs are .com, .org, .edu, .pk, .net, etc. When the root name server tells your computer to ask a TLD name server, your computer then asks the .com TLD name server "Where can I find <a href="http://google.com">google.com</a>?"</p>
<p><strong>What Does dig com NS Show?</strong></p>
<p>When you run the command <code>dig com NS</code>, it shows all the TLD name servers for .com domains. These servers know about all .com domain names and can tell you which server is responsible for each .com domain. For example, if you ask the .com TLD server about <a href="http://google.com">google.com</a>, it will tell you which server manages <a href="http://google.com">google.com</a>'s DNS records.</p>
<p><strong>How TLD Name Servers Work:</strong></p>
<p>Your Computer asks TLD Name Server → "Where is <a href="http://google.com">google.com</a>?"<br />TLD Name Server checks its database<br />TLD Name Server responds with the address of <a href="http://google.com">google.com</a>'s authoritative name server<br />Your Computer now knows where to go to get the actual IP address</p>
<p><strong>The Flow So Far:</strong></p>
<p>Your Computer → Root Name Server (dig . NS) → TLD Name Server (dig com NS) → Authoritative Name Server (coming next)</p>
<p><strong>Understanding dig</strong> <a href="http://google.com"><strong>google.com</strong></a> <strong>NS and Authoritative Name Servers:</strong></p>
<p><strong>What is an Authoritative Name Server?</strong></p>
<p>The authoritative name server is the actual server that knows the IP address of <a href="http://google.com">google.com</a>. It is owned and managed by Google company itself. This is the final step in DNS resolution. Authoritative name servers store the actual DNS records for the domain.</p>
<p><strong>What Does dig</strong> <a href="http://google.com"><strong>google.com</strong></a> <strong>NS Show?</strong></p>
<p>When you run the command <code>dig</code> <a href="http://google.com"><code>google.com</code></a> <code>NS</code>, it shows which servers are the authoritative name servers for <a href="http://google.com">google.com</a>. For Google, you will see servers like <a href="http://ns1.google.com">ns1.google.com</a>, <a href="http://ns2.google.com">ns2.google.com</a>, <a href="http://ns3.google.com">ns3.google.com</a>, <a href="http://ns4.google.com">ns4.google.com</a>. These are Google's own name servers that store the IP address information for <a href="http://google.com">google.com</a> and other Google domains.</p>
<p><strong>How Authoritative Name Servers Work:</strong></p>
<p>Your Computer asks Authoritative Name Server → "What is the IP address of <a href="http://google.com">google.com</a>?"<br />Authoritative Name Server checks its database<br />Authoritative Name Server responds with the IP address: 142.251.41.14<br />Your Computer receives the IP address and connects to Google's server</p>
<p><strong>Why Multiple Authoritative Servers?</strong></p>
<p>Google uses multiple authoritative name servers (ns1, ns2, ns3, ns4) for redundancy and load balancing. If one server goes down, the others can still respond to DNS queries. This ensures that the website remains accessible all the time.</p>
<p><strong>Understanding dig</strong> <a href="http://google.com"><strong>google.com</strong></a> <strong>and the Full DNS Resolution Flow:</strong></p>
<p><strong>What Happens When You Run dig</strong> <a href="http://google.com"><strong>google.com</strong></a><strong>?</strong></p>
<p>When you run the command <code>dig</code> <a href="http://google.com"><code>google.com</code></a>, it shows you the complete DNS resolution process. It shows you the actual IP address of <a href="http://google.com">google.com</a> and how your computer found it. This is the final query after going through all the previous steps.</p>
<p><strong>The Complete DNS Resolution Flow:</strong></p>
<p>Step 1: Your Computer sends request → "I want to visit <a href="http://google.com">google.com</a>"</p>
<p>Step 2: Root Name Server receives it (dig . NS)<br />Root Name Server says "I don't know <a href="http://google.com">google.com</a>, but ask the .com TLD server"</p>
<p>Step 3: Your Computer asks TLD Name Server (dig com NS)<br />TLD Name Server says "I know about .com domains, but for <a href="http://google.com">google.com</a> specifically, go ask <a href="http://ns1.google.com">ns1.google.com</a>"</p>
<p>Step 4: Your Computer asks Authoritative Name Server (dig <a href="http://google.com">google.com</a> NS)<br />Authoritative Name Server (<a href="http://ns1.google.com">ns1.google.com</a>) responds with the IP address: 142.251.41.14</p>
<p>Step 5: Your Computer receives the IP address and connects to Google's server<br />Your Browser displays Google homepage</p>
<p><strong>Why This Process Is Important:</strong></p>
<p>This entire process happens in milliseconds. When you type <a href="http://google.com">google.com</a> in your browser, you are immediately connected to the correct server without knowing the IP address. DNS makes the Internet user-friendly and easy to use.</p>
<p><strong>What Each dig Command Shows:</strong></p>
<ul>
<li><p><code>dig . NS</code> → Shows root name servers</p>
</li>
<li><p><code>dig com NS</code> → Shows TLD name servers for .com</p>
</li>
<li><p><code>dig</code> <a href="http://google.com"><code>google.com</code></a> <code>NS</code> → Shows authoritative name servers for <a href="http://google.com">google.com</a></p>
</li>
<li><p><code>dig</code> <a href="http://google.com"><code>google.com</code></a> → Shows the IP address of <a href="http://google.com">google.com</a> and the complete resolution process</p>
</li>
</ul>
<p><strong>Real-Life Example:</strong></p>
<p>Think of the DNS resolution process like finding someone's address:</p>
<p>You ask your friend (Root Server): "Where does Ali live?"<br />Friend says: "I don't know, ask the city office (TLD Server)"</p>
<p>You go to City Office: "Where does Ali live in this city?"<br />City Office says: "I don't know exactly, but ask his neighborhood office (Authoritative Server)"</p>
<p>You go to Neighborhood Office: "Where does Ali live?"<br />Neighborhood Office says: "Ali lives at House 123, Block 5"</p>
<p>Now you know the exact address and can visit.</p>
<p>Same way, your computer goes from Root Server → TLD Server → Authoritative Server to find the IP address of the website you want to visit.</p>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a><br />Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Understanding Network Devices :]]></title><description><![CDATA[If we need to transfer data from a computer to a mobile device, it can be done directly using a data cable. But when we need to transfer data between two…]]></description><link>https://blog.abdulrdeveloper.me/understanding-network-devices</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/understanding-network-devices</guid><category><![CDATA[modem]]></category><category><![CDATA[router]]></category><category><![CDATA[firewall]]></category><category><![CDATA[SWITCH]]></category><category><![CDATA[Load Balancer]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Tue, 27 Jan 2026 06:19:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/bd1730f9-dba7-48cc-962f-1ae55c94f197.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<ul>
<li><p>If we need to transfer data from a computer to a mobile device, it can be done directly using a data cable. But when we need to transfer data between two computers, a direct cable connection does not work. In this situation, we use network devices for transferring data and communication with each other.</p>
</li>
<li><p>Network Devices work like a <strong>Road</strong>/<strong>bridge</strong> that allows two computers to easily communicate without any security risk .We can use network Devices for communication or interaction between two or more computers.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769483073884/b5c28e27-7b04-4798-b476-0b9855dd755b.png" alt="" style="display:block;margin:0 auto" />

<p>If Both Computers want to connect with each other, then both computer’s cables should be in network device.</p>
<h3><strong>Data Transferring Flow :</strong></h3>
<ul>
<li><p><strong>Computer</strong> sends (0,1,0) data → Using Blue cable → The data reaches at Network Device.</p>
</li>
<li><p>Network Devices receive those data and then decide where to send next.</p>
</li>
<li><p>Network Devices forward the data → in yellow cable → computer 02 receives the data</p>
</li>
<li><p>This flow can be opposite also (Computer 02 - to - Computer 01 )</p>
</li>
</ul>
<hr />
<h3><strong>Commonly used Networking Devices :</strong></h3>
<p>There are a lot of Networking Devices but most commonly used devices are as follows.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769484955495/460a8f11-ecf9-4a5c-88e5-a9ab26c3ca62.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2><strong>Switch :</strong></h2>
<p>Just Suppose , If you are working in a industry/company and there are 100 computers connected with switch , and you want to send data to a specific computer in those 100 computers , then what will you do ?</p>
<p>In this case switch helps to transfer data to a specific computer using mac address.</p>
<p>The Complete workFlow :</p>
<ol>
<li><p>Computer 01 will send data in switch with mac address of the specific computer (where the computer 01 wants to send data)</p>
</li>
<li><p>Switch will check all 100 computers mac addresses (each computer contains unique and only one mac address)</p>
</li>
<li><p>Once the switch found the specific Computer, it will forward whole data on those specific computer.</p>
</li>
</ol>
<p>Switch can be connected through wired connection and wireless , but on large scale, it mostly used wireless because connacting 100 computers with wired can be confusing so wireless also used.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/9101ecf8-7dd2-4faa-a4f5-95f6f748e97f.png" alt="" style="display:block;margin:0 auto" />

<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/6c17eb9e-3623-4351-8fdf-ef2a02745e13/1769489369944-019bfdc8-3da2-732b-8fb4-9a5fefbf3c6a.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260127%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260127T044930Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=cc3ff39c4b626675738216a70b92266b53e011ef2f58bd62cd1fb507684331b9&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="" />

<hr />
<h3>Hub :</h3>
<p>It is one of the oldest and simplest network device which transfer data directly everywhere instead of specific computer.</p>
<p>Just suppose computer 01 want to send data to a specific computer,</p>
<ul>
<li><p>First of all , computer 01 will send data to Hub .</p>
</li>
<li><p>Hub will receive and transfer data in whole 100 computers instead of specific computer.</p>
</li>
<li><p>This can cause more bandwidth and sends unnecassory data in all computers.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69513d1ce0cbcddf469383e9/0f691021-7544-4e7e-8302-0172f68c7c06.png" alt="" style="display:block;margin:0 auto" /></li>
</ul>
<img src="https://messages-prod.27c852f3500f38c1e7786e2c9ff9e48f.r2.cloudflarestorage.com/6c17eb9e-3623-4351-8fdf-ef2a02745e13/1769488679883-019bfdbd-f363-76df-979a-ab3fd5be9dec.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&amp;X-Amz-Credential=af634fe044bd071ab4c5d356fdace60f%2F20260127%2Fauto%2Fs3%2Faws4_request&amp;X-Amz-Date=20260127T043800Z&amp;X-Amz-Expires=3600&amp;X-Amz-Signature=760551bd6e894387d38bd695ce51d77a0fdb6ef350a907eb2c61547553d02a16&amp;X-Amz-SignedHeaders=host&amp;x-amz-checksum-mode=ENABLED&amp;x-id=GetObject" alt="" />

<hr />
<h2>Switch vs Hub :</h2>
<ul>
<li><p>Switch forwards data to specific computer using mac address.</p>
</li>
<li><p>Hub forwards data to all connected computers instead of one.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769490654846/4480260e-1646-40b6-8eb7-609727845d73.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Router :</h2>
<ul>
<li><p>As we discussed earlier that switch is use to send or receive data through LANs( local wires),</p>
</li>
<li><p>But what happened if you want to share or access data from a network which is not accessible locally to you?</p>
</li>
<li><p>Like using <a href="http://google.com">google.com</a>, which is not available offline near you.</p>
</li>
<li><p>Therefore you need a device that connects you to different online network servers. A router uses ip address (address on internet) instead of mac address (local offline address).</p>
</li>
<li><p>Router requests to server and give us server response.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769492335683/ef996028-5637-4863-8cdf-dd794575ab93.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Modem :</h2>
<p>Modem is use to convert data signals given by ISP (fiberr, PTCL etc) ,</p>
<p><strong>How it works :</strong></p>
<ul>
<li>ISP gives you internet or wifi , but it contains analog signals , and modem converts these signals into digital (0,1) and computer connect to internet and wifi.</li>
</ul>
<p>ISP (Analog Signals) → Modem (Converter) → Digital Signals → Your Computer → Internet Access.</p>
<p>without modem , ISP will gives you analog signals but your computer cannot understand and proceed it , and you will be unable to connect with internet.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769181489165/29026d48-3855-45fc-bb1c-aed021c616a9.png" alt="" />

<hr />
<h2>Firewall :</h2>
<ul>
<li><p>A firewall is a security device or software that checks and controls incoming and outgoing network traffic.</p>
</li>
<li><p>It is exact like a security guard who checks everyone before entering in the house from outside.</p>
</li>
<li><p>A firewall decides which data packets are allowed to enter your network and which ones should be blocked.</p>
</li>
<li><p>This all done on firewall by predefined security rules.</p>
</li>
</ul>
<hr />
<p>Load Balanacer :</p>
<ul>
<li><p>Load balancer is used to manage clients request. If the client requests a website,</p>
</li>
<li><p>The request goes to load balancer first.</p>
</li>
<li><p>Load balancer check all available servers and response the minimal traffic server .</p>
</li>
<li><p>Large websites like Google, Facebook, and YouTube use multiple load balancers to handle billions of requests every day.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769183991196/8a277fd2-cfeb-42cc-8bfa-13f76b94410b.png" alt="" />

<hr />
<p>These all Network Devices , internal devices , external devices, ISP etc works combine to run the whole world of the network known as Networking .</p>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a><br />Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item><item><title><![CDATA[Getting Started with cURL]]></title><description><![CDATA[cURL is exactly like a Postman but for terminal/command line. When we want to send letter to someone, we give letter to postman and postman deliver it…]]></description><link>https://blog.abdulrdeveloper.me/getting-started-with-curl</link><guid isPermaLink="true">https://blog.abdulrdeveloper.me/getting-started-with-curl</guid><category><![CDATA[curl]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Abdul Rahman]]></dc:creator><pubDate>Fri, 23 Jan 2026 13:49:49 GMT</pubDate><content:encoded><![CDATA[<p>cURL is exactly like a <strong>Postman</strong> but for terminal/command line. When we want to send letter to someone, we give letter to postman and postman deliver it. Similarly cURL is a tool which send request to server from terminal and get`s response back.</p>
<p><strong>cURL</strong> is a command-line tool that help us to talk with servers and APIs directly using terminal without opening any browser.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769166787285/ba7f6a11-ca2c-47d4-93a4-73e37405a4a9.png" alt="" style="display:block;margin:0 auto" />

<h2>Why Programmers Need cURL ?</h2>
<p>cURL helps programmers to easily access websites and test APIs without opening browsers again and again. Using cURL, programers test APIs in the backend and can get whole HTML code without inspecting the browser.</p>
<hr />
<h2>Making your first request using cURL :</h2>
<p><em><strong>Step 1 : Check if cURL is installed on Windows</strong></em></p>
<p>cURL comes pre-installed with <strong>Windows 10 and later</strong> versions (PowerShell).</p>
<p>Open PowerShell or Command Prompt and type:</p>
<pre><code class="language-powershell">curl --version
</code></pre>
<p>If you see a version number then it`s already installed , or you can download it from <a href="https://curl.se/download"><strong>curl.se/download</strong></a>.</p>
<p><em><strong>Step 2 : Make Your First Request</strong></em></p>
<p>Open PowerShell and run this command:</p>
<pre><code class="language-powershell">curl http://www.google.com
</code></pre>
<p><strong>What will happen?</strong></p>
<ul>
<li><p>cURL will send a GET request to Google server</p>
</li>
<li><p>Server will send data packets</p>
</li>
<li><p>You`ll recieve google homepage HTML code</p>
</li>
</ul>
<hr />
<h2>Common cURL Mistakes to avoid as a Beginner :</h2>
<h3><strong>Forget to Include the Address</strong></h3>
<p>Don`t write like this :</p>
<pre><code class="language-powershell">curl               # this is not correct, because it don`t have any URL.
</code></pre>
<p>Always include a URL because it is exactly like you are giving an address:</p>
<pre><code class="language-powershell">curl http://google.com        # It is Correct because it have url.
</code></pre>
<h3><strong>Use of HTTP and HTTPS</strong></h3>
<p>i) HTTP is less common now , use it when the website supports non secure connection.</p>
<pre><code class="language-powershell"> curl http://google.com         # Non-secure connection
</code></pre>
<p>ii) Use HTTPS when the website supports a secure connections (mostly in modern websites).</p>
<pre><code class="language-powershell"> curl https://google.com       # Secure connection with encryption
</code></pre>
<h3>Writing Incomplete Command :</h3>
<p>Don`t write incomplete or wrong command,</p>
<pre><code class="language-powershell">curl google.com                 # sometimes, this command can be wrong
</code></pre>
<p>This works on many setups , it`s clearer and safer to write:</p>
<pre><code class="language-powershell">curl http://google.com       # this is correct command
</code></pre>
<hr />
<p>You can find more of my work at <a href="https://abdulrdeveloper.me">abdulrdeveloper.me</a><br />Read more posts at <a href="https://blog.abdulrdeveloper.me">blog.abdulrdeveloper.me</a></p>
]]></content:encoded></item></channel></rss>