<?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 Dhruv Prajapati on Medium]]></title>
        <description><![CDATA[Stories by Dhruv Prajapati on Medium]]></description>
        <link>https://medium.com/@itz.dhruv?source=rss-372c24957b75------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vOWKoHaWQ6O-U39Ebpp_Hg.png</url>
            <title>Stories by Dhruv Prajapati on Medium</title>
            <link>https://medium.com/@itz.dhruv?source=rss-372c24957b75------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:23:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itz.dhruv/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[DPDP in Plain English: What Founders & Developers Should Do Next]]></title>
            <link>https://medium.com/@itz.dhruv/dpdp-in-plain-english-what-founders-developers-should-do-next-a278ca709ad4?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/a278ca709ad4</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[dpdp-act]]></category>
            <category><![CDATA[india]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 11:45:16 GMT</pubDate>
            <atom:updated>2025-10-05T11:45:16.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfvKt1eKFvZJoyOOBxfNcg.png" /><figcaption>DPDP in Plain English</figcaption></figure><blockquote>TL;DR — The DPDP Act isn’t asking for magic. It expects clear notice, real user choice, reasonable security, and the ability to prove what happened. This post is a builder’s checklist, not legal advice.</blockquote><h3>What is the DPDP Act (in one paragraph)?</h3><p>India’s Digital Personal Data Protection (DPDP) Act sets baseline duties for anyone handling personal data. In practice: be clear about why you collect data, get and honor consent for non-essential uses, keep data secure, let people withdraw or correct, and don’t keep data forever.</p><h4>Why it matters now</h4><ul><li>Risk: fines and takedowns aren’t theoretical anymore.</li><li>Trust: your customers now expect control and plain language.</li><li>Ops: doing the basics early is cheaper than fire-drills later.</li></ul><h4>The essentials (for product + engineering)</h4><ol><li><strong>Notice, then choice: </strong>Give a simple notice (what/why) and offer affirmative consent for non-essential purposes. Don’t hide controls.</li><li><strong>Gate non-essential scripts: </strong>Analytics/marketing should load only after consent. Necessary stuff (auth, checkout, security) keeps running.</li><li><strong>Keep an audit-ready history: </strong>Log each allow/deny/change/withdraw with timestamp and categories. Append-only. You should be able to export a CSV for an audit.</li><li><strong>Respect withdrawals: </strong>When consent is changed/withdrawn, stop non-essential processing, and log the event.</li><li><strong>Limit retention: </strong>Set a time-to-live (e.g., 13–24 months) and purge on a schedule.</li><li><strong>Reasonable security: </strong>Use least-privilege access, RLS or equivalent, and off-the-shelf monitoring. Encrypt at rest/transit.</li><li><strong>Data principal rights: </strong>Provide a simple email path for access/correction/erasure requests. Respond within a reasonable SLA.</li><li><strong>Children: </strong>If your product targets minors, avoid behavioural tracking and talk to counsel about parental consent. (This post doesn’t cover age-gating.)</li><li><strong>Cross-border: </strong>Be ready to say where data is processed and keep an eye on government restrictions.</li></ol><h4>A 30-day checklist you can actually ship</h4><h4><strong>Week 1 — visibility &amp; copy</strong></h4><ul><li>List all scripts/cookies on your site(s); tag as Necessary / Functional / Analytics / Marketing.</li><li>Update your Privacy page in plain language: purposes, withdrawal method, contact, retention.</li><li>Add a grievance mailbox (e.g., grievances@yourdomain.com) that reaches your support inbox.</li></ul><h4><strong>Week 2 — consent &amp; control</strong></h4><ul><li>Show a banner with clear choices (allow/deny/category toggles).</li><li>Gate analytics/marketing until consent (one small condition around your loaders).</li><li>Add a “Change settings” link in your footer or account menu.</li></ul><h4><strong>Week 3 — proof &amp; retention</strong></h4><ul><li>Log each decision append-only (timestamp, categories, version).</li><li>Build a CSV export by date range.</li><li>Set a retention policy (TTL) and a nightly purge job.</li></ul><h4><strong>Week 4 — operations</strong></h4><ul><li>Create a 1-page incident runbook (who triages, who notifies, 72h target for serious issues).</li><li>Add simple monitors and health checks; alerts to a shared inbox.</li><li>Train the team: what to do for withdraw/erase requests.</li></ul><h4><strong>Common mistakes (easy to avoid)</strong></h4><ul><li>Firing analytics before consent (“we’ll fix it later”).</li><li>Treating “Necessary” as toggleable (it isn’t; explain it instead).</li><li>Editable logs (auditors dislike mutability).</li><li>No way to change consent later.</li><li>Keeping data forever “just in case”.</li></ul><p><strong><em>If you want a head start</em></strong></p><p><strong><em>There are lightweight tools that give you a bilingual banner and an audit-ready consent log you can export in minutes. Pick whatever fits your stack and budget.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a278ca709ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Holding On: Building Your Life from the Edge]]></title>
            <link>https://medium.com/@itz.dhruv/the-art-of-holding-on-building-your-life-from-the-edge-972ff61fdb32?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/972ff61fdb32</guid>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[resilience]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 13:22:38 GMT</pubDate>
            <atom:updated>2025-03-06T13:22:38.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a5ggilOdOeFXgD3V" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybishop?utm_source=medium&amp;utm_medium=referral">Jeremy Bishop</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There’s a moment in everyone’s life when the ground beneath you cracks. Not a gentle fracture, but a jagged split that threatens to swallow you whole. Maybe it’s a job lost, a dream shattered, or a love that slipped through your fingers. You stand there, teetering, and the instinct is to fall — to give up, to let the weight pull you under.</p><p>But here’s the secret no one tells you: <em>that edge, that ruin, is your scaffold.</em> Clutch it. Hold on with everything you’ve got, because from there, you can see the <em>canvas of your life</em> unfold.</p><p>It’s not about waiting for a perfect foundation. Life doesn’t hand you marble pillars; it gives you <em>cracks to root in</em>. Think of the tree that splits concrete to reach sunlight — its strength isn’t in the soil, but in its refusal to break. You don’t need a steady job, a flawless plan, or someone else’s approval. You need the <em>guts to grip what’s in front of you</em> — a shaky idea, a half-broken dream — and stretch toward the sky.</p><p>That’s where the stars live, painted not with ease, but with the sweat of your struggle.</p><p>This isn’t a pretty mindset. Forget the motivational posters with their golden sunsets and bold clichés. This is <em>dirt caked under your nails</em>, a heart pounding out of control, the sharp sting of failure that forces you to stand taller. The canvas isn’t a gift — it’s the world you <strong>forge when you refuse to let go</strong>.</p><p>Take the single mom I once met, grinding through two back-breaking shifts. When schools shut down, her <em>kitchen table became her scaffold</em>, wobbling under exhaustion. She turned it into a classroom for her kids, clutching it through sleepless nights. Money was tight, sleep a distant memory, but her determination <em>carved a canvas of hope</em> — a future where her children could rise.</p><p>Then there’s the man I heard about, a guy who lost a business he’d poured years into. The ruin hit like a sledgehammer: debts piled high, leaving him with nothing but a battered desk from a thrift store. He made that desk his scaffold, scribbling ideas late into the night, the wood creaking under his weight. A friend said he built something new from those notes — not a return to the past, but a bolder start. <em>That wreckage didn’t end him. It became his rebirth.</em></p><p>And consider Phil Knight, the founder of Nike, whose story I stumbled across in <em>Shoe Dog</em>. In 1962, he was a 24-year-old with no business experience, borrowing $50 from his father to chase a wild idea: importing Japanese running shoes to the U.S. He started selling from the trunk of his car, facing cash shortages, skeptical banks, and a legal battle with his original supplier, Onitsuka. That car, that borrowed cash — it was his scaffold, shaky and uncertain. He clutched it through near-bankruptcy, sleepless nights, and the pressure of building a brand from nothing. Years later, that grit turned into a global empire, but the canvas he painted was forged in the fire of those early struggles — <em>imperfect, relentless, real.</em></p><p>Fast-forward to today, and we see creators, entrepreneurs, and artists clawing their way up from the edge. <em>A writer tapping out stories on an old laptop with a flickering screen, a musician composing tracks in a cramped apartment, a small business owner struggling to keep the doors open.</em> They aren’t waiting for perfect conditions. <em>They are building from the cracks</em>, crafting something from nothing, refusing to let failure be the final word.</p><p>So here’s the call: <strong>Find your scaffold.</strong></p><p>Maybe it’s a cracked phone screen where you draft your next move, a quiet park bench where you plot your comeback, or even the memory of a pain that fuels your fire. <strong>Hold it tight.</strong></p><p>The view from there — imperfect, hard-won — is where your canvas takes shape.</p><p>Not everyone will get it. Some will say, <em>Why bother?</em> But you’re not building for them. You’re building for the <strong>you who rises</strong>, unafraid, with stars in your hands.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972ff61fdb32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Configuration and HTTP Servers in NestJS]]></title>
            <link>https://blog.stackademic.com/mastering-configuration-and-http-servers-in-nest-js-e700e4f7630e?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/e700e4f7630e</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[http-server]]></category>
            <category><![CDATA[services]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[configuration]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Wed, 08 May 2024 02:49:06 GMT</pubDate>
            <atom:updated>2024-06-07T04:41:17.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Mastering Configuration and HTTP Servers in Nest.js" src="https://cdn-images-1.medium.com/max/1024/1*9TCIazwTNrQOu-_y8_SR-g.png" /><figcaption>Mastering Configuration and HTTP Servers in NestJS</figcaption></figure><p>NestJS offers robust solutions for application configuration and HTTP server setup. This guide will cover how to manage environment variables, configuration files, and how to securely set up HTTP servers, including listening on multiple ports. Let’s dive into the techniques that can make your NestJS applications more dynamic and secure.</p><h3>Configuration in NestJS</h3><h3>1. Environment Variables Based Configuration</h3><p>Environment variables are essential for keeping your application’s configuration flexible and secure, especially across different deployment environments.</p><p><strong>Key Points:</strong></p><ul><li><strong>Purpose: </strong>Safely store and manage settings like database credentials and API keys.</li><li><strong>Implementation:</strong> Utilize the <strong>dotenv</strong> package to load environment variables from a <strong>.env</strong> file.</li></ul><p><strong>Example:</strong></p><pre>import * as dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br><br>const apiSecret = process.env.API_SECRET;  // Accessing an environment variable</pre><h3>2. Config Files Based Configuration &amp; Namespaces</h3><p>Structured config files allow better management and organization of settings.</p><p><strong>Key Points:</strong></p><ul><li><strong>Purpose:</strong> Enhance readability and maintainability of configurations.</li><li><strong>Implementation:</strong> Use the <strong>@nestjs/config</strong> module for loading structured configuration files.</li></ul><p><strong>Example:</strong></p><pre>// app.config.ts<br>export default () =&gt; ({<br>  port: parseInt(process.env.PORT, 10) || 3000,<br>  database: {<br>    host: process.env.DATABASE_HOST,<br>    port: parseInt(process.env.DATABASE_PORT, 10) || 5432<br>  }<br>});</pre><h3>Using Configurations in Services</h3><p>To utilize these configurations in services, inject the <strong>ConfigService</strong> provided by the <strong>@nestjs/config</strong> module.</p><p><strong>Example:</strong></p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br><br>@Injectable()<br>export class ExampleService {<br>  constructor(private configService: ConfigService) {<br>    const dbHost = this.configService.get&lt;string&gt;(&#39;database.host&#39;);<br>    console.log(`Database Host: ${dbHost}`);<br>  }<br>}</pre><p>This setup allows your service to access the configuration properties defined in your config files, maintaining clean and manageable code.</p><h3>HTTP Server in NestJS</h3><h3>1. HTTPS Server &amp; Multiple Simultaneous Servers Setup</h3><p>Secure your application communications with HTTPS.</p><p><strong>Key Points:</strong></p><ul><li><strong>Purpose:</strong> Secure data in transit.</li><li><strong>Implementation:</strong> Use Node.js’s <strong>https</strong> module along with SSL/TLS certificates.</li></ul><p><strong>Example:</strong></p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import * as fs from &#39;fs&#39;;<br>import * as https from &#39;https&#39;;<br><br>async function bootstrap() {<br>  const httpsOptions = {<br>    key: fs.readFileSync(&#39;./secrets/private-key.pem&#39;),<br>    cert: fs.readFileSync(&#39;./secrets/public-certificate.pem&#39;)<br>  };<br>  const app = await NestFactory.create(AppModule, {<br>    httpsOptions,<br>  });<br>  await app.listen(3000);<br>}<br><br>bootstrap();</pre><h3>2. Listen on Multiple Ports</h3><p>Efficiently manage different types of traffic or services by running your application on multiple ports.</p><p><strong>Key Points:</strong></p><ul><li><strong>Purpose:</strong> Handle different services or types of traffic separately.</li><li><strong>Implementation:</strong> Instantiate multiple modules or the same module multiple times, each configured to listen on different ports.</li></ul><p><strong>Example:</strong></p><pre>async function startMultipleServers() {<br>  const server1 = await NestFactory.create(AppModule);<br>  await server1.listen(3000);<br><br>  const server2 = await NestFactory.create(AppModule);<br>  await server2.listen(4000);<br>}<br><br>startMultipleServers();</pre><h3>Conclusion</h3><p>Understanding and implementing configuration and HTTP server options in NestJS are crucial for creating scalable, secure, and maintainable applications. This guide provides the groundwork for setting up and managing configurations and HTTP servers, ensuring your applications are robust and ready for production.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e700e4f7630e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-configuration-and-http-servers-in-nest-js-e700e4f7630e">Mastering Configuration and HTTP Servers in NestJS</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into the Request-Response Lifecycle of Nest.js Applications]]></title>
            <link>https://medium.com/@itz.dhruv/deep-dive-into-the-request-response-lifecycle-of-nest-js-applications-e53635acf4af?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/e53635acf4af</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[responses]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[request]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 10:55:24 GMT</pubDate>
            <atom:updated>2024-04-15T10:55:24.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1T5HlTeDjx_p8-4tDHakQ.png" /><figcaption>Request-Response Lifecycle of Nest.js Applications</figcaption></figure><h3>Introduction</h3><p>Understanding the request-response lifecycle in a Nest.js application is crucial for effectively managing the flow of data and enhancing application performance and security. Nest.js utilizes a series of well-orchestrated steps involving middleware, guards, interceptors, and pipes that together handle incoming requests and produce responses. This article explores each component involved in the lifecycle to give you a complete understanding of how Nest.js processes requests.</p><h3>Overview of the Request-Response Lifecycle</h3><p>Nest.js processes each request through several layers, each with a specific role in security, data transformation, and response handling. Here’s how a typical request flows through a Nest.js application:</p><h4>1. Middleware</h4><p>Middleware functions are the first point of contact for an incoming request. They can execute any code, make changes to the request and response objects, end the request-response cycle, and call the next middleware function. If the middleware does not end the cycle, it passes control to the next component.</p><p><strong>Order of Execution:</strong></p><ul><li>Globally bound middleware (using app.use())</li><li>Module-bound middleware (specific to module paths)</li></ul><h4>2. Guards</h4><p>Guards determine whether a request will be handled by the route handler or not, primarily used for authentication and authorization.</p><p><strong>Execution Flow:</strong></p><ul><li>Global guards</li><li>Controller-specific guards</li><li>Route-specific guards</li></ul><pre>@UseGuards(Guard1, Guard2)<br>@Controller(&#39;cats&#39;)<br>export class CatsController {<br>  @UseGuards(Guard3)<br>  @Get()<br>  getCats(): Cats[] {<br>    return this.catsService.getCats();<br>  }<br>}</pre><h4>3. Interceptors</h4><p>Interceptors perform extra logic before the method execution and just after method execution, allowing fine-grained control over the call flow and the ability to modify the result or extend the response.</p><p><strong>Flow of Execution:</strong></p><ul><li>Interceptors at the global, controller, and route levels before controller methods</li><li>Interceptors work in a “first in, last out” manner for outgoing responses</li></ul><h4>4. Pipes</h4><p>Pipes handle data transformation and validation for incoming requests. They can transform input data to the desired form or validate data and throw exceptions if the data is incorrect before it reaches the route handler.</p><p><strong>Order and Handling:</strong></p><ul><li>Global pipes</li><li>Controller and route pipes</li><li>Route parameter-specific pipes</li></ul><h4>5. Route Handling (Controller)</h4><p>The controller handles the request after it passes through all the previous components. It executes the business logic and may interact with the service layer to manage data operations.</p><h4>6. Service Layer (Optional)</h4><p>A service layer is optionally used for business logic and data management, abstracted from the controller to keep the controller clean and focused on handling requests.</p><h4>7. Exception Filters</h4><p>Exception filters handle errors during the request processing. They catch unhandled exceptions and format error responses based on the context.</p><p><strong>Filter Application Order:</strong></p><ul><li>Route-specific filters</li><li>Controller-specific filters</li><li>Global filters</li></ul><h4>8. Response</h4><p>Finally, after processing the request and optionally catching any errors, the server sends a response back to the client.</p><h3>Conclusion</h3><p>The request-response lifecycle in Nest.js is a powerful framework that allows developers to handle requests efficiently and securely. By understanding each component involved, developers can create more maintainable, robust, and secure applications.</p><h3>Further Reading and Resources</h3><ul><li><a href="https://docs.nestjs.com/faq/request-lifecycle"><strong>Nest.js Official Documentation on Request Lifecycle:</strong></a> For an in-depth exploration of the request-response lifecycle in Nest.js, consult the official documentation.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e53635acf4af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Lifecycle Events in Nest.js]]></title>
            <link>https://medium.com/@itz.dhruv/comprehensive-guide-to-lifecycle-events-in-nest-js-15c7e8acf8cf?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c7e8acf8cf</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 10:29:29 GMT</pubDate>
            <atom:updated>2024-04-16T02:27:43.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5jSDcX3oaB5SorE5IX0kw.png" /><figcaption>Comprehensive Guide to Lifecycle Events in Nest.js</figcaption></figure><h3>Introduction</h3><p>In Nest.js, effectively managing the lifecycle of an application is pivotal to ensuring robustness and resilience. This framework provides lifecycle hooks that enable developers to interact with the application at critical phases — from initialization through operation to termination. This detailed guide will walk you through each lifecycle event, explaining its significance, practical uses, and providing code examples to illustrate how these can be implemented in your projects.</p><h3>Lifecycle Events Overview</h3><p>Nest.js organizes the application lifecycle into three phases: initializing, running, and terminating. Each phase has specific lifecycle events that allow developers to execute custom logic.</p><h3>Key Lifecycle Events</h3><p>Understanding each event in detail will help you harness the full potential of Nest.js in managing application behavior seamlessly.</p><h4>1. onModuleInit</h4><p><strong>Purpose and Timing: </strong>onModuleInit fires once Nest has instantiated a module and resolved its dependencies but before it is fully operational. This event is crucial for setting up any configurations or initial data needed by the module.</p><p><strong>Usage:</strong> Ideal for initializing data services, setting up connections to databases, or preloading necessary information that your module will need throughout its lifetime.</p><p><strong>Example:</strong></p><pre>@Injectable()<br>export class DataService implements OnModuleInit {<br>  constructor(private readonly configService: ConfigService) {}<br><br>  onModuleInit() {<br>    const dbHost = this.configService.get(&#39;DATABASE_HOST&#39;);<br>    console.log(`Connecting to database at ${dbHost}`);<br>  }<br>}</pre><h4>2. onApplicationBootstrap</h4><p><strong>Purpose and Timing:</strong> This hook executes after all modules are initialized and just before the application starts listening for connections. It’s the final step before the application becomes fully operational.</p><p><strong>Usage:</strong> Use this for actions that need to happen just before the server starts accepting requests, such as setting up scheduled jobs, finalizing configurations, or sending notifications to administrators that the application is live.</p><p><strong>Example:</strong></p><pre>@Injectable()<br>export class SchedulerService implements OnApplicationBootstrap {<br>  onApplicationBootstrap() {<br>    console.log(&#39;Starting scheduled jobs...&#39;);<br>    this.startJobs();<br>  }<br><br>  startJobs() {<br>    // Logic to start scheduled jobs<br>  }<br>}</pre><h4>3. onModuleDestroy</h4><p><strong>Purpose and Timing:</strong> Triggered when the application is about to shut down, onModuleDestroy is essential for cleanup operations.</p><p><strong>Usage:</strong> This event is crucial for releasing resources that your module holds, such as database connections, file handles, or network connections, to prevent memory leaks and other shutdown issues.</p><p><strong>Example:</strong></p><pre>@Injectable()<br>export class ResourceService implements OnModuleDestroy {<br>  onModuleDestroy() {<br>    console.log(&#39;Releasing resources...&#39;);<br>    this.releaseAllResources();<br>  }<br><br>  releaseAllResources() {<br>    // Logic to cleanly release resources<br>  }<br>}</pre><h4>4. beforeApplicationShutdown and onApplicationShutdown</h4><p><strong>Purpose and Timing:</strong> These hooks manage the final moments before the application completely shuts down. beforeApplicationShutdown is your last chance to perform asynchronous operations, while onApplicationShutdown is called right before the application process exits.</p><p><strong>Usage:</strong> beforeApplicationShutdown can be used for tasks that must complete even during a shutdown, like saving final logs to a database or notifying external systems of the shutdown. onApplicationShutdown might log the shutdown reason or perform very final cleanup.</p><p><strong>Example:</strong></p><pre>@Injectable()<br>class ShutdownService implements BeforeApplicationShutdown, OnApplicationShutdown {<br>  beforeApplicationShutdown(signal: string) {<br>    console.log(`Received ${signal}, performing pre-shutdown tasks.`);<br>  }<br><br>  onApplicationShutdown(signal: string) {<br>    console.log(`Shutting down due to ${signal}.`);<br>  }<br>}</pre><h3>Conclusion</h3><p>Lifecycle events in Nest.js are designed to give developers control over the application’s behavior at different stages of its existence. By effectively using these hooks, you can ensure that your application handles initialization and shutdown processes smoothly, maintains good performance, and manages resources efficiently. These insights should empower you to build more robust and reliable applications using Nest.js.</p><h3>Further Reading and Resources</h3><ul><li><a href="https://docs.nestjs.com/fundamentals/lifecycle-events"><strong>Nest.js Official Documentation on Lifecycle Events:</strong></a> Dive into the official documentation for a thorough exploration of lifecycle events, offering detailed explanations, additional examples, and best practices.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c7e8acf8cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Data Transfer Objects (DTOs) and Schema in Nest.JS]]></title>
            <link>https://medium.com/@itz.dhruv/mastering-data-transfer-objects-dtos-and-schema-in-nest-js-22763649ac56?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/22763649ac56</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[data-transfer-object]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 09:37:13 GMT</pubDate>
            <atom:updated>2024-03-04T09:37:13.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7a1XyG3frg-z9X8v1DSyw.png" /><figcaption>Mastering Data Transfer Objects(DTOs) and Schema in Nest.JS</figcaption></figure><h3>Introduction</h3><p>Developing server-side applications requires a deep understanding of how data is managed and transferred. In the Nest.JS framework, two pivotal concepts that stand out in this context are Data Transfer Objects (DTOs) and Schema. This article aims to provide an in-depth understanding of these concepts, their roles in application architecture, and their practical implementation in Nest.JS.</p><h3>What Are Data Transfer Objects (DTOs)?</h3><p>DTOs are simple objects used for transferring data across the layers of an application, particularly in network requests. They are crucial for data encapsulation and ensuring that data structures are maintained consistently.</p><h3>The Role of DTOs in Nest.JS</h3><ul><li><strong>Data Structure Definition:</strong> DTOs define the shape and structure of data as it travels, particularly for incoming requests in APIs.</li><li><strong>Data Validation:</strong> DTOs work hand-in-hand with validation libraries, such as class-validator, to enforce data integrity and rules.</li><li><strong>Decoupling:</strong> They help in decoupling the internal data models from the data exposed to the users.</li></ul><h3>Implementing DTOs in Nest.JS</h3><p>In Nest.JS, DTOs are typically implemented using TypeScript classes. The use of decorators from class-validator enhances DTOs with validation capabilities.</p><h4>Example:</h4><pre>import { IsString, IsInt, IsEmail } from &#39;class-validator&#39;;<br><br>export class CreateUserDto {<br>  @IsEmail()<br>  readonly email: string;<br><br>  @IsString()<br>  readonly name: string;<br><br>  @IsInt()<br>  readonly age: number;<br>}</pre><p>Here, CreateUserDto ensures that the email is a valid email, name is a string, and age is an integer.</p><h3>Understanding Schema in Nest.JS</h3><p>Schema in Nest.JS refers to the structure of data in the database, acting as a blueprint for how data is stored and managed.</p><h3>The Role of Schema</h3><ul><li><strong>Data Representation:</strong> Schema defines the database tables, fields, and the relationships between them.</li><li><strong>Data Validation:</strong> It ensures that the data being persisted adheres to a defined structure and set of constraints.</li><li><strong>Integration with ORM/ODM:</strong> Schemas are central in integrating Object-Relational Mapping (ORM) or Object Document Mapping (ODM) tools like TypeORM or Mongoose in Nest.JS.</li></ul><h3>Implementing Schema in Nest.JS</h3><p>Schemas in Nest.JS are typically associated with ORM/ODM entities. They define the entity’s properties, data types, and relationships.</p><h4>Example with Mongoose:</h4><pre>import * as mongoose from &#39;mongoose&#39;;<br><br>export const UserSchema = new mongoose.Schema({<br>  email: String,<br>  name: String,<br>  age: Number,<br>});</pre><p>In this example, UserSchema outlines a MongoDB schema for a user with email, name, and age fields.</p><h3>Key Differences Between DTOs and Schema</h3><p>While both DTOs and Schema define data structures, they serve different purposes and are used in different contexts:</p><ul><li><strong>Context of Use:</strong> DTOs are used in the application layer for data transfer, while Schemas are used in the data layer for data storage.</li><li><strong>Validation Scope:</strong> DTOs validate incoming data from the client, whereas Schemas ensure data integrity in the database.</li><li><strong>Flexibility:</strong> DTOs provide more flexibility in shaping data for different use cases without impacting the database schema.</li></ul><h3>The Importance of Validators</h3><p>Validators play a crucial role in both DTOs and Schemas:</p><ul><li><strong>In DTOs:</strong> Validators ensure that the incoming data meets the application’s expectations, thereby preventing bad data from entering the system.</li><li><strong>In Schemas:</strong> Validators at the schema level ensure that data conforms to the defined structure before being stored, maintaining database integrity.</li></ul><h3>Conclusion</h3><p>DTOs and Schema are foundational concepts in Nest.JS that facilitate efficient and secure data handling. DTOs offer a structured way to manage data transfer, while Schemas provide a blueprint for data storage and integrity. Understanding and implementing these concepts correctly is essential for creating robust, scalable, and maintainable applications in Nest.JS.</p><h3>Further Reading and Resources</h3><ol><li><a href="https://docs.nestjs.com/"><strong>Nest.JS Official Documentation</strong></a><strong>:</strong> Offers comprehensive guides and API references.</li><li><a href="https://www.npmjs.com/package/class-validator"><strong>Class Validator Library</strong></a><strong>:</strong> Provides detailed documentation on various validation decorators and their usage.</li><li><a href="https://typeorm.io/"><strong>TypeORM Documentation</strong></a><strong>:</strong> A great resource for understanding ORM integration in Nest.JS.</li><li><a href="https://mongoosejs.com/docs/"><strong>Mongoose Documentation</strong></a><strong>:</strong> Offers insights into using Mongoose for schema definition and data modeling in Nest.JS.</li></ol><p>By mastering <strong>DTOs</strong> and <strong>Schema</strong> within the Nest.JS ecosystem, developers can significantly enhance the quality and reliability of their server-side applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22763649ac56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embracing Yarn: A Guide for Angular Teams]]></title>
            <link>https://medium.com/@itz.dhruv/embracing-yarn-a-guide-for-angular-teams-6060b2a434d4?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/6060b2a434d4</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[package-manager]]></category>
            <category><![CDATA[yarn]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 05:41:43 GMT</pubDate>
            <atom:updated>2024-02-15T05:47:44.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*eRnc52Kky9m_65sHiGL_Xw.png" /><figcaption>yarn</figcaption></figure><p>In the dynamic world of JavaScript development, managing project dependencies efficiently and securely is crucial. This is where Yarn enters the scene as a game-changer for Angular teams. Born out of the need for a faster, more secure package manager, Yarn has quickly become a favorite in the developer community. This article introduces Yarn, highlighting its benefits and providing a guide for Angular teams to get started.</p><h3>What Is Yarn?</h3><p><strong>Yarn</strong> is an innovative open-source package manager that enhances project dependency management. It focuses on speed, security, and developer experience, offering features like workspaces, offline caching, and parallel installations. Yarn’s comprehensive approach to managing dependencies makes it an indispensable tool for modern JavaScript projects, including those using Angular.</p><h3>Key Advantages of Yarn</h3><ul><li><strong>Speed:</strong> Yarn caches every package it downloads, enabling fast retrieval and installation. This caching also allows Yarn to operate offline, providing significant time savings.</li><li><strong>Security:</strong> With rigorous integrity checks, Yarn ensures that your project dependencies are secure and tamper-free.</li><li><strong>Efficiency:</strong> Features like workspaces support monorepo projects, allowing for better dependency management across multiple packages within a single project.</li><li><strong>Enhanced Developer Experience:</strong> Yarn’s intuitive CLI and feature set offer developers a streamlined and consistent workflow.</li></ul><h3>Getting Started with Yarn in Angular Projects</h3><ol><li><strong>Installation:</strong> Begin by installing Yarn globally on your system with npm install -g yarn.</li><li><strong>Initializing a Project:</strong> Use yarn init to start a new project or yarn to install all dependencies for an existing project.</li><li><strong>Adding and Updating Dependencies:</strong> Easily add (yarn add [package]) and update (yarn upgrade [package]) packages in your project.</li><li><strong>Leveraging Workspaces:</strong> Utilize workspaces to manage dependencies across multiple packages in monorepo projects.</li></ol><h3>Transitioning from npm to Yarn</h3><p>For Angular teams currently using npm, transitioning to Yarn is straightforward. Yarn is compatible with the npm registry, allowing teams to switch without disrupting their existing workflow. The transition not only offers an immediate boost in performance and security but also introduces a range of features designed to improve the development process.</p><h3>Conclusion</h3><p>As Angular teams strive for efficiency, security, and a better development experience, Yarn stands out as a powerful ally. Its focus on performance, coupled with a robust set of features, makes it an excellent choice for managing dependencies in complex JavaScript projects.</p><p>To explore more about Yarn and dive deeper into its capabilities, check out the official <a href="https://yarnpkg.com/getting-started">Yarn documentation</a> and the <a href="https://classic.yarnpkg.com/lang/en/docs/getting-started/">Yarn Classic documentation</a>. These resources provide comprehensive guides on installation, usage, and best practices for making the most out of Yarn in your Angular projects.</p><p>Embrace Yarn in your Angular team’s workflow to enhance project management, streamline your development process, and ensure your applications are built on a solid, secure foundation of dependencies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6060b2a434d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering OAuth 2.0: A Guide to Access and Refresh Tokens]]></title>
            <link>https://medium.com/@itz.dhruv/mastering-oauth-2-0-a-guide-to-access-and-refresh-tokens-c79ab72d2df9?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/c79ab72d2df9</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[access-token]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[refresh-token]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 10:31:44 GMT</pubDate>
            <atom:updated>2023-11-24T10:31:44.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0lc8mWwgyx47WobbfRQFw.png" /><figcaption>Unlocking Power: The Synergy of Access and Refresh Tokens</figcaption></figure><h3><strong>Introduction</strong></h3><p>OAuth 2.0, a widely adopted protocol for securing APIs, relies on two key components: access tokens and refresh tokens. In this article, we’ll delve into the role of each token, their functionalities, and how they work together to enhance security and user experience.</p><h3><strong>Access Token Unveiled</strong></h3><p>An access token serves as a credential, representing authorization granted to a client to access specific resources on behalf of a user. Key characteristics include:</p><ul><li><strong>Short-lived Nature:</strong> Access tokens are temporary, providing a limited timeframe for accessing protected resources on the server.</li><li><strong>Authentication Tool:</strong> Typically included in API requests, access tokens authenticate the client and authorize its access to requested resources.</li><li><strong>Expiration and Renewal:</strong> Once expired, clients obtain a new access token using either the refresh token (if provided) or by re-authenticating the user.</li></ul><h3><strong>The Role of Refresh Tokens</strong></h3><p>Refresh tokens complement access tokens, playing a crucial role in obtaining a new access token when the current one expires. Key features include:</p><ul><li><strong>Longevity:</strong> Refresh tokens have a longer lifespan and aren’t meant for inclusion in API requests. Instead, they are securely stored on the server-side.</li><li><strong>Enhanced Security:</strong> Storing refresh tokens securely reduces susceptibility to interception, enhancing overall access management.</li><li><strong>Seamless Renewal:</strong> When an access token nears expiration, the client uses the refresh token to request a new access token without requiring user re-authentication.</li></ul><h3><strong>Token Dance: A Seamless Flow</strong></h3><p>Understanding the flow of these tokens is pivotal for implementing robust security. The basic sequence involves:</p><ol><li><strong>Obtaining Tokens:</strong> The client authenticates the user and obtains both access and refresh tokens from the authorization server.</li><li><strong>Accessing Resources: </strong>The client uses the access token to access protected resources on the resource server.</li><li><strong>Renewal Process:</strong> If the access token expires, the client employs the refresh token to obtain a new access token, avoiding the need for the user to log in again.</li><li><strong>Repetition:</strong> This cycle continues as needed, with the refresh token serving as a key to periodic access token renewal.</li></ol><h3><strong>Token Strategy in Chat Applications</strong></h3><p>In the context of a chat application, the choice between access and refresh tokens depends on various factors. Here’s a breakdown:</p><h4>Why Access Tokens Matter:</h4><ul><li><strong>Authentication and Authorization:</strong> Access tokens are like a special key that helps your chat application prove it’s allowed to use certain things, like reading messages or accessing user profiles.</li><li><strong>Short-Lived Validity:</strong> These special keys don’t last very long, and you need to use them quickly. They’re like tickets that expire after a short time. You include them in your requests when asking for important information.</li></ul><h4>Thinking About Refresh Tokens:</h4><ul><li><strong>Keeping Sessions Alive:</strong> Refresh tokens are like magic cards that can keep your chat session going without asking the user to log in again and again.</li><li><strong>Better User Experience:</strong> If your chat app wants to keep running for a long time without bothering users to log in repeatedly, using these magic cards (refresh tokens) can make things smoother.</li></ul><p>In simpler terms, access tokens are your permission keys, and refresh tokens are the secret to keeping your chat app running smoothly without annoying logins every now and then.</p><h3>Implementation Flows</h3><h4>Access Tokens Only</h4><ol><li><strong>User Login:</strong> User logs in.</li><li><strong>Token Acquisition:</strong> Chat application obtains an access token.</li><li><strong>Authentication:</strong> Access token is used for authentication and authorization.</li><li><strong>Renewal:</strong> When the access token expires, the user must log in again to obtain a new one.</li></ol><h4>Access and Refresh Tokens</h4><ol><li><strong>User Login:</strong> User logs in.</li><li><strong>Token Acquisition:</strong> Chat application obtains an access token and a refresh token.</li><li><strong>Authentication:</strong> Access token is used for authentication and authorization.</li><li><strong>Seamless Renewal:</strong> When the access token expires, the chat application uses the refresh token to obtain a new access token without requiring the user to log in again.</li></ol><h3>In Simple Terms:</h3><h4><strong>Choosing the Right Tokens:</strong></h4><p>Deciding whether to use just access tokens or both access and refresh tokens depends on what your chat app needs. It’s like picking the right tools for the job.</p><h4>Balancing Security and Ease:</h4><p>You want to make sure your app is safe and easy to use. Think of it like finding the perfect balance between locking your door securely and making sure it’s easy for you to open when you come home. Striking this balance is key to giving your users a smooth and secure experience with OAuth 2.0.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c79ab72d2df9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Mongoose Middleware in Node.js]]></title>
            <link>https://blog.stackademic.com/understanding-mongoose-middleware-in-node-js-9b67f1e37b44?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b67f1e37b44</guid>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 06:46:58 GMT</pubDate>
            <atom:updated>2023-09-27T05:42:51.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOtqvAfifWEkxoOXV2jlrA.png" /><figcaption>Your Essential Guide to Mongoose Middleware</figcaption></figure><p>If you’re a developer working with Node.js and MongoDB, chances are you’ve heard of Mongoose. It’s a powerful Object Data Modeling (ODM) library that simplifies interacting with MongoDB databases. One of its standout features is middleware, which allows you to add custom functions to execute before or after database operations. In this guide, we’ll delve into Mongoose middleware, its types, and how to use it effectively.</p><h3>What is Mongoose Middleware?</h3><p>Middleware, also known as pre and post hooks, are functions that intercept the execution of asynchronous operations in Mongoose. They are a way to add custom logic before or after various actions on your MongoDB data.</p><h3>Types of Middleware</h3><p>Mongoose middleware comes in four flavors:</p><h3>1. Document Middleware</h3><p>Document middleware is specific to individual documents (instances of a model). It’s triggered during actions like save, validate, remove, updateOne, and deleteOne.</p><p>Here&#39;s how to use it:</p><pre>const mongoose = require(&#39;mongoose&#39;);<br><br>const userSchema = new mongoose.Schema({<br>  name: String,<br>});<br><br>userSchema.pre(&#39;save&#39;, function(next) {<br>  // Custom logic before saving<br>  next();<br>});</pre><h3>2. Model Middleware</h3><p>Model middleware operates on entire collections of documents. It’s triggered during actions like insertMany.</p><p>Example:</p><pre>const mongoose = require(&#39;mongoose&#39;);<br><br>const bookSchema = new mongoose.Schema({<br>  title: String,<br>});<br><br>bookSchema.pre(&#39;insertMany&#39;, function(next) {<br>  // Custom logic before inserting multiple documents<br>  next();<br>});</pre><h3>3. Aggregate Middleware</h3><p>Aggregate middleware is for operations performed using MyModel.aggregate(). It allows you to modify aggregation pipelines.</p><p>Example:</p><pre>const mongoose = require(&#39;mongoose&#39;);<br><br>const productSchema = new mongoose.Schema({<br>  name: String,<br>  price: Number,<br>});<br><br>productSchema.pre(&#39;aggregate&#39;, function() {<br>  // Modify the aggregation pipeline<br>  this.pipeline().unshift({ $match: { price: { $gt: 0 } } });<br>});</pre><h3>4. Query Middleware</h3><p>Query middleware lets you modify queries before or after they are executed. It’s triggered during actions like find, findOne, update, and remove.</p><p>Here&#39;s how to use it:</p><pre>const mongoose = require(&#39;mongoose&#39;);<br><br>const articleSchema = new mongoose.Schema({<br>  title: String,<br>  content: String,<br>});<br><br>articleSchema.pre(&#39;find&#39;, function() {<br>  // Custom logic before executing a find query<br>});</pre><h3>Pre and Post Hooks</h3><p>Mongoose middleware functions can be pre or post hooks:</p><ul><li><strong>Pre Hooks</strong>: These run before the main action, useful for data validation or manipulation.</li><li><strong>Post Hooks</strong>: These run after the main action, ideal for logging or cleanup tasks.</li></ul><p>Here’s an example of a pre hook for data validation:</p><pre>userSchema.pre(&#39;save&#39;, function(next) {<br>  if (this.name === &#39;&#39;) {<br>    next(new Error(&#39;Name cannot be empty.&#39;));<br>  } else {<br>    next();<br>  }<br>});</pre><p>And a post hook for logging:</p><pre>userSchema.post(&#39;save&#39;, function(doc) {<br>  console.log(`${doc.name} has been saved.`);<br>});</pre><h3>Error Handling Middleware</h3><p>Middleware can handle errors during execution. If an error occurs, subsequent middleware or the main action is skipped, and the error is passed to the error handling middleware. You can transform or report errors within error handling middleware.</p><pre>bookSchema.post(&#39;insertMany&#39;, function(error, docs, next) {<br>  if (error) {<br>    console.error(`Error during insertMany: ${error.message}`);<br>  }<br>  next();<br>});</pre><h3>Accessing Parameters in Middleware</h3><ul><li>For document middleware, use this to access the document being processed.</li><li>For query middleware, this refers to the query object.</li></ul><pre>userSchema.pre(&#39;updateOne&#39;, function() {<br>  console.log(this.getUpdate()); // Access the update object<br>});</pre><h3>Define Middleware Before Compiling Models</h3><p>Remember to define your middleware before compiling your Mongoose models. Middleware added after compiling won’t work as expected.</p><h3>Synchronous Hooks</h3><p>Init hooks are synchronous and are used for initializing documents. They do not support promises or callbacks.</p><pre>bookSchema.pre(&#39;init&#39;, function() {<br>  console.log(&#39;Document is being initialized.&#39;);<br>});</pre><h3>Conclusion</h3><p>Mongoose middleware is a powerful tool for adding custom logic to your MongoDB interactions. Whether you’re validating data, logging, or handling complex operations, understanding and effectively using middleware can greatly enhance your Node.js applications.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b67f1e37b44" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/understanding-mongoose-middleware-in-node-js-9b67f1e37b44">Understanding Mongoose Middleware in Node.js</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Dynamic Email Templates with Express Handlebars and Nodemailer in Node.js]]></title>
            <link>https://medium.com/@itz.dhruv/1-introduction-to-express-handlebars-and-nodemailer-8d6174da73b8?source=rss-372c24957b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d6174da73b8</guid>
            <category><![CDATA[template-engine]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nodemailer]]></category>
            <dc:creator><![CDATA[Dhruv Prajapati]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 03:27:26 GMT</pubDate>
            <atom:updated>2023-08-29T03:28:08.443Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction to Express Handlebars and Nodemailer</h3><h3>1.1 Purpose and Benefits</h3><p>Dynamic email templates allow you to send personalized and engaging emails to your users. Express Handlebars is a popular template engine that simplifies the process of creating dynamic HTML templates. Nodemailer is a powerful Node.js library for sending emails, enabling you to seamlessly combine templating and email sending capabilities.</p><h3>1.2 Prerequisites</h3><p>Before you begin, ensure you have Node.js and npm installed. Familiarity with JavaScript and Node.js concepts will be beneficial.</p><h3>2. Setting Up the Project</h3><h3>2.1 Installing Dependencies</h3><p>Start by creating a new project directory and installing the required packages:</p><pre>mkdir dynamic-emails<br>cd dynamic-emails<br>npm init -y<br>npm install express express-handlebars nodemailer</pre><h3>2.2 Project Structure</h3><p>Create the following directory structure:</p><pre>dynamic-emails/<br>|-- templates/<br>|   |-- emails/<br>|       |-- welcome.handlebars<br>|-- node_modules/<br>|-- index.js</pre><h3>3. Creating Dynamic Email Templates with Express Handlebars</h3><h3>3.1 Installing Express Handlebars</h3><p>Install Express Handlebars as the template engine:</p><pre>npm install express-handlebars</pre><h3>3.2 Creating Email Templates</h3><p>In the templates/emails directory, create an email template named welcome.handlebars:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Welcome to Our Platform&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;Hello {{ user.name }}&lt;/h1&gt;<br>  &lt;p&gt;Welcome to our platform! We&#39;re excited to have you on board.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>3.3 Passing Dynamic Data to Templates</h3><p>In your index.js file, configure Express to use Express Handlebars and define a route for sending welcome emails:</p><pre>const express = require(&#39;express&#39;);<br>const exphbs = require(&#39;express-handlebars&#39;);<br>const nodemailer = require(&#39;nodemailer&#39;);<br>const path = require(&#39;path&#39;);<br><br>const app = express();<br><br>// Configure Express Handlebars<br>app.engine(&#39;handlebars&#39;, exphbs());<br>app.set(&#39;view engine&#39;, &#39;handlebars&#39;);<br><br>// Set views directory<br>app.set(&#39;views&#39;, path.join(__dirname, &#39;templates&#39;, &#39;emails&#39;));<br><br>// Nodemailer transporter setup (covered in the next section)<br><br>app.get(&#39;/send-welcome&#39;, async (req, res) =&gt; {<br>  try {<br>    const user = {<br>      name: &#39;John Doe&#39;,<br>      email: &#39;johndoe@example.com&#39;,<br>    };<br><br>    // Render email template<br>    const html = await res.render(&#39;welcome&#39;, { user });<br><br>    // Send email using Nodemailer<br>    // (Nodemailer setup will be covered in the next section)<br>  } catch (error) {<br>    console.error(&#39;Error sending email:&#39;, error);<br>    res.status(500).send(&#39;Internal Server Error&#39;);<br>  }<br>});<br><br>const PORT = 3000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}`);<br>});</pre><h3>4. Setting Up Nodemailer for Sending Emails</h3><h3>4.1 Installing and Configuring Nodemailer</h3><p>Install the Nodemailer package:</p><pre>npm install nodemailer</pre><p>In your index.js file, set up Nodemailer by creating a transporter:</p><pre>const transporter = nodemailer.createTransport({<br>  service: &#39;Gmail&#39;, // Update with your email service provider<br>  auth: {<br>    user: &#39;your-email@gmail.com&#39;,<br>    pass: &#39;your-password&#39;, // Use an &quot;App Password&quot; for security<br>  },<br>});</pre><h3>4.2 Creating Email Transporter</h3><p>Nodemailer provides various transport options, such as SMTP, Sendmail, and more. In this example, we’re using Gmail’s SMTP service.</p><h3>4.3 Handling SMTP Configuration</h3><p>Configure your Gmail account to allow “Less secure apps” and generate an “App Password” for Node.js. This password will be used in the auth.pass field when creating the transporter.</p><h3>5. Combining Express Handlebars and Nodemailer</h3><h3>5.1 Rendering Email Templates with Dynamic Data</h3><p>In the previous section, we’ve demonstrated how to render Express Handlebars templates with dynamic data. The rendered HTML can now be used as the email content.</p><h3>5.2 Generating HTML Content from Templates</h3><p>Use the rendered HTML to generate the email’s HTML content:</p><pre>app.get(&#39;/send-welcome&#39;, async (req, res) =&gt; {<br>  try {<br>    const user = {<br>      name: &#39;John Doe&#39;,<br>      email: &#39;johndoe@example.com&#39;,<br>    };<br><br>    // Render email template<br>    const html = await res.render(&#39;welcome&#39;, { user });<br><br>    const mailOptions = {<br>      from: &#39;your-email@gmail.com&#39;,<br>      to: user.email,<br>      subject: &#39;Welcome to Our Platform&#39;,<br>      html, // Use the rendered HTML from the template<br>    };<br><br>    // Send email using Nodemailer<br>    transporter.sendMail(mailOptions, (error, info) =&gt; {<br>      if (error) {<br>        console.error(&#39;Error sending email:&#39;, error);<br>        res.status(500).send(&#39;Error sending email&#39;);<br>      } else {<br>        console.log(&#39;Email sent:&#39;, info.response);<br>        res.send(&#39;Email sent successfully&#39;);<br>      }<br>    });<br>  } catch (error) {<br>    console.error(&#39;Error sending email:&#39;, error);<br>    res.status(500).send(&#39;Internal Server Error&#39;);<br>  }<br>});</pre><h3>6. Advanced Techniques</h3><h3>6.1 Using Layouts for Consistent Email Design</h3><p>Maintain a consistent email design by using layouts. Create a layout handlebars file and extend it in your email templates.</p><h3>6.2 Including Images and Attachments</h3><p>Nodemailer allows you to attach images and files to your emails, enhancing the visual appeal and functionality of your email content.</p><h3>6.3 Localization and Multi-language Support</h3><p>For multi-language applications, utilize template engines to generate emails in different languages by passing appropriate data to the templates.</p><h3>7. Best Practices for Email Template Design</h3><h3>7.1 Keeping Emails Responsive</h3><p>Ensure your email templates are responsive and display correctly on various devices and email clients.</p><h3>7.2 Testing Across Email Clients</h3><p>Test your emails across different email clients to ensure consistent rendering and functionality.</p><h3>7.3 Including Unsubscribe and Contact Information</h3><p>Follow best practices by including options for users to unsubscribe and providing contact information for support.</p><h3>8. Security Considerations</h3><h3>8.1 Protecting Sensitive Data</h3><p>Safeguard sensitive data such as email credentials and passwords by storing them securely and not exposing them in your codebase.</p><h3>8.2 Preventing Email Injection</h3><p>Prevent email injection attacks by sanitizing user-generated content before rendering it in email templates.</p><h3>9. Putting It All Together: Sending Welcome Emails</h3><h3>9.1 Creating a Welcome Email Template</h3><p>Craft a personalized welcome email template that includes a warm greeting and essential information for new users.</p><h3>9.2 Sending Welcome Emails to New Users</h3><p>Use the Nodemailer transporter and the Express Handlebars template engine to send tailored welcome emails to new users upon registration.</p><h3>10. Conclusion</h3><p>In this guide, you’ve learned how to effectively utilize the Express Handlebars template engine and the Nodemailer library to generate and send dynamic email templates in a Node.js application. By integrating these technologies, you can provide engaging and personalized email communication to your users. Explore further by experimenting with various template designs, advanced features, and expanding your email functionality.</p><p>This detailed guide provides step-by-step instructions for combining Express Handlebars and Nodemailer to create dynamic email templates and send them in a Node.js environment. Feel free to adapt and expand the content to suit your specific use case and requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d6174da73b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>