<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[HasabTech]]></title><description><![CDATA[HasabTech is a learning focused blog sharing practical tutorials, coding guides, and developer insights to help you grow your skills and build real-world softwa]]></description><link>https://getting-started-with-nestjs.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 17 Sep 2026 20:23:51 GMT</lastBuildDate><atom:link href="https://getting-started-with-nestjs.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Modules Re-Exporting in NestJS]]></title><description><![CDATA[Introduction
In previous blogs, we learned how to export providers (like CatsService) from one module and then import them into another module. This is the standard way to share services across different parts of your NestJS application.
But what if ...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/modules-re-exporting-in-nestjs</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/modules-re-exporting-in-nestjs</guid><category><![CDATA[backend]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Wed, 05 Nov 2025 11:05:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1757270708849/71fcfc34-5ad4-4b16-8c94-b121cb5439a7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>In previous blogs, we learned how to <strong>export providers</strong> (like <code>CatsService</code>) from one module and then <strong>import them into another module</strong>. This is the standard way to share services across different parts of your NestJS application.</p>
<p>But what if we want to go one step further?<br />Instead of importing from the original module every time, we can <strong>re-export a module</strong>. This makes it possible to access the same providers indirectly through another module.</p>
<h3 id="heading-what-is-module-re-exporting">What is Module Re-Exporting?</h3>
<p>Module re-exporting works like a chain. Think of it like a math formula:</p>
<p><code>A = B = C</code></p>
<p>Here’s how it works in NestJS:</p>
<ol>
<li><p>We export something from Module A (<code>CatsModule</code>).</p>
</li>
<li><p>We import it into Module B (<code>RequestModule</code>).</p>
</li>
<li><p>Then, we export the same thing again from Module B.</p>
</li>
<li><p>Now, Module C (<code>ResponseModule</code>) can just import Module B and automatically get access to the providers from Module A.</p>
</li>
</ol>
<p>So essentially, re-exporting allows us to “<strong>forward</strong>” dependencies from one module to another, creating a dependency chain.</p>
<h3 id="heading-step-1-exporting-from-catsmodule">Step 1: Exporting from CatsModule</h3>
<p>We start by exporting the <code>CatsService</code> from <code>CatsModule</code>:</p>
<pre><code class="lang-typescript">javsascript
<span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;
<span class="hljs-keyword">import</span> { CatsController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.controller'</span>;

<span class="hljs-meta">@Module</span>({
  controllers: [CatsController],
  providers: [CatsService],
  <span class="hljs-built_in">exports</span>: [CatsService], <span class="hljs-comment">// 👈 exported</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CatsModule {}
</code></pre>
<h3 id="heading-step-2-import-and-re-export-in-requestmodule">Step 2: Import and re-export in RequestModule</h3>
<p>Now, instead of just using <code>CatsService</code> inside <code>RequestModule</code>, we also <strong>re-export</strong> it:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { RequestController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./request.controller'</span>;
<span class="hljs-keyword">import</span> { CatsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'../cats/cats.module'</span>;

<span class="hljs-meta">@Module</span>({
  controllers: [RequestController],
  imports: [CatsModule],   <span class="hljs-comment">// 👈 imported from CatsModule</span>
  <span class="hljs-built_in">exports</span>: [CatsModule],   <span class="hljs-comment">// 👈 re-exported to other modules</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> RequestModule {}
</code></pre>
<h3 id="heading-step-3-import-request-module-in-response-module">Step 3: Import request module in response module</h3>
<p>Finally, in <code>ResponseModule</code>, we don’t need to import <code>CatsModule</code> directly. Instead, we just import <code>RequestModule</code>, and we’ll automatically have access to <code>CatsService</code> because it was re-exported.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { ResponseController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./response.controller'</span>;
<span class="hljs-keyword">import</span> { RequestModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'../request/request.module'</span>;

<span class="hljs-meta">@Module</span>({
  controllers: [ResponseController],
  imports: [RequestModule], <span class="hljs-comment">// 👈 gets CatsService via re-export</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ResponseModule {}
</code></pre>
<h3 id="heading-using-the-service-in-controllers">Using the Service in Controllers</h3>
<pre><code class="lang-typescript"><span class="hljs-comment">// request.controller.ts</span>
<span class="hljs-keyword">import</span> { Controller, Get } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../cats/cats.service'</span>;

<span class="hljs-meta">@Controller</span>(<span class="hljs-string">'request'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> RequestController {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> catsService: CatsService</span>) {}

  <span class="hljs-meta">@Get</span>()
  findAll() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.findAll();
  }
}
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// response.controller.ts</span>
<span class="hljs-keyword">import</span> { Controller, Get } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../cats/cats.service'</span>;

<span class="hljs-meta">@Controller</span>(<span class="hljs-string">'response'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ResponseController {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> catsService: CatsService</span>) {}

  <span class="hljs-meta">@Get</span>()
  findAll() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.findAll();
  }
}
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Module re-exporting in NestJS is a powerful way to <strong>share providers across multiple modules without repeatedly importing the original module</strong>.<br />You export a provider from one module, import and re-export it in another, and then any module that imports the second one automatically gets access.</p>
<p>Think of it as <strong>forwarding dependencies</strong> — simple but effective for keeping your code organised in large applications.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=O71Aeqbv3cc&amp;list=PLgKb0PcT0J0SaWTrS4ZY8ATMaqLeSXgM7&amp;index=13">https://www.youtube.com/watch?v=O71Aeqbv3cc&amp;list=PLgKb0PcT0J0SaWTrS4ZY8ATMaqLeSXgM7&amp;index=13</a></p>
<p>Follow us for more such content:</p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech">https://www.linkedin.com/company/hasabtech</a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Create and Use Global Modules in NestJS]]></title><description><![CDATA[Recap from Previous Blog
In our previous blog, we learned that when working inside the CatsModule, if we want to use a provider (dependency) in another module, the standard approach is to export it from cats.module.ts and then import it into the targ...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/how-to-create-and-use-global-modules-in-nestjs</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/how-to-create-and-use-global-modules-in-nestjs</guid><category><![CDATA[backend]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Thu, 25 Sep 2025 11:12:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756216212160/6b9c27c5-b791-4253-b369-9177d1552868.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-recap-from-previous-blog">Recap from Previous Blog</h3>
<p>In our previous blog, we learned that when working inside the <code>CatsModule</code>, if we want to use a provider (dependency) in another module, the standard approach is to <strong>export it from</strong> <code>cats.module.ts</code> and then <strong>import it into the target module</strong>. This is the preferred way of reusing dependencies across modules.</p>
<p>However, there’s another way: we can make an entire module a <strong>Global Module</strong>.</p>
<h3 id="heading-introducing-global-modules">Introducing Global Modules</h3>
<p>When you mark a module as global, you don’t have to manually import it into every other module where you want to use its providers. Instead, NestJS automatically makes its services available throughout the application.</p>
<p>To achieve this, you simply:</p>
<ol>
<li><p>Import <code>Global</code> from <code>@nestjs/common</code>.</p>
</li>
<li><p>Place <code>@Global()</code> decorator right above the <code>@Module()</code> decorator.</p>
</li>
</ol>
<p>This will make the <code>CatsModule</code> global, so it will now be registered in the global scope. That means we no longer need to import the <code>CatsModule</code> anywhere else. However, one important thing to remember is that whatever dependency you want to share must be explicitly exported, otherwise it won’t be available globally.</p>
<p>Here’s how it looks in code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Global, Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;
<span class="hljs-keyword">import</span> { CatsController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.controller'</span>;

@Global()
@Module({
  <span class="hljs-attr">controllers</span>: [CatsController],
  <span class="hljs-attr">providers</span>: [CatsService],
  <span class="hljs-attr">exports</span>: [CatsService],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsModule</span> </span>{}
</code></pre>
<p>Now, let’s move into the <code>RequestModule</code>. Previously, we imported <code>CatsModule</code> manually. But since <code>CatsModule</code> is now global, we don’t need to import it here anymore:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { RequestController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./request.controller'</span>;

@Module({
  <span class="hljs-attr">controllers</span>: [RequestController],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestModule</span> </span>{}
</code></pre>
<p>Then in the <code>RequestController</code>, we can directly use the <code>CatsService</code> (from <code>CatsModule</code>) without any errors. If you run the application, you’ll notice everything works fine and we have only <strong>one instance</strong> of the service shared globally — this is the main benefit of making a module global.</p>
<h3 id="heading-what-happens-without-global">What Happens Without @Global</h3>
<p>But let’s say we remove the <code>@Global()</code> decorator. Now the module is no longer global, and if we try to use <code>CatsService</code> in the <code>RequestModule</code> without importing it, we’ll get an error. In that case, we need to import it manually again, just like we learned earlier:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { RequestController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./request.controller'</span>;
<span class="hljs-keyword">import</span> { CatsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.module'</span>;

@Module({
  <span class="hljs-attr">controllers</span>: [RequestController],
  <span class="hljs-attr">imports</span>: [CatsModule],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestModule</span> </span>{}
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>So the takeaway is: If there’s a dependency you want to use across multiple modules, you can make the module global. But as mentioned earlier, this is <strong>not the preferred way</strong>. It’s generally better practice to import modules explicitly wherever you need them, to keep your application structure more clear and maintainable.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=VicWxW0RfT0">https://www.youtube.com/watch?v=VicWxW0RfT0</a></p>
<p>Follow us for more such content:</p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech">https://www.linkedin.com/company/hasabtech</a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[What is Modules in NestJS]]></title><description><![CDATA[Understanding Modules in NestJS
In this blog, we will discuss an essential concept in NestJS; Modules.
So far, we have been using the main module to register controllers and providers but we have not specifically explored what a module actually is in...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/what-is-modules-in-nestjs</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/what-is-modules-in-nestjs</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[backend]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Wed, 24 Sep 2025 18:36:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756238244653/f58588c6-1a3c-4298-bf97-b7459e1ea7a9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-understanding-modules-in-nestjs"><strong>Understanding Modules in NestJS</strong></h2>
<p>In this blog, we will discuss an essential concept in NestJS; Modules.</p>
<p>So far, we have been using the main module to register controllers and providers but we have not specifically explored what a module actually is in NestJS.</p>
<h2 id="heading-what-is-a-module"><strong>What is a Module?</strong></h2>
<p>A module in NestJS is a class annotated with the <code>@Module()</code> decorator. This decorator accepts an object with four properties:</p>
<ol>
<li><p>imports for importing other modules.</p>
</li>
<li><p>exports for exporting providers to other modules.</p>
</li>
<li><p>controllers for declaring route handlers.</p>
</li>
<li><p>providers for declaring the services or providers used in the module.</p>
</li>
</ol>
<p>providers for declaring the services or providers used in the module.</p>
<p>You have likely seen the last two (controllers and providers) used frequently, but the full structure gives us more flexibility and modularity in our application.</p>
<h2 id="heading-when-should-you-create-a-module"><strong>When should you create a Module?</strong></h2>
<p>You should create a new module when you want to encapsulate a set of closely related features. For example:</p>
<p>A UserModule might contain a UserController and a UserService.</p>
<p>An AlbumModule might contain an AlbumController and an AlbumService.</p>
<p>This structure helps you organise your codebase in a modular and scalable way.</p>
<pre><code class="lang-javascript">nest generate <span class="hljs-built_in">module</span> users
</code></pre>
<p>This command automatically creates a new module file, which you can then connect with the relevant controller and service</p>
<h2 id="heading-registering-modules"><strong>Registering Modules</strong></h2>
<p>Once you have created multiple feature modules (e.g., UserModule, AlbumModule), you must register them in the imports array of the root module:</p>
<pre><code class="lang-javascript">@Module({
   @Module({
   <span class="hljs-attr">imports</span> : [CatsModule, RequestModule, ResponseModule, RedirectModule]})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppModule</span> </span>{}
</code></pre>
<h2 id="heading-creating-a-module-in-nestjs-example-with-catsmodule"><strong>Creating a Module in NestJS: Example with CatsModule</strong></h2>
<p>In our cats folder, we have a file named <code>cats.module.ts</code>. Let’s walk through what we have done here and why it matters.</p>
<h3 id="heading-step-by-step-breakdown"><strong>Step-by-Step Breakdown</strong></h3>
<p>First, we import the necessary items from NestJS:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;
<span class="hljs-keyword">import</span> { CatsController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.controller'</span>;
</code></pre>
<h3 id="heading-creating-and-exporting-the-module"><strong>Creating and Exporting the Module</strong></h3>
<p>Next, we define and export a class named <code>CatsModule</code></p>
<pre><code class="lang-javascript">@Module({
  <span class="hljs-attr">controllers</span>: [CatsController],
  <span class="hljs-attr">providers</span>: [CatsService],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsModule</span> </span>{}
</code></pre>
<p>In NestJS, modules are not shared automatically across the app. If you want to use a provider from one module in another module, you need to:</p>
<ol>
<li><p>Export it from the source module.</p>
</li>
<li><p>Import the source module into the destination module.</p>
</li>
</ol>
<pre><code class="lang-javascript">@Module({
  <span class="hljs-attr">providers</span>: [CatsService],
  <span class="hljs-attr">exports</span>: [CatsService], <span class="hljs-comment">// 👈 This makes it available to other modules</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsModule</span> </span>{}
</code></pre>
<p>In our <code>CatsModule</code>, we’ve created a service (<code>CatsService</code>) and a controller (<code>CatsController</code>). Here's the basic module structure:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;
<span class="hljs-keyword">import</span> { CatsController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.controller'</span>;

@Module({
  <span class="hljs-attr">controllers</span>: [CatsController],
  <span class="hljs-attr">providers</span>: [CatsService],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsModule</span> </span>{}
</code></pre>
<p>Now, if we run the application, you will notice the following:</p>
<p>NestJS first creates an instance of <code>CatsService</code>.</p>
<p>Then it creates an instance of <code>CatsController</code>.</p>
<p>This happens because <code>CatsController</code> depends on <code>CatsService</code>. So NestJS resolves dependencies from the bottom up. If a service depends on another service, that chain is resolved from the lowest level first ensuring everything is ready before the controller is instantiated.</p>
<p>Here’s how we inject the <code>CatsService</code> into the controller:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">constructor</span>(private readonly catsService: CatsService) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'CatsController instance created'</span>);
}
</code></pre>
<p>This is standard NestJS Dependency Injection (DI). The framework automatically injects the service instance into the controller.</p>
<p>When you add a service to the providers array of a module, NestJS creates a single instance (singleton) of that service:</p>
<p>This single instance is shared across all controllers in the same module.</p>
<p>That’s the core idea of the singleton pattern one shared instance per provider per module.</p>
<p>So, even if multiple controllers depend on <code>CatsService</code>, they will all receive the same instance.</p>
<p>Now, let’s say you try to use <code>CatsService</code> in another controller (e.g., in a RequestController inside RequestModule) like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">constructor</span>(private readonly catsService: CatsService) {}
</code></pre>
<p>If you run the application without importing <code>CatsModule</code>, you’ll get an error like:<br /><em>Nest can't resolve dependencies of the RequestController (...) CatsService at index [0]</em>  </p>
<p>This means that <code>CatsService</code> is not available in the context of RequestModule.<br />NestJS modules are self contained by default. The scope of a provider is limited to the module where it is declared, unless you explicitly export it.</p>
<p>To fix the above error follow these steps:</p>
<p><strong>Step 1</strong>: Export the Service from <code>CatsModule</code>:</p>
<pre><code class="lang-javascript">@Module({
  <span class="hljs-attr">controllers</span>: [CatsController],
  <span class="hljs-attr">providers</span>: [CatsService],
  <span class="hljs-attr">exports</span>: [CatsService], <span class="hljs-comment">// 👈 This allows other modules to use it</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsModule</span> </span>{}
</code></pre>
<p><strong>Step 2:</strong> Import <code>CatsModule</code> into <code>RequestModule</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { RequestController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./request.controller'</span>;
<span class="hljs-keyword">import</span> { CatsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'src/cats/cats.module'</span>;

@Module({
  <span class="hljs-attr">controllers</span>: [RequestController],
  <span class="hljs-attr">imports</span>: [CatsModule], <span class="hljs-comment">// 👈 Import the whole module, not just the service</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestModule</span> </span>{}
</code></pre>
<p>Now NestJS can resolve the dependency, and <code>CatsService</code> will be available in <code>RequestController</code>.</p>
<p>NestJS resolves dependencies from bottom to top resolving providers before controllers.</p>
<p>Providers in NestJS are singleton by default shared within the module.</p>
<p>A provider’s scope is limited to its module unless it is exported.</p>
<p>To use a provider in another module:</p>
<ol>
<li><p>Export it from the source module.</p>
</li>
<li><p>Import the entire module (not just the provider) into the destination module.</p>
</li>
</ol>
<p>This behaviour makes modules self-contained and reusable.</p>
<h3 id="heading-wrapping-up"><strong>Wrapping Up</strong></h3>
<p>We now understand how modules encapsulate their providers and controllers, how singleton services work, and how to properly share services between modules using exports and imports. In the future blog, we’ll explore custom provider scopes like Request, Transient, and how to build global modules.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=D83bP3mfXWE&amp;list=PLgKb0PcT0J0SaWTrS4ZY8ATMaqLeSXgM7&amp;index=11">https://www.youtube.com/watch?v=D83bP3mfXWE&amp;list=PLgKb0PcT0J0SaWTrS4ZY8ATMaqLeSXgM7&amp;index=11</a></p>
<p>Follow us for more such content:</p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech">https://www.linkedin.com/company/hasabtech</a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[What is Inversion Of Control?]]></title><description><![CDATA[Introduction
In our previous blog we explored in detail how to implement Dependency Injection and understood its role in creating loosely coupled and more maintainable code. As we discovered there are multiple ways to implement Dependency Injection, ...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/what-is-inversion-of-control</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/what-is-inversion-of-control</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[backend]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Tue, 23 Sep 2025 14:26:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756237723088/d6e067a7-df1e-4210-bf76-b2946c78b9b3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>In our previous blog we explored in detail how to implement Dependency Injection and understood its role in creating loosely coupled and more maintainable code. As we discovered there are multiple ways to implement Dependency Injection, something we will delve into in future blogs.</p>
<p>In this blog, our focus shifts to a closely related but often misunderstood concept: “Inversion of Control”.</p>
<h2 id="heading-what-is-inversion-of-control"><strong>What is Inversion of Control?</strong></h2>
<p>Inversion of Control is a design principle, not a design pattern and this distinction is crucial. While the terms are sometimes used interchangeably they represent different aspects of software design.<br />In traditional programming, your classes or modules are in charge of creating and managing their own dependencies. However with Inversion of control is inverted an external entity, such as a framework or container takes over the responsibility of providing those dependencies. This shift of responsibility leads to better code reusability, testing, and decoupling.</p>
<h2 id="heading-design-principles-vs-design-patterns"><strong>Design Principles vs. Design Patterns</strong></h2>
<p>Let’s pause for a moment to clear up a common confusion: the difference between design principles and design patterns.</p>
<p>A design principle is a high-level guideline or best practice that helps developers design robust software systems. It is conceptual and theoretical, focusing on how to approach a problem.</p>
<p>A design pattern, on the other hand, is a low-level, practical solution to a recurring programming problem. It provides a specific structure or template that you can use to solve implementation challenges.</p>
<p>In simpler terms:</p>
<p>Design principles guide how to think, while design patterns show how to build.</p>
<h2 id="heading-a-real-life-example"><strong>A real life example</strong></h2>
<p>To understand the concept of dependency, let’s consider a few simple real-world examples.</p>
<p>In everyday language, the word "dependency" means something you rely on. For instance, you depend on your laptop to do your work — this makes the laptop your dependency.</p>
<p>Now let’s take the example of a car. A car depends on many components to function — such as an engine, wheels, doors, windows, and more. Among them, the engine is a crucial part. So, we can say:</p>
<p>The engine is a dependency of the car.</p>
<p>In object-oriented programming, if you're building a Car class, you’ll need to create objects for each of these components. That means you are manually managing the dependencies inside your class. This tight coupling makes your code complex and harder to modify.</p>
<p>For example, if you want to:</p>
<ul>
<li><p>change the engine type</p>
</li>
<li><p>update the tire size,</p>
</li>
<li><p>adjust the window color,</p>
</li>
<li><p>replace the car's color</p>
</li>
</ul>
<p>you’d need to modify the Car class directly. This results in a tightly coupled system where every small change requires direct modifications violating good software design practices.</p>
<p>The goal in modern software engineering is to build loosely coupled systems and that’s where the concept of Inversion of Control comes in.</p>
<p>In the traditional approach, the code controls the creation of dependencies, but Inversion of Control shifts this responsibility away from your class and hands it over to an external entity in our case, the NestJS framework.</p>
<p>So instead of manually creating and managing all the dependencies inside the Car class (or any other class), you delegate that control to the framework.</p>
<p>This concept of transferring control of dependency management from your code to the framework is called Inversion of Control, and in NestJS, it is achieved through Dependency Injection.</p>
<h2 id="heading-applying-inversion-of-control-in-nestjs-with-dependency-injection"><strong>Applying Inversion of Control in NestJS (with Dependency Injection)</strong></h2>
<p>Let’s look at how NestJS handles Inversion of Control using Dependency Injection with a simple example.<br /><code>CatsController</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@injectable()
<span class="hljs-keyword">import</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatService</span> </span>{
    private readonly cats: string [] = []; 

    create(cat:string) {
        <span class="hljs-built_in">this</span>.cats.push.(cat);
    }
    findAll() : string [] {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.cats;
    }
}
</code></pre>
<p>Here we define a <code>CatsService</code> and mark it with the <code>@Injectable()</code> decorator. This tells NestJS that this service can be injected as a dependency into other components like controllers.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Controller, Post, Body, Get, } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;

@Controller(<span class="hljs-string">'cats'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsController</span> </span>{
    <span class="hljs-keyword">constructor</span> (private readonly catsService: CatsService) }


@Post()
async create (@Body() cat:any){
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'cat'</span>, cat);
    <span class="hljs-built_in">this</span>.catsService.create(cat);
}
@Get()
<span class="hljs-keyword">async</span> findAll() : <span class="hljs-built_in">Promise</span>&lt;any[]&gt;{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.findAll();
}
</code></pre>
<p>In the controller, we inject the CatsService through the constructor. This is a clear example of Dependency Injection rather than creating a new instance of the service manually, NestJS provides it automatically.</p>
<p>By using the <code>@Injectable()</code> and constructor pattern, NestJS manages the lifecycle and creation of the <code>CatsService</code> for us.</p>
<p>This is a real world example of Inversion of Control we are no longer manually controlling how the service is created or used. Instead, NestJS takes over that control.</p>
<p>This makes our code more modular, testable, and maintainable.</p>
<h2 id="heading-registering-dependencies-in-the-module"><strong>Registering Dependencies in the Module</strong></h2>
<p>In NestJS, you cannot inject a class (like a service) into a controller unless it’s registered as a provider within a module. This registration allows NestJS to manage the class through its Inversion of Control (IoC) container.</p>
<p>Let’s look at the module definition:</p>
<pre><code class="lang-javascript">@Module({
    <span class="hljs-attr">controllers</span> : [CatsController],
    <span class="hljs-attr">provider</span> : [CatsService],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppModule</span> </span>{}
</code></pre>
<p>In the AppModule, we list CatsService under the providers array.</p>
<p>By doing this, we are telling NestJS to create and manage the instance of <code>CatsService</code> within its IoC container.</p>
<p>Once registered, <code>CatsService</code> becomes available for injection into other parts of the application like the <code>CatsController</code>.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this blog, we explored the concept of Inversion of Control (IoC) and how it's implemented in NestJS using Dependency Injection (DI).</p>
<p>We began by understanding what dependency means using simple real-life examples and explained how managing dependencies manually can lead to tightly coupled and hard-to-maintain code.</p>
<p>Inversion of Control helps solve this by shifting the responsibility of dependency management from your code to the framework. In NestJS, this is achieved through Dependency Injection, a design pattern that allows the framework to supply required services (or other dependencies) into your components.</p>
<p>We also learned that in order to inject any service into a controller, it must first be registered as a provider in a module. Once registered, NestJS uses its built-in IoC container to create and manage instances of that service behind the scenes.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=U0LGQjxyuw8">https://www.youtube.com/watch?v=U0LGQjxyuw8</a></p>
<p>Follow us for more such content:</p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech">https://www.linkedin.com/company/hasabtech</a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[How Dependency Injection Works in NestJS]]></title><description><![CDATA[Introduction
In our previous blog we explored specific library responses in NestJS. Now it’s time to dive into one of the framework’s most powerful and core concepts: Providers specifically Services.
Understanding Dependency Injection
Before we go de...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/how-dependency-injection-works-in-nestjs</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/how-dependency-injection-works-in-nestjs</guid><category><![CDATA[backend]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Mon, 22 Sep 2025 13:37:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756237334240/f3e319e2-3029-469f-ba02-a1d213a38bbe.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>In our previous blog we explored specific library responses in NestJS. Now it’s time to dive into one of the framework’s most powerful and core concepts: Providers specifically Services.</p>
<h2 id="heading-understanding-dependency-injection"><strong>Understanding Dependency Injection</strong></h2>
<p>Before we go deeper into how services work, let’s first understand a foundational concept behind them Dependency Injection.<br />As the name suggests, Dependency Injection refers to the process of providing (or injecting) dependencies into a class rather than creating them manually. In NestJS, this pattern allows us to inject services into controllers.<br />Let’s consider a simple example: a Car and an Engine. The Car depends on the Engine to work.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Engine</span> </span>{
    <span class="hljs-keyword">constructor</span>(type) {
        <span class="hljs-built_in">this</span>.type = type;
    }

    start() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">`The <span class="hljs-subst">${<span class="hljs-built_in">this</span>.type}</span> engine is starting...`</span>;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.engine = <span class="hljs-keyword">new</span> Engine(<span class="hljs-string">'V8'</span>); <span class="hljs-comment">// tightly coupled</span>
    }

    startEngine() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.engine.start();
    }
}
</code></pre>
<p>In the non-dependency injection example, the <code>Car</code> class creates its own <code>Engine</code>, which means it is tightly coupled to a specific engine type. This tight connection makes your code rigid if you want to change the <code>Engine</code> class, you will likely need to update the <code>Car</code> class as well.<br />With Dependency Injection, we solve this problem by injecting the dependency (e.g., Engine or a service) from the outside, rather than creating it inside the class. This allows your classes (like controllers) to remain loosely coupled with the services they use.</p>
<h2 id="heading-making-a-class-injectable"><strong>Making a Class Injectable</strong></h2>
<p>In order to make a class injectable, we use the <code>@Injectable()</code> decorator provided by the NestJS framework. This tells NestJS that the class can be managed by its Dependency Injection system.</p>
<p>Here’s an example using a simple service class called <code>CatService</code>. This service manages a list of cat names. We declare a private and readonly cats array to store string values. Then we define two methods:</p>
<p><code>create()</code> to add a single cat name to the array.</p>
<p><code>findAll()</code> to return the complete list of cat names.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@injectable()
<span class="hljs-keyword">import</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatService</span> </span>{
    private readonly cats: string [] = []; 

    create(cat:string) {
        <span class="hljs-built_in">this</span>.cats.push.(cat);
    }
    findAll() : string [] {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.cats;
    }
}
</code></pre>
<p>Now that we have defined our <code>CatService</code>, let's inject it into a controller so we can use its methods to handle incoming HTTP requests.</p>
<p>To do this, we follow three simple steps:</p>
<p>Import the service.</p>
<ol>
<li><p>Import the service.</p>
</li>
<li><p>Decorate the controller with <code>@Controller()</code>.</p>
</li>
<li><p>Inject the service via the constructor using NestJS Dependency Injection system.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Controller, Post, Body } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;

@Controller(<span class="hljs-string">'cats'</span>)
<span class="hljs-keyword">import</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsController</span> </span>{
    <span class="hljs-keyword">constructor</span> (private readonly catsService: CatsService) }
</code></pre>
<p>After creating the service, we now use it inside our controller to handle incoming POST requests. Here’s how we define the method:</p>
<pre><code class="lang-javascript">@Post()
<span class="hljs-keyword">async</span> create (@Body() cat:any){
    <span class="hljs-built_in">this</span>.catsService.create(cat);
}
}
</code></pre>
<p><code>@Post()</code> is a route handler decorator, It tells NestJS that the following method should handle HTTP POST requests.<br /><code>@Body()</code> is a parameter decorator, It tells NestJS to extract the data from the body of the incoming request.</p>
<p>To verify that we’re correctly receiving the data in our controller, let’s add a simple log inside our create() method:</p>
<pre><code class="lang-javascript">@Post()
<span class="hljs-keyword">async</span> create (@Body() cat:any){
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'cat'</span>, cat);
    <span class="hljs-built_in">this</span>.catsService.create(cat);
}
</code></pre>
<p>Now, when you send a POST request via Postman (e.g., to <a target="_blank" href="http://localhost:3000/cats">http://localhost:3000/cats</a>), you should see the request body logged in your terminal. If you encounter an error like this when running your app:</p>
<p><code>Nest can't resolve dependencies of the CatsController (?). Please make sure that the argument CatsService at index [0] is available in the AppModule context.</code></p>
<h3 id="heading-heres-how-to-fix-it">Here’s how to fix it...</h3>
<p>In NestJS, you can not simply create a service and expect it to work automatically even if you have imported it.<br />For a service to be usable, you must explicitly register it as a provider in the relevant module — usually in AppModule.</p>
<p>Let’s take a look at how to do that.</p>
<p>In your <code>app.module.ts</code> file, add your controller and service like this</p>
<pre><code class="lang-javascript">controllers : [
    CatsController,
    RequestController,
    ResponseController,
    RedirectController,

],
<span class="hljs-attr">providers</span>: [CatsService]
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppModule</span> </span>{}
</code></pre>
<p>NestJS uses Dependency Injection and needs to know which services are available in the current module. Remember, services and controllers are just regular TypeScript classes what makes them behave differently is the decorator you apply <code>@Injectable()</code> for services and <code>@Controller()</code> for <code>controllers</code>. Decorators add the necessary metadata to tell NestJS how to use these classes.</p>
<p>So once your service is created, injected, and registered as a provider, you will be able to send a POST request from Postman to your controller and see it working with the request body successfully logged and handled. In future blogs we will explore how to organize services and controllers using separate modules making your application more scalable and maintainable.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>we explored how Dependency Injection works in NestJS, focusing specifically on how to inject a Service (Provider) into a Controller. We learned how <code>@Injectable()</code> and <code>@Controller()</code> decorators help NestJS recognize and manage these classes, and how important it is to register services in the module's providers array to avoid dependency resolution errors. This structure enables loosely coupled, maintainable, and testable code which is one of the major strengths of the NestJS framework.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=ZCbGVoqAEX0">https://www.youtube.com/watch?v=ZCbGVoqAEX0</a></p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Handle Custom Responses and Headers in NestJS with @Res]]></title><description><![CDATA[In the previous blog, we discussed how to modify HTTP status codes and headers while sending responses to the client. In this post, we'll explore another approach: Modifying headers manually in a NestJS controller using @Res() — similar to how it's d...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/how-to-handle-custom-responses-and-headers-in-nestjs-with-res</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/how-to-handle-custom-responses-and-headers-in-nestjs-with-res</guid><category><![CDATA[backend]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Tue, 26 Aug 2025 14:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754392471932/54bdf279-99f8-405f-898f-2cd0e2500d98.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the previous blog, we discussed how to modify HTTP status codes and headers while sending responses to the client. In this post, we'll explore another approach: Modifying headers manually in a NestJS controller using @Res() — similar to how it's done in Express.js.</p>
<h2 id="heading-express-vs-nestjs-response-flow">Express vs. NestJS Response Flow</h2>
<p>NestJS, by default, handles HTTP responses for you. This means you can simply return a value from your controller, and Nest will convert it into a response, but sometimes, you might want fine-grained control, like setting custom headers or using an existing Express-style library. In such cases, you can manually handle the response.</p>
<h2 id="heading-how-to-modify-headers-with-res">How to Modify Headers with @Res( )</h2>
<p>We already learned how to intercept Express request in our controller so we imported a request like</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {Controller, Get, HttpCode, HttpStatus, Header, Request}<span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
</code></pre>
<p>we can also import a response here like with full form <code>Request</code> or short form <code>Res</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {Controller, Get, HttpCode, HttpStatus, Header, Res}<span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
</code></pre>
<p>Similarly we also import types for this particular Response from Express</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {Response} <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
</code></pre>
<p>Now Create a <code>@Get</code> Request</p>
<pre><code class="lang-javascript">Get()   
FindAll(@Res() response: Response) {
Response.status(HttpStatus.OK) .send();
}
</code></pre>
<h2 id="heading-understanding-res-res-and-response">Understanding @Res, res, and Response</h2>
<p>In this code</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {Controller, Get, HttpStatus, Res} <span class="hljs-keyword">from</span> <span class="hljs-string">"@nestjs/common"</span>;
<span class="hljs-keyword">import</span> { Response } <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;

@Controller(<span class="hljs-string">"response"</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResponseController</span> </span>{
  @Get()
  findAll(@Res() res: Response) {
    res.status(HttpStatus.OK).send();
  }
}
</code></pre>
<ul>
<li><p><code>@Res()</code> → Decorator to inject the response object</p>
</li>
<li><p><code>response</code> → A custom variable name (can also be res)</p>
</li>
<li><p><code>Response</code> → Type from express for better IntelliSense and typing</p>
</li>
</ul>
<p>So finally, we can modify our header manually and send response to our client.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>While NestJS encourages using its built-in response handling, the @Res decorator lets you leverage Express-style syntax for fine-grained control. Use this sparingly to avoid losing Nest’s powerful features.</p>
<p><strong>Note:</strong> Use manual response handling sparingly, as it bypasses features like interceptors, exception filters, and built-in decorator.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=yX0di9NBfdg">https://www.youtube.com/watch?v=yX0di9NBfdg</a></p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[Understanding HTTP Status Codes and Headers in NestJS]]></title><description><![CDATA[When building APIs with NestJS, one of the crucial aspects is handling HTTP status codes and headers in your responses.
These elements provide valuable information to clients about the outcome of their requests and help shape the behavior of the comm...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/understanding-http-status-codes-and-headers-in-nestjs</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/understanding-http-status-codes-and-headers-in-nestjs</guid><category><![CDATA[backend]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Sat, 23 Aug 2025 13:19:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754387798180/84ca6474-9836-4bbe-9ff9-49127e08f635.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When building APIs with <strong>NestJS</strong>, one of the crucial aspects is handling HTTP status codes and headers in your responses.</p>
<p>These elements provide valuable information to clients about the outcome of their requests and help shape the behavior of the communication between the server and the client.</p>
<h2 id="heading-http-status-codes">HTTP Status Codes</h2>
<p>HTTP status codes are three-digit numbers returned by the server to indicate the status of the request made by the client. NestJS makes it straightforward to set these codes in your API responses.</p>
<h2 id="heading-setting-http-status-codes">Setting HTTP Status Codes</h2>
<p>In NestJS, you can set the HTTP status code using the <code>@HttpCode</code> decorator or by directly chaining it with the response. Let's look at an example:</p>
<p>Create a new controller. I created one with the name of <code>response</code> with the help of this:</p>
<pre><code class="lang-javascript">nest g controller response
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Controller, Get, HttpCode } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Controller(<span class="hljs-string">'response'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResponseController</span> </span>{
  @Get()
  @HttpCode(<span class="hljs-number">201</span>)
  findAll() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Shameel is testing 201 response with GET request.'</span>;
  }
}
</code></pre>
<p>By default, a GET request is sent with a 200 status code.<br />In this example, the <code>@HttpCode(201)</code> decorator explicitly sets the HTTP status code to 201 OK.</p>
<p>When you test it with POSTMAN (or any other tool), you should be able to verify it.</p>
<p><img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb0y0k0urtrrdiln85tzi.png" alt="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0y0k0urtrrdiln85tzi.png (800×361)" /></p>
<h2 id="heading-common-http-status-codes">Common HTTP Status Codes</h2>
<p>Here are a few common HTTP status codes and their meanings:</p>
<ul>
<li><p><strong>200 OK:</strong> The request was successful.</p>
</li>
<li><p><strong>201 Created:</strong> The request was successful, and a new resource was created.</p>
</li>
<li><p><strong>400 Bad Request:</strong> The server could not understand the request.</p>
</li>
<li><p><strong>404 Not Found:</strong> The requested resource could not be found.</p>
</li>
</ul>
<p>Ensure to choose the appropriate status code based on the semantics of your API.</p>
<h3 id="heading-using-httpstatus-enum">Using HttpStatus Enum</h3>
<p><code>HttpStatus</code> is an Enum in which you can use proper string names; this way, you won't have to memorize status codes for the particular type of action that you are going to do.</p>
<p>All you have to do is <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/enums.html">impo</a>rt <code>HttpStatus</code> from <code>@nestjs/common</code> and then use it like this:</p>
<p><img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ficm4bui5z093c8sj6c2s.png" alt="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/icm4bui5z093c8sj6c2s.png (700×256)" /></p>
<p>If you hover over <code>CREATED</code> then you can see its actual value. That should be the case with any of the Enum and its string you use in TypeScript.</p>
<p><strong>Code Snippet:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Controller, Get, HttpCode, HttpStatus } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Controller(<span class="hljs-string">'response'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResponseController</span> </span>{
  @Get()
  @HttpCode(HttpStatus.CREATED)
  findAll() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Shameel is testing 201 response with GET request.'</span>;
  }
}
</code></pre>
<h2 id="heading-http-headers">HTTP Headers</h2>
<p>HTTP headers provide additional information about the server's response or the request being made. NestJS allows you to work with headers easily.</p>
<h2 id="heading-setting-http-headers">Setting HTTP Headers</h2>
<p>To set HTTP headers in NestJS, you can use the <code>@Header</code> decorator or directly set them using the response object. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Controller, Get, Header, Res } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Controller(<span class="hljs-string">'example'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleController</span> </span>{
  @Get()
  @Header(<span class="hljs-string">'Cache-Control'</span>, <span class="hljs-string">'no-cache'</span>) <span class="hljs-comment">// Set header using @Header decorator</span>
  findAll(@Res() response): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'This is the response body'</span>;
  }
}
</code></pre>
<p>In this example, the <code>@Header('Cache-Control', 'no-cache')</code> decorator sets the Cache-Control header to <code>'no-cache'</code>.</p>
<h2 id="heading-common-http-headers">Common HTTP Headers</h2>
<ul>
<li><p><strong>Content-Type:</strong> Specifies the media type of the resource.</p>
</li>
<li><p><strong>Cache-Control:</strong> Directs caching mechanisms in both requests and responses.</p>
</li>
<li><p><strong>Authorization:</strong> Contains credentials for authenticating the client with the server.</p>
</li>
</ul>
<p>Below is the code of a POST request handler:</p>
<pre><code class="lang-javascript">  @Post()
  @Header(<span class="hljs-string">'Cache-Control'</span>, <span class="hljs-string">'none'</span>)
  @Header(<span class="hljs-string">'X-My-Header'</span>, <span class="hljs-string">'Shameel'</span>)
  create() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Shameel is POST request with additional headers.'</span>;
  }
</code></pre>
<p>You can try it with POSTMAN like this:</p>
<p><img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffen6ajqex2g4s5eagbfb.png" alt="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fen6ajqex2g4s5eagbfb.png (800×487)" /></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding and effectively using HTTP status codes and headers in your NestJS application is crucial for building robust and reliable APIs. Whether you're indicating the success of a request or controlling caching behaviour, mastering these concepts will enhance the communication between your server and clients.</p>
<p>Remember to refer to the official NestJS documentation for more in-depth information and advanced use cases.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=v7e59lQKz6U">https://www.youtube.com/watch?v=v7e59lQKz6U</a></p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[Redirection in NestJS]]></title><description><![CDATA[Understanding HTTP Redirection: A Brief Overview
HTTP redirection is a mechanism used by web servers to instruct browsers to navigate from one URL to another. This process is crucial for various scenarios, such as when a page has permanently moved or...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/redirection-in-nestjs</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/redirection-in-nestjs</guid><category><![CDATA[Beginner Developers]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Thu, 21 Aug 2025 17:23:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754389497811/8479f65b-2899-4517-8bb9-4cc89f2618b0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-understanding-http-redirection-a-brief-overview">Understanding HTTP Redirection: A Brief Overview</h2>
<p>HTTP redirection is a mechanism used by web servers to instruct browsers to navigate from one URL to another. This process is crucial for various scenarios, such as when a page has permanently moved or when a temporary redirect is needed. Two common status codes used for redirection are 301 (Moved Permanently) and 302 (Found or Moved Temporarily).</p>
<p><strong>301 (Moved Permanently):</strong></p>
<ul>
<li><p>A 301 status code indicates that the requested resource has been permanently moved to a new location.</p>
</li>
<li><p>Browsers and search engines interpret this as a permanent change, and they update their records accordingly.</p>
</li>
<li><p>This is useful when you want to divert your traffic to your new URL.</p>
</li>
</ul>
<p><strong>302 (Found or Moved Temporarily):</strong></p>
<ul>
<li><p>A 302 status code indicates that the requested resource has been temporarily moved to a different location.</p>
</li>
<li><p>Browsers understand this as a temporary redirection and may continue to use the original URL for future requests.</p>
</li>
<li><p>This is beneficial when you need a temporary redirect, such as during maintenance or when testing a new page.</p>
</li>
</ul>
<h2 id="heading-implementing-redirection-in-nestjs">Implementing Redirection in NestJS</h2>
<p>Now, let's delve into the provided <strong>NestJS</strong> code that demonstrates how to implement redirection using these HTTP status codes.</p>
<p>Since you are following a series, your <strong>NestJS</strong> project should be up and running.</p>
<p>Create a new controller by the name of <code>redirect</code>:</p>
<pre><code class="lang-javascript">nest g controller redirect
</code></pre>
<p>Paste the following code in <code>src/redirect</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Controller, Get, Redirect } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Controller(<span class="hljs-string">'redirect'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RedirectController</span> </span>{
  @Get(<span class="hljs-string">'youtube'</span>)
  @Redirect(<span class="hljs-string">'https://www.youtube.com/@hasabTech'</span>, <span class="hljs-number">301</span>) <span class="hljs-comment">//permenant</span>
  redirectToNewUrl301() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Permenant!'</span>);
  }

  @Get(<span class="hljs-string">'github'</span>)
  @Redirect(<span class="hljs-string">'https://github.com/hasabTech'</span>, <span class="hljs-number">302</span>) <span class="hljs-comment">//temporary</span>
  redirectToTemporaryUrl302() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Temporary!'</span>);
  }
}
</code></pre>
<h2 id="heading-code-explanation">Code Explanation:</h2>
<ol>
<li><strong>Decorator Usage:</strong></li>
</ol>
<ul>
<li><p>The <code>@Controller</code> decorator is used to define a controller for handling HTTP requests related to redirection.</p>
</li>
<li><p>The <code>@Get</code> decorator specifies that the following method should handle GET requests for the specified route.</p>
</li>
</ul>
<ol start="2">
<li><strong>Redirection Implementation:</strong></li>
</ol>
<ul>
<li><p>The <code>@Redirect</code> decorator is employed to specify the target URL and the HTTP status code for redirection.</p>
</li>
<li><p>In the <code>redirectToNewUrl301</code> method, a 301 status code is used for a permanent redirect to the YouTube channel.</p>
</li>
<li><p>In the <code>redirectToTemporaryUrl302</code> method, a 302 status code is used for a temporary redirect to the GitHub profile.</p>
</li>
</ul>
<ol start="3">
<li><strong>Code Execution:</strong></li>
</ol>
<ul>
<li>It's important to note that the code block following the redirection decorator (<code>return { url: '</code><a target="_blank" href="https://www.google.com/"><code>https://www.google.com/</code></a><code>' };</code>) will be executed in 302 but not in 301.</li>
</ul>
<h2 id="heading-execution">Execution</h2>
<p>When you hit in browser:</p>
<pre><code class="lang-javascript">localhost:<span class="hljs-number">3000</span>/redirect/youtube
</code></pre>
<p>You will be navigated to our YouTube channel.</p>
<p>But, when you hit this in browser:</p>
<pre><code class="lang-javascript">localhost:<span class="hljs-number">3000</span>/redirect/github
</code></pre>
<p>Then, you would rather be re-directed to the Google page. This is because in 302, the method below <code>@Redirect()</code> is executed, so make sure that you early return it in case the method has some code which is under development so that the users can successfully (temporarily) be navigated to the updated URL.</p>
<p>Update it like this:</p>
<pre><code class="lang-javascript">@Get(<span class="hljs-string">'github'</span>)
  @Redirect(<span class="hljs-string">'https://github.com/hasabTech'</span>, <span class="hljs-number">302</span>) <span class="hljs-comment">//temporary</span>
  redirectToTemporaryUrl302() {
  <span class="hljs-keyword">return</span>
    <span class="hljs-comment">//This will be executed!</span>
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">url</span>: <span class="hljs-string">'https://www.google.com/'</span> };
  }
</code></pre>
<p>By understanding HTTP redirection and reviewing this <strong>NestJS</strong> code, developers can effectively manage URL transitions, ensuring a smooth user experience and proper handling of changes in website structure.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=lmp0mkOb6bo&amp;t=13s">https://www.youtube.com/watch?v=lmp0mkOb6bo&amp;t=13s</a></p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[NestJS Request | Param, Body, Query, Headers, IP]]></title><description><![CDATA[In NestJS, decorators are used to define metadata for various aspects of your application, including request handling. Let's break down each of the decorators for handling a NestJS Request.
1. @Param(key?: string)

Description: This decorator is used...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/nestjs-request-param-body-query-headers-ip</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/nestjs-request-param-body-query-headers-ip</guid><category><![CDATA[backend]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Sat, 16 Aug 2025 12:05:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754388954607/d6eb440b-afe9-4b89-b49f-84c235c7c26e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In NestJS, decorators are used to define metadata for various aspects of your application, including request handling. Let's break down each of the decorators for handling a NestJS Request.</p>
<h3 id="heading-1-paramkey-string">1. <code>@Param(key?: string)</code></h3>
<ul>
<li><p><strong>Description:</strong> This decorator is used to extract parameters from the request URL.</p>
<ul>
<li><p><strong>Usage:</strong> It can be applied to method parameters in a controller class to capture specific parameters from the URL.</p>
<h3 id="heading-example"><strong>Example:</strong></h3>
</li>
</ul>
</li>
</ul>
<pre><code class="lang-javascript"> @Get(<span class="hljs-string">'/param/:id'</span>)
  getParam(@Param(<span class="hljs-string">'id'</span>) id: string) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Param ID: <span class="hljs-subst">${id}</span>`</span>;
  }
</code></pre>
<p>In this example, the <code>:id</code> in the route will be captured and passed to the <code>getParam</code> method.</p>
<h3 id="heading-2-bodykey-string">2. <code>@Body(key?: string)</code></h3>
<ul>
<li><p><strong>Description:</strong> Used to extract data from the request body.</p>
<ul>
<li><p><strong>Usage:</strong> Apply it to a method parameter to receive data from the body of a POST or PUT request.</p>
<h3 id="heading-example-1"><strong>Example:</strong></h3>
</li>
</ul>
</li>
</ul>
<pre><code class="lang-javascript">   @Post()
  postBody(@Body() body: any) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Body Data: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(body)}</span>`</span>;
  }
</code></pre>
<p>This example expects a JSON object with a key <code>data</code> in the request body.</p>
<h3 id="heading-3-querykey-string">3. <code>@Query(key?: string)</code></h3>
<ul>
<li><p><strong>Description:</strong> Extracts parameters from the query string in the URL.</p>
</li>
<li><p><strong>Usage:</strong> Apply it to a method parameter to capture query parameters.</p>
<h3 id="heading-example-2"><strong>Example:</strong></h3>
</li>
</ul>
<pre><code class="lang-javascript">  @Get()
  getQuery(@Query() query: any) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Query Parameter:<span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(query)}</span>`</span>;
  }
</code></pre>
<p>If the URL is <code>/example?name=</code>hasabTech, the <code>getQuery</code> method will receive <code>{name=:hasabTech}</code></p>
<h3 id="heading-4-headersname-string">4. <code>@Headers(name?: string)</code></h3>
<ul>
<li><p><strong>Description:</strong> Extracts values from the request headers.</p>
</li>
<li><p><strong>Usage:</strong> Apply it to a method parameter to get a specific header value.</p>
<h3 id="heading-example-3"><strong>Example:</strong></h3>
<pre><code class="lang-javascript">    @Get(<span class="hljs-string">'/header/'</span>)
    getHeaders(@Headers() headers: any) {
      <span class="hljs-keyword">return</span> <span class="hljs-string">`Header: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(headers)}</span>`</span>;
    }
</code></pre>
<p>  This example extracts the value of the <code>authorization</code> header.</p>
</li>
</ul>
<h3 id="heading-5-ip">5. <code>@Ip()</code></h3>
<ul>
<li><p><strong>Description:</strong> Retrieves the client's IP address from the request.</p>
</li>
<li><p><strong>Usage:</strong> Apply it to a method parameter to get the client's IP.</p>
<h3 id="heading-example-4"><strong>Example:</strong></h3>
<pre><code class="lang-javascript">   @Get(<span class="hljs-string">'ip'</span>)
    getIp(@Ip() ip: string) {
      <span class="hljs-keyword">return</span> <span class="hljs-string">`Client IP: <span class="hljs-subst">${ip}</span>`</span>;
    }
</code></pre>
<p>  This example retrieves the IP address of the client making the request.</p>
</li>
</ul>
<h2 id="heading-complete-controller-code">Complete Controller Code</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {
  Body,
  Controller,
  Get,
  Ip,
  Param,
  Post,
  Query,
  Headers,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Controller(<span class="hljs-string">'request'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestController</span> </span>{
  @Get(<span class="hljs-string">'/param/:id'</span>)
  getParam(@Param(<span class="hljs-string">'id'</span>) id: string) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Param ID: <span class="hljs-subst">${id}</span>`</span>;
  }

  @Post()
  postBody(@Body() body: any) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Body Data: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(body)}</span>`</span>;
  }

  @Get()
  getQuery(@Query() query: any) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Query Parameter:<span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(query)}</span>`</span>;
  }

  @Get(<span class="hljs-string">'/header/'</span>)
  getHeaders(@Headers() headers: any) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Header: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(headers)}</span>`</span>;
  }

  @Get(<span class="hljs-string">'ip'</span>)
  getIp(@Ip() ip: string) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Client IP: <span class="hljs-subst">${ip}</span>`</span>;
  }
}
</code></pre>
<p>These decorators simplify the process of handling different parts of the HTTP request in your <strong>NestJS</strong> application by providing a clean and structured way to access request parameters, body, headers, IP address, and host parameters.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=0EuhRfJn0Aw&amp;embeds_referring_euri=https%3A%2F%2Fdev.to%2F&amp;source_ve_path=MjM4NTE">https://www.youtube.com/watch?v=0EuhRfJn0Aw&amp;embeds_referring_euri=https%3A%2F%2Fdev.to%2F&amp;source_ve_path=MjM4NTE</a></p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[NestJS Nested Routing, Wildcard, Request]]></title><description><![CDATA[In previous blog, we talked about about NestJS controllers and now we will be exploring a bit about nested routing, wildcard and starting with NestJS request.
NestJS Nested Routing: A Modular Approach
NestJS encourages a modular and organised structu...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/nestjs-nested-routing-wildcard-request</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/nestjs-nested-routing-wildcard-request</guid><category><![CDATA[backend]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Thu, 14 Aug 2025 22:44:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754388651314/850bce56-25b1-43c2-9e06-43dced127f93.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In previous blog, we talked about about <strong>NestJS</strong> controllers and now we will be exploring a bit about nested routing, wildcard and starting with <strong>NestJS</strong> request.</p>
<h2 id="heading-nestjs-nested-routing-a-modular-approach">NestJS Nested Routing: A Modular Approach</h2>
<p><strong>NestJS</strong> encourages a modular and organised structure for building applications. One key aspect is nested routing, where routes are organised hierarchically, mirroring the structure of your application. This approach provides clarity and maintainability, making it easier to manage the complexity of larger applications.</p>
<p>This is a simple <strong>NestJS</strong> controller:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Controller, Get, Param, Post } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Controller(<span class="hljs-string">'cats'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsController</span> </span>{
@Get()
  findAll(): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'This action returns all cats of hasabTech!'</span>;
  }
}
</code></pre>
<p>If you send GET request to <code>/cats/</code> then it will return <code>'This action returns all cats of hasabTech!'</code>.</p>
<p>In order to make nested routes within this controller for GET request handler for this case, all you have to make changes is in <code>@Get()</code> decorator to something like this:</p>
<pre><code class="lang-javascript">@Get(<span class="hljs-string">'/hasabTech/123'</span>)
</code></pre>
<p>Now you can access this route with this:</p>
<pre><code class="lang-javascript">/cats/hasabTech/<span class="hljs-number">123</span>
</code></pre>
<h2 id="heading-wildcard-routes">Wildcard Routes</h2>
<p>Wildcard routes in <strong>NestJS</strong> provide a way to capture dynamic or unpredictable segments in a URL, enabling the handling of various scenarios within a single route.</p>
<p>You can make changes like this:</p>
<pre><code class="lang-javascript">@Get(<span class="hljs-string">'/hasab*ech/'</span>)
</code></pre>
<p>Now you can access it with any character between "hasab" and "ech". For example:</p>
<pre><code class="lang-javascript">/cats/hasabTech
/cats/hasabMech
/cats/hasabRech
</code></pre>
<h2 id="heading-nestjs-request">NestJS Request</h2>
<p>In <strong>NestJS</strong>, the <code>@Req()</code> decorator is used to access the underlying Express.js request object. This decorator allows developers to tap into the details of an incoming HTTP request, gaining access to headers, parameters, and other request-specific information.</p>
<p>For better typing in TypeScript, please install this as dev dependency:</p>
<pre><code class="lang-javascript">npm install @types/express --save-dev
</code></pre>
<p>Now you need to replace the controller code with this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Controller, Get, Req } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { Request } <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;

@Controller(<span class="hljs-string">'cats'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsController</span> </span>{
  @Get()
  findAll(@Req() req: Request): string {
    <span class="hljs-built_in">console</span>.log(req);
    <span class="hljs-keyword">return</span> <span class="hljs-string">'This action returns all cats of hasabTech!'</span>;
  }
}
</code></pre>
<p>As you can see that we have added <code>@Req</code> as a decorator and when you check your terminal after hitting <code>/cats/</code>, then you will observe request object similar to <strong>Express.js</strong>.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=-7oCm3I0544">https://www.youtube.com/watch?v=-7oCm3I0544</a>  </p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[NestJS Controllers]]></title><description><![CDATA[NestJS, a progressive Node.js framework, has gained popularity for its modular and scalable architecture. One of its key components is the Controller, which plays a pivotal role in handling incoming requests and defining the application's routing log...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/nestjs-controllers</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/nestjs-controllers</guid><category><![CDATA[nestjs]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Thu, 14 Aug 2025 11:45:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754388264504/3660787a-3b06-4a6a-bff6-5631499c91b3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>NestJS</strong>, a progressive Node.js framework, has gained popularity for its modular and scalable architecture. One of its key components is the Controller, which plays a pivotal role in handling incoming requests and defining the application's routing logic. In this blog post, we will dive into the <strong>NestJS</strong> Controller and explore its routing mechanism with practical coding examples.</p>
<h2 id="heading-understanding-nestjs-controllers">Understanding NestJS Controllers</h2>
<p>Controllers in <strong>NestJS</strong> are responsible for handling incoming HTTP requests, processing them, and returning an appropriate response. They act as the bridge between the client (request) and the server (application logic). Controllers are decorated with the <code>@Controller</code> decorator, and they contain methods that handle specific routes.</p>
<p>Let's create a simple <strong>NestJS</strong> controller to illustrate the basic structure:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Controller, Get } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Controller(<span class="hljs-string">'cats'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsController</span> </span>{
  @Get()
  findAll(): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'This action returns all cats'</span>;
  }
}
</code></pre>
<p>In this example, we've created a <code>CatsController</code> decorated with <code>@Controller('cats')</code>. The argument passed to <code>@Controller</code> specifies the base route for all the methods within this controller. The <code>@Get()</code> decorator is used to define an HTTP GET route, and the <code>findAll</code> method is the handler for this route.</p>
<h2 id="heading-routing-in-nestjs">Routing in NestJS</h2>
<p><strong>NestJS</strong> follows a decorator-based approach for defining routes within controllers. Decorators are special functions prefixed with <code>@</code> that provide metadata to <strong>NestJS</strong>, allowing it to understand the structure of the application.</p>
<p>Let's extend our <code>CatsController</code> to include more routes and demonstrate different HTTP methods:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// cats.controller.ts</span>

<span class="hljs-keyword">import</span> { Controller, Get, Post, Put, Delete } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Controller(<span class="hljs-string">'cats'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsController</span> </span>{
  @Get()
  findAll(): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'This action returns all cats'</span>;
  }

  @Get(<span class="hljs-string">':id'</span>)
  findOne(@Param(<span class="hljs-string">'id'</span>) id: string): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`This action returns cat #<span class="hljs-subst">${id}</span>`</span>;
  }

  @Post()
  create(): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'This action creates a new cat'</span>;
  }

  @Put(<span class="hljs-string">':id'</span>)
  update(@Param(<span class="hljs-string">'id'</span>) id: string): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`This action updates cat #<span class="hljs-subst">${id}</span>`</span>;
  }

  @Delete(<span class="hljs-string">':id'</span>)
  remove(@Param(<span class="hljs-string">'id'</span>) id: string): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`This action removes cat #<span class="hljs-subst">${id}</span>`</span>;
  }
}
</code></pre>
<p>In this extended example, we've added methods for handling GET, POST, PUT, and DELETE requests. The <code>@Get(':id')</code> decorator defines a route with a dynamic parameter (<code>id</code>), and the <code>@Param('id')</code> decorator extracts that parameter from the request.</p>
<h2 id="heading-organizing-controllers-in-modules">Organizing Controllers in Modules</h2>
<p><strong>NestJS</strong> encourages the use of modules to organize the application. Controllers are often associated with modules, and the <code>@Module</code> decorator is used for this purpose. Here's an example of how you might organize your controllers into a module:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// cats.module.ts</span>

<span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.controller'</span>;

@Module({
  <span class="hljs-attr">controllers</span>: [CatsController],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CatsModule</span> </span>{}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p><strong>NestJS</strong> controllers and routing mechanisms simplify the process of handling HTTP requests in your application. By using decorators, you can easily define routes and extract parameters from incoming requests. This modular and expressive approach contributes to the overall readability and maintainability of your code.</p>
<p>Remember, this is just a basic overview, and <strong>NestJS</strong> offers many more features for handling authentication, validation, and other aspects of web development.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=zy3wtZVe0so&amp;embeds_referring_euri=https%3A%2F%2Fdev.to%2F&amp;source_ve_path=MjM4NTE">https://www.youtube.com/watch?v=zy3wtZVe0so&amp;embeds_referring_euri=https%3A%2F%2Fdev.to%2F&amp;source_ve_path=MjM4NTE</a>  </p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[Understanding Default NestJS Project Structure]]></title><description><![CDATA[In previous blog, we understood the use-cases for Node.js, Express.js and NestJS and then learned how to install NestJS CLI and initiated our project.
In this blog, we will understand default NestJS project structure.
We will not be diving deep into ...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/understanding-default-nestjs-project-structure</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/understanding-default-nestjs-project-structure</guid><category><![CDATA[nestjs]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Thu, 07 Aug 2025 12:01:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754568367162/4fc3c95a-ef9b-4abe-9737-43c6642d31cf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In previous blog, we understood the use-cases for Node.js, Express.js and NestJS and then learned how to install NestJS CLI and initiated our project.</p>
<p>In this blog, we will understand default NestJS project structure.</p>
<p>We will not be diving deep into any of the configuration files; rather, we'd discuss core files which we will be using for our NestJS series.</p>
<h2 id="heading-starting-the-project">Starting the project</h2>
<p>In package.json file, you can find these two:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"start"</span>: <span class="hljs-string">"nest start"</span>,
<span class="hljs-string">"start:dev"</span>: <span class="hljs-string">"nest start --watch"</span>,
</code></pre>
<p>If you use <code>npm run start</code> then whenever you make changes, you will have to restart your server. So, during development mode, always run this: <code>npm run start:dev</code> so that as soon as you make any changes in the file, the server restarts automatically.</p>
<h2 id="heading-nestjs-default-core-files">Nest.js Default Core Files</h2>
<p>When diving into a NestJS project, the <code>src/</code> directory plays host to several essential files. Let's take a closer look at each one:</p>
<h4 id="heading-maints">main.ts:</h4>
<p>As the gateway to your application, <code>main.ts</code> is where the NestJS application instance comes to life and is registered to a specific port (i.e., 3000 by default), enabling access from your client apps:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { NestFactory } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>;
<span class="hljs-keyword">import</span> { AppModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.module'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create(AppModule);
  <span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
}
bootstrap();
</code></pre>
<h3 id="heading-appmodulets">app.module.ts:</h3>
<p>This file takes center stage as the root module for your application. Every other module you create will find its registration within this file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { AppController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.controller'</span>;
<span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;

@Module({
  <span class="hljs-attr">imports</span>: [],
  <span class="hljs-attr">controllers</span>: [AppController],
  <span class="hljs-attr">providers</span>: [AppService],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppModule</span> </span>{}
</code></pre>
<h3 id="heading-appcontrollerts">app.controller.ts:</h3>
<p>This file serves as the foundation for your controllers, featuring a basic controller class with a single route definition.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Controller, Get } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;

@Controller()
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppController</span> </span>{
  <span class="hljs-keyword">constructor</span>(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.appService.getHello();
  }
}
</code></pre>
<h3 id="heading-appcontrollerspects">app.controller.spec.ts:</h3>
<p>This is the unit test file designed for the <code>app.controller.ts</code> class. It ensures the reliability of your controller through testing. Here's a snippet illustrating a basic test:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Test, TestingModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/testing'</span>;
<span class="hljs-keyword">import</span> { AppController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.controller'</span>;
<span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;

describe(<span class="hljs-string">'AppController'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> appController: AppController;

  beforeEach(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> app: TestingModule = <span class="hljs-keyword">await</span> Test.createTestingModule({
      <span class="hljs-attr">controllers</span>: [AppController],
      <span class="hljs-attr">providers</span>: [AppService],
    }).compile();

    appController = app.get&lt;AppController&gt;(AppController);
  });

  describe(<span class="hljs-string">'root'</span>, <span class="hljs-function">() =&gt;</span> {
    it(<span class="hljs-string">'should return "Hello World!"'</span>, <span class="hljs-function">() =&gt;</span> {
      expect(appController.getHello()).toBe(<span class="hljs-string">'Hello World!'</span>);
    });
  });
});
</code></pre>
<h3 id="heading-appservicets">app.service.ts:</h3>
<p>Here, you'll encounter a fundamental service responsible for executing logic utilized by your controller:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Injectable()
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppService</span> </span>{
  getHello(): string {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello Shameel!'</span>;
  }
}
</code></pre>
<p>Understanding the purpose of each core file empowers you to navigate and structure your NestJS project effectively.</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=3q06vqkSI_A&amp;list=PLgKb0PcT0J0SaWTrS4ZY8ATMaqLeSXgM7&amp;index=2">https://www.youtube.com/watch?v=3q06vqkSI_A&amp;list=PLgKb0PcT0J0SaWTrS4ZY8ATMaqLeSXgM7&amp;index=2</a></p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item><item><title><![CDATA[Getting Started With NestJS]]></title><description><![CDATA[Introduction
Hello everyone, we are starting a series where we will be learning about NestJS as a framework, understanding fundamental concepts and getting down to its depth.
Node.js → Express.js → NestJS
Lets discover how we arrived at NestJS.
The a...]]></description><link>https://getting-started-with-nestjs.hashnode.dev/getting-started-with-nestjs</link><guid isPermaLink="true">https://getting-started-with-nestjs.hashnode.dev/getting-started-with-nestjs</guid><category><![CDATA[nestjs]]></category><category><![CDATA[backend]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[hasabTech]]></dc:creator><pubDate>Tue, 05 Aug 2025 18:33:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754307033141/78af467e-9d48-4ad5-beeb-9a99c84d808e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello everyone, we are starting a series where we will be learning about NestJS as a framework, understanding fundamental concepts and getting down to its depth.</p>
<h2 id="heading-nodejs-expressjs-nestjs">Node.js → Express.js → NestJS</h2>
<p>Lets discover how we arrived at NestJS.</p>
<p>The arrival of NestJS by no means makes Node.js or Express.js obsolete.</p>
<p>Node.js in itself can be used in variety of applications like scripting, automation and stuff, while Express.js is also being utilized substantially in industry, on top of which great applications have been built and are currently in use.</p>
<h3 id="heading-nodejs">Node.js</h3>
<p>Initially, JavaScript used to execute only in Web Browser.</p>
<p>Node.js came with a <strong>BANG</strong> and allowed JavaScript to be written and executed on the server.</p>
<p><em>Note: Node.js is not a library or framework of JavaScript but it's a Runtime Environment.</em></p>
<p>However, in Node.js, we had to write a lot of code for a server to make simple CRUD applications.</p>
<p>Thus came: Express.js!</p>
<h3 id="heading-expressjs">Express.js</h3>
<p>It is an unopinionated, minimalist framework built on top of Node.js</p>
<p>It solved extra over-code which we used to do it in Node.js. However, it's unopinionated, meaning anyone can create and use their own structure however they wish. It doesn’t enforce any strict conventions —developers are free to do whatever they want, in whatever way they prefer. No specific design pattern is enforced. It's essentially a 'do as you like' approach.</p>
<p>Next came: NestJS!</p>
<h3 id="heading-nestjs">NestJS</h3>
<p>NestJS uses Express.js as underlying technology which is built on top of Node.js.</p>
<p>It provides a proper structure for development, with implied design patterns and a standardized modular approach for using Controllers and Services. You have to follow a global standard to make things work.</p>
<p><em>Note: NestJS also allows you to use Fastify as underlying tech if you don't want to use Express.js.</em></p>
<h3 id="heading-problems-tackled-in-each-of-these">Problems tackled in each of these</h3>
<p>Each of these frameworks solved their own problems. Node.js allowed JavaScript to be written on server. Express.js removed extra code which we used to write in Node.js and allowed ease in development and NestJS restricted developers to use good coding practices.</p>
<h3 id="heading-prerequisite">Prerequisite</h3>
<p>You should have knowledge of the following before moving forward with our the NestJS series:</p>
<ul>
<li><p>JavaScript</p>
</li>
<li><p>TypeScript</p>
</li>
<li><p>Node.js</p>
</li>
<li><p>Client-Server Architecture</p>
</li>
<li><p>Express.js (at least a basic understanding)</p>
</li>
</ul>
<h3 id="heading-installing-nestjs">Installing Nest.js</h3>
<p>You should have Node.js installed. You can verify it by running the following command in CMD:</p>
<pre><code class="lang-javascript">node -v
</code></pre>
<p>Open command prompt in <em>Administrative</em> mode and run this:</p>
<pre><code class="lang-javascript">npm i -g @nestjs/cli
</code></pre>
<p>This will install NestJS globally in your system.</p>
<h3 id="heading-creating-our-first-nestjs-project">Creating our first NestJS Project</h3>
<p>After installing NestJS, you can create scaffold a project with the following:</p>
<pre><code class="lang-javascript">nest <span class="hljs-keyword">new</span> &lt;project-name&gt;
</code></pre>
<p>For example:</p>
<pre><code class="lang-javascript">nest <span class="hljs-keyword">new</span> shameel-project
</code></pre>
<p>You will be provided with these three package managers:</p>
<ul>
<li><p>npm</p>
</li>
<li><p>yarn</p>
</li>
<li><p>pnpm</p>
</li>
</ul>
<p>I proceeded with <code>npm</code>. After waiting for a minute, your first NestJS project will be created.</p>
<h3 id="heading-whats-next">What's Next?</h3>
<p>Next, we will be exploring and understanding the folder structure and what each file means which have been created by default from executing the above command.</p>
<p>Stay tuned! =)</p>
<p>If you’re a visual learner, check out the following video tutorial for this blog:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=l2W2FxK0WjU&amp;t=1s">https://www.youtube.com/watch?v=l2W2FxK0WjU&amp;t=1s</a></p>
<p><strong><em>Follow us for more such content:</em></strong></p>
<p><a target="_blank" href="https://www.linkedin.com/company/hasabtech"><strong>https://www.linkedin.com/company/hasabtech</strong></a></p>
<p><a target="_blank" href="https://www.youtube.com/@hasabTech">https://www.youtube.com/@hasabTech</a></p>
<p><a target="_blank" href="https://www.instagram.com/hasab.tech/">https://www.instagram.com/hasab.tech/</a></p>
<p><a target="_blank" href="https://www.facebook.com/hasabTech">https://www.facebook.com/hasabTech</a></p>
]]></content:encoded></item></channel></rss>