<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nandhakumar Srinivasan on Medium]]></title>
        <description><![CDATA[Stories by Nandhakumar Srinivasan on Medium]]></description>
        <link>https://medium.com/@nandhakumar.io?source=rss-6b83e0207741------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*67lYBEqzBQPssIGfd3ezLg.png</url>
            <title>Stories by Nandhakumar Srinivasan on Medium</title>
            <link>https://medium.com/@nandhakumar.io?source=rss-6b83e0207741------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:44:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nandhakumar.io/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Webpack: Setting Up Webpack with TypeScript For Node.js — Part 2]]></title>
            <link>https://javascript.plainenglish.io/mastering-webpack-setting-up-webpack-with-typescript-for-node-js-part-2-ff319a36713c?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff319a36713c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Sat, 04 May 2024 04:02:18 GMT</pubDate>
            <atom:updated>2024-05-07T16:06:16.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Webpack: Setting Up Webpack with TypeScript For Node.js — Part 2</h3><p>Discover the essentials of module bundling, explore how Webpack optimizes your project’s assets, and learn the steps to configure Webpack with TypeScript effectively.</p><blockquote><em>O</em><strong><em>riginally Posted On </em></strong><em>— </em><a href="https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-web-part-2">https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-web-part-2</a></blockquote><blockquote><strong>For Part 1<em>— </em></strong><a href="https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-node-js-part-1">https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-node-js-part-1</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqSjLlUVVyxlALPbLp_LIQ.png" /></figure><p>This is Part 2 of our Mastering Webpack series. If you need a refresher on the fundamentals of Webpack and module bundling, consider revisiting Part 1 of this series.</p><p>In this post, we are going to see how webpack can be configured for web, by default when we setup webpack it will work fine in the node.js environment, but if we try to use the bundled version of JS by opening in a browser the js file won’t support and it won’t work</p><p>Continuing configuration based on the previous post</p><h3>Step 1: Create Separate webpack config for web</h3><p>Create a separate webpack config file called webpack.config.web.ts in the root directory, Then add the below code which is the configurations that tell how the project code should be compiled and bundled</p><pre>// webpack.config.web.ts<br><br>import { Configuration } from &quot;webpack&quot;;<br>import { resolve } from &quot;path&quot;;<br><br>const config: Configuration = {<br>  mode: &quot;none&quot;, // Sets bundling mode to &#39;none&#39; (no optimizations).<br>  entry: {<br>    bundle: &quot;./src/index.ts&quot;, // Entry point of the application.<br>  },<br>  target: &quot;web&quot;, // Correctly sets the bundle target to web environments.<br>  module: {<br>    rules: [<br>      {<br>        exclude: /node_modules/, // Excludes node_modules from processing.<br>        use: {<br>          loader: &quot;ts-loader&quot;, // Processes TypeScript files.<br>          options: {<br>            transpileOnly: true, // Speeds up compilation by skipping type checking.<br>            configFile: &quot;tsconfig.web.json&quot;, // Using tsconfig created for web platform<br>          },<br>        },<br>      },<br>    ],<br>  },<br>  resolve: {<br>    extensions: [&quot;.tsx&quot;, &quot;.ts&quot;, &quot;.js&quot;], // Resolves these file extensions.<br>  },<br>  output: {<br>    filename: &quot;[name].web.js&quot;, // Names output file after its entry point (&#39;bundle.js&#39;).<br>    path: resolve(__dirname, &quot;dist&quot;), // Output directory for the bundled files.<br>  },<br>};<br><br>export default config;</pre><p><strong>Notes:</strong></p><ul><li>The [name].js in the filename field tells Webpack to name the output file based on the name of the entry point. For instance, since your entry point is named bundle, the output file will be bundle.web.js.</li><li>Most of this file resembles the configuration we created for the Node.js environment. The key differences here are, The target is set to web instead of node, The output filename is changed to bundle.web.js to distinguish it from the Node.js bundle, and The configuration is set to tsconfig.web.json</li></ul><h3>Step 2: Create separate ts config for web</h3><p>Create a new tsconfig file for the web version named tsconfig.web.json and add the following code</p><pre>//tsconfig.web.json<br><br>{<br>  &quot;extends&quot;: &quot;./tsconfig.json&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;module&quot;: &quot;ES6&quot;<br>  }<br>}</pre><p><strong>Notes:</strong></p><ul><li>Here, we are extending the base tsconfig.json to avoid repeating configurations. We set the module to ES6 to utilize the latest JavaScript features in the browser.</li><li>Additionally module is set to ES6 , to use the latest features of JS in the browser environment</li></ul><h3>Step 3: Include bundle generated for web in HTML</h3><p>Add index.html file in the root directory, and add the bundle script that will be generated for the web</p><pre>// index.html<br><br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Typescript with webpack&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;p&gt; Check the console by opening inspect window!&lt;/p&gt;<br>    <br>    &lt;!-- Adding bundle file that will be generated for web --&gt;<br>    &lt;script src=&quot;./dist/bundle.web.js&quot;&gt;&lt;/script&gt; <br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Step 4: Add build script for web</h3><p>Add build script for the web version in package.json file</p><pre>// package.json<br><br>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node dist/bundle.js&quot;,<br>    &quot;build&quot;: &quot;webpack&quot;,<br>    &quot;build-web&quot;: &quot;webpack --config webpack.config.web.ts&quot;,<br>  },</pre><p>Note:</p><ul><li>--config webpack.config.web.ts - is added to mention that we need to use webpack.config.web.ts configuration when bundling</li></ul><h3>Step 5: Build the bundle</h3><p>Execute npm run build-web, to generate the bundle for the web</p><p><strong>Note: If you’re following from Part 1, you might encounter an error related to the </strong>crypto<strong> module. This occurs because </strong>crypto<strong> is a Node.js native module and isn&#39;t natively supported in the browser. We&#39;ll fix this by adding the necessary polyfills.</strong></p><pre>ERROR in ./src/utils.ts 1:0-28<br>Module not found: Error: Can&#39;t resolve &#39;crypto&#39; in &#39;/Users/nandhu/Desktop/Learnings/typescript/src&#39;BREAKING CHANGE: webpack &lt; 5 used to include polyfills for node.js core modules by default.<br>This is no longer the case. Verify if you need this module and configure a polyfill for it.<br>If you want to include a polyfill, you need to:<br>        - add a fallback &#39;resolve.fallback: { &quot;crypto&quot;: require.resolve(&quot;crypto-browserify&quot;) }&#39;<br>        - install &#39;crypto-browserify&#39;<br>If you don&#39;t want to include a polyfill, you can use an empty module like this:<br>        resolve.fallback: { &quot;crypto&quot;: false }</pre><blockquote><strong><em>Why Polyfill?</em></strong><em> Polyfills are used to emulate the functionality of APIs or components that are available in some environments but missing in others, typically in web browsers that do not support certain modern web standards. When developing applications that need to work both in Node.js and the browser, it’s crucial to understand which Node.js native modules require polyfills to function correctly in the browser.</em></blockquote><p>Install polyfill of crypto library and it’s dependent polyfill libraries(these dependent libraries are required to be installed to make crypto work)</p><pre>npm install buffer vm-browserify stream-browserify --save</pre><p>Add a fallback library for crypto library, under resolve section in webpack.config.web.ts</p><pre>// webpack.config.web.ts<br><br>resolve: {<br>    extensions: [&quot;.tsx&quot;, &quot;.ts&quot;, &quot;.js&quot;],<br>    fallback: {<br>    // Polyfill for &#39;crypto&#39; and it&#39;s dependent polyfill modules<br>      &quot;buffer&quot;: require.resolve(&quot;buffer/&quot;),<br>      &quot;stream&quot;: require.resolve(&quot;stream-browserify&quot;),<br>      &quot;vm&quot;: require.resolve(&quot;vm-browserify&quot;),<br>      &quot;crypto&quot;: require.resolve(&quot;crypto-browserify&quot;)  <br>    }<br>  }</pre><p>Basically what we are doing here is, we are telling webpack to use crypto-browserify instead of crypto native library, similar for other polyfill-dependent libraries</p><p>Now again execute the npm run build-web , bundle file will be generated successfully</p><h3>Step 6: Test the bundle generated for web</h3><p>Since the HTML file includes our web version of Webpack bundle. Open the html in a browser and check the console to see the outputs from your TypeScript code.</p><p>Congratulations! You’ve successfully configured Webpack to bundle your TypeScript project for both web and node.js environments. Now, your application is more versatile and ready for deployment across different platforms. Experiment with adding more complex functionalities and optimizations to your Webpack configuration to further enhance your project.</p><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p>I welcome your questions, feedback, and discussions on this topic. Don’t hesitate to reach out if there’s something you’d like to talk about.</p><p>If you find this post helpful <a href="https://twitter.com/intent/tweet/?text=Nandhakumar%20Wrote%20this%20Article&amp;url=https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-web-part-2&amp;via=nandhakumar_io"><strong>Tweet this Post</strong></a></p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="/service/mailto:contact@nandhakumar.io">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><p>Cheers ✌️</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff319a36713c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mastering-webpack-setting-up-webpack-with-typescript-for-node-js-part-2-ff319a36713c">Mastering Webpack: Setting Up Webpack with TypeScript For Node.js — Part 2</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Webpack: Setting Up Webpack with TypeScript For Node.js — Part 1]]></title>
            <link>https://javascript.plainenglish.io/mastering-webpack-setting-up-webpack-with-typescript-for-node-js-part-1-5b19da547297?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b19da547297</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Wed, 01 May 2024 12:17:33 GMT</pubDate>
            <atom:updated>2024-05-07T16:04:57.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Webpack: Setting Up Webpack with TypeScript For Node.js — Part 1</h3><p>Discover the essentials of module bundling, explore how Webpack optimizes your project’s assets, and learn the steps to configure Webpack with TypeScript effectively.</p><blockquote><strong>Originally Posted On </strong>— <a href="https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-node-js-part-1"><em>https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-node-js-part-1</em></a></blockquote><blockquote><strong>For Part 2 </strong>— <a href="https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-web-part-2">https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-web-part-2</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqSjLlUVVyxlALPbLp_LIQ.png" /></figure><p>Before diving into the Webpack setup, let’s understand what Webpack is and why we use it.</p><p>Webpack is a module bundling tool. If you’re new to module bundling, it’s a critical process in web development that optimizes the application’s loading time and runtime efficiency by combining and optimizing multiple code files and assets from a project into a smaller number of files.</p><p>This process not only consolidates scripts and styles but also manages dependencies to ensure they are loaded in the correct order. Modern bundlers can also perform additional optimizations such as minification, tree shaking, and lazy loading to improve loading times and application performance.</p><p>Some of the advantages of module bundling include:</p><ul><li>Reducing the number of HTTP requests by combining multiple files into fewer bundles.</li><li>Automating the management of assets and dependencies, making it easier to maintain and scale large applications.</li><li>Including tools and processes like polyfills and transpilers to ensure code works across various browsers.</li><li>Implementing techniques such as minification, tree shaking, and lazy loading to minimize file sizes.</li><li>Enhancing the developer experience with features like Hot Module Replacement.</li></ul><p>Coming back to Webpack,</p><p>It is a powerful module bundler primarily used in web development. It compiles and optimizes all your project’s assets, such as JavaScript, HTML, and CSS, into fewer and more efficient files suited for production environments. Webpack also provides advanced features like code splitting, lazy loading, and module caching to enhance application performance.</p><p>Since this post focuses on setting up Webpack for a TypeScript project, it’s important to understand how module bundling works with TypeScript. Here’s a simplified overview:</p><p>1. <strong>TypeScript Compilation</strong>: First, the TypeScript compiler (tsc) transforms TypeScript code into JavaScript. This step converts TypeScript’s syntax and features into JavaScript that browsers or Node.js environments can execute.</p><p>2. <strong>Module Bundling</strong>: Next, the compiled JavaScript code is bundled into a single file or a few files by a module bundler. This process optimizes the code and manages dependencies to ensure they are loaded correctly.</p><p>Note that while Webpack is one of the most popular module bundlers, there are several others widely used in the development community, including:</p><ul><li><strong>Rollup</strong>: Known for its efficiency and suitability for libraries.</li><li><strong>Esbuild</strong>: Praised for its speed, written in Go, and leveraging multithreading.</li><li><strong>Vite:</strong> A modern build tool that combines the best of Esbuild and Rollup for both development and production builds.</li></ul><p>Each of these tools has its strengths and can be chosen based on the specific needs of a project.</p><p>Enough of the theory, now let’s jump into setting up Webpack with TypeScript</p><h4>Step 1: Initialize a Node Project</h4><pre>npm init -y</pre><p><strong>Note: </strong>The -y flag automatically populates the package.json file with default values.</p><h4>Step 2: Install Required Development Dependencies</h4><pre>npm i -D typescript @types/node webpack webpack-cli ts-node ts-loader @types/webpack</pre><p><strong>Notes:</strong></p><ul><li>-D flag is to indicate these dependencies are not needed in the production environment but are essential during development</li><li>typescript — Essential for converting TypeScript code to JavaScript.</li><li>@types/node — These are TypeScript declaration files for Node.js. They provide type definitions for Node.js modules.</li><li>webpack — Webpack tool required to bundle the code</li><li>webpack-cli— This is the command line interface for Webpack used to execute webpack based commands</li><li>ts-node— TypeScript execution engine, Allows you to run TypeScript files directly in Node.js without pre-compiling.</li><li>ts-loader — This is a Webpack loader that handles the compilation of TypeScript files into JavaScript.</li><li>@types/webpack— Similar to @types/node, these are TypeScript declaration files but for Webpack itself</li></ul><h4>Step 3: Generate TypeScript Configuration File (tsconfig.json)</h4><pre>tsc --init</pre><p>This command generates a tsconfig.json with a set of default compiler options commonly used in most TypeScript projects. It is customizable as per your project requirements.</p><h4>Step 4: Create `webpack.config.ts` in the Root Directory</h4><pre>// webpack.config.ts<br><br>import { Configuration } from &quot;webpack&quot;;<br>import { resolve } from &quot;path&quot;;<br><br>const config: Configuration = {<br>  mode: &quot;none&quot;, // Sets bundling mode to &#39;none&#39; (no optimizations).<br>  entry: {<br>    bundle: &quot;./src/index.ts&quot;, // Entry point of the application.<br>  },<br>  target: &quot;node&quot;, // Bundles code for Node.js environment.<br>  module: {<br>    rules: [<br>      {<br>        exclude: /node_modules/, // Excludes node_modules from processing.<br>        use: {<br>          loader: &quot;ts-loader&quot;, // Processes TypeScript files.<br>          options: {<br>            transpileOnly: true, // Speeds up compilation by skipping type checking.<br>          },<br>        },<br>      },<br>    ],<br>  },<br>  resolve: {<br>    extensions: [&quot;.tsx&quot;, &quot;.ts&quot;, &quot;.js&quot;], // Resolves these file extensions.<br>  },<br>  output: {<br>    filename: &quot;[name].js&quot;, // Names output file after its entry point (&#39;bundle.js&#39;).<br>    path: resolve(__dirname, &quot;dist&quot;), // Output directory for the bundled files.<br>  },<br>};<br>export default config;</pre><h4>Step 5: Define the Entry Point</h4><p>Create a src directory, and within it, create two files: index.ts (entry file) and utils.ts (to export functions used in index.ts).</p><pre>// src/utils.ts<br><br>import crypto from &quot;crypto&quot;;<br><br>// Create a function to generate a SHA-256 hash<br>export const generateHash = (input: string): string =&gt; {<br>  return crypto.createHash(&quot;sha256&quot;).update(input).digest(&quot;hex&quot;);<br>};</pre><pre>// src/index.ts<br><br>import { generateHash } from &#39;./utils&#39;;<br><br>console.log(&quot;Typescript Works!&quot;)<br>console.log(&quot;Node Works!&quot;)<br><br>const hash = generateHash(&quot;Webpack is Working!&quot;)<br>console.log(&#39;SHA-256 Hash:&#39;, hash)</pre><h4>Step 6: Add Custom Scripts in `package.json`</h4><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;node dist/bundle.js&quot;,<br>  &quot;build&quot;: &quot;webpack&quot;,<br>}</pre><h4>Step 7: Execute `npm run build`</h4><p>This will bundle the code and generate a dist directory containing bundle.js.</p><h4>Step 8: Test the Bundled Code</h4><p>Execute npm run start. If everything is set up correctly, you should see outputs confirming that TypeScript and Node are working, along with a SHA-256 hash generated by your utility function.</p><pre>❯ npm run start<br><br>&gt; Typescript Webpack Setup@1.0.0 start<br>&gt; node dist/bundle.js<br><br>Typescript Works!<br>Node Works!<br>SHA-256 Hash: a7929e1f857cca0a8c9c1345e79f3b1a1976e603c9ce4e77a808988658b36181</pre><p>However, there’s a limitation with this configuration: it’s not suitable for web environments. If you add an index.html and try to include the bundled script, it won’t work. We’ll explore how to modify this setup for web compatibility in Part 2 of this series.</p><blockquote><strong>For Part 2 </strong>— <a href="https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-web-part-2">https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-web-part-2</a></blockquote><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p>I welcome your questions, feedback, and discussions on this topic. Don’t hesitate to reach out if there’s something you’d like to talk about.</p><p>If you find this post helpful <a href="https://twitter.com/intent/tweet/?text=Nandhakumar%20Wrote%20this%20Article&amp;url=https://nandhakumar.io/post/mastering-webpack-setting-up-webpack-with-typeScript-for-node-js-part-1&amp;via=nandhakumar_io"><strong>Tweet this Post</strong></a></p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="/service/mailto:contact@nandhakumar.io">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><p>Cheers ✌️</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b19da547297" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mastering-webpack-setting-up-webpack-with-typescript-for-node-js-part-1-5b19da547297">Mastering Webpack: Setting Up Webpack with TypeScript For Node.js — Part 1</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using Date Time Libraries like Moment, Dayjs, etc …]]></title>
            <link>https://javascript.plainenglish.io/stop-using-date-time-libraries-like-moment-dayjs-etc-cda02f5ea61b?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/cda02f5ea61b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Mon, 15 May 2023 10:17:20 GMT</pubDate>
            <atom:updated>2023-05-15T10:17:20.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Using Date Time Libraries like Moment, Day.js, etc.</h3><p>learn how to manipulate data and time yourself without using libraries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IVXKg2NyQr_xMYM6Qn19A.png" /></figure><p>I used Moment and Dayjs library a lot for basic date calculations like adding, subtracting, and finding the difference between dates.</p><p>But, Later I found that JS itself has a good number of Date time methods to solve simple Date time use cases</p><p>Let’s see what are those methods and how we can use them,</p><p><strong><em>Note: For more complex DateTime calculations, it is better to use the libraries. We don’t want to waste time writing complex logic from scratch.</em></strong></p><h3>Manipulating Date time</h3><h3>Hours</h3><p>Adding &amp; Subtracting Hours</p><pre>const currentTime = new Date()<br><br>// currentTime<br>// Thu May 11 2023 06:44:51 GMT+0530 (India Standard Time)<br><br>// Adding 5 Hours to the time<br>currentTime.setHours(currentTime.getHours() + 5) // Thu May 11 2023 11:44:51 GMT+0530 (India Standard Time)<br><br>// Subtracting 5 Hours to the time<br>currentTime.setHours(currentTime.getHours() - 5) // Thu May 11 2023 06:44:51 GMT+0530 (India Standard Time)</pre><h3>Minutes</h3><p>Adding &amp; Subtracting Minutes</p><pre>const currentTime = new Date()// currentTime<br>// Thu May 11 2023 11:44:51 GMT+0530 (India Standard Time)<br><br>// Adding 5 Minutes to the time<br>currentTime.setHours(currentTime.getHours() + 5) // Thu May 11 2023 11:49:51 GMT+0530 (India Standard Time)<br><br>// Subtracting 5 Minutes to the time<br>currentTime.setHours(currentTime.getHours() - 5) // Thu May 11 2023 11:44:51 GMT+0530 (India Standard Time)</pre><h3>Seconds</h3><p>Adding &amp; Subtracting Seconds</p><pre>const currentTime = new Date() // currentTime<br>// Thu May 11 2023 11:44:51 GMT+0530 (India Standard Time)<br><br>// Adding 5 Seconds to the time<br>currentTime.setSeconds(currentTime.getSeconds() + 5) // Thu May 11 2023 11:49:56 GMT+0530 (India Standard Time)<br><br>// Subtracting 5 Seconds to the time<br>currentTime.setSeconds(currentTime.getSeconds() - 5) // Thu May 11 2023 11:44:51 GMT+0530 (India Standard Time)</pre><p>You can also try manipulating year, milliseconds, timestamps etc.. Take it as an exercise and try it by yourself.</p><h3>Finding Difference</h3><p>Finding differences between months and years are bit tricky so, let’s focus on finding the difference between days, hours, seconds, and even milliseconds.</p><p>So first we need to define the base value of days, hours, seconds, and milliseconds</p><pre>const milliseconds = 1; <br>const second = 1000; // 1000 milliseconds = 1 second<br>const minute = second * 60; // 60 seconds = 1 minute<br>const hour = minute * 60; // 60 minute =  1 hour<br>const day = hour * 24; // 24 hour = 1 day</pre><p>since we have the base value now, finding the difference will be easy</p><ul><li>Define two dates to find the difference,</li></ul><pre>const dateOne = new Date(2023, 5, 1);  // June 1, 2023 <br>const dateTwo = new Date(2023, 5, 10); // June 10, 2023</pre><ul><li>Find the timestamp difference between the two dates</li></ul><pre>const timeStampDiff = Math.abs(dateOne.getTime() - dateTwo.getTime()); // 777600000</pre><blockquote>Why we are using <em>Math.abs()</em>? <strong><em>Math.abs()</em></strong> is used to ensure that the result is always a positive number, regardless of the order of the dates. It usually doesn&#39;t make sense to have a negative value when finding the difference</blockquote><p>Now divide the difference by the base value that we defined earlier</p><pre>const difference =  timeStampDiff / day; // 9</pre><p>since we divided by the day’s base value we got the day difference between the two dates</p><p>which is 9, similarly you can divide timeStampDiff by other base values to get the appropriate result.</p><h3>Finding the Difference between months</h3><h3>Months</h3><p>Finding the Difference between months has two possible solutions,</p><p><strong>Solution 1 (Not the best solution)</strong></p><p>This is straight forward solution, Get the month of two dates and get subtract to get the difference</p><pre>const dateOne = new Date(2023, 5, 1);  // June 1, 2023<br>const dateTwo = new Date(2023, 9, 10); // Oct 10, 2023</pre><pre>const difference = Math.abs(dateOne.getMonth() - dateTwo.getMonth()) // 4</pre><p>Even though this solution is working fine. There is an issue with this solution. If the year of the two dates is different the result(the difference) would be incorrect.</p><p>For example, for <strong>dateOne = new Date(2022, 11, 1)</strong> (December 2022) and <strong>dateTwo = new Date(2023, 0, 1)</strong> (January 2023), the result would be <strong>Math.abs(0 - 11) = 11</strong>, which is incorrect as the difference is actually 1 month.</p><p><strong>Solution 2</strong></p><p>This is a bit tricky, But I’ll explain to you step by step</p><ul><li>Let’s define the date first</li></ul><pre>const dateOne = new Date(2022, 5, 1);  // June 1, 2022 <br>const dateTwo = new Date(2023, 9, 10); // Oct 10, 2023</pre><p><strong><em>Note: In Js Dates, months start from 0 i.e (Jan → 0, Feb → 1)</em></strong></p><ul><li>Find the year difference</li></ul><pre>const yearDifference = dateTwo.getFullYear() - dateOne.getFullYear(); // 1</pre><ul><li>Find the month difference</li></ul><pre>const monthDifference = dateTwo.getMonth() - dateOne.getMonth(); // 4</pre><ul><li>Calculating the total no. of months of the yearDifference</li></ul><pre>let months = yearDifference * 12 // 12</pre><ul><li>Now add the monthDifference to months</li></ul><pre>months += monthDifference; // 16</pre><p>That’s it we have found the difference.</p><p>Also, you can add Math.abs(months) as one other step, so you can avoid getting negative values</p><h3>Finding the Difference between years</h3><p>This is also a bit tricky, but not like months</p><ul><li>Let’s First Define the dates</li></ul><pre>const dateOne = new Date(2022, 5, 1);  // June 1, 2022 <br>const dateTwo = new Date(2023, 9, 10); // Oct 10, 2023</pre><ul><li>Find the difference in the year</li></ul><pre>let difference = dateTwo.getFullYear() - dateOne.getFullYear();</pre><ul><li>You might think just subtracting two years can get the expected result. But, there are a few scenarios to be handled. For Example: If you have dates like Jan 1 2023 and Dec 31 2023, here the year is the same but the diff is 1 year. and in another case, if the dates are Dec 31 2023, and Jan 1 2024, here the year is different but the actual difference is 1 day.</li></ul><p>You get the point right?</p><p>So to handle this, you can add few conditions</p><pre>if (dateTwo.getMonth() &lt; dateOne.getMonth() || <br>   (dateTwo.getMonth() == dateOne.getMonth() &amp;&amp; <br>    dateTwo.getDate() &lt; dateOne.getDate())) {<br>    difference--;<br>}<br><br>difference = Math.abs(difference)</pre><p>Let’s break down the conditions</p><ul><li>`dateTwo.getMonth() &lt; dateOne.getMonth()` — This means that in the current year of `dateTwo`, `dateTwo` has not yet reached the month of `dateOne`.<br>For example, if `dateOne` is June 10, 2023 and `dateTwo` is March 15, 2024, even though `dateTwo`’s year is 2024, it hasn’t yet reached the month of June, so we should consider the year difference as 0, not 1.</li><li>`(date2.getMonth() == date1.getMonth() &amp;&amp; date2.getDate() &lt; date1.getDate())` — This means that even though `dateTwo` is in the same month as `dateOne`, it hasn’t yet reached the day of `dateOne` in its current year. <br>For example, if `dateOne` is June 10, 2023 and `dateTwo` is June 5, 2024, even though `dateTwo`’s year is 2024 and the month is June, it hasn’t yet reached the 10th of June, so we should consider the year difference as 0, not 1.</li></ul><p>In both of these conditions, we decrease difference by one (difference--) to accurately reflect the year difference considering the month and day, not just the year.</p><p>Finally, we use Math.abs() as we don’t want negative values</p><h3>Conclusion</h3><p>In this post, you learned how to manipulate data and time yourself without using libraries. However, the Date time libraries are always a time saver. When you have a more complex use case to solve that is based on Date time, You can use these libraries.</p><p>If you are going to perform only simple calculations utilize the existing Date time module in node.js.</p><p>Again this is my thought, based on your requirement you can decide whether to use libraries or not.</p><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p>If you find this post helpful <a href="https://twitter.com/intent/tweet/?text=Nandhakumar%20Wrote%20this%20Article&amp;url=https://nandhakumar.io/post/step-by-step-guide-to-dockerize-vite-react-app-in-dev-environment&amp;via=nandhakumar_io"><strong>Tweet this Post</strong></a></p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="/service/mailto:contact@nandhakumar.io">Email</a>, and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><p>Cheers ✌️</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cda02f5ea61b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/stop-using-date-time-libraries-like-moment-dayjs-etc-cda02f5ea61b">Stop Using Date Time Libraries like Moment, Dayjs, etc …</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PhaseScriptExecution failed with a nonzero exit code — XCode]]></title>
            <link>https://medium.com/@nandhakumar.io/phasescriptexecution-failed-with-a-nonzero-exit-code-xcode-175e1d39cbba?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/175e1d39cbba</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Wed, 10 May 2023 02:35:19 GMT</pubDate>
            <atom:updated>2023-05-10T02:35:19.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>PhaseScriptExecution failed with a nonzero exit code — XCode</h3><p>Learn how to resolve the “PhaseScriptExecution failed with a nonzero exit code” error when publishing your IOS app</p><blockquote>Originally Posted on <a href="https://www.nandhakumar.io/post/phase-script-execution-failed-with-a-nonzero-exit-code">https://www.nandhakumar.io/post/phase-script-execution-failed-with-a-nonzero-exit-code</a></blockquote><p>If you have updated Xcode from <strong>14.2</strong> to <strong>14.3,</strong> there is an issue in archiving &amp; publishing your app to App Store</p><p>After researching this issue, I found a workaround in Apple’s Developer forum</p><p>Forum Ref — <a href="https://developer.apple.com/forums/thread/725230">https://developer.apple.com/forums/thread/725230</a></p><p>And the solution is simple,</p><p>Open [Your App Name]/ios/App/Pods/Target Support Files/Pods-[Your App]/Pods-[Your App]-frameworks.sh</p><p>Replace source=&quot;$(readlink &quot;${source}&quot;)&quot; with source=&quot;$(readlink -f &quot;${source}&quot;)&quot;</p><p>And people say that the issue is due to CocoaPods.</p><p>Hope this helps you to resolve the issue.</p><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p>If you find this post helpful <a href="https://twitter.com/intent/tweet/?text=Nandhakumar%20Wrote%20this%20Article&amp;url=https://nandhakumar.io/post/step-by-step-guide-to-dockerize-vite-react-app-in-dev-environment&amp;via=nandhakumar_io"><strong>Tweet this Post</strong></a></p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="/service/mailto:contact@nandhakumar.io">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><p>Cheers ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=175e1d39cbba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS: How to Store, Read and Validate Environment Variable Using @nestjs/config]]></title>
            <link>https://javascript.plainenglish.io/nestjs-how-to-store-read-and-validate-environment-variable-using-nestjs-config-40a5fa0702e4?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a5fa0702e4</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Thu, 19 Jan 2023 08:16:24 GMT</pubDate>
            <atom:updated>2024-09-03T05:08:17.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Nest JS | TypeScript | JavaScript | Nest Config</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLbUHLtuGnKQLz_6y_f8vw.png" /><figcaption>How to Store, Read and Validate Environment Variable Using @nestjs/config</figcaption></figure><p>Hi There! 👋</p><p>Usually, when you are working on a project you are not going to write code for all the features you are developing, sometime you might use third-party tools or services like AWS, SendGrid, Google Cloud, etc…</p><p>And these platforms will provide some secret or API keys to access the service and If you hardcode these keys on your code, there is a chance that anyone can misuse it.</p><p>So as a best practice, you should never hardcode these keys in code or push these keys to GitHub or any cloud repositories.</p><p>Instead, store these keys in the environment file and remember you shouldn’t push this file to the repository.</p><p>In Node.js applications, it’s common to use .env files, holding key-value pairs where each key represents a particular value.</p><p>Before we get started with the implementation. Make sure you have a Nest Js project with these dependencies</p><pre># yarn<br>yarn add @nestjs/config class-validator class-transformer<br><br># npm<br>npm i @nestjs/config class-validator class-transformer -s</pre><h3>Store Environment Variables</h3><p>Create a file “.env “at the root level of the project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*bie7-ugsvhzX4FVl" /><figcaption>Project Structure</figcaption></figure><p>Add your secret keys to the ‘.env’ file</p><pre># .env<br>SECRET_KEY=&quot;This is a Secret Key&quot;</pre><p>Great! You have created your environment variable.</p><p>To avoid pushing the ‘.env’ file to the repository. Add ‘.env’ to ‘.gitignore’ file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*V45nRy8II66rL7ai" /><figcaption>.gitignore</figcaption></figure><blockquote><em>💡</em><strong> Learn how to implement a custom validation pipe in a NestJS application:</strong></blockquote><p><a href="https://differ.blog/p/request-multi-dtos-validation-nestjs-ed0b72">Request Multi DTOs Validation - NestJS</a></p><blockquote><em>👉</em> To read more such acrticles, <a href="https://differ.blog/"><strong>sign up for free on Differ</strong></a>.</blockquote><h3>Setting Up Nest Config Module</h3><p>If you haven’t installed the dependency that I mentioned at the begging of this tutorial. please install.</p><p>Once Installed</p><p>Import ConfigModule in app.module.ts</p><pre>// App.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br><br>@Module({<br>  imports: [ConfigModule.forRoot()], // Import ConfigModule<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>The forRoot() method registers the ConfigService provider which provides a get() method to read the environment variables.</p><p>Since @nestjs/config uses dotenv library under the hood, by default forRoot()</p><p>the method will search for .env in the root of the project.</p><p>If you have named your environment file with a different name like .dev.env then you need to pass the file name to the forRoot() method</p><pre>ConfigModule.forRoot({<br>  envFilePath: &#39;.dev.env&#39;,<br>})</pre><blockquote><strong>Pro Tip<br></strong>If you want to use ConfigService in other modules you have to import ConfigModule again, To avoid importing in multiple modules and to globalise ConfigModule you can set isGlobal to true</blockquote><pre>ConfigModule.forRoot({<br>  envFilePath: &#39;.dev.env&#39;,<br>  isGlobal: true<br>})</pre><h3>Reading Environment Variables Using ConfigService</h3><p>To read environment variable value, we need to inject ConfigService which is already registered by ConfigModule that we imported in the app.module.ts</p><p>In my starter project, I want to read environment variable in the app.service.ts file, So injecting ConfigService in it. You can inject where ever you need.</p><pre>// app.service.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br><br>@Injectable()<br>export class AppService {<br>  constructor(private readonly configService: ConfigService) {}<br><br>  getSecretKey(): string {<br>    return this.configService.get(&#39;SECRET_KEY&#39;); // read environment variable<br>  }<br>}</pre><p>Use get() and pass the variable name that you want to read.</p><h3>Validating Environment Variables</h3><p>ConfigModule provides an additional option to validate the environment variables by passing custom validation functions.</p><p><strong>Why validation is required?<br></strong>If you are working on a team and any developer miss any variable in the .env file, that might break the application</p><p>Make sure you have installed the required dependencies class-validator and class-transformer</p><p>Create a file environment.validation.ts</p><p>Add a class EnvironmentVariables with all the variables that you have in the .env file</p><pre>// environment.validation.ts<br><br>import { IsString , validateSync} from &#39;class-validator&#39;;<br>import { plainToClass } from &#39;class-transformer&#39;;<br><br>class EnvironmentVariables {<br>  @IsString({ message: &#39;Invalid SECRET_KEY&#39; })<br>  SECRET_KEY: string;<br>}</pre><p>Now create the validation function</p><pre>// environment.validation.ts<br><br>export const validate = (config: Record&lt;string, unknown&gt;) =&gt; {<br>  <br>  // `plainToClass` to converts plain object into Class<br>  const validatedConfig = plainToClass(EnvironmentVariables, config, {<br>    enableImplicitConversion: true,<br>  });<br> <br>  // `validateSync` method validate the class and returns errors<br>  const errors = validateSync(validatedConfig, {<br>    skipMissingProperties: false,<br>  });<br><br>  if (errors.length &gt; 0) {<br>    throw new Error(errors.toString());<br>  }<br>  return validatedConfig;<br>};</pre><p>Import the validate functions in app.module.ts and pass it to ConfigModule</p><pre>// app.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>import { validate } from &#39;./environment.validation&#39;;<br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      validate,<br>    }),<br>  ], // Import ConfigModule<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><h3>Time For Testing</h3><p>I am running my server at <a href="http://localhost:3000/">http://localhost:3000</a></p><p>Use any API testing tool like(postman) to test the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*TbC_iEy4lh67cOHZ" /><figcaption>API Testing</figcaption></figure><p>And you can see when I hit my API, I am getting the secret key stored in the .env file as the response.</p><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p><a href="https://medium.com/@nandhakumar.io">Follow me</a> to get notified of all upcoming posts on this series.</p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="https://mailto:contact@nandhakumar.io/">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><p><strong>Originally Posted On </strong>— <a href="https://www.nandhakumar.io/post/nest-js-tutorial-3-route-and-query-param"><em>https://www.nandhakumar.io/post/nest-js-tutorial-3-route-and-query-param</em></a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a5fa0702e4" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/nestjs-how-to-store-read-and-validate-environment-variable-using-nestjs-config-40a5fa0702e4">NestJS: How to Store, Read and Validate Environment Variable Using @nestjs/config</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regex #1: Learn the fundamentals of regex, regex methods and its flags]]></title>
            <link>https://javascript.plainenglish.io/understanding-regex-regex-based-string-methods-and-regex-flags-3501cc3af9fd?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/3501cc3af9fd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 10:16:40 GMT</pubDate>
            <atom:updated>2023-01-14T03:22:03.768Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Regex, Regex-Based String Methods and Regex Flag</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DejAEWHWZD9lB2QtpjS4pg.png" /><figcaption>Regex #1: Understanding Regex, Regex-Based String Methods and Regex Flags</figcaption></figure><p>Hi There! 👋</p><p>In this post, you will learn the fundamentals of regex.</p><h3>Why Regex?</h3><p>The most common feature every application has is user registration and login.</p><p>Nowadays, Libraries(Eg: Class Validator NPM Package) that you use for form validation has a direct method to validate input value like isEmail(), etc...</p><p>Which is very helpful, But each application has its own use case. So, these direct methods won’t be helpful in that case.</p><p>For Example, Not all application has the same rules for password.</p><p>In such scenarios, you can use Regex Pattern to validate the user input values.</p><blockquote><strong><em>Note:</em></strong><em> Regex is not limited to use only for Input Validation</em></blockquote><p>Most of the time I used to find the required Regex pattern from Google.</p><p>At some point, I thought why can’t we try to understand regex instead of searching on Google?</p><p>Just gave try!</p><p>After understanding some basics, Regex was interesting. And I regret that I didn’t learn Regex so far.</p><p>That’s How I started learning Regex in depth.</p><blockquote><strong><em>Note:</em></strong><em> Examples I share in this post are based on<br>javascript, but the concepts can be applied to any<br>programming language</em></blockquote><h3>Defining a Regex Pattern?</h3><p>When you add a pattern between /, it is considered a regex pattern</p><pre>/[regex pattern]/</pre><blockquote><strong><em>Note:</em></strong><em> There shouldn’t be any </em><em>&#39; or </em><em>&quot; around the </em><em>/</em></blockquote><h3>Two Ways to test Regex Pattern</h3><h3>Using Regex Methods</h3><ul><li>.test() - It will return a boolean value if the pattern matches the string</li></ul><pre>// regex Pattern<br>const pattern = /world/ <br><br>// string to be tested against the pattern<br>const text = &#39;Hello world&#39; <br><br>// returns `true` as the `world` is present in the message<br>console.log(&#39;[Test Method] - &#39;, pattern.test(message))</pre><pre>// output<br>[Test Method] - true</pre><ul><li>.exec() - It will return an array with the index and additional info on the matching pattern</li></ul><pre>// regex Pattern<br>const pattern = /world/ <br><br>// string to be tested against the pattern<br>const text = &#39;Hello world&#39; <br><br>// returns Array with index and additional info<br>console.log(&#39;[Exec Method] - &#39;, pattern.exec(message))</pre><pre>// output<br>[Exec Method] - [ &#39;world&#39;, index: 6, input: &#39;Hello world&#39;, groups: undefined ]</pre><h3>Using String Methods</h3><ul><li>.match() - It will return an array with the index and additional info on the matching pattern (similar to .exec() method) if only one match is found. Otherwise, it will return all the string that matches the pattern as an array.</li></ul><pre>// regex Pattern<br>const pattern = /world/ <br><br>// string to be tested against the pattern<br>const text = &#39;Hello world&#39; <br><br>// returns Array with index and additional info<br>console.log(&#39;[Exec Match] - &#39;, text.match(pattern))</pre><pre>// output<br>[Exec Match] - [ &#39;world&#39;, index: 6, input: &#39;Hello world&#39;, groups: undefined ]</pre><ul><li>.replace() - It will replace the string that matches the pattern with the string that is to be replaced.</li></ul><pre>// regex Pattern<br>const pattern = /world/ <br><br>// string to be tested against the pattern<br>const text = &#39;Hello world&#39; <br><br>// returns Array with index and additional info<br>console.log(&#39;[Exec Replace] - &#39;, text.replace(pattern, &#39;Word&#39;))</pre><pre>// output<br>[Exec Replace] - Hello Word</pre><ul><li>.split() - It will split the text into an array based on the matching pattern</li></ul><pre>// regex Pattern<br>const pattern = /world/ <br><br>// string to be tested against the pattern<br>const text = &#39;Hello world&#39; <br><br>// returns Array with index and additional info<br>console.log(&#39;[Exec Split] - &#39;, text.split(pattern))</pre><pre>// output<br>[Exec Split] - [ &#39;Hello &#39;, &#39;&#39; ]</pre><h3>Regex Flags</h3><p>There are three 3 flags in Regex</p><ul><li>g - Global</li></ul><p>Usually, when you try to match a pattern, it will match only the first occurrence in the string.</p><p>By adding the Global flag to the Regex pattern, it can match multiple occurrences of the pattern in the string</p><pre>// regex Pattern with global flag<br>const pattern = /the/g<br><br>// string to be tested against the pattern<br>const text = &#39;Get the Work Done and the work will pay off.&#39;<br><br>// Returns Array of strings matching the pattern<br>console.log(&#39;[Exec Global Flag] - &#39;, text.match(pattern))</pre><pre>// output<br>[Exec Global Flag] - [ &#39;the&#39;, &#39;the&#39; ]</pre><ul><li>i - Case Insensitive</li></ul><p>By default, matching string with regex is case-sensitive.</p><p>By adding the Case Insensitive flag to the Regex pattern, it can match the string with Case Insensitive</p><pre>// regex Pattern with global and Case Insensitive flag<br>const pattern = /work/gi<br><br>// string to be tested against the pattern<br>const text = &#39;Get the Work Done and the work will pay off.&#39;<br><br>// Returns Array of strings matching the pattern<br>console.log(&#39;[Exec Global &amp; Case Insensitive Flag] - &#39;, text.match(pattern))</pre><pre>// output<br>[Exec Global &amp; Case Insensitive Flag] - [ &#39;Work&#39;, &#39;work&#39; ]</pre><ul><li>m - Multi Line</li></ul><p>When you try to match a pattern with a multi-line string, By default the match is found only in the first line even though we have a match in the second line</p><p>By adding the Multi Line flag to the Regex pattern, it can find the matches in multiple lines.</p><pre>// regex Pattern with global and Multi-Line flag<br>const pattern = /^The/gm <br><br>// starts with &quot;The&quot;// string to be tested against the pattern<br>const text = `The the Work Done.<br>The work will pay off.`<br><br>// Returns Array of strings matching the pattern<br>console.log(&#39;[Exec Global &amp; Multi Line Flag] - &#39;, text.match(pattern))</pre><pre>// output<br>[Exec Global &amp; New Line Flag] - [ &#39;The&#39;, &#39;The&#39; ]</pre><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p><a href="https://medium.com/@nandhakumar.io">Follow me</a> to get notified of all upcoming posts.</p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="https://mailto:contact@nandhakumar.io/">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><p><em>Originally Posted On —</em></p><p><a href="https://www.nandhakumar.io/post/regex-1-understanding-regex-methods-and-flags">Regex #1: Understanding Regex, Regex-Based String Methods and Regex Flags</a></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3501cc3af9fd" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-regex-regex-based-string-methods-and-regex-flags-3501cc3af9fd">Regex #1: Learn the fundamentals of regex, regex methods and its flags</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Tutorial: Query & Route Params]]></title>
            <link>https://javascript.plainenglish.io/nestjs-tutorial-query-route-params-221cc8000518?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/221cc8000518</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 10:16:50 GMT</pubDate>
            <atom:updated>2024-09-17T13:17:46.736Z</atom:updated>
            <content:encoded><![CDATA[<h3>NestJS #3: Query &amp; Route Params</h3><h4>Understand what is route &amp; query param, when to use it and how to use it in NestJS</h4><figure><img alt="Nest JS Tutorial #3 : Query &amp; Route Params" src="https://cdn-images-1.medium.com/max/1024/1*42hckoSfwjK75sEcQ88mGQ.png" /><figcaption>Nest JS Tutorial #3 : Query &amp; Route Params</figcaption></figure><h3>Hi There! 👋</h3><p>In this post, you will learn what is route &amp; query param, when to use it and how to use it in <a href="https://nestjs.com/">Nest JS</a></p><p>This post is a part Nest JS tutorial series, Do check out my other post on nest js to know more about it.</p><blockquote><strong><em>Originally Posted On </em></strong><em>— </em><a href="https://www.nandhakumar.io/post/nest-js-tutorial-3-route-and-query-param">https://www.nandhakumar.io/post/nest-js-tutorial-3-route-and-query-param</a></blockquote><h3>Prerequisite</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">JavaScript</a></li><li><a href="https://www.typescriptlang.org/">TypeScript</a> (Optional)</li><li>Basics Of OOPS</li><li><a href="https://www.postman.com/">Postman</a> (For API Testing)</li><li><a href="https://code.visualstudio.com/">Code Editor</a></li><li><a href="https://nodejs.org/en/">Node.JS</a></li></ul><blockquote><strong><em>💡</em>Also learn how to stream video from a Node.js application:</strong></blockquote><p><a href="https://differ.blog/inplainenglish/how-to-stream-video-from-a-node-js-application-a85c6e">Stream Video By NodeJs Guide</a></p><blockquote><em>👉</em> To read more such articles, <a href="https://differ.blog/"><strong>sign up for free on Differ</strong></a>.</blockquote><h3>Understanding Route and Query param</h3><h4>Route Param</h4><p>Route Params are used to get specific data.</p><p>Example Scenario,<br>Let&#39;s say you want to get a user detail by ID, so ID can be will be passed as a route param like this 👇</p><pre>http://api.com/5689</pre><p>Here, 5689 is the ID of the user</p><h4>Query Param</h4><p>Query params are used when you want to filter, sort and paginate the data.</p><p>Example Scenario,<br>Let&#39;s say you want to get a list of users that matches a name. so, here name can be passed as a query param like this 👇</p><pre>http://api.com?name=tamilan</pre><p>Here, the nametamilan is passed as a query param. To get results matching the name.</p><p>You can also pass multiple query param.</p><p>In addition to filter by name, we can also add a sort query with the existing name query like this 👇</p><pre>http://api.com?name=tamilan&amp;sort=name</pre><p>That&#39;s a short brief on route and query param!</p><p>Now let&#39;s see how to capture these query and route param in nest js</p><h3>Using Route and Query Param in Nest JS</h3><p>To get started, Create a new nest project using nest cli. If you are not sure how to create a new project, check out this <a href="https://medium.com/javascript-in-plain-english/nest-js-part-1-creating-your-first-api-71471ac39d3e">post</a></p><p>I have created a new nest project, with its starter code.</p><p>Here&#39;s the project structure I have now,</p><figure><img alt="Nest JS Starter Project Structure" src="https://cdn-images-1.medium.com/max/467/1*1nC8zA5K0US6A0LiICjAgw.png" /><figcaption>Nest JS Starter Project Structure</figcaption></figure><h3>Requirements</h3><p>We need two routes,</p><p>/user</p><ul><li>It should be a GET request</li><li>It should return all the users when there is no query param</li><li>It should return all the users that match the name when the name query param is passed</li></ul><p>/user/:id</p><ul><li>It should be a GET request</li><li>It should return the user that matches the id passed as a route param</li></ul><h3>Implementation</h3><h4>Step 1:</h4><p>Add some mock user data to the service file.</p><p>As we are using typescript it would be nice to add an interface for the user.</p><pre>// app.service.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br><br>// user interface<br>export interface IUser {<br>  id: number;<br>  name: string;<br>  age: number;<br>}<br><br>@Injectable()<br>export class AppService {<br>  // list of users<br>  private users: IUser[] = [<br>    {<br>      id: 1,<br>      name: &#39;Tamilan&#39;,<br>      age: 23,<br>    },<br>    {<br>      id: 1,<br>      name: &#39;Nandha&#39;,<br>      age: 24,<br>    },<br>    {<br>      id: 1,<br>      name: &#39;Nandha Kumar&#39;,<br>      age: 24,<br>    },<br>  ];<br>}</pre><h4>Step 2:</h4><p>Create a method findUsersByName that returns users matching the &#39;name&#39; query or all the users when there is no name query.</p><p>Add this method to the same service file</p><pre>findUsersByName(nameToBeMatched: string): IUser[] {<br>    return nameToBeMatched<br>      ? this.users.filter((user) =&gt;<br>          // return users with name matching<br>          // &#39;name&#39; query param<br>          user.name.toLowerCase().includes(nameToBeMatched),<br>        )<br>      : // returns all the users if the<br>        // &#39;name&#39; query param is &#39;null&#39; or &#39;&#39;<br>        this.users;<br>  }</pre><h4>Step 3:</h4><p>Create another method findUserById that returns a user matching the &#39;id&#39; route param</p><p>Add this method to the same service file</p><pre>findUserById(id: string): IUser {<br>    // return user with id matching &#39;id&#39; route param<br><br>    // By Default when you get value from query or route<br>    // param it will be string, But in our case user id is of<br>    // type number. So we are making a type conversion for id<br>    return this.users.find((user) =&gt; user.id === Number(id));<br>  }</pre><h4>Step 4:</h4><p>Update the base route of the controller to /user</p><pre>import { Controller, Get} from &#39;@nestjs/common&#39;;<br>import { AppService, IUser } from &#39;./app.service&#39;;<br><br>@Controller(&#39;/user&#39;) // update the base route to &#39;/user&#39;<br>export class AppController {<br>  constructor(private readonly appService: AppService) {}<br><br>}</pre><h4>Step 5:</h4><p>Implementing the first part of the requirement.</p><p>Create a method getUsers with @Get() decorator.</p><p>And it should take @Query() decorator as its argument. So that whenever we add the query to the URL, those params will be captured by this argument.</p><p>In the implementation pass the query params to the service method(findUsersByName) that we have already implemented in the service</p><p>Finally, return the data</p><pre>import { Controller, Get} from &#39;@nestjs/common&#39;;<br>import { AppService, IUser } from &#39;./app.service&#39;;<br><br>@Controller(&#39;/user&#39;)<br>export class AppController {<br>  constructor(private readonly appService: AppService) {}<br><br>  @Get()<br>  getUsers(@Query() params: any): IUser[] {<br>    return this.appService.findUsersByName(params.name);<br>  }<br>}</pre><p><strong>Pro Tip</strong></p><p>If you want a specific property from the query, you can specify the property name in the @Query() decorator like this 👇</p><pre>@Get()<br>  getUsers(@Query(&#39;name&#39;) name: string): IUser[] {<br>    return this.appService.findUsersByName(name);<br>  }</pre><h4>Step 6:</h4><p>Implementing the second part of the requirement.</p><p>Create a method getUserById with @Get(&#39;:id&#39;) decorator.</p><blockquote><strong><em>Note:<br></em></strong><em>Here we have defined &#39;:id&#39; route param in the </em><em>@Get()<br>decorator.</em></blockquote><p>And it should take @Param() decorator as its argument. So that the route param will be captured by this argument.</p><p>In the implementation pass the query params to the service method(findUserById) that we have already implemented in the service</p><p>Finally, return the data</p><pre>import { Controller, Get, Param, Query } from &#39;@nestjs/common&#39;;<br>import { AppService, IUser } from &#39;./app.service&#39;;<br><br>@Controller(&#39;/user&#39;)<br>export class AppController {<br>  constructor(private readonly appService: AppService) {}<br><br>  @Get()<br>  getUsers(@Query() params: any): IUser[] {<br>    return this.appService.findUsersByName(params.name);<br>  }<br><br>  @Get(&#39;:id&#39;)<br>  getUserById(@Param() params: any): IUser {<br>    return this.appService.findUserById(params.id);<br>  }<br>}</pre><p><strong>Pro Tip</strong></p><p>Similar to the @Query() decorator you can specify the property id in the @Param() decorator like this 👇</p><pre>@Get()<br>  getUsers(@Param(&#39;id&#39;) id: string): IUser {<br>    return this.appService.findUsersByName(id);<br>  }</pre><p>That&#39;s it!</p><p>As per the requirement, you have implemented the API.</p><h3>Testing</h3><p>Let&#39;s test the implementation now!</p><p>Start the server by executing</p><pre>npm run start:dev</pre><p>Open the server URL http://localhost:3000 in <a href="https://www.postman.com/">Postman</a> or any API Testing Tool</p><h4><strong>Test Case 1:</strong></h4><p>Getting all Users, without query params</p><figure><img alt="Nest JS Query and Route Param, Test Case — 1" src="https://cdn-images-1.medium.com/max/874/1*1uOdANnly7cA-hS84uYXig.png" /><figcaption>Nest JS Query and Route Param, Test Case — 1</figcaption></figure><p>And we got all the users.</p><p>✅ Test Case Passed!</p><h4><strong>Test Case 2:</strong></h4><p>Getting all Users, with name query param</p><figure><img alt="Nest JS Query and Route Param, Test Case — 2" src="https://cdn-images-1.medium.com/max/874/1*ZLhWsozFf6X2ZQ7YgR2Kxg.png" /><figcaption>Nest JS Query and Route Param, Test Case — 2</figcaption></figure><p>And we got all the users matching the name passed in the query param.</p><p>✅ Test Case Passed!</p><h4><strong>Test Case 3:</strong></h4><p>Getting User by id, with id route param</p><figure><img alt="Nest JS Query and Route Param, Test Case — 3" src="https://cdn-images-1.medium.com/max/874/1*DWW6AlB3hYA2vmBdCGCrOA.png" /><figcaption>Nest JS Query and Route Param, Test Case — 3</figcaption></figure><p>And we got the user with the id we passed in the route</p><p>✅ Test Case Passed!</p><p>Try implementing different scenarios with multiple Query and Route params.</p><p>Congratulation! 👏</p><p>You have successfully implemented APIs with Query and Route param in Nest.JS</p><p>Get the completed source code from <a href="https://github.com/nandhakumar-rs/nest-js-tutorial-series">here</a>.</p><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p><a href="https://medium.com/@nandhakumar.io">Follow me</a> to get notified of all upcoming posts on this series.</p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="https://mailto:contact@nandhakumar.io/">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221cc8000518" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/nestjs-tutorial-query-route-params-221cc8000518">NestJS Tutorial: Query &amp; Route Params</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nest JS Tutorial #2: HTTP Request & Data Validation]]></title>
            <link>https://javascript.plainenglish.io/nest-js-tutorial-2-http-request-data-validation-10c6493de2c9?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c6493de2c9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 04:17:36 GMT</pubDate>
            <atom:updated>2023-01-10T02:02:35.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdWE_9PG5g4cc7mxx4mOGg.png" /><figcaption>Nest JS Tutorial #2: HTTP Request &amp; Data Validation</figcaption></figure><h3>NestJS #2: HTTP Request &amp; Data Validation</h3><p>Hi There! 👋</p><p>In this post, you will learn what is HTTP Request and how to validate the request data in <a href="https://nestjs.com/">Nest JS</a></p><p>If you don’t know what is Nest JS, Check out <a href="https://medium.com/javascript-in-plain-english/nest-js-part-1-creating-your-first-api-71471ac39d3e">my previous post</a></p><blockquote><strong>Originally Posted On </strong>— <a href="https://www.nandhakumar.io/post/nest-js-tutorial-2-http-request-data-validation">https://www.nandhakumar.io/post/nest-js-tutorial-2-http-request-data-validation</a></blockquote><h3>Prerequisite</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">Javascript</a></li><li><a href="https://www.typescriptlang.org/">Typescript</a> (Optional)</li><li>Basics Of OOPS</li><li><a href="https://www.postman.com/">Postman</a> (For API Testing)</li><li><a href="https://code.visualstudio.com/">Code Editor</a></li><li><a href="https://nodejs.org/en/">Node.JS</a></li></ul><h3>What is an HTTP Request?</h3><p>HTTP Request is sent from the client machine(web browser or any other client application) to access or get information from the server.</p><p>These Requests are sent with the help of URLs like this 👇</p><pre>https://yourapp.com/api/v1/users</pre><h4>Three parts of HTTP Request</h4><p><strong>Methods</strong> — It defines the type of the request</p><p><strong>Headers</strong> — It will have the information about the request and sender(client), you can add custom parameters as well. Usually, Authorization Cookies will be attached to Headers.</p><p><strong>Body</strong> — It will have the request data. For example, when registering a new user, you have to pass user information as request data to store it in the server</p><h4>HTTP Request Methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*vGabLzO5quAzEF6pgGsL-A.png" /><figcaption>HTTP Request Methods</figcaption></figure><p>That’s a short brief on HTTP Requests.</p><p>To know more about HTTP Request, <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods"><strong>Click Here!</strong></a></p><h4>Why Request Data Validation?</h4><p>As you know the body part of the HTTP Request may have some data.</p><p>When the HTTP Request reaches the server, Getting the Body data directly without validating is not good. Sometimes you may get malicious data. So, it is required that you always validate your Request Body data.</p><h3>Understanding Nest.JS Validation</h3><p>In Nest.JS, We have something called a validation pipe. Whenever a request body is passed through this pipe and validated. If there are any invalid data, it will throw an error.</p><p><strong>Before moving further you need to understand what is DTO(Data Transfer Object)</strong></p><p><strong>DTO is a class where you will define the validation rules. If you are not sure about this no worries, you’ll understand this when implementing.</strong></p><h4>Two Parts Of Validation Pipe</h4><p><strong>Class Transformer -- </strong>It helps to transform your request body into a class instance of DTO and then the instance will be passed to the class validation</p><p><strong>Class Validator -- </strong>It will validate the request body based on the rules defined in the DTO and throws an error if there are any invalid data</p><p>Now let’s start the implementation for the example scenario given below</p><p><strong>Scenario: Need to add a new user and the user should have email, age, name, and country( Country is an optional property).</strong></p><p>As per the scenario, it’s clear that we need to add data to the server</p><p>So, it is an HTTP POST Method and we need to pass user data in the request body.</p><p>Hope you have already created a Nest.JS Project, If not follow my previous <a href="https://medium.com/javascript-in-plain-english/nest-js-part-1-creating-your-first-api-71471ac39d3e">tutorial</a> to create one.</p><p>Now, Let’s do the implementation step by step,</p><h3>Step 1:</h3><p>Install class validator and class transformer on your project</p><pre>npm i class-validator class-transformer -s</pre><h3>Step 2:</h3><p>Generate User Controller.</p><pre>nest g controller user</pre><blockquote><strong>Note: to execute nest commands you should have installed<br>nest cli globally</strong></blockquote><h3>Step 3:</h3><p>Generate User Module</p><pre>nest g module user/user --flat</pre><blockquote><strong>Note: As we have already created a user folder in Step 2,<br>To avoid creating additional folders --flag is used</strong></blockquote><h3>Step 4:</h3><p>Add User Controller to User Module</p><pre>// user.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { UserController } from &#39;./user.controller&#39;;<br>@Module({<br>  imports: [],<br>  providers: [],<br>  controllers: [UserController], // add user controller<br>})<br>export class UserModule {}</pre><h3>Step 5:</h3><p>Add User Module to App Module</p><pre>// app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { UserModule } from &#39;./user/user.module&#39;;<br><br>@Module({<br>  imports: [UserModule], // add user module<br>  controllers: [],<br>  providers: [],<br>})<br>export class AppModule {}</pre><h3>Step 6:</h3><p>Create a dto folder under the user folder and create a file called user.dto.ts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*ewtZaJWnfct2BcLf.png" /><figcaption>Nest JS Project Structure — User DTO</figcaption></figure><h3>Step 7:</h3><ul><li>Create UserDTO Class</li><li>Add the user properties to UserDTO as per the scenario</li></ul><pre>// user.dto.ts<br>export class UserDTO {<br>  email: string;<br>  age: string;<br>  name: number;<br>  country: number;<br>}</pre><h3>Step 8:</h3><p>Nest.JS uses <a href="https://www.typescriptlang.org/">Typescript</a> decorators extensively.</p><blockquote><strong>Note: </strong><a href="https://www.typescriptlang.org/docs/handbook/decorators.html"><strong>Decorators</strong></a><strong> are a simple function that helps to modify<br>the targeted value<br>Decorators are defined like </strong><strong>@[decoratorname]()</strong></blockquote><p>Coming back to the UserDTO,</p><p><strong>Class-Validator</strong> has a list of validation functions which can be used in the form of a decorator</p><p>Now, Let’s try to add the validation decorators to the class properties</p><pre>import { IsEmail, IsNumber, IsOptional, IsString } from &#39;class-validator&#39;;<br><br>export class UserDTO {<br>  @IsEmail()<br>  email: string;<br><br>  @IsNumber()<br>  age: string;<br><br>  @IsString()<br>  name: number;<br><br>  // add @IsOptional to make the country property optional<br>  @IsOptional() <br>  @IsString()<br>  country: number;<br>}</pre><h3>Step 9:</h3><ul><li>Create a controller to add a user</li><li>Add UserDTO as the type of the request body</li></ul><pre>import { Body, Controller, Post } from &#39;@nestjs/common&#39;;<br><br>import { UserDTO } from &#39;./dto/user.dto&#39;;<br>@Controller(&#39;user&#39;)<br>export class UserController {<br>  @Post()<br>  async addUser(@Body() user: UserDTO) {<br>    return user;<br>  }<br>}</pre><blockquote><em>Note:<br>I have added </em><a href="https://dev.to/post"><em>@post</em></a><em> Decorator to the function addUser as we &gt; are dealing with Post HTTP Request<br>Also, the @Body Decorator to get the request body</em></blockquote><h3>Step 10:</h3><p>Add Validation Pipe middleware globally in <strong>main.ts</strong>. By adding this globally, it helps DTO to validate the data all over the application.</p><pre>// main.ts<br>import { ValidationPipe } from &#39;@nestjs/common&#39;;<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>const CookieSession = require(&#39;cookie-session&#39;);<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br><br>  app.useGlobalPipes(<br>    // By adding this validation pipe globally, nest js helps us to validate body params, query param etc..<br>    new ValidationPipe({<br>      whitelist: true, // When Whitelist is set to true, You will not be allowed to send additional props apart from DTO Property<br>    }),<br>  );<br><br>  // Add Cookie Session Middleware to store user id in cookies on the response and the request.<br>  app.use(<br>    CookieSession({<br>      keys: [&#39;SecretKey&#39;],<br>    }),<br>  );<br>  app.listen(3000);<br>}<br>bootstrap();</pre><p>That’s it we have added validation to the addUser request body</p><h3>Testing</h3><p>Let’s test the implementation now!</p><p>Start the server by executing</p><pre>npm start:dev</pre><p>Open the server URL http://localhost:3000 in <a href="https://www.postman.com/">Postman</a> or any API Testing Tool</p><p><strong>Test Case 1:</strong></p><p>Passing all the user properties with an invalid email</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*Ui41Pckqg6c_PcBJ.png" /><figcaption>Nest.JS Postman Test Case #1</figcaption></figure><p>And the validation works!</p><p><strong>Test Case 2:</strong></p><p>Since the country property has been set to optional, Now let’s try to send the request without the country property</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*ncb81ZPt26BgUn79.png" /><figcaption>Nest.JS Postman Test Case #2</figcaption></figure><p>Now we got success response, even without the country property.</p><p>Try testing with different scenarios by passing invalid data and the validation should work as expected</p><p>Congratulation! 👏</p><p>You have successfully validated the request body in Nest.JS</p><p>Get the completed source code from <a href="https://github.com/nandhakumar-rs/nest-js-tutorial-series">here</a></p><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p><a href="https://medium.com/@nandhakumar.io">Follow me</a> to get notified of all upcoming posts on this series.</p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="https://mailto:contact@nandhakumar.io//">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c6493de2c9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/nest-js-tutorial-2-http-request-data-validation-10c6493de2c9">Nest JS Tutorial #2: HTTP Request &amp; Data Validation</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nest JS Part 1: Creating Your First API]]></title>
            <link>https://javascript.plainenglish.io/nest-js-part-1-creating-your-first-api-71471ac39d3e?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/71471ac39d3e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 06:16:37 GMT</pubDate>
            <atom:updated>2023-01-10T02:03:01.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ft5vokDOF1EHMcJGNc1GYQ.png" /><figcaption>NestJS Tutorial #1: Create Your First API</figcaption></figure><h3>NestJS #1: Create Your First API</h3><blockquote>Originally Posted On — https://www.nandhakumar.io/post/nest-js-tutorial-1-create-your-first-api</blockquote><p>Hi There! 👋</p><p>It’s been a couple of months working with <a href="https://nestjs.com/">Nest.JS</a> and I love the way the framework build to develop scalable server-side applications</p><p>I am still trying to learn more about Nest.JS, So thought of sharing my learning in the form of tutorial series from Beginner to Advanced.</p><p><a href="https://medium.com/@nandhakumar.io">Follow me</a> to get notified of all upcoming posts on this series.</p><p>Let’s Get Started Now! 🚀</p><h3>Prerequisite</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">Javascript</a></li><li><a href="https://www.typescriptlang.org/">Typescript</a> (Optional)</li><li>Basics Of OOPS</li><li><a href="https://www.postman.com/">Postman</a> (For API Testing)</li><li><a href="https://code.visualstudio.com/">Code Editor</a></li><li><a href="https://nodejs.org/en/">Node.JS</a></li></ul><h3>What is Nest.JS?</h3><p>Nest.JS is a framework to build highly scalable Node.JS server-side applications. It comes with the full support of typescript(It also allows us to build the app with pure JS as well).</p><p>It combines OOP(Object Oriented Programming) and Functional Programming to write clean and reusable code.</p><p>If you have ever built a server-side application, you would have heard about <a href="https://expressjs.com/">Express.JS</a> and <a href="https://www.fastify.io/">Fastify</a> libraries.</p><p>Under the hood, Nest.JS uses Express.JS as its default HTTP Server. If you prefer to use Fastify, you can switch easily <a href="https://docs.nestjs.com/first-steps">(More about this on official docs)</a></p><p>That’s a short brief on Nest.JS</p><h3>Generating Nest.JS Project</h3><p>Before generating the project, make sure you have installed the latest version of Node.JS on your system</p><p>I am using Node.JS Version v18.12.1</p><p>To generate a Nest.JS Project first, you need to install <a href="https://docs.nestjs.com/cli/overview">Nest Cli</a></p><pre>npm i -g @nestjs/cli</pre><p>Now generate a new Nest.JS project</p><pre>nest new [your project name]</pre><p>It will ask for,</p><ul><li>Which package manager (<a href="https://www.npmjs.com/">npm</a>, <a href="https://yarnpkg.com/">yarn</a>, <a href="https://pnpm.io/">pnpm</a>) to use? (I choose yarn, you can choose as you wish)</li></ul><p>Now open the project on your code editor</p><h3>Understanding Nest.JS Project Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*7OL0kPjKMxVK7AMB.png" /></figure><ul><li><strong>node_modules</strong> — Contains all the libraries that are required for your project.</li><li><strong>src</strong> — Contains your application source code, Under this directory Nest.JS has generated a starter code. Let’s explore what they are,</li><li><strong>app.controller.spec.ts</strong> — Contains unit test cases for each controller implementation</li><li><strong>app.controller.ts</strong> — Contains the implementation of the <a href="https://en.wikipedia.org/wiki/API">API</a></li><li><strong>app.service.ts</strong> — Contains business logic which will be used in the controller</li><li><strong>app.module.ts</strong> — Contains Imports, Exports and DI(Dependency Injection). More on this later…</li><li><strong>main.ts</strong> — Contains implementation to bootstrap the application. This is the starting point of your application</li><li><strong>test</strong> — Contains E2E test case implementations</li><li><strong>.eslintrc.js</strong> — Contains lint configuration that helps to identify incorrect syntax, typescript standards and more …</li><li><strong>.gitignore</strong> — Contains files &amp; directories to ignore when pushing the code to GitHub</li><li><strong>.prettierrc</strong> — Contains prettier config to format your code</li><li><strong>nest-cli.json</strong> — Basic Nest.JS Configuration</li><li><strong>package.json</strong> — Contains dependency, scripts, project version and more required for your project</li><li><strong>README.md</strong> — Contains documentation of your project</li><li><strong>tsconfig.json</strong> — Contains typescript configurations</li></ul><h3>Basic Understanding Of API(You can skip this section if you know what is an API)</h3><p>If you are a complete beginner in API development.</p><p>In simple terms,<br>Let’s say you have a raw cloth material and you want it to be stitched.</p><p>So you will go to a tailor and give your cloth to stitch. You will also give some instructions on how the design should be.</p><p>Considering the above example, In the computer world frontend application(Apps with user interfaces) will request certain data with some parameters(raw cloth material and instruction to design the cloth) to the server(tailor) in return server will send you the requested data as a response(stitched cloth).</p><p>These requests are sent using an API URL.</p><p>An API(Application programming interface) will look like this 👇</p><pre>// Example API<br>&quot;https://google.com/api/users&quot; // returns a list of users</pre><p>If you are still confused. Don’t worry, going forward you will figure it out.</p><h3>Creating Your First API</h3><p>Let’s start the server first</p><p>Open your terminal</p><p>Navigate to your project directory</p><p>And Run</p><pre>yarn start:dev</pre><blockquote><em>Replace </em><em>yarn with </em><em>npm or </em><em>pnpm if you have configured those package managers initially</em></blockquote><p>Now your server should have been started on</p><pre>http://localhost:3000</pre><p>To test the starter code generated by Nest.JS</p><p>Open Postman(tool to test the API)</p><p>Choose <strong>GET</strong> Method and Add the <strong>API URL(</strong><a href="http://localhost:3000/"><strong>http://localhost:3000</strong></a><strong>)</strong> then hit <strong>Send</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*W6LZn0WkEGHgjWtL.png" /></figure><p>You will see the response as “Hello World!”</p><p>Great!</p><p>You have executed your first API.</p><p>Now let’s try to customise this API in a way to get a list of user names</p><h3>Step 1</h3><p>Open <strong>app.controller.ts</strong></p><ul><li>Add <strong>/user</strong> route to <strong>@Controller()</strong> decorator</li><li>Change the function name under <strong>@Get()</strong> decorator to <strong>getUsers</strong></li><li>Change return type from <strong>string</strong> to <strong>string[]</strong></li><li>Change the App Service method name to <strong>getUsers</strong></li></ul><p>Code Snippet 👇</p><pre>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br><br>@Controller(&#39;/users&#39;) // Add &#39;/user&#39; route<br>export class AppController {<br>  constructor(private readonly appService: AppService) {}<br>// Change the function name to getUsers<br>  @Get()<br>  getUsers(): string[] { // Change return type to string[](stirng Array) <br>     // Change the service method name to getUsers<br>     return this.appService.getUsers(); <br>  }<br>}</pre><h3>Step 2</h3><p>Open <strong>app.service.ts</strong></p><ul><li>Change the function name <strong>getHello()</strong> inside AppService Class to <strong>getUsers()</strong></li><li>Change return type from <strong>string</strong> to <strong>string[]</strong></li><li>Change the return value from <strong>‘Hello World!’</strong> to [&#39;userOne&#39;,&#39;userTwo&#39;]</li></ul><p>Code Snippet 👇</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class AppService {<br>  // Change function name to getUsers<br>  getUsers(): string[] { // Change return type to string[](stirng Array) <br>    return [&#39;userOne&#39;, &#39;userTwo&#39;];<br>  }<br>}</pre><p>That’s it your user API is ready now.</p><p>Let’s test it in Postman</p><ul><li>Open Postman</li><li>Choose <strong>GET</strong> Method and Add the <strong>API URL(</strong><a href="http://localhost:3000/users"><strong>http://localhost:3000/users</strong></a><strong>)</strong> then hit <strong>Send</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*G57EtUs7A2m9HrYl.png" /></figure><p>If you got a response as a list of user names.</p><p>Congratulation! 👏</p><p>You have created your first API in Nest.JS</p><p>Get the completed source code from <a href="https://github.com/nandhakumar-rs/nest-js-tutorial-series">here</a></p><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p><a href="https://medium.com/@nandhakumar.io">Follow me</a> to get notified of all upcoming posts on this series.</p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="https://mailto:rsnk2013@gmail.com/">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-io/">LinkedIn</a> for more interesting stuff like this.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71471ac39d3e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/nest-js-part-1-creating-your-first-api-71471ac39d3e">Nest JS Part 1: Creating Your First API</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step By Step Guide To Dockerize React App Created Using Vite]]></title>
            <link>https://javascript.plainenglish.io/step-by-step-guide-to-dockerize-react-app-created-using-vite-90772423f7fb?source=rss-6b83e0207741------2</link>
            <guid isPermaLink="false">https://medium.com/p/90772423f7fb</guid>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nandhakumar Srinivasan]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 23:07:09 GMT</pubDate>
            <atom:updated>2024-08-27T06:10:37.062Z</atom:updated>
            <content:encoded><![CDATA[<p>React | Docker | Vite</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*730bnEXvIl-4zp-qc__M6g.jpeg" /></figure><blockquote><em>Originally Posted On — </em><a href="https://www.nandhakumar.io/post/step-by-step-guide-to-dockerize-vite-react-app-in-dev-environment"><em>https://www.nandhakumar.io/post/step-by-step-guide-to-dockerize-vite-react-app-in-dev-environment</em></a></blockquote><p>Hey Folks!</p><p>In this post, you’ll learn how to dockerize your react app created using the Vite tool for the development environment</p><h3>Prerequisites</h3><ul><li>Basic knowledge of React</li><li>Basic understanding of what is docker (I’ll give a brief on it as well)</li><li>Docker on your local system</li></ul><h3>What is Docker?</h3><p>Docker is a tool that helps to create a common environment(called as <strong>Container</strong> in the docker world) for development, testing and production.</p><p>Let’s say you are developing a react app on your local environment(development)</p><p>Now, once you are done with the development you need to hand over the source code to the testing team and if the testing team doesn’t have the same environment as your local environment there might be some issues which would be a blocker for testing.</p><p>Similar scenario for production as well.</p><p>So How can we ship the environment to all the places where ever you run the application?</p><p>And here comes Docker, It will create a virtual environment for your app to run and you can create and use the environment where ever you need to run your app.</p><p>Awesome right?</p><p>That’s a short brief on Docker.</p><p>If you want to know more about it check out the <a href="https://www.docker.com/">Official Docker Site</a></p><p>Now Let’s see how to Dockerize your React app.</p><blockquote><em>💡</em> <strong>Also, take a look at the most useful React hooks for your next project:</strong></blockquote><p><a href="https://differ.blog/p/most-useful-react-hooks-for-your-next-project-9b6060">🚀 Most Useful React Hooks for Your Next Project 🚀</a></p><blockquote><em>👉</em> To read more such acrticles, <a href="https://differ.blog/"><strong>sign up for free on Differ</strong></a>.</blockquote><h3>Step 1: Create React App Using Vite (Skip this step if you already have a react app)</h3><pre>npm create vite@latest</pre><p>You’ll be asked for</p><ul><li>App Name</li><li>Which Framework to use like React, Angular, or Vue? Choose React</li><li>Then, Typescript or Javascript. Choose as you wish</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*vqY_a4mTIkHdWWKJ.png" /><figcaption>Vite Project Initialization</figcaption></figure><p>Now switch to the project directory</p><pre>cd [your project name]</pre><h3>Step 2: Update vite.config File</h3><p>This step is required to map the port between Docker container and your React app</p><p>Now replace this code snippet in vite.config</p><pre>export default defineConfig({<br>  plugins: [react()],<br>})</pre><p>to</p><pre>export default defineConfig({<br>  plugins: [react()],<br>  server: {<br>    watch: {<br>      usePolling: true,<br>    },<br>    host: true, // needed for the Docker Container port mapping to work<br>    strictPort: true,<br>    port: 5173, // you can replace this port with any port<br>  }</pre><h3>Step 3: Create a Dockerfile</h3><p>Create a file called Dockerfile in the root of your project directory like this 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*5ApOMvlbtNSjeJe0.png" /></figure><h3>Step 4: Add Commands to Dockerfile</h3><p>Copy these commands to your Dockerfile</p><pre>FROM node<br>WORKDIR /app<br>COPY package.json .<br>RUN npm i<br>COPY . .<br>## EXPOSE [Port you mentioned in the vite.config file]<br>EXPOSE 5173<br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;dev&quot;]</pre><p>If you don’t know what are these commands, read the explanation 👇</p><ul><li>FROM node - Will create a node environment in the container</li><li>WORKDIR /app - Will create a directory app and switch to that directory</li><li>COPY package.json . - Copies package.json file to /app directory</li><li>RUN npm i - Runs npm install to create node_modules for your app</li><li>COPY . . - Copies the source code to /app directory</li><li>EXPOSE 5173 - Exposes the port to access the app from outside the container i.e from the browser</li><li>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;dev&quot;] - Executes npm run dev to start the server</li></ul><h3>Step 5: Build the Dockerfile</h3><p>In the terminal navigate to your project directory, then execute</p><p>!! Remove the [ ] when executing</p><pre>docker build -t [any name] .</pre><p><strong>Flag used in the command</strong></p><ul><li>-t - To tag the container (This will be your container name)</li></ul><p>After the build completion, a docker image will be created.</p><p>Docker Image is a template to run the container.</p><p>To check your Docker Image, execute</p><pre>docker images</pre><p>It will show the list of images available on your system</p><p>Check whether the name of the image you have given when running the docker build command is available in the list.</p><h3>Step 6: Run the Docker Container</h3><p>Execute this command in the terminal 👇</p><p>!! Remove the [ ] when executing</p><pre>docker run -d --rm -p 5173:5173 --name [name of the container] [your docker image name]</pre><p><strong>Flag used in the command</strong></p><ul><li>-d - To run the container in the background (Detach Mode )</li><li>--rm - To delete the container, when you stop the container</li><li>-p - Port Mapping between container and outside world.</li><li>5173:5173 - [Port access from Browser]: [Port exposed from the container]</li></ul><p>To check whether your docker container is running or not, execute</p><pre>docker ps</pre><p>It will show the list of containers running on your system</p><p>Check whether the name of the container you have given when running the docker run command is available in the list.</p><h3>Step 7: Open the App in the Browser</h3><p>Open the Browser and access http://localhost:[Port you mentioned in the docker run command] as per the configuration we did so far it should be <a href="http://localhost:5173/">http://localhost:5173</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*FLGJYIN67ieh7gOn.png" /></figure><h3>Thanks For Reading!</h3><p>Hope you have learned something new today 😊.</p><p>Follow and connect with me on <a href="https://twitter.com/nandhakumar_io">Twitter</a>, <a href="https://www.instagram.com/nandhakumar.io/">Instagram</a>, <a href="https://mailto:rsnk2013@gmail.com/">Email</a> and <a href="https://www.linkedin.com/in/nandhakumar-dev/">LinkedIn</a> for more interesting stuff like this.</p><p>My Personal Blog <a href="https://www.nandhakumar.io/">nandhakumar.io</a></p><p>Cheers ✌️</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90772423f7fb" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/step-by-step-guide-to-dockerize-react-app-created-using-vite-90772423f7fb">Step By Step Guide To Dockerize React App Created Using Vite</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>