<?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 Mahabubur Rahman on Medium]]></title>
        <description><![CDATA[Stories by Mahabubur Rahman on Medium]]></description>
        <link>https://medium.com/@mahabub-r?source=rss-c6c2715785a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sAWkHq3vhm-FlRpg7oJTEw.png</url>
            <title>Stories by Mahabubur Rahman on Medium</title>
            <link>https://medium.com/@mahabub-r?source=rss-c6c2715785a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:25:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahabub-r/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[How to Scale a Web Application]]></title>
            <link>https://mahabub-r.medium.com/how-to-scale-a-web-application-8ceaeb07ca96?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ceaeb07ca96</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[scale]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 22:08:11 GMT</pubDate>
            <atom:updated>2026-04-14T22:08:11.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPcwd7REJ19EVZXEuPdY7g.png" /></figure><h3>Web application working fine from the beginning</h3><p>A few users sign up. Pages load quickly. The database responds instantly. Deployments feel easy. Then traffic comes, features are added, and all of a sudden the app that was “fast enough” is beginning to crawl under realistic load.</p><p>Scaling a web app is not merely about handling more users. It is about creating a system that can remain fast, stable, and easy to maintain as demand grows.</p><p>This article will teach you how to scale a web app — the real, practical approach — through the first bottlenecks to the architecture patterns that allow real, serious scale.</p><h3>What scaling actually means</h3><p>Scaling refers to making your application able to handle more traffic, more data, and more work without breaking.</p><h4>That usually includes:</h4><ul><li>serving more concurrent users</li><li>processing more requests per second</li><li>retrieving bigger volume of data over it</li><li>maintaining performance during traffic spikes</li><li>maximizing minimal downtime and losses</li></ul><p>Just because it’s “big” doesn’t mean it’s a scalable app. And it is made to scale seamlessly without a full rewrite every few months.</p><h3>Start by understanding your bottlenecks</h3><p>Stop changing architecture — find out what is actually your system bottleneck</p><h4>One of these is usually a bottleneck for most web applications:</h4><ul><li>the application server</li><li>the database</li><li>external APIs</li><li>file storage</li><li>slow frontend assets</li><li>inefficient code</li><li>network latency</li></ul><p>Moving everything at once is a classic error. That wastes time and money. Instead, measure, and then work on the most painful things.</p><h4>Useful signals to monitor include:</h4><ul><li>response time</li><li>CPU and memory usage</li><li>database query performance</li><li>request throughput</li><li>error rate</li><li>cache hit ratio</li></ul><p>You can not scale if you do not have the visibility of what is going on right?</p><h3>Vertical scaling: the first step</h3><p>Vertical scaling is the simplest method of scaling.</p><p>It entails simply provisioning your server with more resources: more CPU, more RAM, faster storage.</p><p>For instance, switching from a larger instance to a smaller one can buy you sometime and lessen the current pressure.</p><h4>Pros</h4><ul><li>simple to implement</li><li>no major code changes</li><li>fast short-term fix</li></ul><h4>Cons</h4><ul><li>has limits</li><li>can become expensive</li><li>establish one point of failure</li></ul><p>So vertical scaling is great at early stages but rarely sufficient for long-term.</p><h3>Horizontal scaling: adding more servers</h3><p>Scaling horizontally — spin up more instances of the app and distribute traffic between them.</p><p>Instead of running one large, expensive server, you run many servers behind a load balancer.</p><p>This makes for a far better growth model as capacity can be added slowly as traffic grows.</p><p>If your app is stateless out goes horizontal scaling.</p><h4>That means:</h4><ul><li>never ever save session data in memory</li><li>do not rely on local files</li><li>stay data in remote stores such as redis, object store or database</li></ul><p>If servers are stateless, then any request may be served by any instance. It simplifies the use of load balancing.</p><h3>Use a load balancer</h3><p>Load balancer — A load balancer routes incoming read requests among multiple machines.</p><h4>This improves:</h4><ul><li>availability</li><li>fault tolerance</li><li>traffic distribution</li><li>deployment flexibility</li></ul><p>If one server dies, the load balancer can redirect traffic to healthy instances。</p><p>Not only does a load balancer help in rolling deployments, blue-green releases and auto-scaling policies.</p><p>In simple terms it acts as a traffic controller for your system.</p><h3>Optimize your database early</h3><p>The first really serious bottleneck becomes the database for many applications.</p><p>Even a well-optimized application will start to slow down as traffic increases if the queries hitting the database are inefficient.</p><p>These are the best ways to scale a database driven app.</p><h4>Add indexes carefully</h4><p>Indexes Make Reads Faster They are particularly useful for columns that are frequently used in filtering or join operations.</p><p>However, too many indexes can degrade write performance. Only, add them based on real query patterns and not guessing.</p><h4>Avoid N+1 queries</h4><p>If your application makes dozens or hundreds of tiny queries per request it simply will not perform under load.</p><p>Come Up with Fancier Queries Preload Related Data Minimize Unnecessary Round Trips</p><h4>Use read replicas</h4><p>Read replicas can help offload query traffic from the primary database if your application has a lot more reads than writes.</p><h4>Archive or partition old data</h4><p>The higher the number of records in your large tables, the slower they get. Partitioning / archiving old records maintains hot data fast</p><h4>Consider sharding only when necessary</h4><p>Sharding divides your data into different databases. Now that can dramatically increase scale, however, it does increase complexity.</p><p>It is strong, but it should be your last resort.</p><h3>The biggest win is caching</h3><p>Caching reduces repeated work.</p><p>Your system uses previously computed results rather than generating the same response or querying the same data again and again.</p><ul><li>Popular things to cache include:</li><li>database query results</li><li>rendered pages</li><li>API responses</li><li>session data</li><li>static assets</li></ul><p>This is usually done with a tool like Redis.</p><p>There are multiple tiers of caching happening:</p><h4>Application cache</h4><p>The backend you are using keeps the most hot results in memory or a cache service.</p><h4>Database cache</h4><p>Your database will cache most commonly accessed pages but you cannot rely on that alone.</p><h4>CDN cache</h4><p>It can store image, JavaScript, CSS and even full responses all over the world, closer to users.</p><p>Caching Sometimes provides the greatest performance gain for the least amount of architectural pain.</p><h3>Relocate extensive work to Background jobs</h3><p>Some things do not have to happen in the request response cycle.</p><p>Your app doesn’t always need to immediately resize a photo right before returning a response when a user uploads one. You should not have to send emails to your customers, generate invoices, and let analytics tools know, before presenting the order confirmation page if someone has placed an order.</p><p>Shift those jobs into background processes.</p><h4>Examples include:</h4><ul><li>sending emails</li><li>image processing</li><li>report generation</li><li>video encoding</li><li>syncing with external systems</li><li>notifications</li></ul><p>Use a queue and worker system so that your web servers can continue to respond quickly to front-end requests.</p><p>This helps overcome responsiveness thereby making the platform more resilient under load.</p><h3>Scale the frontend too</h3><p>Scalability is a term mostly associated with the server side aspect of the application, but the UI of the application is equally important.</p><p>Even a strong backend can feel weak with a slow frontend.</p><p>To improve frontend scalability:</p><ul><li>compress images</li><li>minify CSS and JavaScript</li><li>lazy load non-critical content</li><li>reduce bundle size</li><li>use a CDN for static assets</li><li>optimize rendering on mobile devices</li><li>avoid unnecessary API calls</li></ul><p>Performance is not just speed of servers. This helps in finding the speed at which users will get engaged with the page.</p><h3>Design for failure</h3><p>A truly scalable application is built around the assumption of failures.</p><p>Servers crash. APIs time out. databases lock. Networks split. The traffic spikes hit at the most inconvenient time.</p><p>That is also the reason behind scalability and reliability going hand in hand.</p><h4>Build with:</h4><ul><li>retries for transient failures</li><li>timeouts for external services</li><li>circuit breakers for unstable dependencies</li><li>health checks for instances</li><li>autoscaling policies</li><li>graceful degradation when features fail</li><li>backups and disaster recovery plans</li></ul><p>A three-sigma system is not scalable if it requires everything to be perfect. It is fragile.</p><h3>Use observability, not guesswork</h3><p>Debugging becomes increasingly difficult as systems scale.</p><p>You want to have insight into what is occurring across your stack.</p><p>Three things matter most:</p><h4>Metrics</h4><p>Keep record of the usage, errors, latency, saturation, and resource usage.</p><h4>Logs</h4><p>Adopt the use of structured logs so you can easily trace problems in no time.</p><h4>Tracing</h4><p>With distributed tracing, you get observability into the request path and hidden bottlenecks in the time taken by different services.</p><p>By making scaling an engineering discipline instead of a guessing game — a byproduct of observability.</p><h3>Monolith or microservices?</h3><p>This question is one that crops up with nearly every scaling conversation.</p><p>The truth: for most applications, you should begin with a good monolith.</p><p>It is easier to build, test, deploy and reason about a monolith. An agile project delivery is usually the quickest way of providing value to the company.</p><h4>Microservices make sense when:</h4><ul><li>teams need to deploy independently</li><li>the scaling requirements for different parts of the system are completely different</li><li>The codebase is too big not to have a way to manage.</li><li>strong service boundaries already exist</li></ul><p>Microservices are not something you need to adopt just because they seem to be the new trend. They introduce overhead in terms of network complexity, operational and debugging Kow.</p><p>If your business and your team need it, then scale your architecture.</p><h3>Security must scale too</h3><p>With more traffic comes risk.</p><p>When scaling a web app, you scale your security practices as well.</p><h4>Important areas include:</h4><ul><li>rate limiting</li><li>DDoS protection</li><li>input validation</li><li>secret management</li><li>access control</li><li>audit logging</li><li>patching dependencies</li><li>secure backups</li></ul><p>An architecture that can scale to a million users but cannot pass a primary cognitive security assessment is not production-ready.</p><h3>A practical scaling roadmap</h3><p>However, if you are wondering how to get started, here is a reasonable order:</p><h4>Stage 1: Early growth</h4><ul><li>optimize obvious slow queries</li><li>add monitoring</li><li>improve code efficiency</li><li>upgrade server resources</li><li>use a CDN for static assets</li></ul><h4>Stage 2: Growing traffic</h4><ul><li>introduce caching</li><li>add load balancing</li><li>run multiple application instances</li></ul><p>The development phase includes migrating the long-running tasks to background workers</p><h4>Stage 3: Serious scale</h4><ul><li>add read replicas</li><li>improve failover and recovery</li><li>introduce autoscaling</li><li>isolate heavy workloads</li><li>refine deployment and observability systems</li></ul><h4>Stage 4: Large-scale platform</h4><ul><li>split services where justified</li><li>shard data if truly necessary</li><li>optimize regional performance</li></ul><p>To invest in platform engineering and reliability practices</p><p>The important part is to figure out the next problem, not all problems to come.</p><h3>Final thoughts</h3><p>Scaling a web application has little to do with chasing down complexity. It is about strategizing at the right time.</p><p>Start simple. Measure everything. Fix real bottlenecks. Add caching. Scale horizontally. Offload heavy work. Strengthen your database. Build for failure.</p><p>The most impressive scaling strategy is not the best scaling strategy. It is the one that helps you keep your app performant, reliable, and scalable as your user base increases.</p><p>Because after all — scaling is not merely a technical achievement.</p><p>It means people are physically arriving to utilize what you constructed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ceaeb07ca96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How ORM Works Internally]]></title>
            <link>https://mahabub-r.medium.com/how-orm-works-internally-1bbc322b4840?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bbc322b4840</guid>
            <category><![CDATA[backend-architecture]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[database-abstraction]]></category>
            <category><![CDATA[application-data-layer]]></category>
            <category><![CDATA[orm]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 08:06:38 GMT</pubDate>
            <atom:updated>2025-12-22T08:06:38.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>N+1 query problemsHow ORM Works Internally</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMPM7l_e4CbABkiG_7wc0g.png" /></figure><p>ORMs are often misunderstood as “SQL generators.”<br>That description misses what actually makes an ORM powerful — and complex.</p><p>An ORM is a <strong>stateful system that manages object identity, tracks changes, and synchronizes an in-memory object graph with a relational database</strong>.</p><p>This article explains how ORM works internally, step by step, with <strong>diagrams explained in text</strong> so it’s easy to follow on Medium.</p><h3>1. The High-Level Architecture</h3><p>At runtime, an ORM sits between your application and the database driver.</p><pre>Application Code<br>   ↓ (objects)<br>ORM Core<br>   ├─ Metadata Mapping<br>   ├─ Identity Map<br>   ├─ Unit of Work<br>   ├─ Query Compiler<br>   ↓ (SQL)<br>Database Driver<br>   ↓<br>Relational Database</pre><ul><li>Your code never talks to SQL directly.</li><li>The ORM never works with business logic.</li><li>Each layer has a strict responsibility.</li></ul><h3>2. Metadata Mapping (Class → Table)</h3><p>When the application starts, the ORM scans entity definitions and builds a <strong>metadata model</strong>.</p><pre>User class<br> ├─ id      → users.id (PRIMARY KEY)<br> ├─ email   → users.email<br> └─ status  → users.status<br><br>Metadata Registry (in memory)<br> ├─ Entity: User<br> ├─ Table: users<br> ├─ Columns:<br> │    id → INTEGER<br> │    email → VARCHAR<br> │    status → VARCHAR</pre><p>From this point forward:</p><ul><li>The ORM <strong>does not reflect on your class</strong></li><li>It operates on metadata objects only</li></ul><p>This makes runtime behavior fast and predictable.</p><h3>3. Identity Map (Object Uniqueness)</h3><p>ORMs enforce a critical rule:</p><blockquote><em>One database row = one object instance per session.</em></blockquote><pre>Identity Map (Session)<br> ├─ (User, id=1) → 0xA12F<br> ├─ (User, id=2) → 0xB77C</pre><p>When you fetch the same row twice:</p><pre>SELECT * FROM users WHERE id = 1;</pre><h4>The ORM:</h4><ol><li>Checks the identity map</li><li>Finds an existing object</li><li>Returns the same reference</li></ol><h4>This guarantees:</h4><ul><li>Consistent state</li><li>Safe updates</li><li>No duplicated objects</li></ul><h3>4. Query Compilation Pipeline</h3><p>ORM queries are <strong>not SQL strings</strong>. They are structured expressions.</p><pre>Query Expression Tree<br> ├─ SELECT: User<br> ├─ WHERE:<br> │    email = &quot;a@x.com&quot;<br> └─ LIMIT: 1</pre><p>Execution pipeline:</p><pre>Query AST<br>   ↓<br>Dialect Resolver (Postgres / MySQL / SQLite)<br>   ↓<br>Parameterized SQL<br>   ↓<br>Database Driver</pre><h4>This design allows:</h4><ul><li>Database portability</li><li>Query optimization</li><li>SQL injection protection</li></ul><h3>5. Result Hydration (Rows → Objects)</h3><p>Databases return <strong>rows</strong>, not objects.</p><pre>Raw Result Row<br> ├─ id = 1<br> ├─ email = &quot;a@x.com&quot;<br> └─ status = &quot;ACTIVE&quot;</pre><p>Hydration process:</p><pre>Row<br> ↓<br>Check Identity Map<br> ↓<br>Create or Reuse Object<br> ↓<br>Populate Fields<br> ↓<br>Attach to Session</pre><h4>Important detail:</h4><ul><li>Constructors are often skipped</li><li>Field values are injected directly</li></ul><p>This avoids side effects during loading.</p><h3>6. Unit of Work (Change Tracking Engine)</h3><p>The <strong>Unit of Work</strong> tracks every object attached to a session.</p><pre>Unit of Work<br> ├─ New Objects<br> ├─ Clean Objects<br> ├─ Dirty Objects<br> └─ Removed Objects</pre><p>State transitions:</p><pre>New → Persistent → Dirty → Deleted</pre><h4>On commit():</h4><ol><li>Compute differences</li><li>Order operations safely</li><li>Emit minimal SQL</li></ol><p>You modify objects freely — the ORM decides <em>how</em> to persist them.</p><h3>7. Dirty Checking (Detecting Changes)</h3><p>ORMs detect changes using <strong>field instrumentation</strong>.</p><pre>User.email = &quot;new@x.com&quot;<br>      ↓<br>Field Setter Intercepted<br>      ↓<br>Mark User as Dirty</pre><p>No SQL runs at this point. SQL is generated only during <strong>flush</strong>.</p><h3>8. Relationship Management and Lazy Loading</h3><p>Relationships are usually <strong>lazy by default</strong>.</p><pre>User Object<br> ├─ id = 1<br> └─ posts = &lt;proxy (not loaded)&gt;</pre><p>When accessed:</p><pre>user.posts<br>   ↓<br>Proxy Intercepts Access<br>   ↓<br>Generate SQL:<br>SELECT * FROM posts WHERE user_id = 1<br>   ↓<br>Hydrate Post Objects</pre><h4>This explains:</h4><ul><li>N+1 query problems</li><li>Session-bound entities</li><li>Detached object errors</li></ul><h3>9. Flush vs Commit</h3><p>ORMs separate <strong>synchronization</strong> from <strong>transaction finalization</strong>.</p><pre>In-Memory Objects<br>   ↓ (flush)<br>SQL Statements Executed<br>   ↓ (commit)<br>Transaction Finalized</pre><h4>Flush may occur:</h4><ul><li>Before queries</li><li>Explicitly</li><li>Before commit</li></ul><p>Understanding flush behavior is essential for debugging ORM issues.</p><h3>Why ORMs Feel “Heavy”</h3><p>ORM overhead comes from:</p><ul><li>Identity tracking</li><li>Change detection</li><li>Relationship resolution</li><li>SQL generation layers</li></ul><p>ORMs optimize <strong>correctness and developer productivity</strong>, not raw SQL speed.</p><p>Used correctly, they are predictable and safe.</p><h3>Final Thoughts</h3><p>An ORM is not a database shortcut.</p><p>It is a <strong>transactional object graph manager</strong> that carefully controls:</p><ul><li>Identity</li><li>State</li><li>Consistency</li><li>Persistence</li></ul><p>Once you understand the internal flow, ORM behavior stops feeling magical — and starts feeling engineered.</p><p>And engineered systems can be reasoned about, optimized, and trusted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bbc322b4840" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres + Prisma: Mastering Relations from Basic to Advanced]]></title>
            <link>https://mahabub-r.medium.com/postgres-prisma-mastering-relations-from-basic-to-advanced-d205f94babc3?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d205f94babc3</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[database-relationships]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[prisma-orm]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 18:02:04 GMT</pubDate>
            <atom:updated>2025-10-09T18:02:04.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUSOtlYfK6z7cA-aHuBoNQ.png" /></figure><p>If you’ve ever worked with databases, you know that <em>relations</em> are the heart of everything. They connect your data together — like how users have posts, posts have comments, and comments belong to users again.</p><p>When using <strong>PostgreSQL</strong> with <strong>Prisma</strong>, handling these relations becomes both powerful and simple — once you understand the concepts.</p><p>In this article, we’ll go from <strong>basic to advanced Prisma relations</strong>, with examples, tips, and best practices.</p><h3>What is Prisma?</h3><p><strong>Prisma</strong> is a modern ORM (Object-Relational Mapper) for Node.js and TypeScript.</p><p>It helps you:</p><ul><li>Interact with your database safely</li><li>Write less SQL manually</li><li>Keep your schema synced with your code</li></ul><p>Paired with <strong>PostgreSQL</strong>, Prisma allows you to model and manage data in a <strong>type-safe and developer-friendly</strong> way.</p><h3>⚙️ Setup: Postgres + Prisma</h3><p>Install Prisma and initialize a project:</p><pre>npm init -y<br>npm install prisma typescript ts-node @types/node<br>npx prisma init</pre><p>In your .env file, set the Postgres connection string:</p><pre>DATABASE_URL=&quot;postgresql://user:password@localhost:5432/mydb?schema=public&quot;</pre><p>In prisma/schema.prisma:</p><pre>datasource db {<br>  provider = &quot;postgresql&quot;<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}<br><br>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}</pre><h3>1. One-to-One Relation</h3><p>Example: Each <strong>user</strong> has one <strong>profile</strong>.</p><pre>model User {<br>  id       Int      @id @default(autoincrement())<br>  email    String   @unique<br>  profile  Profile?<br>}<br><br>model Profile {<br>  id       Int    @id @default(autoincrement())<br>  bio      String?<br>  user     User   @relation(fields: [userId], references: [id])<br>  userId   Int    @unique<br>}</pre><h3>Example Usage:</h3><pre>const newUser = await prisma.user.create({<br>  data: {<br>    email: &quot;alex@example.com&quot;,<br>    profile: { create: { bio: &quot;I love TypeScript!&quot; } }<br>  },<br>  include: { profile: true }<br>});</pre><h3>2. One-to-Many Relation</h3><p>Example: A <strong>user</strong> can have many <strong>posts</strong>.</p><pre>model User {<br>  id     Int     @id @default(autoincrement())<br>  email  String  @unique<br>  posts  Post[]<br>}<br><br>model Post {<br>  id       Int    @id @default(autoincrement())<br>  title    String<br>  content  String?<br>  user     User   @relation(fields: [userId], references: [id])<br>  userId   Int<br>}</pre><h4>Example:</h4><pre>const userWithPosts = await prisma.user.create({<br>  data: {<br>    email: &quot;john@example.com&quot;,<br>    posts: { create: [{ title: &quot;First Post&quot; }, { title: &quot;Second Post&quot; }] }<br>  },<br>  include: { posts: true }<br>});</pre><h3>3. Many-to-Many Relation</h3><p>Example: <strong>Posts</strong> can have many <strong>Tags</strong>, and <strong>Tags</strong> can belong to many <strong>Posts</strong>.</p><pre>model Post {<br>  id     Int     @id @default(autoincrement())<br>  title  String<br>  tags   Tag[]   @relation(&quot;PostTags&quot;)<br>}<br><br>model Tag {<br>  id     Int     @id @default(autoincrement())<br>  name   String  @unique<br>  posts  Post[]  @relation(&quot;PostTags&quot;)<br>}</pre><h4>Example: Create Post with Tags</h4><pre>const newPost = await prisma.post.create({<br>  data: {<br>    title: &quot;Learn Prisma Relations&quot;,<br>    tags: { create: [{ name: &quot;Prisma&quot; }, { name: &quot;Postgres&quot; }] }<br>  },<br>  include: { tags: true }<br>});</pre><h4>Connect Existing Tags:</h4><pre>await prisma.post.update({<br>  where: { id: 1 },<br>  data: { tags: { connect: [{ id: 2 }] } }<br>});</pre><h3>4. Custom Join Tables (Extra Fields)</h3><p>Sometimes you need extra information in the join table, e.g., <strong>likes with timestamps</strong>.</p><pre>model User {<br>  id     Int     @id @default(autoincrement())<br>  email  String  @unique<br>  likes  Like[]<br>}</pre><pre>model Post {<br>  id     Int     @id @default(autoincrement())<br>  title  String<br>  likes  Like[]<br>}</pre><pre>model Like {<br>  user      User     @relation(fields: [userId], references: [id])<br>  userId    Int<br>  post      Post     @relation(fields: [postId], references: [id])<br>  postId    Int<br>  createdAt DateTime @default(now())<br>  <br>  @@id([userId, postId])<br>}</pre><h4>Example:</h4><pre>await prisma.like.create({<br>  data: {<br>    user: { connect: { id: 1 } },<br>    post: { connect: { id: 3 } }<br>  }<br>});</pre><h3>5. Self-Relations (Hierarchical Data)</h3><pre>model Employee {<br>  id          Int        @id @default(autoincrement())<br>  name        String<br>  manager     Employee?  @relation(&quot;ManagerRelation&quot;, fields: [managerId], references: [id])<br>  managerId   Int?<br>  subordinates Employee[] @relation(&quot;ManagerRelation&quot;)<br>}</pre><p>Example: Employees with managers.</p><pre>model Employee {<br>  id          Int        @id @default(autoincrement())<br>  name        String<br>  manager     Employee?  @relation(&quot;ManagerRelation&quot;, fields: [managerId], references: [id])<br>  managerId   Int?<br>  subordinates Employee[] @relation(&quot;ManagerRelation&quot;)<br>}</pre><h4>Example Query:</h4><pre>const managerWithTeam = await prisma.employee.findUnique({<br>  where: { id: 1 },<br>  include: { subordinates: true }<br>});</pre><h3>6. Advanced Relation Filters</h3><p>Prisma allows filtering using some, every, and none.</p><pre>const posts = await prisma.post.findMany({<br>  where: {<br>    tags: {<br>      some: { name: { contains: &quot;Prisma&quot; } },<br>      none: { name: { contains: &quot;Deprecated&quot; } }<br>    }<br>  },<br>  include: { tags: true }<br>});</pre><ul><li>some: at least one related record matches</li><li>every: all related records match</li><li>none: no related records match</li></ul><h3>7. Nested Writes</h3><p>You can <strong>create or update multiple related records in one query</strong>.</p><pre>const user = await prisma.user.create({<br>  data: {<br>    email: &quot;sara@example.com&quot;,<br>    posts: {<br>      create: [<br>        {<br>          title: &quot;Nested Writes Rocks&quot;,<br>          tags: { create: [{ name: &quot;Advanced&quot; }, { name: &quot;Prisma&quot; }] }<br>        }<br>      ]<br>    }<br>  },<br>  include: { posts: { include: { tags: true } } }<br>});</pre><h3>8. Transactions with Relations</h3><p>Ensure data consistency when updating multiple related records.</p><pre>const [user, post] = await prisma.$transaction([<br>  prisma.user.create({ data: { email: &quot;txn@example.com&quot; } }),<br>  prisma.post.create({ data: { title: &quot;Transaction-safe post&quot;, userId: 1 } })<br>]);</pre><h3>9. Cascading Deletes &amp; Updates</h3><p>Use onDelete: Cascade to automatically delete related records.</p><pre>model Post {<br>  id      Int    @id @default(autoincrement())<br>  title   String<br>  user    User   @relation(fields: [userId], references: [id], onDelete: Cascade)<br>  userId  Int<br>}</pre><h3>10. Performance Tips for Relations</h3><ol><li><strong>Select only needed fields</strong>: Avoid include: { posts: true } if you only need titles.</li><li><strong>Avoid N+1 queries</strong>: Use include or select to fetch related data in one go.</li><li><strong>Use indexes</strong>: Foreign keys and join tables should be indexed.</li><li><strong>Paginate large relations</strong>: take and skip for controlled fetches.</li><li><strong>Batch writes with transactions</strong>: $transaction is faster and safer.</li></ol><h3>11. Advanced Many-to-Many with Extra Fields</h3><pre>model User {<br>  id      Int         @id @default(autoincrement())<br>  name    String<br>  projects UserProject[]<br>}</pre><pre>model Project {<br>  id      Int         @id @default(autoincrement())<br>  title   String<br>  members UserProject[]<br>}</pre><pre>model UserProject {<br>  user      User      @relation(fields: [userId], references: [id])<br>  userId    Int<br>  project   Project   @relation(fields: [projectId], references: [id])<br>  projectId Int<br>  role      String<br>  joinedAt  DateTime  @default(now())<br><br>  @@id([userId, projectId])<br>}</pre><h3>🏁 Final Thoughts</h3><p>Prisma transforms <strong>Postgres relations from simple tables into powerful, type-safe, and programmable objects</strong>.</p><p>From <strong>one-to-one</strong> to <strong>complex self-relations, nested writes, and transactional operations</strong>, you can model any real-world scenario.</p><p>The key is <strong>thinking in data structures</strong> while using Prisma’s syntax — making your database robust, maintainable, and future-proof.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d205f94babc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Different Types of Search in MongoDB and Mongoose]]></title>
            <link>https://mahabub-r.medium.com/understanding-different-types-of-search-in-mongodb-and-mongoose-31cf8bfc343f?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/31cf8bfc343f</guid>
            <category><![CDATA[full-stack-development]]></category>
            <category><![CDATA[search-optimization]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 05:45:18 GMT</pubDate>
            <atom:updated>2025-10-07T05:45:18.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bO2pVduAH7ffq2iC0VqqFg.png" /></figure><p>Searching for data is one of the most important parts of working with databases. Whether you’re building an e-commerce app, a social platform, or a blog, you’ll often need to find the right information — maybe a product, a user, or a post.</p><p>When working with <strong>MongoDB</strong> (a NoSQL database) and <strong>Mongoose</strong> (the ODM that connects MongoDB with Node.js), you get powerful ways to search your data. Some are simple, while others can be very advanced — like full-text and aggregation searches.</p><p>In this article, let’s go step-by-step, from the most basic types of searches to more advanced ones, so you can master how to query MongoDB like a pro.</p><h3>1. Basic Equality Search</h3><p>Let’s start with the simplest type of search — finding documents that exactly match a condition.</p><p>For example, if you want to find all users whose name is “John”:</p><pre>const users = await User.find({ name: &quot;John&quot; });</pre><p>This will return all users where the name field exactly equals “John”.</p><p>You can also find a single document:</p><pre>const user = await User.findOne({ email: &quot;john@example.com&quot; });</pre><p>or even search by ID:</p><pre>const user = await User.findById(&quot;652fcb9d2b1d4e9a6b123abc&quot;);</pre><p>This is the foundation of searching — exact matches. But real-world searches often need more flexibility, so let’s move on.</p><h3>2. Searching with Comparison Operators</h3><p>MongoDB allows comparison operators like $gt, $gte, $lt, $lte, and $ne to search using numerical or date-based conditions.</p><p>For example, finding all products that cost more than 100:</p><pre>const products = await Product.find({ price: { $gt: 100 } });</pre><p>Or, finding users between 18 and 30 years old:</p><pre>const users = await User.find({ age: { $gte: 18, $lte: 30 } });</pre><p>You can even combine multiple fields easily.</p><p>These types of queries are super helpful when working with numbers, prices, or timestamps.</p><h3>3. Searching with Logical Operators</h3><p>Sometimes you need to combine multiple search conditions. MongoDB gives you operators like $or, $and, $nor, and $not for logical searching.</p><p>For example, if you want to find users who are either from the USA <strong>or</strong> have more than 1000 followers:</p><pre>const users = await User.find({<br>  $or: [{ country: &quot;USA&quot; }, { followers: { $gt: 1000 } }]<br>});</pre><p>If you need both conditions to be true (like users who are active <strong>and</strong> verified):</p><pre>const users = await User.find({<br>  $and: [{ isActive: true }, { isVerified: true }]<br>});</pre><p>Logical operators give you control when you need to combine multiple rules together.</p><h3>4. Searching with Pattern Matching (Regex)</h3><p>Many times, users don’t know the exact spelling or casing of what they’re searching for. That’s where <strong>regular expressions (regex)</strong> help.</p><p>Regex allows you to match patterns in strings.</p><p>For example, if you want to find all users whose name starts with “Jo”:</p><pre>const users = await User.find({ name: { $regex: /^Jo/, $options: &quot;i&quot; } });</pre><p>Here:</p><ul><li>^Jo means the name should start with “Jo”.</li><li>$options: &quot;i&quot; makes it case-insensitive (so it matches “john” or “JOHN”).</li></ul><p>You can also search for names that <em>contain</em> a word anywhere:</p><pre>const users = await User.find({ name: { $regex: &quot;doe&quot;, $options: &quot;i&quot; } });</pre><p>Regex searches are great for “search as you type” features but keep in mind they can be slower on large datasets since they don’t always use indexes.</p><h3>5. Searching for Data Inside Arrays</h3><p>MongoDB can store arrays directly inside documents, and you can search inside those arrays easily.</p><p>For example, if each post has a list of tags:</p><pre>const posts = await Post.find({ tags: &quot;mongodb&quot; });</pre><p>MongoDB automatically checks if &quot;mongodb&quot; exists in the tags array.</p><p>If you want to check for multiple values:</p><pre>const posts = await Post.find({ tags: { $all: [&quot;mongodb&quot;, &quot;database&quot;] } });</pre><p>This finds posts that have <em>both</em> tags.</p><h3>6. Searching Nested Fields</h3><p>MongoDB documents can have nested objects, and you can search inside them using dot notation.</p><p>For example, if a user’s profile looks like this:</p><pre>{<br>  name: &quot;Alice&quot;,<br>  profile: {<br>    city: &quot;New York&quot;,<br>    country: &quot;USA&quot;<br>  }<br>}</pre><p>You can search inside the nested field like this:</p><pre>const users = await User.find({ &quot;profile.city&quot;: &quot;New York&quot; });</pre><p>This makes MongoDB super flexible when working with structured data like profiles, settings, or embedded documents.</p><h3>7. Full-Text Search</h3><p>MongoDB has a <strong>built-in full-text search</strong> feature that works great for searching keywords in text fields — like titles, descriptions, or articles.</p><p>Before you use it, you need to create a text index:</p><pre>await Post.collection.createIndex({ title: &quot;text&quot;, content: &quot;text&quot; });</pre><p>Then you can perform a text search easily:</p><pre>const posts = await Post.find({ $text: { $search: &quot;mongodb tutorial&quot; } });</pre><p>You can even rank results by relevance using $meta:</p><pre>const posts = await Post.find(<br>  { $text: { $search: &quot;mongoose search&quot; } },<br>  { score: { $meta: &quot;textScore&quot; } }<br>).sort({ score: { $meta: &quot;textScore&quot; } });</pre><p>This is perfect for blog articles, product searches, or any app where you want users to search by words or phrases.</p><h3>8. Using Aggregation for Advanced Search</h3><p>When you need more complex searches — like combining filters, sorting, and grouping — you can use <strong>MongoDB’s Aggregation Framework</strong>.</p><p>Aggregation lets you process data step by step, kind of like a pipeline.</p><p>For example, let’s say you want to find the top 5 most expensive products in a certain category:</p><pre>const results = await Product.aggregate([<br>  { $match: { category: &quot;electronics&quot; } },<br>  { $sort: { price: -1 } },<br>  { $limit: 5 }<br>]);</pre><p>You can also perform text searches inside aggregation using $regexMatch or $text.</p><p>Aggregation gives you more flexibility and power when working with big or complex datasets.</p><h3>9. Case-Insensitive and Smart Searching</h3><p>By default, MongoDB searches are case-sensitive. But you can easily make them case-insensitive using regex.</p><p>For example:</p><pre>const users = await User.find({<br>  name: { $regex: new RegExp(searchQuery, &quot;i&quot;) }<br>});</pre><p>This way, if the user types “john”, it will still match “John”, “JOHN”, or “JoHn”.</p><p>If you want even smarter searching — like handling typos or partial matches — you can use <strong>MongoDB Atlas Search</strong>, which is built on top of Lucene (the same technology behind Elasticsearch).</p><h4>Atlas Search gives you features like:</h4><ul><li>Fuzzy search (handles spelling mistakes)</li><li>Autocomplete</li><li>Relevance scoring</li><li>Highlighting search terms</li></ul><p>It’s a bit advanced but super powerful for building search-heavy applications.</p><h3>10. Paginating Search Results</h3><p>When you display search results, you usually don’t want to show everything at once. You can use .skip() and .limit() for pagination.</p><p>Example:</p><pre>const page = 2;<br>const limit = 10;<br>const skip = (page - 1) * limit;<br><br>const products = await Product.find({ name: { $regex: &quot;phone&quot;, $options: &quot;i&quot; } })<br>  .skip(skip)<br>  .limit(limit);</pre><p>This will skip the first 10 results and show the next 10 — perfect for creating “Next” and “Previous” page buttons.</p><h3>🏁 Wrapping Up</h3><p>MongoDB offers an amazing range of ways to search data — from the simplest equality checks to full-text and aggregation-based searches. With Mongoose, all of these become even easier thanks to its clean, promise-based syntax.</p><p>Here’s what we covered:</p><ul><li>Basic equality searches</li><li>Comparison and logical operators</li><li>Regex pattern matching</li><li>Searching inside arrays and nested fields</li><li>Full-text search</li><li>Aggregation framework</li><li>Case-insensitive and fuzzy search</li><li>Pagination</li></ul><p>When you understand all these types of searches, you can handle almost any kind of data query your app needs — efficiently and elegantly.</p><p>So next time you’re building a feature like a search bar, product filter, or user finder, you’ll know exactly which MongoDB search technique to use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31cf8bfc343f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developer Authentication Options: A Complete Guide (2025)]]></title>
            <link>https://mahabub-r.medium.com/developer-authentication-options-a-complete-guide-2025-9fef16f8fbe1?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fef16f8fbe1</guid>
            <category><![CDATA[developer-guide]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authentication-methods]]></category>
            <category><![CDATA[api-security]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 08:47:25 GMT</pubDate>
            <atom:updated>2025-07-14T08:47:25.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wL8yPGR4Ff4N7ZGUf74buQ.png" /></figure><p>Authentication is the backbone of security in any application, especially when developers build APIs, services, or tools that interact with sensitive data or infrastructure. Whether you’re building a public-facing API, a backend service, or a secure internal tool, how you authenticate users or other services is critical.</p><p>In this article, we’ll explore the different authentication methods developers can use, along with their use cases, benefits, and potential downsides. No jargon — just plain English.</p><h3>Why Developer Authentication Matters</h3><p>Before jumping into the methods, let’s clarify <strong>why</strong> authentication is such a big deal in development:</p><ul><li>🛡️ Prevent unauthorized access to services and data</li><li>🔍 Identify and track users, clients, or machines</li><li>🔐 Enforce roles and permissions</li><li>🌐 Protect APIs from abuse or malicious use</li><li>🤝 Integrate securely with third-party systems</li></ul><p>Now, let’s look at the best options developers have today.</p><h3>API Key Authentication</h3><h4>What is it?</h4><p>An API key is a unique string that identifies and authenticates a client calling your API. Think of it like a password you include in every request.</p><pre>GET /api/data<br>Authorization: Api-Key abc123xyz456</pre><h4>Pros:</h4><ul><li>Easy to generate and use</li><li>Works well for simple use cases (e.g., internal tools)</li></ul><h4>Cons:</h4><ul><li>No user identity; just identifies the app</li><li>Can be leaked if stored in public repos</li><li>No built-in expiration or rotation mechanism</li></ul><h4>Use Cases:</h4><ul><li>Internal APIs</li><li>Non-sensitive data or public endpoints with rate limiting</li></ul><h3>JWT (JSON Web Tokens)</h3><h4>What is it?</h4><p>JWT is a compact, self-contained token that includes encoded data (claims) like user ID, expiration time, and roles. It’s signed by the server so it can be verified but not tampered with.</p><pre>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6...</pre><h4>Pros:</h4><ul><li>Stateless — no need for server-side session storage</li><li>Includes user info (like roles) in the token</li><li>Easy to use in SPAs and mobile apps</li></ul><h4>Cons:</h4><ul><li>If stolen, it’s dangerous (no built-in revoke unless managed)</li><li>Should be stored securely (never in localStorage in sensitive apps)</li></ul><h4>Use Cases:</h4><ul><li>Web and mobile apps</li><li>Microservices needing identity propagation</li><li>APIs that require scalable authentication</li></ul><h3>OAuth 2.0</h3><h4>What is it?</h4><p>OAuth 2.0 is an authorization framework that allows one app to act on behalf of a user without sharing their password. It’s widely used to log in with third-party providers like Google or GitHub.</p><h4>Common Flows:</h4><ul><li><strong>Authorization Code</strong> — Most secure, used in web apps</li><li><strong>Client Credentials</strong> — For machine-to-machine auth</li><li><strong>Device Code</strong> — Used in devices like smart TVs</li><li><strong>PKCE</strong> — Secure for mobile and single-page apps</li></ul><h4>Pros:</h4><ul><li>Granular access control (scopes)</li><li>Works across platforms and services</li><li>Widely adopted and supported</li></ul><h4>Cons:</h4><ul><li>Can be complex to implement</li><li>Requires token management (refresh, revoke, etc.)</li></ul><h4>Use Cases:</h4><ul><li>“Login with Google/GitHub” type apps</li><li>APIs that access third-party services</li><li>Backend services needing delegated access</li></ul><h3>OpenID Connect (OIDC)</h3><h4>What is it?</h4><p>OIDC is built on top of OAuth 2.0 and adds identity features. It not only authorizes but also authenticates users and provides their profile data securely.</p><h4>Pros:</h4><ul><li>Combines login + user info</li><li>Compatible with social login providers</li><li>Token-based and stateless</li></ul><h4>Cons:</h4><ul><li>Slightly more complex than OAuth alone</li></ul><h4>Use Cases:</h4><ul><li>Single Sign-On (SSO)</li><li>Web/mobile user login</li><li>Identity federation across systems</li></ul><h3>Session Cookies (with CSRF Protection)</h3><h4>What is it?</h4><p>This is the traditional method used in server-rendered websites. The server keeps a session in memory or a database, and sets a cookie on the client’s browser.</p><h4>Pros:</h4><ul><li>Time-tested</li><li>Built-in support in most backend frameworks</li><li>Secure with CSRF protection</li></ul><h4>Cons:</h4><ul><li>Doesn’t scale well across servers without session sharing</li><li>Not great for APIs or stateless architectures</li></ul><h4>Use Cases:</h4><ul><li>Server-side rendered websites (e.g., Django, Rails)</li><li>Admin dashboards</li><li>Apps where CSRF/XSS is managed well</li></ul><h3>Refresh Tokens</h3><h4>What is it?</h4><p>In token-based systems like OAuth or JWT, refresh tokens allow users to get a new access token without re-authenticating. They’re usually long-lived and stored securely.</p><h4>Pros:</h4><ul><li>Allows short-lived access tokens (more secure)</li><li>Keeps users logged in without prompting them</li></ul><h4>Cons:</h4><ul><li>If not implemented properly, they can be abused</li><li>Requires careful token management</li></ul><h4>Use Cases:</h4><ul><li>Mobile and SPA apps</li><li>Systems with long user sessions</li><li>OAuth 2.0 flows with access token expiry</li></ul><h3>Mutual TLS (mTLS)</h3><h4>What is it?</h4><p>In mTLS, <strong>both the client and server present certificates</strong> to verify each other’s identity. It’s a very secure method, especially in internal or enterprise networks.</p><h4>Pros:</h4><ul><li>Extremely secure</li><li>Perfect for service-to-service communication</li></ul><h4>Cons:</h4><ul><li>Complex to set up and manage</li><li>Requires certificate management and rotation</li></ul><h4>Use Cases:</h4><ul><li>Microservices in Kubernetes</li><li>Financial or health APIs</li><li>Zero-trust networks</li></ul><h3>SSH Key Authentication</h3><h4>What is it?</h4><p>SSH keys are a secure way to authenticate developers or services to servers, Git platforms, or CI/CD tools. You generate a public/private key pair, and only the private key holder can access systems where the public key is trusted.</p><h4>Pros:</h4><ul><li>Very secure (especially with passphrase)</li><li>Widely supported</li></ul><h4>Cons:</h4><ul><li>Keys must be managed and rotated securely</li><li>Not ideal for web applications or user-facing systems</li></ul><h4>Use Cases:</h4><ul><li>Git and server access</li><li>Secure CI/CD pipelines</li><li>DevOps and infrastructure work</li></ul><h3>SAML (Security Assertion Markup Language)</h3><h4>What is it?</h4><p>SAML is an XML-based protocol for exchanging authentication and authorization data. It’s used mostly in <strong>enterprise SSO systems</strong>, like logging into multiple internal tools with one account.</p><h4>Pros:</h4><ul><li>Mature and secure</li><li>Enterprise-grade</li><li>Integrates well with corporate directories</li></ul><h4>Cons:</h4><ul><li>Verbose and more complex than modern protocols</li><li>Not API-friendly</li></ul><h4>Use Cases:</h4><ul><li>Enterprise SSO</li><li>Internal employee tools</li><li>HR/Finance/Legal dashboards in corporations</li></ul><h3>Bonus: Adaptive and Context-Aware Authentication</h3><p>Some systems go beyond fixed methods and <strong>adapt authentication based on behavior</strong>:</p><ul><li>Recognize device fingerprints</li><li>Check for IP reputation</li><li>Block logins from unfamiliar countries or times</li><li>Add friction only when risk is high (e.g., re-authentication)</li></ul><p>These are usually built into modern identity platforms like Okta, Auth0, or AWS Cognito.</p><h3>Choosing the Right Authentication Method</h3><p>Not sure which authentication method to use? Here’s a quick guide based on different use cases:</p><ul><li><strong>For a simple internal API:</strong><br> Use <strong>API Key authentication</strong>. It’s easy to implement and manage for basic, low-risk access.</li><li><strong>For web or mobile user login:</strong><br> Go with <strong>JWT combined with OAuth 2.0 or OpenID Connect (OIDC)</strong>. This setup is secure, scalable, and works well across platforms.</li><li><strong>For third-party logins (like Google, GitHub, Apple, etc.):</strong><br> Use <strong>OAuth 2.0 with OpenID Connect</strong> to delegate authentication and access user profile data safely.</li><li><strong>For secure communication between microservices:</strong><br> Use <strong>mutual TLS (mTLS)</strong> or <strong>JWT</strong> for authenticated and encrypted service-to-service calls.</li><li><strong>For DevOps tasks or CI/CD pipelines:</strong><br> Authenticate using <strong>SSH keys</strong> for secure access to servers, Git repositories, and automation tools.</li><li><strong>For enterprise dashboards or internal tools (Single Sign-On):</strong><br> Implement <strong>SAML-based authentication</strong>, which integrates well with identity providers like Okta, Azure AD, and Google Workspace.</li><li><strong>For apps that require long user sessions (without frequent logins):</strong><br> Use <strong>JWT with refresh tokens</strong> to securely manage session longevity and token renewal.</li></ul><h3>Final Thoughts</h3><p>Authentication is not one-size-fits-all. The best method depends on what you’re building, who it’s for, and how much security you need. For developers, understanding these tools isn’t just useful — it’s <strong>essential</strong>.</p><p>Start simple, but build with scalability and security in mind. If you’re ever unsure, combine approaches like <strong>JWT + OAuth + Refresh Tokens</strong>, or lean on identity platforms like <strong>Auth0, Okta, Firebase, or AWS Cognito</strong> to do the heavy lifting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fef16f8fbe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Mongoose Middleware: Pre and Post Hooks Explained]]></title>
            <link>https://mahabub-r.medium.com/understanding-mongoose-middleware-pre-and-post-hooks-explained-b14f2559aeae?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b14f2559aeae</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 17:24:58 GMT</pubDate>
            <atom:updated>2025-07-03T17:24:58.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I98d4nzUQwKiUFiEWGdG1Q.png" /></figure><p>When building applications with MongoDB and Node.js, <strong>Mongoose</strong> is one of the most popular libraries to manage your data. It provides a smooth way to define your data models and interact with your MongoDB database. One powerful feature Mongoose offers is <strong>middleware</strong>, which lets you run custom logic before or after certain database operations.</p><p>This guide will take you through everything you need to know about Mongoose middleware, focusing specifically on <strong>pre</strong> and <strong>post</strong> middleware hooks. We will cover what they are, why they are useful, which operations support them, and how to write your own middleware effectively.</p><h3>What is Mongoose Middleware?</h3><p>Middleware in Mongoose is a way to tap into the lifecycle of a document or a query. It allows you to execute code <strong>before</strong> or <strong>after</strong> specific Mongoose methods such as saving a document, updating records, or finding documents.</p><p>Imagine you want to automatically check if a user’s email is valid before saving it, or you want to log whenever a record is deleted. Middleware helps you do this cleanly and consistently, without scattering that logic all over your code.</p><p>Middleware functions in Mongoose are often called <strong>hooks</strong>, and they come in two flavors:</p><ul><li><strong>Pre middleware</strong>: Runs <em>before</em> a Mongoose operation.</li><li><strong>Post middleware</strong>: Runs <em>after</em> a Mongoose operation.</li></ul><h3>Why Use Middleware?</h3><p>Middleware helps in various common tasks:</p><ul><li><strong>Validation</strong>: Checking data before it’s saved.</li><li><strong>Data transformation</strong>: Modifying data before saving, such as hashing passwords.</li><li><strong>Logging</strong>: Recording when certain operations happen.</li><li><strong>Cleaning up</strong>: Removing or updating related documents after an operation.</li><li><strong>Triggering other processes</strong>: For example, sending an email after user registration.</li></ul><p>Without middleware, you would have to add these checks and logic in every place you call your database operations, which leads to repetitive, error-prone code.</p><h3>How Does Middleware Work in Mongoose?</h3><p>Mongoose middleware works by letting you register functions on a schema for specific methods. When Mongoose runs these methods, it automatically runs your middleware functions at the right time.</p><h4>You can register middleware on both <strong>documents</strong> and <strong>queries</strong>:</h4><ul><li><strong>Document middleware</strong> affects individual documents (like when you call .save() on a document).</li><li><strong>Query middleware</strong> affects query operations (like when you call Model.find() or Model.updateOne()).</li></ul><h3>Pre Middleware (Before the Operation)</h3><p>Pre middleware functions run <strong>before</strong> a specific action. You typically use pre middleware to:</p><ul><li>Validate data.</li><li>Modify data before saving.</li><li>Stop the operation if something is wrong.</li></ul><h4>Example: Pre Save Middleware</h4><pre>userSchema.pre(&#39;save&#39;, function(next) {<br>  if (!this.email) {<br>    return next(new Error(&#39;Email is required&#39;));<br>  }<br>  next();<br>});</pre><p>In this example, before saving a user document, the middleware checks if the email is provided. If not, it stops the save with an error.</p><p>Pre middleware receives a next callback. You call this callback to tell Mongoose to proceed. You can also pass an error to stop the operation.</p><h3>Post Middleware (After the Operation)</h3><p>Post middleware functions run <strong>after</strong> an operation completes. They are often used for:</p><ul><li>Logging the result.</li><li>Triggering other asynchronous operations.</li><li>Modifying the returned data (less common).</li></ul><h4>Example: Post Save Middleware</h4><pre>userSchema.post(&#39;save&#39;, function(doc) {<br>  console.log(&#39;User saved:&#39;, doc);<br>});</pre><p>This runs after a user document is saved and logs the saved document.</p><p>Post middleware does not receive a next function because the operation is already complete. You can access the document or result that was just saved or updated.</p><h3>Supported Operations for Middleware</h3><p>Not all Mongoose methods have middleware hooks, but many do. Here’s a more detailed breakdown.</p><h3>Document Middleware Methods</h3><p>These methods operate on individual documents and support both pre and post middleware:</p><ul><li>validate</li><li>save</li><li>remove</li><li>updateOne</li><li>deleteOne</li><li>replaceOne</li><li>deleteMany (rarely used on documents)</li><li>init (only post hook, runs when a document is loaded from the database)</li></ul><h3>Query Middleware Methods</h3><p>These methods operate on queries and support pre and post middleware:</p><ul><li>count</li><li>countDocuments</li><li>deleteMany</li><li>deleteOne</li><li>distinct</li><li>estimatedDocumentCount</li><li>find</li><li>findOne</li><li>findOneAndDelete</li><li>findOneAndRemove</li><li>findOneAndReplace</li><li>findOneAndUpdate</li><li>remove</li><li>replaceOne</li><li>update</li><li>updateOne</li><li>updateMany</li></ul><h3>How to Define Middleware in Mongoose</h3><p>You define middleware directly on the schema using .pre() and .post() methods. The first argument is the name of the Mongoose method you want to hook into, and the second argument is the middleware function.</p><h4>Syntax:</h4><pre>schema.pre(&#39;methodName&#39;, function(next) {<br>  // your pre middleware code here<br>  next();<br>});<br><br>schema.post(&#39;methodName&#39;, function(doc) {<br>  // your post middleware code here<br>});</pre><p>For async middleware, you can use async functions and await inside:</p><pre>schema.pre(&#39;save&#39;, async function() {<br>  // async code, like hashing a password<br>});</pre><h3>Practical Examples</h3><h4>1. Hashing Passwords Before Saving</h4><p>A common use case is to hash passwords automatically before saving a user.</p><pre>const bcrypt = require(&#39;bcrypt&#39;);<br><br>userSchema.pre(&#39;save&#39;, async function(next) {<br>  if (this.isModified(&#39;password&#39;)) {<br>    this.password = await bcrypt.hash(this.password, 10);<br>  }<br>  next();<br>});</pre><p>This middleware checks if the password field was modified and hashes it before saving.</p><h4>2. Logging After Document Removal</h4><p>You can log whenever a document is deleted:</p><pre>userSchema.post(&#39;remove&#39;, function(doc) {<br>  console.log(&#39;User removed:&#39;, doc._id);<br>});</pre><h4>3. Validate Fields Before Saving</h4><pre>userSchema.pre(&#39;validate&#39;, function(next) {<br>  if (!this.email.includes(&#39;@&#39;)) {<br>    next(new Error(&#39;Invalid email&#39;));<br>  } else {<br>    next();<br>  }<br>});</pre><p>This middleware checks if the email contains an ‘@’ symbol before allowing the save.</p><h4>4. Query Middleware Example</h4><p>You might want to log every time a find query is made:</p><pre>userSchema.pre(&#39;find&#39;, function() {<br>  console.log(&#39;A find query is about to run&#39;);<br>});</pre><p>Or modify the query to exclude inactive users automatically:</p><pre>userSchema.pre(&#39;find&#39;, function() {<br>  this.where({ isActive: true });<br>});</pre><h3>Best Practices with Middleware</h3><ul><li><strong>Keep middleware focused and simple</strong>: Don’t overload middleware with multiple unrelated tasks.</li><li><strong>Avoid long-running tasks</strong> inside middleware to prevent slowing down your app.</li><li><strong>Always call </strong><strong>next() in pre middleware</strong> unless you want to stop the operation.</li><li><strong>Use async/await for asynchronous operations</strong> to keep code clean.</li><li><strong>Add middleware before creating the model</strong>: Once a model is created, adding middleware won’t affect it.</li></ul><h3>Things to Watch Out For</h3><ul><li><strong>Middleware doesn’t run for all operations</strong>: For example, raw MongoDB operations on the collection bypass Mongoose middleware.</li><li><strong>insertMany() does not trigger middleware</strong> for each document unless you handle it manually.</li><li><strong>Query middleware does not run on document methods like </strong><strong>save()</strong>, and vice versa.</li><li>The order you register middleware matters if you have multiple hooks on the same method.</li></ul><h3>Conclusion</h3><p>Mongoose middleware is an essential feature that helps you manage side effects and logic tied to database operations cleanly and consistently. Understanding <strong>pre</strong> and <strong>post</strong> middleware hooks allows you to automatically validate, transform, and react to changes in your data without cluttering your application code.</p><p>By using middleware, you write code that is easier to maintain and less error-prone. Whether you’re hashing passwords, validating inputs, logging activity, or controlling queries, pre and post middleware hooks are powerful tools in your Mongoose toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b14f2559aeae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Writing Secure Code]]></title>
            <link>https://mahabub-r.medium.com/a-beginners-guide-to-writing-secure-code-4afbaf80ec3e?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4afbaf80ec3e</guid>
            <category><![CDATA[secure-coding]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[code-safely]]></category>
            <category><![CDATA[beginner-programmers]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 13:45:42 GMT</pubDate>
            <atom:updated>2025-06-17T13:45:42.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cd_Ga3tZHz4jswmKtqNQA.jpeg" /></figure><p>If you’re just starting out as a developer, there’s a good chance you’ve spent more time worrying about features and deadlines than about security. It’s understandable — security can feel abstract or “someone else’s job.” But here’s the hard truth: it’s your job too. Every developer, no matter their level, writes code that either opens or closes the door to attackers.</p><p>The good news? You don’t need to be a cybersecurity expert to write code that’s reasonably secure. You just need to understand a few key principles and make them part of your development habits.</p><p>Let’s walk through the basics of writing secure code — with simple, real-world practices you can start applying today.</p><h3>1. 🐞 Know the Common Vulnerabilities</h3><p>Before you can write secure code, you need to know what makes code <em>insecure</em> in the first place. Start with the <a href="https://owasp.org/www-project-top-ten/"><strong><em>OWASP Top 10</em></strong></a> — a widely used list of the most common security risks in software.</p><h4>Here are a few that beginners often run into:</h4><ul><li><strong>SQL Injection</strong> — When user input is directly used in SQL queries without sanitization. This can let attackers run their own queries on your database.</li></ul><pre># ❌ Dangerous:<br>cursor.execute(&quot;SELECT * FROM users WHERE name = &#39;&quot; + username + &quot;&#39;&quot;)</pre><ul><li><strong>Cross-Site Scripting (XSS)</strong> — Injecting malicious scripts into web pages viewed by others, usually via input fields.</li><li><strong>Cross-Site Request Forgery (CSRF)</strong> — Trick users into submitting unwanted actions, like changing a password or sending money.</li></ul><p>Even basic form inputs can be dangerous if mishandled. The rule? <strong>Never trust user input. Ever.</strong></p><h3>2. 🔐 Validate and Sanitize Input</h3><p>This one’s simple but powerful. Always validate and sanitize any data coming from the outside — whether it’s from a user, an API, or a form.</p><ul><li><strong>Validation</strong> means checking that the data is in the right shape or format.</li><li><strong>Sanitization</strong> means cleaning it up to prevent harmful content.</li></ul><h4>Example (Python):</h4><pre># ✅ Validate that a username is alphanumeric and under 20 characters<br>if not username.isalnum() or len(username) &gt; 20:<br>    raise ValueError(&quot;Invalid username&quot;)</pre><p>Use <strong>whitelisting</strong> (what <em>is</em> allowed) instead of <strong>blacklisting</strong> (what isn’t allowed) whenever possible. It’s more secure.</p><h3>3. 🔑 Don’t Roll Your Own Security</h3><p>Building your own authentication system or encryption algorithm might sound fun… until it gets hacked.</p><h4>Use battle-tested libraries for:</h4><ul><li><strong>Authentication</strong> — Libraries like bcrypt, Passport.js, or Spring Security.</li><li><strong>Password storage</strong> — Hash with bcrypt or Argon2, never store passwords in plain text.</li><li><strong>Encryption</strong> — Use trusted libraries like crypto in Node.js or cryptography in Python.</li></ul><p>Also, always use <strong>HTTPS</strong> — especially if you’re dealing with login or personal data. No excuses.</p><h3>4. 📁 Protect Sensitive Data</h3><p>Sensitive information like passwords, API keys, and tokens need special care.</p><h4><strong>Best Practices:</strong></h4><ul><li>Store secrets in <strong>environment variables</strong>, not in your code.</li><li>Never commit .env files or API keys to GitHub.</li><li>Use tools like <strong>Vault</strong>, <strong>AWS Secrets Manager</strong>, or <strong>Doppler</strong> for managing secrets securely.</li><li>Encrypt data both <strong>in transit</strong> (e.g., via HTTPS) and <strong>at rest</strong> (e.g., encrypted database fields).</li></ul><h3>5. 🧪 Test for Security — Early and Often</h3><p>Security isn’t just a final checklist — it’s part of writing quality code from day one.</p><h4><strong>Try these tools:</strong></h4><ul><li><strong>Static Analysis (SAST):</strong> Tools like Bandit (Python), ESLint security plugin (JavaScript), or SonarQube.</li><li><strong>Dependency Scanners:</strong> Tools like npm audit, pip-audit, or GitHub’s Dependabot alerts.</li><li><strong>Fuzz Testing:</strong> Test how your app handles weird or malformed input.</li></ul><p>Even writing simple <strong>unit tests for edge cases</strong> can help you discover security issues early.</p><h3>6. ⚠️ Pay Attention to Warnings</h3><p>You’ve seen those dependency warnings in your terminal or on GitHub. Don’t ignore them.</p><p>Security vulnerabilities in third-party libraries are one of the most common ways hackers get in. Keep your dependencies updated regularly — but do it carefully and test afterward.</p><blockquote>Bonus tip: Use tools like npm-check-updates, pip-review, or renovate bots to automate safe updates.</blockquote><h3>7. 🛠 Design with Security in Mind</h3><p>Good architecture leads to secure software. Here are some design principles even beginners can apply:</p><ul><li><strong>Least Privilege:</strong> Give users, services, and code only the access they absolutely need.</li><li><strong>Secure Defaults:</strong> Turn off features you don’t use. Disable directory listing. Block all but essential ports.</li><li><strong>Fail Securely:</strong> Don’t reveal stack traces or sensitive info in error messages. Use generic error messages for users.</li></ul><h3>8. 📂 Watch Out for File Upload Vulnerabilities</h3><p>Allowing file uploads? That’s a huge attack surface if not done properly. It might seem simple — but users can upload anything: executable code, malware, or massive files meant to crash your server.</p><p><strong>Tips to handle uploads securely:</strong></p><ul><li>Only allow specific file types (e.g. .jpg, .png, .pdf)</li><li>Set strict file size limits</li><li>Store uploaded files outside your main project directory</li><li>Rename files to avoid path manipulation or code injection</li><li>Use antivirus scanning tools (like ClamAV or VirusTotal API)</li></ul><p><strong>Worst mistake:</strong> Allowing users to upload .php or .exe files on a server that executes them. Don’t do this.</p><h3>9. ⚙️ Set Secure HTTP Headers</h3><p>Security isn’t just about your code — your server config matters too.</p><p>Add these HTTP headers to your responses to reduce attack risks:</p><ul><li>Content-Security-Policy: Blocks inline scripts and limits what resources your site can load.</li><li>X-Frame-Options: Prevents clickjacking (common on login pages).</li><li>Strict-Transport-Security: Forces HTTPS connections.</li><li>X-Content-Type-Options: nosniff: Stops browsers from guessing file types.</li><li>Referrer-Policy: Controls how much referrer info is shared.</li></ul><blockquote>If you’re using <strong>Express.js</strong>, add the Helmet middleware to do most of this automatically:</blockquote><pre>const helmet = require(&#39;helmet&#39;);<br>app.use(helmet());</pre><h3>10. 📉 Handle Errors Without Leaking Information</h3><p>When something goes wrong, what users see — and what attackers see — can make a big difference.</p><h4>Bad example:</h4><pre>{<br>  &quot;error&quot;: &quot;SQLSyntaxErrorException: Unknown column &#39;password&#39; in &#39;field list&#39;&quot;<br>}</pre><h4>Better:</h4><pre>{<br>  &quot;error&quot;: &quot;Something went wrong. Please try again later.&quot;<br>}</pre><h4><strong>Tips:</strong></h4><ul><li>Never show raw stack traces or SQL errors in production.</li><li>Log technical details on the server for debugging — not in the response to the client.</li><li>Use error boundaries or fallbacks in frontend frameworks (React, Vue, etc.)</li></ul><h3>11. 🧾 Log Responsibly</h3><p>Good logging helps you detect attacks or investigate problems. But bad logging can expose private data.</p><h4><strong>Secure logging habits:</strong></h4><ul><li>✅ Never log passwords or full tokens</li><li>✅ Redact sensitive fields (email, ssn, etc.)</li><li>✅ Use a consistent format for easier monitoring</li><li>✅ Avoid logging user data from GET parameters</li></ul><blockquote>If you’re using structured logging (like winston in Node.js or loguru in Python), you can configure redaction rules to prevent leaks.</blockquote><h3>12. 🔁 Stay Updated — but Test First</h3><p>Your dependencies are someone else’s code — and someone else’s bugs. Old packages often have known vulnerabilities, and attackers target them.</p><h4><strong>Best practices:</strong></h4><ul><li>Run npm audit, pip-audit, or your package manager’s security tools.</li><li>Set up <strong>Dependabot</strong> (on GitHub) to monitor for vulnerabilities.</li><li>Update regularly, but don’t blindly auto-update — always test your app after dependency changes.</li></ul><h3>13. 🤖 Use Linters and Static Analysis</h3><p>Linters do more than catch typos — they can find security issues too.</p><h4><strong>Examples:</strong></h4><ul><li>bandit (Python) – finds insecure code patterns</li><li>eslint-plugin-security (JavaScript) – checks for common JS issues</li><li>phpstan or psalm (PHP) – for static analysis</li><li>SonarQube, Semgrep, or GitHub Code Scanning – for deep, customizable analysis</li></ul><p>These tools help catch bugs <strong>before you even run the code.</strong></p><h3>14. 🧠 Think Like a Hacker</h3><p>Security gets much easier when you switch your mindset from “What can go right?” to “What can go wrong?”</p><h4>Ask yourself:</h4><ul><li>What happens if someone sends unexpected input?</li><li>Can a user access another user’s data?</li><li>What if someone spams this endpoint a million times?</li><li>What if they skip the frontend and call my API directly?</li></ul><p>This “red team” mindset will help you spot flaws before anyone else can exploit them.</p><h3>✅ Secure Code Checklist (Quick Recap)</h3><ul><li>Validate all inputs (length, format, type)</li><li>Sanitize outputs (especially in HTML/JS)</li><li>Never store passwords in plain text</li><li>Use environment variables for secrets</li><li>Keep dependencies up to date</li><li>Don’t trust user input — ever</li><li>Always use HTTPS</li></ul><h3>🧠 Final Thoughts</h3><p>Writing secure code isn’t about paranoia — it’s about responsibility. Whether you’re building a blog or a fintech app, the principles are the same: validate input, limit access, and avoid reinventing the wheel when good libraries exist.</p><p>You don’t have to become a security expert to build safer software. But by making security a habit now, you’ll save yourself — and your users — from a lot of pain later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4afbaf80ec3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Every Developer Should Understand Domain-Driven Design (DDD)]]></title>
            <link>https://mahabub-r.medium.com/why-every-developer-should-understand-domain-driven-design-ddd-eaba9444490b?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaba9444490b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[techfordevelopers]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 08:39:04 GMT</pubDate>
            <atom:updated>2025-06-04T08:39:04.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4RzBW8s9sK7xFDXlfj5kA.jpeg" /></figure><p>In the realm of software engineering, buzzwords seem to pop up and fade away like the seasons. We’ve witnessed trends come and go — new programming languages, frameworks, and methodologies. However, Domain-Driven Design (DDD), which Eric Evans introduced in his groundbreaking 2003 book, has managed to endure through the years. It may not be flashy or cutting-edge, but it holds immense significance — especially for those of us working on complex software within a collaborative team.</p><p>Yet, it’s surprising how many developers don’t take the time to really dig into it.</p><p>In this article, we’re going to discuss why every software developer — not just architects or seasoned engineers — should have a solid grasp of DDD. We’ll simplify it into practical, easy-to-understand concepts and show you how DDD can enhance your software design, improve team collaboration, and even boost your career.</p><h3>🧠 What Is Domain-Driven Design, Really?</h3><p>At its heart, Domain-Driven Design is all about really getting to know the problem space and letting that understanding shape the way we build our software.</p><h4>Here’s the main takeaway:</h4><blockquote>“Software should be crafted around the business domain it aims to support.”</blockquote><p>This means we don’t kick things off with tech tools or databases. Instead, we begin with the business challenge, the terminology used by domain experts, and the actual processes we’re trying to model. The closer we align our code with these elements, the more maintainable, accurate, and adaptable our software will be.</p><h4>DDD Is Not a Framework — It’s a Mindset.</h4><p>It’s a way of thinking about software that helps teams create systems that are better aligned and less prone to failure.</p><h3>💡 Why Should You Care as a Developer?</h3><p>Even if you’re not an architect, team lead, or business analyst, DDD offers <strong>huge benefits</strong>:</p><h4>1. It Enhances Your Code Quality</h4><p>DDD encourages you to shape your code around the business logic rather than getting bogged down by technical details. Instead of a jumble of utility classes, services, and controllers, you begin crafting clear, meaningful classes like Order, Invoice, or PaymentPolicy.</p><p>You shift from coding “what the system does” to modeling “what the business needs.”</p><h4>2. You Communicate in a Common Language with Stakeholders</h4><p>In DDD, developers and business experts share a common vocabulary, known as the Ubiquitous Language. This means no more guessing what a <strong>“transaction processor”</strong> or <strong>“handler service”</strong> entails — your code reflects the business language.</p><p>This approach minimizes bugs and miscommunication. You’re not just translating requirements into code; you’re building with terms everyone understands.</p><h4>3. You Create More Maintainable Systems</h4><p>Thanks to DDD’s separation of different business logic areas into bounded contexts, changes in one part of the system won’t send shockwaves through everything else.</p><p>This is a significant advantage in real-world systems, where businesses are always evolving.</p><h3>📦 Key Concepts of DDD (Simplified)</h3><p>Let’s briefly unpack some of the main building blocks of DDD:</p><h4>Ubiquitous Language</h4><p>This is all about having a common, clear vocabulary that everyone in the business — developers, analysts, product managers, and so on — can use.</p><p><strong><em>🧠 Why it matters:</em></strong> It cuts down on confusion and enhances communication across different roles.</p><h4>Entities &amp; Value Objects</h4><ul><li>Entities are unique and have a life cycle (think of a Customer or an Order).</li><li>Value Objects, on the other hand, are unchangeable and defined solely by their attributes (like Money or Address).</li></ul><p><strong><em>🧠 Why it matters:</em></strong> This approach mirrors the real world more accurately, resulting in cleaner and more predictable code.</p><h4>Aggregates</h4><p>An Aggregate is a group of related objects that are treated as a single unit. It has one main object, known as the Aggregate Root, which is the gateway to everything else.</p><p><strong><em>🧠 Why it matters</em>:</strong> This setup helps avoid unintended side effects and ensures consistency within your domain.</p><h4>Bounded Contexts</h4><p>A Bounded Context sets a logical boundary where a specific domain model is applicable. Different teams or sections of the business can develop their own models.</p><p><strong><em>🧠 Why it matters:</em></strong> It keeps complexity in check and supports a modular architecture.</p><h3>🛠️ Real-World Example: E-Commerce Platform</h3><p>Imagine you’re setting up an e-commerce site. Here’s how Domain-Driven Design (DDD) can make a difference:</p><ul><li>Instead of just a standard OrderService, you’d create a detailed Order aggregate that takes care of everything — adding items, calculating totals, applying discounts, and confirming shipments.</li><li>You’d incorporate value objects like Money (complete with currency) or ProductId.</li><li>The checkout process could be housed in a CheckoutContext, while the shipping system would function within a LogisticsContext — each with its own unique language and logic.</li><li>Everyone involved — developers, product managers, and domain experts — can easily discuss “carts,” “products,” and “discount policies” without needing to translate.</li></ul><p>The outcome? A system that reflects the business accurately, can grow independently in various areas, and steers clear of the chaotic Big Ball of Mud architecture.</p><h3>⚠️ Common Misconceptions</h3><h4>DDD is only for large enterprises.</h4><p>That’s a misconception! Even smaller projects can reap the benefits of the clarity that DDD offers, especially as they expand.</p><h4>DDD is too complex.</h4><p>You don’t have to dive into every concept all at once. Start with the basics: focus on using a common language and value objects.</p><h4>I can’t use DDD unless I’m the lead architect.</h4><p>Not true! Every developer has the ability (and should take the initiative) to create better models and advocate for a shared understanding.</p><h3>🎯 How to Start Applying DDD</h3><ol><li>Engage with domain experts to really grasp the problem you’re tackling.</li><li>Name things clearly — use everyday language in your code.</li><li>Focus on behavior, not just data — think about what an Order does, not just what it is.</li><li>Utilize Value Objects — represent meaningful concepts like Email, Price, or Coordinates.</li><li>Recognize natural boundaries — break down logic into distinct contexts.</li></ol><h3>🧭 Final Thoughts</h3><p>DDD isn’t just another technical toolkit; it’s a powerful approach to fostering a deeper understanding of the problem space and crafting code that resonates with people. In a landscape filled with cumbersome codebases and fragile systems, grasping the principles of DDD empowers developers to create cleaner, more adaptable, and maintainable software.</p><p>Whether you’re just starting out as a junior developer or you’re a seasoned pro, DDD equips you with the tools to think critically, communicate effectively, and code with purpose. It’s not solely for architects; it’s for everyone.</p><p>So, the next time you kick off a project, don’t just ponder, “What framework should we choose?” Instead, ask yourself:</p><blockquote>“Do we truly understand the domain well enough to design the right system?”</blockquote><p>That’s the essence of DDD.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaba9444490b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How JSON.stringify() and JSON.parse()]]></title>
            <link>https://mahabub-r.medium.com/how-json-stringify-and-json-parse-f455dae70619?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f455dae70619</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[data-serialization]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Thu, 22 May 2025 17:10:18 GMT</pubDate>
            <atom:updated>2025-05-22T17:10:18.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>How JSON.stringify() and JSON.parse() Work Behind the Scenes — and How to Handle Complex JavaScript Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qK0F7z4PzkgHM1nYHn8gQ.jpeg" /></figure><p>When working with JavaScript, JSON.stringify() and JSON.parse() are the go-to methods for converting objects into strings and back. They&#39;re critical for saving data in localStorage, sending it over the network, or persisting it in files. But if you&#39;ve ever tried to serialize a Map, Set, or Date, or dealt with circular references, you&#39;ve probably run into confusing errors or data loss.</p><p>This article dives <strong>under the hood</strong> of how these functions work, why they behave the way they do, and how to build your own versions that support complex JavaScript types.</p><p>Let’s start by understanding the foundation.</p><h3>Understanding JSON.stringify()</h3><p>At its core, JSON.stringify() takes a JavaScript value — usually an object or array — and turns it into a JSON-formatted string. But not everything gets serialized. Here&#39;s what happens behind the curtain:</p><h4>1. Recursive Traversal</h4><p>When you pass an object to JSON.stringify(), JavaScript <strong>recursively walks through</strong> every key-value pair.</p><pre>const user = { name: &quot;Alice&quot;, age: 30 };<br>console.log(JSON.stringify(user));<br>// → {&quot;name&quot;:&quot;Alice&quot;,&quot;age&quot;:30}</pre><p>This looks simple, but behind the scenes, JavaScript checks every value, one by one, and decides how to turn it into a string.</p><h4>2. Type Filtering</h4><p>Here’s what JSON.stringify() <strong>does include</strong>:</p><ul><li>Strings, numbers, booleans, null</li><li>Arrays</li><li>Nested plain objects</li></ul><p>And here’s what it <strong>ignores or breaks on</strong>:</p><ul><li>undefined</li><li>Functions</li><li>Symbols</li><li>Circular references (throws an error)</li></ul><pre>const obj = {<br>  name: &quot;Bob&quot;,<br>  sayHi: function () {},<br>  info: undefined,<br>  symbol: Symbol(&quot;id&quot;)<br>};<br><br>console.log(JSON.stringify(obj));<br>// → {&quot;name&quot;:&quot;Bob&quot;} ← everything else is skipped</pre><h3>3. Customization with Replacer</h3><p>You can customize the behavior using a replacer — a function that decides which values to keep or change.</p><pre>const data = { name: &quot;Eve&quot;, age: 35 };<br><br>const json = JSON.stringify(data, (key, value) =&gt; {<br>  if (key === &quot;age&quot;) return undefined;<br>  return value;<br>});<br><br>console.log(json); <br>// → {&quot;name&quot;:&quot;Eve&quot;}</pre><h3>Understanding JSON.parse()</h3><p>JSON.parse() takes a string produced by JSON.stringify() and rebuilds the original object. But here’s the catch: JSON is a <strong>data format</strong>, not a JavaScript execution environment.</p><h4>This means:</h4><ul><li>Functions, undefined, and symbols <strong>cannot be revived</strong>.</li><li>Special objects like Date, Map, and Set become <strong>plain strings or objects</strong>.</li></ul><pre>const json = &#39;{&quot;created&quot;:&quot;2024-05-22T12:00:00.000Z&quot;}&#39;;<br>const parsed = JSON.parse(json);<br><br>console.log(typeof parsed.created); <br>// → &quot;string&quot; — not a Date!</pre><p>To fix that, you can use a <strong>reviver function</strong>:</p><pre>const revived = JSON.parse(json, (key, value) =&gt; {<br>  if (key === &quot;created&quot;) return new Date(value);<br>  return value;<br>});</pre><h3>The Limitations of JSON.stringify() and JSON.parse()</h3><p>These methods were built for <strong>simple data</strong>. They don’t handle complex objects like:</p><ul><li>Date</li><li>Map</li><li>Set</li><li>BigInt</li><li>RegExp</li><li>Circular structures</li></ul><p>Let’s look at what happens when we try to use them:</p><h4>Date Becomes String</h4><pre>const obj = { date: new Date() };<br>const json = JSON.stringify(obj);<br>console.log(json);<br>// → {&quot;date&quot;:&quot;2025-05-22T14:00:00.000Z&quot;}<br><br>const parsed = JSON.parse(json);<br>console.log(parsed.date instanceof Date); <br>// → false</pre><h4>Map and Set Are Lost</h4><pre>const obj = {<br>  map: new Map([[&quot;a&quot;, 1]]),<br>  set: new Set([1, 2, 3])<br>};<br><br>console.log(JSON.stringify(obj));<br>// → {&quot;map&quot;:{},&quot;set&quot;:{}} ← both structures gone</pre><h4>Circular References Crash</h4><pre>const obj = {};<br>obj.self = obj;<br><br>JSON.stringify(obj);<br>// ❌ TypeError: Converting circular structure to JSON</pre><h3>Building a Custom Serializer for Complex Data</h3><p>To make JSON truly useful for complex data, we need to write custom versions of stringify and parse that:</p><ul><li>Detect and label special objects (Date, Map, Set)</li><li>Prevent circular reference errors</li><li>Restore the original types when parsing</li></ul><p>Here’s how.</p><h4>Step 1: Custom stringifyWithMetadata</h4><p>We’ll tag special types using a custom __type field.</p><pre>function stringifyWithMetadata(obj) {<br>  const seen = new WeakMap();<br><br>  return JSON.stringify(obj, function (key, value) {<br>    if (typeof value === &quot;object&quot; &amp;&amp; value !== null) {<br>      if (seen.has(value)) return { __type: &quot;CircularRef&quot; };<br>      seen.set(value, true);<br>    }<br><br>    if (value instanceof Date) {<br>      return { __type: &quot;Date&quot;, value: value.toISOString() };<br>    }<br><br>    if (value instanceof Map) {<br>      return { __type: &quot;Map&quot;, value: Array.from(value.entries()) };<br>    }<br><br>    if (value instanceof Set) {<br>      return { __type: &quot;Set&quot;, value: Array.from(value) };<br>    }<br><br>    return value;<br>  });<br>}</pre><h4>Step 2: Custom parseWithMetadata</h4><p>This will recognize our special tags and revive the correct types.</p><pre>function parseWithMetadata(json) {<br>  return JSON.parse(json, function (key, value) {<br>    if (value &amp;&amp; typeof value === &quot;object&quot;) {<br>      switch (value.__type) {<br>        case &quot;Date&quot;: return new Date(value.value);<br>        case &quot;Map&quot;: return new Map(value.value);<br>        case &quot;Set&quot;: return new Set(value.value);<br>        case &quot;CircularRef&quot;: return &quot;[Circular]&quot;;<br>      }<br>    }<br>    return value;<br>  });<br>}</pre><h4>Step 3: Test It</h4><pre>const original = {<br>  date: new Date(),<br>  map: new Map([[&quot;key&quot;, 123]]),<br>  set: new Set([1, 2, 3]),<br>};<br>original.self = original; // circular<br><br>const json = stringifyWithMetadata(original);<br>console.log(&quot;Serialized:&quot;, json);<br><br>const restored = parseWithMetadata(json);<br>console.log(&quot;Restored:&quot;, restored);</pre><h3>Conclusion: JSON in Real-World JavaScript</h3><p>JSON.stringify() and JSON.parse() were designed for basic data — and they do that very well. But when you&#39;re working with real-world JavaScript objects, especially in modern apps that rely on Date, Map, Set, or graphs with circular references, you need to go beyond the built-in tools.</p><p>By building your own custom serializers, you gain <strong>full control</strong> over how your data is stored and restored, ensuring type safety and structure integrity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f455dae70619" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript Loops: From Beginner to Advanced]]></title>
            <link>https://mahabub-r.medium.com/mastering-javascript-loops-from-beginner-to-advanced-9938ae0efff5?source=rss-c6c2715785a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9938ae0efff5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-tutorial]]></category>
            <category><![CDATA[programming-basic]]></category>
            <category><![CDATA[javascript-loops]]></category>
            <category><![CDATA[coding-for-beginners]]></category>
            <dc:creator><![CDATA[Mahabubur Rahman]]></dc:creator>
            <pubDate>Tue, 13 May 2025 06:40:54 GMT</pubDate>
            <atom:updated>2025-05-13T06:40:54.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEyQWB7s1O2OmJ9qVMtboA.jpeg" /></figure><p>Loops are an essential concept in programming, and JavaScript provides several types of loops to handle repetitive tasks. Whether you’re a beginner or an experienced developer, understanding loops is crucial to writing efficient and readable code. In this guide, we will take a deep dive into JavaScript loops, starting from the basics and advancing through more complex and powerful techniques.</p><h3>Table of Contents:</h3><ol><li><strong>What Are Loops in JavaScript?</strong></li><li><strong>Basic Loops</strong></li><li><strong>Object Iteration with </strong><strong>for...in</strong></li><li><strong>Array Iteration with </strong><strong>for...of</strong></li><li><strong>Iterating with Array Methods</strong></li><li><strong>Advanced Looping Concepts</strong></li><li><strong>Performance Considerations and Best Practices</strong></li><li><strong>When to Use Each Type of Loop</strong></li><li><strong>Conclusion</strong></li></ol><h3>1. What Are Loops in JavaScript?</h3><p>In programming, a <strong>loop</strong> is a control structure that allows you to repeat a block of code multiple times. Loops are incredibly useful for tasks where you need to process multiple items, such as iterating through a list of numbers, processing elements of an array, or modifying object properties. In JavaScript, there are several types of loops, each suited for different scenarios.</p><h3>2. Basic Loops</h3><h4>The for Loop: A Classic Choice for Repeated Actions</h4><p>The for loop is one of the most commonly used loops in JavaScript. It gives you complete control over the initialization of the loop counter, the condition that needs to be met for the loop to continue, and the update step for each iteration.</p><h4>Syntax:</h4><pre>for (initialization; condition; update) {<br>  // Code to run on each iteration<br>}</pre><h4>Example:</h4><pre>console.log(&quot;For Loop:&quot;);<br>for (let i = 0; i &lt; 3; i++) {<br>  console.log(i);<br>}</pre><h4>Explanation:</h4><ul><li><strong>Initialization (</strong><strong>let i = 0)</strong>: Sets up the loop variable.</li><li><strong>Condition (</strong><strong>i &lt; 3)</strong>: Continues the loop until this condition becomes false.</li><li><strong>Update (</strong><strong>i++)</strong>: Increments the loop variable after each iteration.</li></ul><h4>Output:</h4><pre>0<br>1<br>2</pre><h4>Use Case:</h4><p>Use the for loop when you know the exact number of iterations beforehand, such as when you want to iterate through an array or repeat a task a fixed number of times.</p><h3>The while Loop: Keep Going Until the Condition</h3><p>The while loop runs as long as a specified condition is <strong>true</strong>. It’s useful when you don&#39;t know how many iterations you need in advance, but you have a condition that needs to be checked after each iteration.</p><h4>Syntax:</h4><pre>while (condition) {<br>  // Code to run as long as the condition is true<br>}</pre><h4>Example:</h4><pre>console.log(&quot;While Loop:&quot;);<br>let i = 0;<br>while (i &lt; 3) {<br>  console.log(i);<br>  i++;<br>}</pre><h4>Explanation:</h4><ul><li>The loop will continue running as long as i &lt; 3.</li><li>After each iteration, i is incremented.</li></ul><h4>Output:</h4><pre>0<br>1<br>2</pre><h4>Use Case:</h4><p>Use the while loop when the number of iterations is not known beforehand, but you know the loop should stop once a certain condition is met (e.g., waiting for user input).</p><h3>The do...while Loop: Guaranteed One Run</h3><p>The do...while loop guarantees that the loop body will be executed <strong>at least once</strong>. After that, it checks the condition. If the condition is true, it will continue running.</p><h4>Syntax:</h4><pre>do {<br>  // Code to run at least once<br>} while (condition);</pre><h4>Example:</h4><pre>console.log(&quot;Do...While Loop:&quot;);<br>let i = 0;<br>do {<br>  console.log(i);<br>  i++;<br>} while (i &lt; 3);</pre><h4>Explanation:</h4><ul><li>The loop runs at least once, even if i is 3 from the start.</li><li>After each iteration, it checks if i &lt; 3 to continue or exit.</li></ul><h4>Output:</h4><pre>0<br>1<br>2</pre><h4>Use Case:</h4><p>Use the do...while loop when you need to ensure that the loop body is executed <strong>at least once</strong>, such as prompting the user for input until a valid response is given.</p><h3>3. Object Iteration with for...in</h3><p>The for...in loop is used to iterate over the <strong>keys</strong> of an object. It’s helpful when you want to process the properties of an object.</p><h4>Syntax:</h4><pre>for (let key in object) {<br>  // Access object[key] or use key<br>}</pre><h4>Example:</h4><pre>console.log(&quot;For...In Loop:&quot;);<br>const person = { name: &#39;Alice&#39;, age: 25 };<br>for (let key in person) {<br>  console.log(key, person[key]);<br>}</pre><h4>Output:</h4><pre>For...In Loop:<br>name Alice<br>age 25</pre><h4>Use Case:</h4><p>Use for...in when you need to loop through the properties of an object.</p><h3>4. Array Iteration with for...of</h3><p>The for...of loop is used to iterate over <strong>iterable objects</strong>, such as arrays, strings, or Maps. It allows you to directly access the <strong>values</strong> of an array without needing the index.</p><h4>Syntax:</h4><pre>for (let value of iterable) {<br>  // Access each value of the iterable<br>}</pre><h4>Example:</h4><pre>console.log(&quot;For...Of Loop:&quot;);<br>const arr = [100, 200, 300];<br>for (let value of arr) {<br>  console.log(value);<br>}</pre><h4>Output:</h4><pre>For...Of Loop:<br>100<br>200<br>300</pre><h4>Use Case:</h4><p>Use for...of when you need to loop over the <strong>values</strong> of an iterable object, like an array.</p><h3>5. Iterating with Array Methods</h3><p>In addition to traditional loops, JavaScript provides several array methods that allow you to perform operations on arrays in a clean, functional way.</p><h4>forEach() Method</h4><p>The forEach() method runs a function on each element of an array. It’s a <strong>cleaner</strong> way to loop through arrays but doesn&#39;t allow for early exits or modifications to the array.</p><h4>Syntax:</h4><pre>array.forEach((item) =&gt; {<br>  // Code to run for each item<br>});</pre><h4>Example:</h4><pre>console.log(&quot;ForEach Example:&quot;);<br>const numbers = [1, 2, 3];<br>numbers.forEach(num =&gt; console.log(num));</pre><h4>Output:</h4><pre>ForEach Example:<br>1<br>2<br>3</pre><h4>Use Case:</h4><p>Use forEach() for simple tasks like logging or modifying elements without needing to control the loop flow.</p><h3>map(), filter(), reduce() Methods</h3><p>These functional methods provide a more powerful way to work with arrays:</p><ul><li><strong>map()</strong>: Transforms an array into a new array by applying a function to each element.</li><li><strong>filter()</strong>: Filters an array based on a condition, returning a new array with the elements that pass the test.</li><li><strong>reduce()</strong>: Reduces an array to a single value, based on a function you provide.</li></ul><h4>Examples:</h4><pre>const nums = [1, 2, 3, 4, 5];<br><br>// Using map to double each number<br>const doubled = nums.map(num =&gt; num * 2);<br><br>// Using filter to get even numbers<br>const evens = nums.filter(num =&gt; num % 2 === 0);<br><br>// Using reduce to sum all numbers<br>const sum = nums.reduce((acc, num) =&gt; acc + num, 0);<br><br>console.log(doubled); // [2, 4, 6, 8, 10]<br>console.log(evens);   // [2, 4]<br>console.log(sum);     // 15</pre><h3>6. Advanced Looping Concepts</h3><h4>Nested Loops: Loops Inside Loops</h4><p>Nested loops are used when you need to perform repetitive actions within another loop. A common use case is iterating over 2D arrays or matrices.</p><h4>Example:</h4><pre>const matrix = [<br>  [1, 2, 3],<br>  [4, 5, 6],<br>  [7, 8, 9]<br>];<br><br>for (let i = 0; i &lt; matrix.length; i++) {<br>  for (let j = 0; j &lt; matrix[i].length; j++) {<br>    console.log(matrix[i][j]);<br>  }<br>}</pre><h4>Output:</h4><pre>1 2 3<br>4 5 6<br>7 8 9</pre><h4>Use Case:</h4><p>Use nested loops when you need to iterate over multi-dimensional arrays, such as 2D matrices.</p><h3>Breaking and Continuing Loops</h3><ul><li><strong>break</strong>: Exits the loop immediately.</li><li><strong>continue</strong>: Skips the current iteration and continues with the next one.</li></ul><h4>Example with break:</h4><pre>for (let i = 0; i &lt; 10; i++) {<br>  if (i === 5) {<br>    break;  // Exit the loop when i reaches 5<br>  }<br>  console.log(i);<br>}</pre><h4>Output:</h4><pre>0<br>1<br>2<br>3<br>4</pre><h4>Example with continue:</h4><pre>for (let i = 0; i &lt; 10; i++) {<br>  if (i % 2 === 0) {<br>    continue;  // Skip even numbers<br>  }<br>  console.log(i);<br>}</pre><h4>Output:</h4><pre>1<br>3<br>5<br>7<br>9</pre><h3>7. Performance Considerations and Best Practices</h3><ul><li><strong>Avoid heavy operations inside loops</strong>: Minimize computationally expensive operations (like DOM manipulation) within loops for better performance.</li><li><strong>Use </strong><strong>forEach() and </strong><strong>map() carefully</strong>: These methods are often slower than for loops for large arrays, though they provide more readability.</li></ul><h3>8. When to Use Each Type of Loop</h3><ul><li><strong>for loop</strong>: Use when you know the exact number of iterations or when you need the loop counter for calculations.</li><li><strong>while and </strong><strong>do...while loops</strong>: Use when the number of iterations is dependent on conditions that are checked during the loop.</li><li><strong>for...in loop</strong>: Use for looping over object properties.</li><li><strong>for...of loop</strong>: Best for iterating over array values and other iterable objects.</li><li><strong>Array methods (</strong><strong>forEach(), </strong><strong>map(), </strong><strong>filter(), </strong><strong>reduce())</strong>: Great for functional-style programming when working with arrays.</li></ul><h3>9. Conclusion</h3><p>Mastering JavaScript loops is essential for writing efficient and scalable code. By understanding the different types of loops — <strong>for</strong>, <strong>while</strong>, <strong>do...while</strong>, <strong>for...in</strong>, <strong>for...of</strong>, and array methods like <strong>forEach()</strong>—you can easily handle repetitive tasks in your code. By practicing with examples and understanding when to use each loop, you can write better, cleaner, and more optimized JavaScript code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9938ae0efff5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>