<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Asthapthn on Medium]]></title>
        <description><![CDATA[Stories by Asthapthn on Medium]]></description>
        <link>https://medium.com/@asthapthn?source=rss-d13895abe135------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Asthapthn on Medium</title>
            <link>https://medium.com/@asthapthn?source=rss-d13895abe135------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 28 May 2026 00:58:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asthapthn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Diffrent ways to use nodemon]]></title>
            <link>https://medium.com/@asthapthn/diffrent-ways-to-use-nodemon-aa67aa041cbc?source=rss-d13895abe135------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa67aa041cbc</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodemon]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Asthapthn]]></dc:creator>
            <pubDate>Tue, 26 May 2026 09:45:25 GMT</pubDate>
            <atom:updated>2026-05-26T09:45:25.062Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>npm i --save-dev nodemon: Downloads and saves the package into your project&#39;s node_modules folder and lists it in package.json. This is best for long-term project use.</li><li>npx nodemon: A &quot;package runner&quot; that executes the package. If it&#39;s already installed locally, it runs that version; if not, it downloads a temporary version to execute and then discards it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa67aa041cbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Express.json [PART 3]]]></title>
            <link>https://medium.com/@asthapthn/express-json-part-3-7f38c674df3c?source=rss-d13895abe135------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f38c674df3c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Asthapthn]]></dc:creator>
            <pubDate>Tue, 26 May 2026 07:38:13 GMT</pubDate>
            <atom:updated>2026-05-26T07:38:16.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding express.json() Middleware</h3><p>Every modern web application relies on the seamless exchange of data between the frontend and the backend. When a user submits a form, logs in, or saves a profile, the frontend packages that data into a neat JavaScript object, converts it into a string, and shoots it across the network.</p><p>However, when that data hits an Express.js backend, it encounters a surprising roadblock: <strong>Express is completely blind to it by default.</strong></p><p>To bridge this gap, developers rely on a vital built-in tool: express.json().</p><h3>What Is It?</h3><p>express.json() is a built-in piece of middleware in Express that acts as an automated <strong>incoming data translator</strong>. Its sole responsibility is to intercept raw network data streams, recognize if the incoming payload is formatted as JSON, and parse it into a native JavaScript object that your backend can actually read and manipulate.</p><h3>Terminology Check:</h3><ul><li><strong>The Request Body (</strong>req.body<strong>):</strong> The property on the Express request object where incoming data (like usernames, passwords, or form inputs) is stored. By default, before any middleware runs, req.body is completely undefined.</li><li><strong>Streams and Chunks:</strong> Data traveling across the internet does not arrive all at once in a neat package. It is broken down into tiny, raw binary pieces called <strong>buffers</strong> or <strong>chunks</strong> and streamed sequentially over the network.</li><li><strong>Serialization vs. Deserialization:</strong> * <em>Serialization:</em> The frontend turns a live JavaScript object into a JSON string (JSON.stringify()) so it can travel through network pipes.</li><li><em>Deserialization:</em> The backend takes that raw string and turns it back into a live JavaScript object (JSON.parse()). express.json() automates this step.</li></ul><h3>The Architectural Problem: The Raw Stream Wall</h3><p>When a frontend application sends data to your server via a POST, PUT, or PATCH request, it transmits that data inside the HTTP request body.</p><p>If you attempt to log that data immediately inside a standard Express route handler, you will run into a frustrating roadblock:</p><p>JavaScript</p><pre>app.post(&#39;/api/v1/users&#39;, (req, res) =&gt; {<br>  console.log(req.body); // Output: undefined<br>  res.send(`Welcome, ${req.body.name}`); // Crashes! Cannot read properties of undefined<br>});</pre><h3>Why does this happen?</h3><p>Node.js and Express are built to be incredibly fast and lightweight. To handle massive amounts of traffic efficiently, Node.js processes incoming network data as a <strong>raw stream of binary data (Bytes)</strong>.</p><p>Express does not want to waste CPU cycles parsing and assembling those raw bytes unless you explicitly tell it to. Without a translator sitting in front of your routes, the raw text sits in the network buffer, and req.body remains unpopulated.</p><h3>What Does It Do &amp; How Does It Matter?</h3><p>The express.json() middleware acts as a customs inspector standing at the gates of your server. It performs three critical actions behind the scenes for every incoming request:</p><ul><li><strong>Content-Type Inspection:</strong> It looks at the incoming HTTP request headers. Specifically, it searches for Content-Type: application/json. If it doesn&#39;t find it, it ignores the request and passes it along.</li><li><strong>Buffer Assembly:</strong> If the data <em>is</em> JSON, it listens to the network stream, catches all the tiny incoming binary chunks, and stitches them together into one complete text string.</li><li><strong>Safe Parsing:</strong> It executes a controlled JSON.parse() on that string and neatly assigns the resulting JavaScript object to req.body.</li></ul><p>By the time the request reaches your route handler, the data is sitting there, perfectly formatted and ready to be stored in a database.</p><h3>Technical Implementation</h3><p>In modern Express development, implementing this parser requires just one line of code placed at the top of your middleware pipeline:</p><p>JavaScript</p><pre>const express = require(&#39;express&#39;);<br>const app = express();</pre><pre>// 1. Inject the JSON parsing middleware globally<br>app.use(express.json());</pre><pre>// 2. A secure endpoint ready to receive structured data<br>app.post(&#39;/api/v1/products&#39;, (req, res) =&gt; {<br>  // Thanks to express.json(), req.body is fully populated<br>  const { title, price, stock } = req.body;</pre><pre>  if (!title || !price) {<br>    return res.status(400).json({ error: &quot;Missing required product fields.&quot; });<br>  }</pre><pre>  res.status(201).json({<br>    message: &quot;Product created successfully!&quot;,<br>    receivedData: { title, price, stock }<br>  });<br>});</pre><h3>Deep-Dive FAQ</h3><h3>Q1: I see old tutorials using bodyParser.json(). Is that different from express.json()?</h3><p><strong>The Simple Answer:</strong> Mechanically, they are exactly the same thing.</p><p><strong>The History:</strong> Historically, Express was purely a routing framework and did not include built-in data parsing. Developers had to install a separate external package called body-parser.</p><ul><li>In Express v4.x, the framework creators decided to bundle body-parser directly into the core library for convenience.</li><li>Writing app.use(express.json()) is simply a native shortcut for running the body-parser library under the hood. You do <strong>not</strong> need to install body-parser separately in modern backend development.</li></ul><h3>Q2: What happens if a malicious user sends a massive 50GB JSON file to my server? Will express.json() crash it</h3><p><strong>The Simple Answer:</strong> No, because express.json() comes built-in with strict defensive guardrails.</p><p>By default, express.json() imposes a strict <strong>1MB limit</strong> on incoming JSON payloads. If an attacker or an accidental script tries to flood your endpoint with a massive JSON body, the middleware will instantly cut the connection off and throw a 413 Payload Too Large error, protecting your server&#39;s memory from overloading.</p><p>If you are building a specific endpoint that legitimately requires larger JSON payloads (like syncing large batches of data), you can configure the threshold manually:</p><p>JavaScript</p><pre>// Customize the limit for larger payloads safely<br>app.use(express.json({ limit: &#39;5mb&#39; }));</pre><h3>Q3: What happens if the frontend sends malformed JSON (e.g., missing a closing brace or quote)?</h3><p><strong>The Simple Answer:</strong> The middleware tries to parse it, fails, and instantly short-circuits the request by throwing a 400 Bad Request error.</p><p>Because express.json() runs globally <em>before</em> your routes, a JSON syntax error will trigger an unhandled exception that can surface an ugly stack trace to the user. In professional production environments, developers catch this by placing a custom error-handling middleware directly underneath express.json() to cleanly intercept parsing errors:</p><p>JavaScript</p><pre>app.use(express.json());</pre><pre>// Custom error-handling middleware to catch malformed JSON<br>app.use((err, req, res, next) =&gt; {<br>  if (err instanceof SyntaxError &amp;&amp; err.status === 400 &amp;&amp; &#39;body&#39; in err) {<br>    return res.status(400).json({ <br>      error: &quot;Invalid JSON format. Please check your syntax.&quot; <br>    });<br>  }<br>  next();<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f38c674df3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js Backend Startup Flow: Fixing Express App Imports, File Paths, and npm Scripts]]></title>
            <link>https://medium.com/@asthapthn/node-js-backend-startup-flow-fixing-express-app-imports-file-paths-and-npm-scripts-4da06594a734?source=rss-d13895abe135------2</link>
            <guid isPermaLink="false">https://medium.com/p/4da06594a734</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[nodemon]]></category>
            <dc:creator><![CDATA[Asthapthn]]></dc:creator>
            <pubDate>Sun, 24 May 2026 12:44:51 GMT</pubDate>
            <atom:updated>2026-05-24T12:44:51.220Z</atom:updated>
            <content:encoded><![CDATA[<p>In this project, I was working with a basic Node.js backend using Express.js. The goal was to understand how the backend server starts and why the error was happening.</p><p>The project had two important files:</p><p>```text<br>src/app.js<br>src/server.js<br>```</p><p>`app.js` creates the Express application.</p><p>```js<br>const express = require(‘express’);<br>const app = express();</p><p>module.exports = app;<br>```</p><p>Line by line:</p><p>```js<br>const express = require(‘express’);<br>```</p><p>This imports the Express package into the file.</p><p>```js<br>const app = express();<br>```</p><p>This creates an Express application. This `app` object is the main backend application.</p><p>```js<br>module.exports = app;<br>```</p><p>This exports the `app` object so another file can import and use it.</p><p>`server.js` starts the server.</p><p>Correct code:</p><p>```js<br>const app = require(‘./app’);</p><p>app.listen(3000, () =&gt; {<br> console.log(‘Server is running on port 3000’);<br>});<br>```</p><p>Line by line:</p><p>```js<br>const app = require(‘./app’);<br>```</p><p>This imports the `app` object from `app.js`.</p><p>Since `server.js` and `app.js` are in the same `src` folder, the path is:</p><p>```js<br>‘./app’<br>```</p><p>The `./` means “look in the same folder.”</p><p>```js<br>app.listen(3000, () =&gt; {<br>```</p><p>This tells Express to start listening for requests on port `3000`.</p><p>```js<br>console.log(‘Server is running on port 3000’);<br>```</p><p>This message prints only after the server starts successfully.</p><p>The earlier code was wrong because it used this:</p><p>```js<br>import { listen } from ‘./app’;<br>```</p><p>That was incorrect for two reasons.</p><p>First, the project uses CommonJS. This is shown in `package.json`:</p><p>```json<br>“type”: “commonjs”<br>```</p><p>So the code should use:</p><p>```js<br>require()<br>module.exports<br>```</p><p>Second, `app.js` does not export a separate function named `listen`. It exports the full `app` object. The `listen` function belongs to the `app` object, so it must be called like this:</p><p>```js<br>app.listen()<br>```</p><p>Not like this:</p><p>```js<br>listen()<br>```</p><p>The next error was:</p><p>```<br>Error: Cannot find module ‘C:\Users\viren\OneDrive\Desktop\COMPLETE BACKEND\server.js’<br>```</p><p>This happened because this command was run:</p><p>```powershell<br>node server.js<br>```</p><p>But there is no `server.js` file directly inside:</p><p>```<br>COMPLETE BACKEND<br>```</p><p>The actual file is inside the `src` folder:</p><p>```<br>COMPLETE BACKEND\src\server.js<br>```</p><p>So the correct command is:</p><p>```powershell<br>node src/server.js<br>```</p><p>This tells Node exactly where the file is.</p><p>The role of `npm` is to run commands from `package.json`.</p><p>Instead of typing this every time:</p><p>```powershell<br>node src/server.js<br>```</p><p>we can add a script in `package.json`:</p><p>```json<br>“scripts”: {<br> “start”: “node src/server.js”<br>}<br>```</p><p>Now when we run:</p><p>```powershell<br>npm start<br>```</p><p>npm looks inside `package.json`, finds the `”start”` script, and runs:</p><p>```powershell<br>node src/server.js<br>```</p><p>So these two commands do the same thing:</p><p>```powershell<br>node src/server.js<br>```</p><p>```powershell<br>npm start<br>```</p><p>A `dev` script works the same way, but it must be defined first:</p><p>```json<br>“scripts”: {<br> “start”: “node src/server.js”,<br> “dev”: “node src/server.js”<br>}<br>```</p><p>Then it can be run using:</p><p>```powershell<br>npm run dev<br>```</p><p>In real backend projects, `dev` usually uses `nodemon`:</p><p>```json<br>“scripts”: {<br> “dev”: “nodemon src/server.js”<br>}<br>```</p><p>`nodemon` restarts the server automatically whenever code changes.</p><p>The `test` script also works the same way:</p><p>```json<br>“scripts”: {<br> “test”: “echo \”Error: no test specified\” &amp;&amp; exit 1&quot;<br>}<br>```</p><p>When this command is run:</p><p>```powershell<br>npm test<br>```</p><p>npm runs the command inside the `”test”` script.</p><p>In this case, it only shows an error message because no real tests have been added yet.</p><p>Final clear flow:</p><p>1. package.json says the project uses CommonJS.<br>2. app.js imports Express.<br>3. app.js creates the Express app.<br>4. app.js exports the app.<br>5. server.js imports the app from app.js.<br>6. server.js calls app.listen(3000).<br>7. The backend starts on port 3000.<br>8. The correct command to run it is node src/server.js.<br>9. npm start can be used as a shortcut if package.json has a start script.</p><p>Final conclusion:</p><p>The problem was not caused by Express. The server failed because Node was looking for `server.js` in the wrong folder, and earlier the import style was also incorrect. After using `require(‘./app’)`, `app.listen(3000)`, and the correct command `node src/server.js`, the backend server started correctly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4da06594a734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Package.json(the result of the command npm init)]]></title>
            <link>https://medium.com/@asthapthn/understanding-package-json-the-result-of-the-command-npm-init-90a15e0fcc15?source=rss-d13895abe135------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a15e0fcc15</guid>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Asthapthn]]></dc:creator>
            <pubDate>Sun, 24 May 2026 12:16:43 GMT</pubDate>
            <atom:updated>2026-05-24T12:16:43.309Z</atom:updated>
            <content:encoded><![CDATA[<h4>npm init is a terminal command used to create a brand new package.json file from scratch. It acts as a setup wizard for your project.</h4><h4>What is npm init?</h4><p>npm init is a terminal command used to create a brand new <strong>package.json</strong> file from scratch. It acts as a setup wizard for your project.</p><h4>Why do we use it?</h4><p>When you start a new coding project, you have an empty folder. Instead of manually creating a package.json file and typing out all the curly braces { }, quotes, and fields by hand, you type npm init.</p><p>The computer will then ask you a series of quick questions in the terminal:</p><ol><li><em>What is your project’s name?</em></li><li><em>What version is it?</em></li><li><em>What is the main file?</em></li></ol><p>Once you answer, it automatically generates the file for you.</p><h4>Why does it matter? (The Real Tech Reason)</h4><p>Without running npm init to create that package.json file, <strong>your project is blind</strong>.</p><ul><li><strong>You cannot install tools:</strong> If you try to run npm install express, it will fail or create a mess because there is no grocery list (package.json) to record it in .</li><li><strong>Other developers can’t run your code:</strong> If you share your project folder on GitHub without a package.json, another developer will have no idea what tools (dependencies) your app needs to run.</li></ul><h4>The Shortcut</h4><p>If you do not want to answer the wizard’s questions and just want the file instantly, you can type:</p><p>npm init -y</p><p>The -y stands for <strong>&quot;yes&quot;</strong>. It skips all questions, automatically says &quot;yes&quot; to the default settings, and creates your package.json file in exactly one second.</p><h3>Understanding package.json</h3><p>Think of your project as a <strong>packaged electronic toy</strong> you bought from a store. This file is the instruction manual and the sticker on the back of the box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBKN7hwazc2pAFuPEUV40Q.png" /></figure><h3>1. name (&quot;complete-backend&quot;)</h3><ul><li><strong>Simple words:</strong> The official name printed on the front of the box.</li><li><strong>Real-world example:</strong> “lego-star-wars”. It must be completely unique so people can find it on the internet store (npm).</li></ul><h3>2. version (&quot;1.0.0&quot;)</h3><ul><li><strong>Simple words:</strong> The edition number of your toy.</li><li><strong>Real-world example:</strong> If you buy a board game, &quot;1.0.0&quot; is the first edition. &quot;2.0.0&quot; means they completely redesigned the game.</li></ul><h3>3. description (&quot;&quot;)</h3><ul><li><strong>Simple words:</strong> The short summary paragraph on the back of the box.</li><li><strong>Real-world example:</strong> &quot;A fast-paced card game for 4 players.&quot; It tells shoppers instantly what the project actually does.</li></ul><h3>4. main (&quot;index.js&quot;)</h3><ul><li><strong>Simple words:</strong> The main power button or the front door.</li><li><strong>Real-world example:</strong> The exact button you press to turn the toy on. In your project, index.js is the very first file the computer opens to start your app.</li></ul><h3>5. scripts (&quot;test&quot;: &quot;...&quot;)</h3><ul><li><strong>Simple words:</strong> Remote control shortcut buttons.</li><li><strong>Real-world example:</strong> Instead of telling a robot, <em>“Move left leg, move right leg, wave arm,”</em> you just press a button labeled &quot;Dance&quot;. In your app, running npm run test automatically fires off long, complex terminal commands for you.</li></ul><h3>6. keywords ([])</h3><ul><li><strong>Simple words:</strong> Search tags for an online store.</li><li><strong>Real-world example:</strong> Hashtags like #space, #blocks, or #robot on Amazon. They help other developers find your project if you upload it to the internet.</li></ul><h3>7. author (&quot;&quot;)</h3><ul><li><strong>Simple words:</strong> The inventor or creator.</li><li><strong>Real-world example:</strong> The “Written By” name on a book cover. It tells the world who wrote this specific code.</li></ul><h3>8. license (&quot;ISC&quot;)</h3><ul><li><strong>Simple words:</strong> The legal rulebook for sharing.</li><li><strong>Real-world example:</strong> A sign on a public park bench that says, <em>“Free for anyone to sit here.”</em> Licenses like ISC or MIT tell other developers, <em>&quot;You can copy and use my code for free, just don&#39;t sue me if it breaks.&quot;</em></li></ul><h3>9. type (&quot;commonjs&quot;)</h3><ul><li><strong>Simple words:</strong> The specific language dialect your project speaks.</li><li><strong>Real-world example:</strong> Choosing whether your office speaks British English (require()) or American English (import). Your computer needs to know this so it can read your files correctly.</li></ul><h3>10. dependencies (&quot;express&quot;: &quot;^5.2.1&quot;)</h3><ul><li><strong>Simple words:</strong> An expansion pack or a grocery list of tools you borrowed from other people.</li><li><strong>Real-world example:</strong> If you open a restaurant, you don’t build the ovens and fridges from scratch; you buy them from a factory. Here, you are borrowing express to act as your pre-built engine to handle web requests.</li></ul><p>⚠️ Quick Rule: The Caret Symbol (^)</p><ul><li><strong>^5.2.1</strong> means: <em>&quot;If the creators of Express release bug fixes (like </em><em>5.2.2) or small updates (like </em><em>5.3.0), download them automatically. But </em><strong><em>never</em></strong><em> download </em><em>6.0.0 because a major update might break my app!&quot;</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a15e0fcc15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every modern web application faces a major architectural hurdle when attempting to connect its…]]></title>
            <link>https://medium.com/@asthapthn/every-modern-web-application-faces-a-major-architectural-hurdle-when-attempting-to-connect-its-5eef924af772?source=rss-d13895abe135------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eef924af772</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Asthapthn]]></dc:creator>
            <pubDate>Sat, 23 May 2026 05:47:34 GMT</pubDate>
            <atom:updated>2026-05-23T05:47:34.479Z</atom:updated>
            <content:encoded><![CDATA[<p>Every modern web application faces a major architectural hurdle when attempting to connect its frontend codebase to its backend server. That hurdle is a mandatory browser security wall known as CORS.</p><h4>What Is It?</h4><p>CORS stands for Cross-Origin Resource Sharing. It is a strict network access control mechanism enforced directly by web browsers (such as Google Chrome, Safari, or Firefox), not by your backend server.</p><blockquote><em>#Terminology Check:<br>An Origin: The distinct identity of a web URL, strictly defined by three components: the Protocol (</em><em>http vs </em><em>https), the Domain (</em><em>mywebsite.com), and the Port (</em><em>3000 vs </em><em>5173). If even </em>one<em> of these elements changes, the browser flags it as a completely separate origin.</em></blockquote><h4>The Architecture Problem: The Same-Origin Policy</h4><p>By default, web browsers protect internet users using a foundational security model called the Same-Origin Policy. This rule dictates that an application running on <em>Origin A</em> is forbidden from reading private data loaded from a server on <em>Origin B</em>.</p><p>This prevents malicious websites from running silent background scripts to steal data from your active banking sessions or private social media accounts.</p><p>However, this creates a major roadblock for modern developers. In production-level software development, the client and the API are decoupled and hosted on separate ports or domains:</p><ul><li>The Frontend Client (e.g., React): Hosted at <a href="http://localhost:5173">http://localhost:5173</a></li><li>The Backend Server (Express API): Hosted at <a href="http://localhost:3000">http://localhost:3000</a></li></ul><p>Because the ports do not match, the browser triggers a cross-origin violation. The moment your frontend attempts a network request, the browser blocks the data transfer and surfaces the infamous red console error: CORS policy: No &#39;Access-Control-Allow-Origin&#39; header is present.</p><h4>What Does It Do &amp; How Does It Matter?</h4><p>The cors() middleware acts as an official permission slip issuer for your backend. When an external cross-origin request hits your Express server, cors() intercepts the outbound response and appends custom HTTP headers containing access metadata.</p><p>1. Public Data Sharing (Open APIs)</p><ul><li>The Scenario: You are building a public utility API (e.g., weather or sports statistics) and want any frontend app on the internet to consume your endpoints.</li><li>The Action: Initializing basic middleware app.use(cors()) instructs Express to attach a wildcard header: Access-Control-Allow-Origin: *. The browser reads the * symbol, recognizes it as global clearance, and permits any website to load the data payload.</li></ul><p>2. Private App Locking (Production Whitelisting)</p><ul><li>The Scenario: You are building a proprietary corporate platform. You want your specific React frontend to communicate with the API, but you want to completely block a competitor’s frontend from tapping your server.</li><li>The Action: You configure cors() with an explicit whitelist. The middleware monitors incoming request headers; if the requesting origin matches your production domain, it appends a targeted permission stamp: Access-Control-Allow-Origin: http://localhost:5173. If a rogue domain makes the same call, the browser detects the missing header and shields the client from reading your API response.</li></ul><h4>Technical Implementation</h4><p>In professional backend development, you enforce strict origin filtering using the standard cors npm package:</p><p>javascript</p><pre>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const app = express();</pre><pre>// 1. Define a strict production whitelist<br>const corsOptions = {<br>  origin: &#39;http://localhost:5173&#39;,            // Permit ONLY this trusted client domain<br>  methods: [&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;DELETE&#39;],   // Explicitly limit permitted HTTP verbs<br>  optionsSuccessStatus: 200                    // Patches legacy browser parsing bugs<br>};</pre><pre>// 2. Inject configuration into the middleware pipeline<br>app.use(cors(corsOptions));</pre><pre>app.get(&#39;/api/v1/secure-dashboard&#39;, (req, res) =&gt; {<br>  res.json({ data: &quot;Highly sensitive production records.&quot; });<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*pRXpY-1K1AUiIPQ4nHKp1A.png" /></figure><p>Q1: If CORS blocks a request, does that mean my Node.js server crashed or never received the request?</p><p>The Simple Answer: No! Your Node.js server is completely healthy, and it actually executed your code perfectly.</p><p>What happens mechanically:</p><ol><li>Your frontend sends a request to the backend.</li><li>Your Express backend receives it, queries the database, and sends the data back.</li><li>The data arrives at the browser.</li><li>The browser opens the packet, sees that your backend forgot to include the Access-Control-Allow-Origin header, and deliberately hides the data from your frontend JavaScript code.</li></ol><p>CORS is a browser-side data shield, not a backend execution blocker.</p><p>Q2: If the backend executes the code anyway, how does CORS protect anyone from a malicious hacker?</p><p>The Simple Answer: It depends entirely on whether the hacker is trying to steal data (Read) or change data (Write/Delete). CORS only protects against data stealing.</p><ul><li>How it protects against Stealing Data: If a malicious site secretly triggers a request to read your private profile, your server pulls that data and responds. However, the browser destroys the incoming packet before the malicious script can read it. The hacker learns absolutely nothing.</li><li>Where it fails against Changing Data: If a malicious site triggers a request to delete your account, your server executes the deletion immediately upon receiving the request. The browser will still block the hacker from reading the success message, but the damage is already done.</li></ul><p>Q3: How do developers fix the loophole where a malicious site can trigger data changes despite CORS?</p><p>The Simple Answer: Developers use two professional mechanisms alongside CORS to ensure malicious code cannot trigger state-changing actions: Preflight Requests and Strict Cookies.</p><p>Mechanism 1: Preflight Requests (OPTIONS)</p><p>For dangerous actions like POST, PUT, or DELETE, the browser automatically shoots a lightweight &quot;test request&quot; called a Preflight Request before the actual request. It asks the backend: <em>&quot;Are you going to allow this external domain to delete data?&quot;</em> If your backend&#39;s CORS options say no, the browser cancels the transaction entirely, and the actual code never runs.</p><p>Mechanism 2: SameSite Cookie Enforcement</p><p>When your backend generates a login session cookie, professionals lock it down using the SameSite attribute. This instructs the browser to completely strip the login cookie away if a request originates from an external site.</p><p>Here is the code to implement both secure CORS filtering and secure cookie handling:</p><p>javascript:</p><pre>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const app = express();</pre><pre>// 1. Strict CORS Options (Handles Preflights automatically)<br>const corsOptions = {<br>  origin: &#39;http://localhost:5173&#39;, // Only allow your specific frontend domain<br>  methods: [&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;DELETE&#39;], // Whitelist allowed operations<br>  optionsSuccessStatus: 200 // Handles legacy browser compatibility<br>};<br>app.use(cors(corsOptions));</pre><pre>// 2. Secure SameSite Session Token Configuration</pre><pre>app.get(&#39;/api/v1/auth/login&#39;, (req, res) =&gt; {<br>  // We issue a cookie that the browser will refuse to send if an attack is launched from an external site<br>  res.cookie(&#39;session_token&#39;, &#39;secure_xyz_token&#39;, {<br>    httpOnly: true, // Stops malicious frontend scripts from stealing the cookie<br>    secure: true,   // Forces the cookie to only travel over encrypted HTTPS<br>    sameSite: &#39;lax&#39; // Blocks cross-origin malicious state-changing attacks<br>  });<br>  <br>  res.json({ message: &quot;Login successful!&quot; });<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eef924af772" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What app.js file in the Backend folder src contains,its components and how do they matter? [Part 1]]]></title>
            <link>https://medium.com/@asthapthn/what-app-js-file-in-the-backend-folder-src-contains-its-components-and-how-do-they-matter-part-1-2477b75c7687?source=rss-d13895abe135------2</link>
            <guid isPermaLink="false">https://medium.com/p/2477b75c7687</guid>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[require]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Asthapthn]]></dc:creator>
            <pubDate>Fri, 22 May 2026 10:36:30 GMT</pubDate>
            <atom:updated>2026-05-22T10:39:44.363Z</atom:updated>
            <content:encoded><![CDATA[<p>The app.js file serves as the configuration center for your server. Instead of just starting the server(the application we consider as backend:BUT is not the frontend and backend together make the application →In production level,both are considered a separate applications).</p><p>App.js’ purpose is to define how the application behaves.</p><blockquote>// 1. IMPORT DEPENDENCIES<br>const express = require(‘express’);<br>const cors = require(‘cors’);<br>const cookieParser = require(‘cookie-parser’);</blockquote><blockquote>// 2. INITIALIZE INSTANCE<br>const app = express();</blockquote><blockquote>// 3. MIDDLEWARE CONFIGURATION (The Parsing Pipeline)<br>app.use(cors()); // Allows external frontends to talk to this API<br>app.use(express.json()); // Converts raw incoming text streams into req.body objects<br>app.use(cookieParser()); // Parses the incoming cookie headers into req.cookies</blockquote><blockquote>// 4. API ROUTES REGISTRATION (The Routing Table)<br>// We map a specific URL prefix to a dedicated routing sub-file<br>const authRoutes = require(‘./routes/authRoutes’);<br>const notesRoutes = require(‘./routes/notesRoutes’);</blockquote><blockquote>app.use(‘/api/v1/auth’, authRoutes); // Directs all /api/v1/auth/* requests<br>app.use(‘/api/v1/notes’, notesRoutes); // Directs all /api/v1/notes/* requests</blockquote><blockquote>// 5. EXPORT THE INSTANCE<br>module.exports = app;</blockquote><p>All this code above could sound confusing, here i am listing them down with what they do and how do they matter (focusing on the middleware configurations).These are the core components in app.js(The CORE LAYER) and we have more components that are used when we scale in the ADVANCED LAYER.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LfMosSv9RAISZGQI" /></figure><p>Mental map structure → What happens, what is it, what it does, how does it matter ?</p><p>The definition of confusing words are starting with ‘#’.</p><p>Lets start with the component RATE LIMITER in app.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*JhecID28viuGS4h4chy5GQ.png" /></figure><p>A Rate Limiter is a traffic control middleware for your backend server. It limits the number of requests a specific user (identified by their IP address) can make to your API within a defined window of time.</p><p>#Defined window time-&gt;a specific, fixed block of time that the server uses to track and count a user’s requests. It is the “reset clock” for the rate limiter.Here is an example in theh figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxrPdbp3xATNYRmG1wsfPQ.png" /></figure><p>A rate limiter acts as a digital bouncer at the very entrance of your app.js pipeline.</p><p>1. Preventing Brute-Force Attacks (Login Protection)</p><h4>The Scenario: A hacker writes a script that tries 10,000 different passwords on your <em>/api/v1/auth/login</em> route in 2 minutes to crack a user&#39;s account.</h4><ul><li>When Used: You apply a strict rate limiter to authentication routes.</li><li>The Action: The limiter detects the massive spike from the hacker’s IP address. After the 5th failed attempt, it blocks that IP address entirely for the next 15 minutes.</li></ul><p>2. Stopping DDoS and Server Overload</p><h4>The Scenario: A malicious botnet target your API, flooding it with millions of requests simultaneously to crash your server.</h4><ul><li>When Used: You apply a global rate limiter at the very top of your application pipeline.</li><li>The Action: The server handles a safe maximum per user (e.g., 100 requests per minute). Excess automated traffic is discarded instantly before it can consume memory or overwhelm your database.</li></ul><p>3. Preventing API Scraping &amp; Abuse</p><h4>The Scenario: A competitor writes a web-scraper script to hit your /api/v1/products route repeatedly to copy your entire catalog and prices.</h4><ul><li>When Used: Applied to data-heavy endpoints.</li><li>The Action: It slows down or cuts off the scraper, forcing them to wait and making it impossible to crawl your site rapidly.</li></ul><blockquote>const rateLimit = require(‘express-rate-limit’);</blockquote><blockquote>// Configure the rate limiter rules<br>const limiter = rateLimit({<br> windowMs: 15 * 60 * 1000, // 15 minutes window<br> max: 100, // Limit each IP to 100 requests per window<br> message: {<br> status: 429,<br> message: “Too many requests from this IP, please try again later.”<br> }<br>});</blockquote><blockquote>// Apply the limiter globally at the top of app.js<br>app.use(limiter);</blockquote><p><em>“If a hacker gets blocked, but the rate limiter’s window is only 2 minutes long, won’t the hacker just be able to start attacking my server again after those 2 minutes are up?”</em></p><p>Yes, if we only use a basic setup. If we configure a simple 2-minute timer, the block will vanish after 2 minutes, and the hacker can try again.</p><p>To stop this from happening, professional developers use two different strategies to enforce longer punishments:</p><p>Strategy 1: The Long Timeout Window</p><p>For sensitive parts of our app — like the login screen — developers don’t use a 2-minute window. They deliberately set a much larger window, like 15 minutes or 1 hour.</p><ul><li>How it works: If you only allow 5 attempts per 15 minutes, a hacker who spams 5 fast guesses in the first 10 seconds is completely trapped. The server will refuse to talk to them for the remaining 14 minutes and 50 seconds.</li></ul><p>Strategy 2: The Temporary Penalty Box (Advanced)</p><p>For maximum security, developers link the rate limiter to a fast database or memory storage (like Redis).</p><ul><li>How it works:</li></ul><ol><li>The rate limiter watches the traffic on a 2-minute cycle.</li><li>The moment a hacker breaks the rule, a script fires that flags their IP address as “Banned for 24 hours” inside the database.</li><li>Even when the rate limiter’s 2-minute clock resets back to zero, a security check reads that database flag, sees the 24-hour ban, and continues to throw them out.</li></ol><p>Helmet Security in PART 2…..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2477b75c7687" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do the things in Backend set up matter?(Node JS,Express)]]></title>
            <link>https://medium.com/@asthapthn/how-do-the-things-in-backend-set-up-matter-node-js-express-713600e3397a?source=rss-d13895abe135------2</link>
            <guid isPermaLink="false">https://medium.com/p/713600e3397a</guid>
            <category><![CDATA[setup]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[Asthapthn]]></dc:creator>
            <pubDate>Wed, 20 May 2026 10:44:02 GMT</pubDate>
            <atom:updated>2026-05-20T10:44:02.660Z</atom:updated>
            <content:encoded><![CDATA[<p>When I was learning to set up my Node.js server (I was using Javascript for backend as a language),i was required to install certain things to do it.</p><p>If you are a beginner finding yourself asking questions like what is this,why is it here,how does it matter,what it contains,how does it help?then this article is the blog which got your back.</p><p>1)The Core Foundation (Node vs. npm)</p><p>Before we write a single line of backend code, we have to download our core foundation. Let’s clear up a massive confusion right away: Node.js and npm are not the same thing.</p><ul><li>Node.js: This is the environment that lets your computer execute JavaScript code outside of a web browser (on your actual machine).</li><li>npm (Node Package Manager): This is the automated assistant that gets installed <em>with</em> Node.js. It handles downloading and managing external code libraries(also known as Packages which are written by developers to reduce the pressure for writing same code again and again for the other developers,discussed below…).</li></ul><p>How to check if it is installed</p><p>Open your terminal (macOS) or Command Prompt/PowerShell (Windows) and type:</p><p>node -v</p><p>If you see a version number (like v20.11.0), you did your installation task well!</p><p>2)What Exactly are “Packages” and how do they travel?</p><p>Think of a Package as a pre-built Lego block. Instead of writing 500 lines of code to handle security encryption or file uploads from scratch, you download a package that someone else already built and tested.</p><p>The Journey of a Package</p><ol><li>The Cloud Reservoir: Millions of open-source packages live on the internet inside the central npm registry.(Lives here -<a href="https://www.npmjs.com/">https://www.npmjs.com/</a>)</li><li>The Order: When you run an install command, npm acts as a delivery drone. It flies up to the cloud registry, finds the exact package you asked for, and downloads it.</li><li>The Destination: It delivers the package files straight into your local project folder on your computer.(The installed packages are stored in the node modules we will discuss it further).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09zqbJwrCZ5sycUIgrmKOA.png" /></figure><p>3)Starting the Project with npm init</p><p>To tell npm, <em>“Hey, look at this folder, it is now an official coding project,”</em> you run this command in your terminal:</p><p>npm init</p><p><em>(Pro-tip: Run </em><em>npm init -y to skip all the setup questions and use the default settings instantly!)</em></p><p>This command immediately spawns the most important file in your project: package.json</p><p>4) Cracking Open the Mystery Files</p><p>Once you start installing things (like Express), you will suddenly see three new items in your directory. Here is the ultimate breakdown of what they are and why they matter:</p><p>1. package.json (The Manifest)</p><ul><li>What it is: The official identity card/blueprint of your project.</li><li>What it contains: Your project name, version, custom script shortcuts, and a clean list of the packages your project needs.</li><li>How it helps: It stays tiny and lightweight. If you share your code with a friend, they only need this file. They can run npm install, and npm will read this blueprint to fetch everything automatically.</li></ul><p>2. package-lock.json (The Locksmith)</p><ul><li>What it is: The hyper-strict version history book.</li><li>What it contains: The exact, microscopic version numbers of your packages and all the hidden sub-packages they rely on.</li><li>How it helps: It guarantees absolute consistency. It makes sure that your app behaves exactly the same way on your laptop, your teammate’s MacBook, and the live production server without unexpected breakdown bugs caused by random package updates.</li></ul><p>3. node_modules/ (The Heavy Toolbox)</p><ul><li>What it is: The physical folder where the downloaded package code actually lives.</li><li>What it contains: Folders upon folders of raw JavaScript code downloaded from the npm cloud registry.</li><li>How it helps: Your local code reads directly from this folder when you use commands like require(&#39;express&#39;).</li><li>CRITICAL WARNING: This folder gets absolutely massive (often hundreds of megabytes). Never upload this folder to GitHub! You must create a file named .gitignore and type node_modules inside it to tell your computer to leave it behind when saving your work online.</li></ul><p>5) Dependencies vs. DevDependencies</p><p>When installing packages, you will notice they get sorted into two different categories inside your package.json:</p><ul><li>Dependencies: The vital organs. These are packages your app absolutely requires to run live on the internet (e.g., express for your server or mongoose for your database).</li><li><em>How to install:</em> npm install express</li><li>DevDependencies: The temporary construction tools. These are packages you only need while you are sitting at your desk writing code (e.g., nodemon to restart your server automatically when you save, or code formatters). They are stripped out when the app goes live to the public.</li><li><em>How to install:</em> npm install nodemon --save-dev (or -D for short)</li></ul><p>Now coming to the main topic ,what to do after all this is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*xFZnxwiv5PXjuW8tKy05Tg.png" /></figure><p>This is the code written in the server file to create the server and start it that is done using express.</p><h3>What is the exact distinction between require(&#39;express&#39;), const app = express();, and app.listen() when setting up a server?</h3><p>Writing Your First Server Code: The 3-Step Lifecycle</p><p>Once you install Express, you will create your main server file (like index.js).</p><p>Beginners always ask: What is the exact difference between these three lines of code?</p><p>javascript:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>app.listen(3000);</pre><p>Think of this as a simple 3-step timeline: Import, Build, and Run.</p><p>Step 1: require(&#39;express&#39;) — Import the Tools</p><ul><li>What it does: Loads the Express code from your heavy node_modules folder into your computer&#39;s memory.</li><li>The Metaphor: Opening your toolbox. You haven’t built anything yet; you just laid out the tools.</li></ul><p>Step 2: const app = express(); — Build the Engine</p><ul><li>What it does: Runs the Express function to create your actual server object (stored in the variable app). This object holds all your future website routes and settings.</li><li>The Metaphor: Building a car engine. The engine is fully constructed, but it is sitting silently in the garage with the power turned off.</li></ul><p>Step 3: app.listen(port, callback); — Turn on the Machine</p><ul><li>What it does: Binds your server to a specific internet port (like 3000) and wakes it up. It is now actively waiting for people to visit your website.</li><li>The Metaphor: Turning the key in the ignition. The engine roars to life, and the car is out on the live street!</li></ul><p>The Ultimate Teamwork Breakdown</p><ul><li>Without Node.js: Your computer couldn’t read your backend JavaScript code at all. It would just see a plain text file.</li><li>Without npm: You would spend weeks writing thousands of lines of manual code for security, routing, and databases instead of using pre-made packages.</li><li>Without package.json: Your project would lose its identity blueprint, making it impossible to share with other developers or deploy online.</li><li>Without Express (app): You wouldn&#39;t have an organized engine to route incoming visitors to the right pages or database entries.</li><li>Without app.listen(): Your server engine would stay locked in the garage forever, completely deaf to the internet traffic trying to reach it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=713600e3397a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>