<?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 Angular&amp;NodeEnthusiast on Medium]]></title>
        <description><![CDATA[Stories by Angular&amp;NodeEnthusiast on Medium]]></description>
        <link>https://medium.com/@ramya-bala221190?source=rss-f2cd68202ac6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Angular&amp;amp;NodeEnthusiast on Medium</title>
            <link>https://medium.com/@ramya-bala221190?source=rss-f2cd68202ac6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:30:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramya-bala221190/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[Setting up Docker-in-Docker for testing Docker Swarm locally]]></title>
            <link>https://blog.stackademic.com/setting-up-docker-in-docker-for-testing-docker-swarm-locally-c32a4ae6b8d6?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c32a4ae6b8d6</guid>
            <category><![CDATA[worker-node]]></category>
            <category><![CDATA[node-manager]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[docker-swarm]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 11:43:49 GMT</pubDate>
            <atom:updated>2025-11-04T05:46:07.914Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker Compose and Docker Swarm are both tools within the Docker ecosystem, but they serve different purposes.</p><p>Docker Compose is for managing multi-container applications on a single machine, for development and testing. Use Docker Swarm when you need to deploy and manage containerized applications at scale across multiple machines in a production environment, requiring features like high availability and load balancing.</p><p>Docker-in-Docker (DIND) is useful for testing Docker Swarm locally to avoid the overhead of managing multiple VMs or cloud instances. This is because it allows you to simulate a multi-node Swarm cluster on a single physical machine.</p><p>With this setup you can run multiple Docker daemons as containers, mimicking separate nodes in a Swarm cluster without needing multiple physical or virtual machines. Each DIND container acts as an independent Docker engine, thus making it easy to spin up clean, isolated environments for testing orchestration, networking, and service deployment</p><p>Everything runs locally, which is faster and cheaper for development and experimentation.</p><p>Lets begin !</p><ol><li>We are going to simulate a multi-node Swarm cluster entirely on a single machine by running multiple DIND containers. You’ll run several containers by pulling the <strong>docker:dind</strong> image. Each container acts as a separate Docker host. Then you’ll initialize Swarm on one of the DIND containers(which will function as the manager) and join other DIND containers as workers.</li></ol><p>The docker swarm services/containers will run within the DIND containers(functioning as swarm nodes).</p><p>Open the command prompt window and lets first create a custom docker network: <strong>dind-net </strong>to enable communication between the DIND containers, which we shall launch shortly.</p><pre>docker network create --driver bridge dind-net</pre><p>Next, we create the manager,worker1,worker2 and worker3 DIND containers using the below commands.</p><pre>docker run --privileged --name manager -p 4000:4000 --network dind-net -d docker:dind<br>docker run --privileged --name worker1 --network dind-net -d docker:dind<br>docker run --privileged --name worker2 --network dind-net -d docker:dind<br>docker run --privileged --name worker3 -p 4001:4001 --network dind-net -d docker:dind</pre><p><strong>docker run</strong> command will launch a new container from the <strong>docker:dind</strong> image.</p><p>The <strong>— privileged </strong>flag grants extended privileges to the container, allowing it to run Docker inside Docker (DIND). This is essential for Swarm testing.</p><p>The <strong>— name</strong> flag assigns the name to the container, making it easier to reference.</p><p>The <strong>— network dind-net </strong>flag connects the container to the custom docker network <strong>dind-net</strong> we create earlier. This enables communication between the DIND containers.</p><p>The<strong> -d </strong>flag runs the container in detached mode (in the background).</p><p>Finally lets understand the<strong> -p</strong> flag in the first and last command. The purpose of the flag is to achieve port mapping between the host machine and the DIND container.</p><pre>docker run --privileged --name manager -p 4000:4000 --network dind-net -d docker:dind</pre><p>In the above command we are mapping <strong>port 4000 on your host</strong> to <strong>port 4000 inside the manager DIND container. </strong>If a docker swarm service/container runs within the manager DIND container, with its host port set to 4000 as well, this flag makes that particular service accessible from your host machine at <strong>localhost:4000</strong>. We will be deploying the API and Edge gateway services to the manager DIND container which will be thus accessible from localhost:4000. We will get into the details of the application later in the story.</p><p>Similarly, in the below command, we are mapping <strong>port 4001 on your host</strong> to <strong>port 4001 inside the worker3 DIND container. </strong>If a docker swarm service/container runs within the manager DIND container, with its host port set to 4001 as well, this flag makes it accessible from your host machine at <strong>localhost:4001</strong>. We will be deploying the ELK(ElasticSearch Logstash Kibana)stack to the worker3 DIND container to access the Kibana dashboard from<strong> localhost:4001</strong>.</p><pre>docker run --privileged --name worker3 -p 4001:4001 --network dind-net -d docker:dind</pre><p>We do not want expose the services running in the worker1 and worker2 DIND containers. Hence there is no <strong>-p flag </strong>when launching these containers. We will be deploying the 2 Express JS microservices to these 2 DIND containers. The API/Edge gateway will route client requests to these microservices. Hence these 2 microservices have no need to be exposed.</p><p>Post execution of above commands, you will find 4 running DIND containers in docker desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rU-uv4Zo9-0Z0G1sVHM89A.png" /></figure><p>Check each container’s port bindings. Below is an example for manager DIND container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50EbOfMP6vaM4IcvK8b75Q.png" /></figure><p>Below is for worker3 DIND container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiKBihiHLzBGuqTkz6c3dg.png" /></figure><p>2. Lets now inspect the shared docker network <strong>dind-net </strong>to extract the manager DIND container IP4 address:<strong> 172.26.0.3. </strong>You can also find the IPv4 addresses of other containers as well using the below command</p><pre>docker network inspect dind-net</pre><p>3. The next step here, would be to start a Docker Swarm cluster using <strong>docker swarm init</strong> command.</p><p>Running <strong>docker swarm init</strong> inside a DIND container performs the below steps:</p><p>=&gt;It turns the DIND container into the <strong>first manager node</strong> of a new Docker Swarm cluster. This node can now orchestrate services and manage other nodes.</p><p>=&gt;It creates <strong>join tokens</strong> for worker and manager nodes, which you can use to add other DIND containers to the cluster using <strong>docker swarm join</strong>.</p><p>Note: Its recommended to have odd no of managers in the docker swarm cluster. In this example, we have only 1 manger node. But the recommendation would be to have 3–5 manager nodes in swarm cluster.</p><p>Lets now initialize a swarm cluster and turn the DIND container with name “manager” into the first manager node of the cluster using the docker swarm join command. <strong>176.26.0.3</strong> is the manager container IP we have have extracted from the <strong>dind-net</strong> network inspection earlier.</p><pre>docker exec -it manager docker swarm init --advertise-addr 172.26.0.3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ixm_P4YRu3Wbp7iQ7RiGsQ.png" /></figure><p>If you observe the above screenshot, you can see separate instructions for adding worker nodes and additional manager nodes to the cluster.</p><p><strong>Note: In case you closed the CMD window by mistake at this stage and have no idea what is the joining token for worker nodes, you just need to execute the below command to retrieve the joining token for worker nodes.</strong></p><pre>docker swarm join-token worker</pre><p>Now lets make the DIND containers with names: worker1, worker2 and worker3 join the swarm cluster as worker nodes using the below commands.</p><pre>docker exec -it worker1 docker swarm join --token SWMTKN-1-5jsdqidwxvwqnw94ggh5qrc4ukeng84cy11t6qdcidralbupqr-9vjgub8pg5yk331xr8f8fru1d 172.26.0.3:2377<br>docker exec -it worker2 docker swarm join --token SWMTKN-1-5jsdqidwxvwqnw94ggh5qrc4ukeng84cy11t6qdcidralbupqr-9vjgub8pg5yk331xr8f8fru1d 172.26.0.3:2377<br>docker exec -it worker3 docker swarm join --token SWMTKN-1-5jsdqidwxvwqnw94ggh5qrc4ukeng84cy11t6qdcidralbupqr-9vjgub8pg5yk331xr8f8fru1d 172.26.0.3:2377</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GerlyYwvY8e4gElcU1wKBQ.png" /></figure><p>In this example, I am not adding additional manager nodes.</p><p>But in case you want to add 1 or more DIND containers as manager nodes to the cluster, you need to execute the below command to get a unique joining token and follow the instructions given.</p><pre>docker swarm join-token manager</pre><p>4. Lets now shell back into the manager DIND container and list out the swarm cluster nodes using<strong> docker node ls</strong>. Each row represents a swarm node i.e a <strong>DIND container that has joined the Swarm cluster</strong>, either as <strong>manager</strong> or <strong>worker node.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-Ul_uz-dqdE3tfsMz2VaA.png" /></figure><p>The node with ID <strong>l34n9pq6ze5hbpxb0ibqmmcak </strong>is the manager node(evident from the Manager Status column).</p><p>How do we identify which node is the worker1 node, worker2 and worker3 node ? Hostname comes to the rescue.</p><p>In <strong>DockerDesktop app</strong>, inspect the hostname field in the <strong>worker1 </strong>DIND container. It is <strong>d4966bb78cd4. </strong>From the above screenshot the node ID corresponding to this hostname is<strong> m8rw01olnu82tu45q8sdb4joo</strong>. This is the node ID for <strong>worker1 </strong>node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wZkBjAsGDSmEykFr4qHZA.png" /></figure><p>In <strong>DockerDesktop</strong>, inspect the hostname field in the <strong>worker2 </strong>DIND container. It is <strong>c2c8d56424b5. </strong>From the above screenshot the node ID corresponding to this hostname is<strong> zqx1aizf1sazjslc83cwcpjnt</strong>. This is the node ID for <strong>worker2 </strong>node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rs-J1wV4w6hFYTiGtXoydA.png" /></figure><p>This obviously means that <strong>uwjez4gu4fqgvmi142yqncmc2 </strong>is the node ID for <strong>worker3 </strong>node.</p><p><strong>We need these node IDS to assign a role label to the nodes.</strong> <strong>It is very important to distinguish between swarm nodes when deploying the docker services.</strong></p><p>For this, again we need to shell into the manager DIND container and execute the below commands:</p><pre>docker node update --label-add role=manager l34n9pq6ze5hbpxb0ibqmmcak<br>docker node update --label-add role=worker1 m8rw01olnu82tu45q8sdb4joo<br>docker node update --label-add role=worker2 zqx1aizf1sazjslc83cwcpjnt<br>docker node update --label-add role=worker3 uwjez4gu4fqgvmi142yqncmc2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDSHGfM7Er9B0eX2tckGwg.png" /></figure><p>Once these commands are executed, how do we verify the update ? We use the below command</p><pre>docker node inspect &lt;node-id&gt;</pre><p>Lets do it for <strong>worker1 </strong>node and check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XlWf2rHzKjEOe3xPVMpdw.png" /></figure><p>5. Let’s remain shelled into the manager DIND container.</p><p>We are going to deploy the gateway, 2 microservices and ELK stack into the swarm nodes.</p><p>Below is how the application flows. The nginx service receives the request from the client. The nginx acts as a reverse proxy and also as a loadbalancer if there are multiple instances of the express-gateway service. It forwards the request to one of the express-gateway instance using the default round robin loadbalancing algorithm. The express-gateway instance acts as a router and a loadbalancer for multiple instances of the Cart and Product Microservice. It routes the request to the correct microservice based on the request URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94sDE1IrrOFwsWt0TPWoBw.png" /></figure><p>How does ELK stack fit here ?</p><p><strong>Microservices and Gateways</strong>: Generate logs (e.g., application logs, access logs).</p><p><strong>Filebeat</strong>: It tails these log files and forwards them.</p><p><strong>Logstash</strong>: Ingests logs from Filebeat , parses and transforms them (e.g., JSON decoding, filtering).</p><p><strong>Elasticsearch</strong>: Stores and indexes the logs for fast search and analytics.</p><p><strong>Kibana</strong>: Visualizes the data from Elasticsearch with dashboards and queries.</p><p>=&gt;The Express-Gateway API gateway and Nginx Edge Gateway is deployed to the manager node.</p><p>=&gt;The cart and product microservice is deployed to worker1 and worker2 nodes respectively.</p><p>=&gt;Finally the ELK stack will be deployed to worker3 node.</p><p>While we remain shelled into the manager DIND container, lets also create 2 overlay networks <strong>shared-swarm-net-dev</strong> and <strong>shared-swarm-net-prod</strong>. I will explain the purpose of these 2 networks.</p><pre>docker network create --driver overlay shared-swarm-net-dev<br>docker network create --driver overlay shared-swarm-net-prod</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hE0y5J922H-1ZZGOfI5tg.png" /></figure><p>Why do we need these 2 networks ?</p><p>In a Docker Swarm setup using Docker-in-Docker (DIND), you typically have <strong>two types of containers</strong>:</p><p><strong>DIND Containers : </strong>These are the containers running the Docker daemon inside them. Each DIND container acts like a <strong>virtual Docker host</strong>. You run <strong>docker swarm init</strong> or <strong>docker swarm join</strong> inside these containers to make them behave as manager or worker nodes and form the swarm cluster. Examples are manager, worker1, worker2 and worker3 containers discussed in the beginning of the story.</p><p><strong>Swarm Service Containers: </strong>These are the containers created when you deploy services using <strong>docker service create</strong> or <strong>docker stack deploy</strong>. The purpose of these containers is to run your actual application. Examples are containers running nginx, express-gateway, express JS applications, Mongo DB etc. We have not discussed this. This we will discuss as we progress in the story.</p><p>So when I say “containers”, it depends on context:</p><p>=&gt;If you’re listing DIND nodes: you’re seeing <strong>DIND containers</strong>.</p><p>=&gt;If you’re listing services deployed via Swarm: you’re seeing <strong>Swarm service containers</strong>.</p><p>So the purpose of <strong>shared-swarm-net-dev</strong> and <strong>shared-swarm-net-prod </strong>networks is to enable communication between the <strong>Swarm service containers </strong>running on different nodes in the swarm cluster.</p><p><strong>shared-swarm-net-dev </strong>and <strong>shared-swarm-net-prod </strong>could help to differentiate the service containers for different application environments. Although in this story, we stick to a single environment: dev.</p><p>Lets now exit the manager DIND container shell.</p><p>6. Lets begin with the API and Edge Gateway deployment to the manager DIND container(functioning as manager node).</p><p>It is essential that we have built the docker images for the services and have pushed the images to a registry like <strong>DockerHub </strong>beforehand.</p><p>This is the project structure. I have highlighted the folders relevant to this example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*J4sRj9aQV6x6bDDvBRIUTA.png" /></figure><p>Below is the <strong>docker-compose.stack.yml.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13243a917a4a9c9f5dae318ba0832c9e/href">https://medium.com/media/13243a917a4a9c9f5dae318ba0832c9e/href</a></iframe><p>In this file, we have 3 services: <strong>nginx, express-gateway-service and filebeat</strong>.</p><p>Lets now understand what is a <strong>stack </strong>?</p><p>In Docker, a <strong>stack</strong> is a collection of services that make up an application and are deployed together using Docker Swarm. Stacks are defined in a compose file as you see above, but used in <strong>Swarm mode</strong>.</p><p>A <strong>stack</strong> includes:</p><ul><li>Multiple services (e.g., web server, database, cache)</li><li>Networks connecting those services</li><li>Volumes for persistent storage</li><li>Deployment rules (e.g., replicas, placement constraints)</li></ul><p>Lets check the <strong>deploy </strong>section in each of these docker services. This section is used to configure deployment settings for services in Docker Swarm mode.</p><pre>deploy:<br>   restart_policy:<br>       condition: on-failure<br>   placement:<br>       constraints: [node.labels.role == manager]</pre><p><strong>condition:on-failure </strong>means that the container will only restart if it exits with a non-zero status (i.e., it failed). It won’t restart on successful exit or manual stop.</p><p><strong>constraints: [node.labels.role == manager] </strong>ensures the swarm service runs only on nodes labeled with <strong>role=manager</strong>.</p><p>Below is the override file for development environment: <strong>docker-compose.stack.dev.override.yml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1badf5310393af04af0a87f9a2d4e360/href">https://medium.com/media/1badf5310393af04af0a87f9a2d4e360/href</a></iframe><p>In the override file, observe the ports for nginx service. We have mapped the <strong>host port 4000</strong> to the <strong>container port 8400</strong>.</p><p>Please recall that we launched the manager DIND container with the host-container port mapping =&gt;<strong> 4000:4000</strong>.</p><p>This means the requests on<strong> localhost:4000</strong> in the browser will be forwarded to the <strong>manager DIND container listening on port 4000</strong>. The manager DIND container which has become the manager node of the swarm cluster is acting as a host for the nginx docker container. So any requests to the manager DIND container on port 4000 will be forwarded to the nginx docker container listening on port 8400.</p><p>I have written a <strong>copyAndDeploy.bat </strong>script within the <strong>scripts </strong>folder in the project, to help copy the stack compose files and environment files to the manager DIND container and deploy the stack easily.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90ffd8744fb3eaaf5c840e1686569f0f/href">https://medium.com/media/90ffd8744fb3eaaf5c840e1686569f0f/href</a></iframe><p>This script performs the below steps:</p><ol><li>Creates 2 directories: <strong>gateway/environments</strong> and <strong>gateway/swarm</strong> in the manager DIND container.</li></ol><pre>docker exec %CONTAINER_NAME% mkdir -p /%FOLDER_NAME% /%FOLDER_NAME%/environments /%FOLDER_NAME%/swarm</pre><p>2. We are copying all the relevant<strong> .env</strong> files <strong>/gateway/environments</strong> directory and the<strong> .stack </strong>files into the<strong> /gateway/swarm </strong>directory. We are also copying a <strong>deploy.sh</strong> shell script into the <strong>gateway </strong>folder. The purpose of this shell script is to undeploy any existing stack for the project and redeploy the new stack.</p><pre>docker cp ../docker/swarm/docker-compose.stack.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.yml<br>docker cp ../docker/swarm/docker-compose.stack.dev.override.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.dev.override.yml<br>docker cp ../docker/swarm/docker-compose.stack.prod.override.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.prod.override.yml<br>docker cp ../docker/environments/dev.env %CONTAINER_NAME%:/%FOLDER_NAME%/environments/dev.env<br>docker cp ../docker/environments/common.env %CONTAINER_NAME%:/%FOLDER_NAME%/environments/common.env<br>docker cp deploy.sh %CONTAINER_NAME%:/%FOLDER_NAME%/deploy.sh</pre><p>Below is the<strong> deploy.sh</strong> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42e05c4519c37e3c2422ef6131f35204/href">https://medium.com/media/42e05c4519c37e3c2422ef6131f35204/href</a></iframe><p>3. Finally we make the <strong>deploy.sh </strong>shell script executable using the <strong>chmod </strong>command and then execute it. <strong>Note that the shell script is executed while we remain shelled into the manager DIND container.</strong></p><pre>docker exec %CONTAINER_NAME% chmod +x /%FOLDER_NAME%/%SCRIPT_NAME%<br>docker exec %CONTAINER_NAME% /bin/sh /%FOLDER_NAME%/%SCRIPT_NAME%</pre><p>What does the <strong>deploy.sh</strong> do ? Observe the commands in the file.</p><pre>docker stack rm “$STACK_NAME”</pre><p>This command must be run in the manager DIND container(functioning as manager node). It is used to remove an entire application stack from a Docker Swarm cluster. It stops and removes all the services, networks, and secrets associated with the specified stack. In our case the stack name is <strong>mygatewayStack</strong>.</p><p>Once we have removed any existing stack with the name <strong>mygatewayStack</strong>, we redeploy the <strong>mygatewayStack </strong>with the below command. We have passed the <strong>docker-compose.stack.yml</strong> and the <strong>docker-compose.stack.dev.override.yml </strong>file as values to the <strong>c flag</strong>. We have also passed the stack name.</p><pre>docker stack deploy -c “$COMPOSE_FILE” -c “$OVERRIDE_FILE” “$STACK_NAME”</pre><p>This command performs the below actions:</p><p><strong>=&gt; Deploys the stack</strong> named <strong>mygatewayStack </strong>using the configuration in <strong>docker-compose.stack.yml</strong> and the <strong>docker-compose.stack.dev.override.yml </strong>file</p><p><strong>=&gt; Creates docker swarm services for each defined container</strong>. In the <strong>docker-compose.stack.yml</strong> we have 2 docker compose services: <strong>nginx </strong>and <strong>express-gateway-service</strong>. Via the <strong>replicas </strong>field ,we have provided the instruction to created <strong>3 replicas of the docker swarm express-gateway-service</strong> and a <strong>single nginx service</strong>(absence of replicas field defaults to 1 swarm service).<strong> So we are expecting 3 docker containers and 3 docker swarm services for the express-gateway-service. We are also expecting 1 docker container and 1 docker swarm service for nginx service.</strong></p><p><strong>=&gt; Distributes containers</strong> across nodes in the Swarm cluster. Both the <strong>express-gateway-service and nginx service are configured to run in the manager node via placement constraints.</strong></p><p><strong>=&gt; Applies deployment settings</strong> like replicas, placement constraints, restart policies, etc.</p><p>So i will navigate to the project folder and execute the <strong>copyAndDeploy.bat</strong> script to automate the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gimplRFdzV6tvnq37bU_3A.png" /></figure><p>You can now shell into the manager DIND container and check the <strong>mygatewayStack </strong>created using the below command</p><pre>docker stack services mygatewayStack</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KUiNIczXRCcf3VjdqMrBQ.png" /></figure><p>You can further inspect each service using the below command for any errors or the status of the service.</p><pre>docker service ps &lt;service-name&gt;</pre><p>Lets check the running containers in the manager DIND container using the <strong>docker ps</strong> command . We have 5 running containers: 3 containers for <strong>express-gateway-service</strong>, 1 container for <strong>filebeat </strong>and the last for <strong>nginx</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBdrx5AXKRwaZfYtJK16PA.png" /></figure><p>So let me summarize the functions of the manager and worker nodes in the swarm stack.</p><p>=&gt; <strong>Manager node functions as the Orchestrator</strong>. When you run <strong>docker stack deploy</strong>, you’re telling the <strong>manager node</strong> to interpret the Compose file and orchestrate the deployment. It decides which nodes should run which swarm services. The manager schedules the swarm services, maintains cluster state, and handles scaling, updates, and rollbacks.</p><p>=&gt;<strong>Worker nodes functions as the Executors</strong>. The swarm service containers are run on <strong>worker nodes</strong> based on resource availability and placement constraints. Worker nodes receive instructions from the manager and report back on health and status. They don’t make scheduling decisions — they just execute. Worker nodes pull the necessary images and start swarm service containers.</p><p>2. Lets begin with the deployment of <strong>CartMicroservices </strong>app to the <strong>worker1 DIND container(functioning as worker1 node).</strong>Again here we have built the docker images for the services and have pushed the images to a registry like <strong>DockerHub </strong>beforehand.</p><p>Below is the project structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*EudfpU9EMqN7x4qBQXIZLQ.png" /></figure><p>Below is the <strong>docker-compose.stack.yml. </strong>Here please observe the <strong>placement.contraints</strong> section. The manager node <strong>interprets the placement constraints</strong> and ensures the service is scheduled only on the specified <strong>worker1 </strong>DIND container(functioning as a<strong> worker1 node</strong>). This ensures the service runs only on the particular worker node. The manager node will handle orchestration but won’t run the service container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a53353845f0176c1e8d95c42ca16969a/href">https://medium.com/media/a53353845f0176c1e8d95c42ca16969a/href</a></iframe><p>Below is the <strong>docker-compose.stack.dev.override.yml. </strong>We have not specified any port mapping for the <strong>worker1 </strong>DIND container. Hence any docker swarm services(containers) running within the <strong>worker1 </strong>DIND container(functioning as worker node) cannot be accessed from the browser. As mentioned earlier, the swarm service containers running in different nodes(DIND containers) can communicate with each other via the overlay network created in the beginning.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57ced0f5067ef3909b17572a769d17fe/href">https://medium.com/media/57ced0f5067ef3909b17572a769d17fe/href</a></iframe><p>We have again written a similar <strong>copyAndDeploy.bat</strong> script in the project to automate the local deployment process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4daea29c8464e089531ed528b34f17e0/href">https://medium.com/media/4daea29c8464e089531ed528b34f17e0/href</a></iframe><p>This script performs the below steps:</p><ol><li>Creates 2 directories: <strong>cartmicrosvcs/environments</strong> and <strong>cartmicrosvcs/swarm</strong> in the manager DIND container.</li></ol><pre>docker exec %CONTAINER_NAME% mkdir -p /%FOLDER_NAME% /%FOLDER_NAME%/environments /%FOLDER_NAME%/swarm</pre><p>2. We are copying all the relevant<strong> .env</strong> files <strong>/cartmicrosvcs/environments</strong> directory and the<strong> .stack </strong>files into the <strong>/cartmicrosvcs/swarm</strong> directory. We are also copying a similar <strong>deploy.sh</strong> shell script into the <strong>cartmicrosvcs </strong>folder to undeploy and redeploy.</p><pre>docker cp ../docker/swarm/docker-compose.stack.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.yml<br>docker cp ../docker/swarm/docker-compose.stack.dev.override.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.dev.override.yml<br>docker cp ../docker/swarm/docker-compose.stack.prod.override.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.prod.override.yml<br>docker cp ../docker/environments/dev.env %CONTAINER_NAME%:/%FOLDER_NAME%/environments/dev.env<br>docker cp ../docker/environments/common.env %CONTAINER_NAME%:/%FOLDER_NAME%/environments/common.env<br>docker cp deploy.sh %CONTAINER_NAME%:/%FOLDER_NAME%/deploy.sh</pre><p>Below is the <strong>deploy.sh</strong> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe1a72fe9a8f40ed02df46a8c9fed9e6/href">https://medium.com/media/fe1a72fe9a8f40ed02df46a8c9fed9e6/href</a></iframe><p>3. Finally we make the <strong>deploy.sh </strong>shell script executable using the <strong>chmod </strong>command and then execute it.</p><pre>docker exec %CONTAINER_NAME% chmod +x /%FOLDER_NAME%/%SCRIPT_NAME%<br>docker exec %CONTAINER_NAME% /bin/sh /%FOLDER_NAME%/%SCRIPT_NAME%</pre><p>What does the <strong>deploy.sh</strong> do ? As already discussed, it removes any existing application stack with name <strong>mycartStack </strong>and redeploys a new <strong>mycartStack.</strong></p><p>In the <strong>docker-compose.stack.yml</strong> we have 3 docker compose services: cart-node, cart-db and filebeat. Via the <strong>replicas </strong>field ,we have provided the instruction to created <strong>3 replicas of the docker swarm cart-node service </strong>and a <strong>single cart-db and filebeat service</strong>(absence of replicas field defaults to 1 swarm service).<strong> So we are expecting 3 docker containers and 3 docker swarm services for the cart-node service. We are also expecting 1 docker container and 1 docker swarm service each for the cart-db and filebeat service.</strong></p><p>The <strong>cart-node, cart-db </strong>and <strong>filebeat</strong> swarm services <strong>are configured to run in the worker1 node.</strong></p><p>So i will navigate to the project folder and execute the <strong>copyAndDeploy.bat</strong> script to automate the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjvI-J6U1mm21p5BOmj5zg.png" /></figure><p>Shell into the <strong>manager </strong>DIND container to inspect the <strong>mycartStack.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5mKwopqoP7If_Y0Nr3c_A.png" /></figure><p>Lets exit the <strong>manager </strong>DIND container and check the running containers in the <strong>worker1 </strong>DIND container using the <strong>docker ps</strong> command. We have 5 running containers: 3 for<strong> cart-node </strong>swarm service, 1 each for <strong>cart-db </strong>and <strong>filebeat </strong>service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jK0tBQG8OvVQCSNmk0MpBw.png" /></figure><p>3.Lets begin with the deployment of <strong>ProductMicroservices </strong>app to the <strong>worker2 DIND container</strong> (functioning as <strong>worker2 node</strong>). Again we have built the docker images for the services and have pushed the images to a registry like <strong>DockerHub </strong>beforehand.</p><p>Below is the project structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*Qz64Nu-ObCYhbrQYs4hrxQ.png" /></figure><p>Below is the <strong>docker-compose.stack.yml. </strong>Here please observe the <strong>placement.contraints</strong> section. The manager node <strong>interprets the placement constraints</strong> and ensures the service is scheduled only on the specified <strong>worker2 </strong>DIND container(functioning as a <strong>worker2 node</strong>). This ensures the service runs only on the particular worker node. The manager node will handle orchestration but won’t run the service container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a4a9465884bde64a5670022cda59c5b/href">https://medium.com/media/7a4a9465884bde64a5670022cda59c5b/href</a></iframe><p>Below is the <strong>docker-compose.stack.dev.override.yml. </strong>We have not specified any port mapping for the worker2 DIND container when launching it in the beginning of the story. Hence any docker swarm services(containers) running within the <strong>worker2 </strong>DIND container(functioning as worker node) cannot be accessed from the browser. As mentioned earlier, the swarm service containers running in different nodes(DIND containers) can communicate with each other via the overlay network created in the beginning.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b28f0964bd5243c0a6b61e031213eb74/href">https://medium.com/media/b28f0964bd5243c0a6b61e031213eb74/href</a></iframe><p>We have again written a similar <strong>copyAndDeploy.bat</strong> script in the project to automate the local deployment process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/339a68e859483ad58f16537c588bdf82/href">https://medium.com/media/339a68e859483ad58f16537c588bdf82/href</a></iframe><p>This script performs the below steps:</p><ol><li>Creates 2 directories: <strong>productmicrosvcs/environments</strong> and <strong>productmicrosvcs/swarm</strong> in the manager DIND container.</li></ol><pre>docker exec %CONTAINER_NAME% mkdir -p /%FOLDER_NAME% /%FOLDER_NAME%/environments /%FOLDER_NAME%/swarm</pre><p>2. We are copying all the relevant<strong> .env</strong> files <strong>/productmicrosvcs/environments</strong> directory and the<strong> .stack </strong>files into the <strong>/productmicrosvcs/swarm </strong>directory. We are also copying a <strong>deploy.sh</strong> shell script into the <strong>productmicrosvcs </strong>folder to undeploy and redeploy the stack.</p><pre>docker cp ../docker/swarm/docker-compose.stack.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.yml<br>docker cp ../docker/swarm/docker-compose.stack.dev.override.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.dev.override.yml<br>docker cp ../docker/swarm/docker-compose.stack.prod.override.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.prod.override.yml<br>docker cp ../docker/environments/dev.env %CONTAINER_NAME%:/%FOLDER_NAME%/environments/dev.env<br>docker cp ../docker/environments/common.env %CONTAINER_NAME%:/%FOLDER_NAME%/environments/common.env<br>docker cp deploy.sh %CONTAINER_NAME%:/%FOLDER_NAME%/deploy.sh</pre><p>Below is the <strong>deploy.sh</strong> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f6960c863439ed9268c6e7a906387c4/href">https://medium.com/media/7f6960c863439ed9268c6e7a906387c4/href</a></iframe><p>3. Finally we make the <strong>deploy.sh </strong>shell script executable using the <strong>chmod </strong>command and then execute it.</p><pre>docker exec %CONTAINER_NAME% chmod +x /%FOLDER_NAME%/%SCRIPT_NAME%<br>docker exec %CONTAINER_NAME% /bin/sh /%FOLDER_NAME%/%SCRIPT_NAME%</pre><p>The <strong>deploy.sh</strong> will remove any existing application stack with the name <strong>myproductStack </strong>and redeploy the new <strong>myproductStack.</strong></p><p>In the <strong>docker-compose.stack.yml</strong> we have 3 docker compose services: <strong>product-node, product-db </strong>and <strong>filebeat</strong>. Via the <strong>replicas </strong>field ,we have provided the instruction to created <strong>3 replicas of the docker swarm product-node service </strong>and a <strong>single product-db and filebeat service</strong>(absence of replicas field defaults to 1 swarm service).<strong> So we are expecting 3 docker containers and 3 docker swarm services for the product-node service. We are also expecting 1 docker container and 1 docker swarm service each for the product-db and filebeat service.</strong></p><p>The <strong>product-node</strong>,<strong>product-db</strong> and<strong> filebeat</strong> swarm services <strong>are configured to run in the worker2 node via placement constraints.</strong></p><p>So i will navigate to the project folder and execute the <strong>copyAndDeploy.bat</strong> script to automate the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpEucpFfMIWlxSavgWxvsA.png" /></figure><p>Shell into the manager DIND container to check the <strong>myproductStack </strong>created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVGv_gxlYwOtWnyUK6rPaQ.png" /></figure><p>To view the containers, you need to exit the manager DIND container and shell into the <strong>worker2 DIND </strong>container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYgE29udd7BZjW4W10AO0w.png" /></figure><p>Lets verify if we are able to access the product and cart microservice by accessing nginx service on port 4000.</p><p>Hitting <strong>localhost:4000/mycart </strong>and <strong>localhost:4000/mycart/carts</strong> in the browser has successfully routed the request from nginx to express-gateway and then finally to the cart microservice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLilDMlANF3UjGLGldQkZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8dC27zANw_1Aj1RBwwk-eg.png" /></figure><p>Hitting <strong>localhost:4000/myproduct </strong>and <strong>localhost:4000/myproduct/products</strong> in the browser has successfully routed the request from nginx to express-gateway and then finally to the product microservice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JkZvk8XmYf8ALOTapAmDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAy327gNZz4eEl22YfF4XA.png" /></figure><p>4. Lets begin with the deployment of ELK stack to the <strong>worker3 DIND container</strong> (functioning as <strong>worker3 node</strong>). Again we have built the docker images for the services and have pushed the images to a registry like <strong>DockerHub </strong>beforehand.</p><p>Below is the project structure. I have highlighted the files/folders relevant to this story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*Q9e7Y7g3n4pTeAwgGoYF5Q.png" /></figure><p>Below is the <strong>docker-compose.stack.yml. </strong>Here please observe the <strong>placement.contraints</strong> section. The manager node <strong>interprets the placement constraints</strong> and ensures the service is scheduled only on the specified <strong>worker3 </strong>DIND container(functioning as a <strong>worker3 node</strong>). This ensures the service runs only on the particular worker node. The manager node will handle orchestration but won’t run the service container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3bb2dd0e5b6d6b634d54f207572e9a9/href">https://medium.com/media/d3bb2dd0e5b6d6b634d54f207572e9a9/href</a></iframe><p>Below is the <strong>docker-compose.stack.dev.override.yml. </strong>We have specified specified the port mapping for the worker3 DIND container as <strong>4001:4001</strong> when launching the container in the beginning of the story. Thus I can access the docker swarm service running in the worker3 node, whose <strong>host port is exposed as 4001 </strong>via <strong>localhost:4001</strong> in the browser. In the .yml file below, observe that the host port of the kibana service is 4001 and the container port is 5601. Thus we can access the Kibana dashboard, when we hit localhost:4001 in the browser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c03c3c2f713234be4f4f0b9cf0411b0/href">https://medium.com/media/9c03c3c2f713234be4f4f0b9cf0411b0/href</a></iframe><p>We have again written a similar <strong>copyAndDeploy.bat</strong> script in the <strong>scripts </strong>folder in the project to automate the local deployment process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf522e7b9e3539354181aa8925ddd532/href">https://medium.com/media/bf522e7b9e3539354181aa8925ddd532/href</a></iframe><p>This script performs the below steps:</p><ol><li>Creates 2 directories: <strong>elk/environments</strong> and <strong>elk/swarm</strong> in the manager DIND container.</li></ol><pre>docker exec %CONTAINER_NAME% mkdir -p /%FOLDER_NAME% /%FOLDER_NAME%/environments /%FOLDER_NAME%/swarm</pre><p>2. We are copying all the relevant<strong> .env</strong> files<strong> /elk/environments </strong>directory and the<strong> .stack </strong>files into the <strong>/elk/swarm</strong> directory. We are also copying the <strong>deploy.sh</strong> shell script into the <strong>elk </strong>folder.</p><pre>docker cp ../docker/swarm/docker-compose.stack.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.yml<br>docker cp ../docker/swarm/docker-compose.stack.dev.override.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.dev.override.yml<br>docker cp ../docker/swarm/docker-compose.stack.prod.override.yml %CONTAINER_NAME%:/%FOLDER_NAME%/swarm/docker-compose.stack.prod.override.yml<br>docker cp ../docker/environments/dev.env %CONTAINER_NAME%:/%FOLDER_NAME%/environments/dev.env<br>docker cp ../docker/environments/common.env %CONTAINER_NAME%:/%FOLDER_NAME%/environments/common.env<br>docker cp deploy.sh %CONTAINER_NAME%:/%FOLDER_NAME%/deploy.sh</pre><p>Below is the <strong>deploy.sh</strong> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b844e78a7b63487a7f6c55fe932a2e10/href">https://medium.com/media/b844e78a7b63487a7f6c55fe932a2e10/href</a></iframe><p>3. Finally we make the <strong>deploy.sh </strong>shell script executable using the <strong>chmod </strong>command and then execute it.</p><pre>docker exec %CONTAINER_NAME% chmod +x /%FOLDER_NAME%/%SCRIPT_NAME%<br>docker exec %CONTAINER_NAME% /bin/sh /%FOLDER_NAME%/%SCRIPT_NAME%</pre><p>The deploy.sh will remove any existing application stack with the name <strong>elkStack </strong>and redeploy the new stack <strong>elkStack</strong>.</p><p>In the <strong>docker-compose.stack.yml</strong> we have 3 docker compose services: <strong>elasticsearch, logstash </strong>and <strong>kibana</strong>. We are also expecting 1 docker container and 1 docker swarm service for each of these services.</p><p>The elasticsearch, logstash and kibana swarm services <strong>are configured to run in the worker3 node.</strong></p><p>So i will navigate to the project folder and execute the <strong>copyAndDeploy.bat</strong> script to automate the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGFSmzqylvRuTrx-mq5OSQ.png" /></figure><p>Hitting <strong>localhost:4001 </strong>in the browser, opens the Kibana Dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QrIjIiuYrDqmyli65ixE3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*sQXjixNhSGt0bi5hB-QYag.png" /></figure><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c32a4ae6b8d6" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/setting-up-docker-in-docker-for-testing-docker-swarm-locally-c32a4ae6b8d6">Setting up Docker-in-Docker for testing Docker Swarm locally</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Is @angular-builders/custom-webpack effective to access environment variables updated at…]]></title>
            <link>https://javascript.plainenglish.io/angular-is-angular-builders-custom-webpack-effective-to-access-environment-variables-updated-at-7a892da32919?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a892da32919</guid>
            <category><![CDATA[dotenv]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[custom-webpack]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 17:32:52 GMT</pubDate>
            <atom:updated>2025-08-25T17:32:52.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular: Is @angular-builders/custom-webpack effective to access environment variables updated at runtime in Docker ?</h3><p>The <strong>@angular-builders/custom-webpack</strong> npm package allows us to customize the build configuration and add a custom webpack configuration.</p><p>In this story, the purpose of adding a custom webpack configuration is to access environment variables in the angular application using the <strong>process.env</strong> object. But will this be good enough to reflect any runtime update of environment variables with docker ? Not really.</p><p>We have different configurations for different deployment environments but a docker image is built only once when deploying to a lower environment, say development and the same image is then pulled and promoted to higher environments as well, say production. This is the recommended approach.</p><p>In order for the configurations for an environment to reflect when the application is running in higher environment,<strong> it is essential to make runtime update of environment variables work so that the configurations can be updated for higher environments.</strong></p><p>Let me demonstrate this with an example project. Below is the structure. We will deploy the angular app to nginx web server in a docker container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*tYo8yn1gY5sZlEY_Ap2Ktw.png" /></figure><p>The git repo for this example can be found here.</p><p><a href="https://github.com/ramyabala221190/AngularEnvCustomWebpack">GitHub - ramyabala221190/AngularEnvCustomWebpack: Accessing environment variables via process.env using custom webpack configuration in angular app</a></p><p><strong>I. Docker configuration and .env files</strong></p><p>I have defined a separate <strong>.env file</strong> for each environment: <strong>dev.env </strong>and <strong>prod.env</strong> files within the <strong>docker/environments</strong> folder.</p><p><strong>prod.env</strong></p><pre>VAR1=&quot;Logging var1 in production environment&quot;<br>VAR2=&quot;Logging var2 in production environment&quot;<br>NGINX_PORT=81<br>APP_ENV=prod</pre><p><strong>dev.env</strong></p><pre>VAR1=&quot;Logging var1 in development environment&quot;<br>VAR2=&quot;Logging var2 in development environment&quot;<br>NGINX_PORT=80<br>APP_ENV=dev</pre><p>We require the <strong>NGINX_PORT</strong> variable to be accessible in the docker container and the remaining variables need to be accessed within the application.</p><p>We have a<strong> docker-compose.yml</strong> which contains the base configuration for the 2 environments. We have 2 override files: <strong>docker-compose.dev.yml</strong> and <strong>docker-compose.prod.yml</strong> to provide environment specific overrides.</p><p><strong>docker-compose.yml</strong></p><p>We have specified the docker image name:<strong>nginx-custom-webpack</strong>, which is common to all environments, location of the Dockerfile and also mounted the nginx configuration file onto a specific path in the container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/948b04fd8855763066c0373b6e70d51b/href">https://medium.com/media/948b04fd8855763066c0373b6e70d51b/href</a></iframe><p><strong>docker-compose.dev.yml</strong></p><p>We have defined the container name: <strong>nginx-dev-container </strong>and the ports i.e angular app will run on port 3000 and nginx will be listening on port 80.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0580f8f429945cc6eb79c3d8272d508/href">https://medium.com/media/e0580f8f429945cc6eb79c3d8272d508/href</a></iframe><p><strong>docker-compose.prod.yml</strong></p><p>We have defined the container name: <strong>nginx-prod-container </strong>and the ports i.e angular app will run on port 3200 and nginx will be listening on port 81.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1400fd6640b517c6cd1e67fcb89d461e/href">https://medium.com/media/1400fd6640b517c6cd1e67fcb89d461e/href</a></iframe><p>In the override files, also observe the <strong>env_file</strong> field, which loads the <strong>dev.env</strong> or the <strong>prod.env </strong>file. This field will make the variables defined in the <strong>dev.env</strong> or the <strong>prod.env</strong>, available for access in the docker container. This is important because we have accessed the <strong>NGINX_PORT</strong> variable in the <strong>nginx.config</strong> file below and it needs to be substituted with the correct value based on the environment. In the development environment, the nginx webserver listens on port 80 and in production environment, it listen on port 81.</p><p>Below is the nginx configuration in the<strong> nginx.config</strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3501ea7af036757a7e5c21ded294abfc/href">https://medium.com/media/3501ea7af036757a7e5c21ded294abfc/href</a></iframe><p><strong>Dockerfile</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea922887d5c9aac6031533268c892d69/href">https://medium.com/media/ea922887d5c9aac6031533268c892d69/href</a></iframe><p><strong>II. Additional Dev Dependencies and process.env</strong></p><p>Lets now go to the <strong>package.json</strong> file. Below is the “build” script executed in the <strong>Dockerfile</strong>. Please note that we will be building the application only once, creating a docker image and promoting that image to higher environments.</p><pre>&quot;build&quot;: &quot;ng build --configuration production&quot;,</pre><p>The <strong>production </strong>configuration is used, irrespective of the environment due to the multiple benefits it provides like reduced bundle size, AOT compilation, faster load time etc.</p><p><strong>How can we use process.env in angular application?</strong></p><p><strong>process.env</strong> is a Node.js global object which represents the state of the system environment variables where the Node.js process is running. In the context of Angular, <strong>process.env</strong> is not directly available in the browser environment where the Angular application runs.</p><p>In order to use the <strong>process.env</strong> object in the angular app, we require 3 additional npm packages as dev dependencies.</p><p>=&gt;The <strong>dotenv</strong> npm package loads environment variables from the <strong>dev.env/prod.env file</strong> into the<strong> process.env </strong>object.</p><pre>npm i --save-dev dotenv</pre><p>=&gt;<strong>custom-webpack</strong> npm package allows us to customize the build configuration. Since I am using Angular 16, I have used the 16.0.0 version of the npm package. Adjust the version based on the angular version you are using.</p><pre>npm i -- save-dev @angular-builders/custom-webpack@16.0.0</pre><p>=&gt;The <strong>process </strong>object provided by Nodejs, is still something, which the TS compiler cant understand. We need to use <strong>d.ts</strong> files i.e Typescript Definition files to tell the compiler about the library you want to load.</p><p>To get the type definitions for Node, we need to install the <strong>@types/node</strong> npm package as a dev dependency.</p><pre>npm i --save-dev @types/node@16</pre><p>In the <strong>tsconfig.app.json</strong> file lying in the root of the project, the <strong>types</strong> compiler option is set to [] to disable automatic inclusion of declarations from @types/* .</p><p>Update the <strong>compilerOptions</strong> property in the <strong>tsconfig.app.json</strong> file in the root of the project to add the newly installed declarations to the list of <strong>types</strong>.</p><p>FROM</p><pre>“compilerOptions”: {<br>“outDir”: “./out-tsc/app”,<br>“types”: []<br>},</pre><p>TO</p><pre>“compilerOptions”: {<br>“outDir”: “./out-tsc/app”,<br>“types”: [&quot;node&quot;]<br>},</pre><p>Once these 3 packages are installed, lets move to update the <strong>angular.json</strong> file.</p><ol><li>Update the <strong>architect.build.builder</strong> from @angular-devkit/build-angular:browser to<strong> @angular-builders/custom-webpack:browser</strong></li></ol><p>2. Update the <strong>architect.serve.builder</strong> from @angular-devkit/build-angular:dev-server to <strong>@angular-builders/custom-webpack:dev-server</strong></p><p>3. Finally add a <strong>customWebpackConfig</strong> property to the the <strong>architect.build.options</strong> section. The <strong>customWebpackConfig </strong>property is an object, in which we have set the <strong>path </strong>field to the path of the custom webpack configuration file: <strong>custom-webpack.js.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*iZvTO4Vp5BX-iatvqCXIQQ.png" /></figure><pre>“customWebpackConfig”: {<br>“path”: “custom-webpack.js”<br>},</pre><p>Below is the content of <strong>custom-webpack.js.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dcb2b97b8afe6d8149faa4bdcfb5f94/href">https://medium.com/media/1dcb2b97b8afe6d8149faa4bdcfb5f94/href</a></iframe><p><strong>DefinePlugin </strong>provided by webpack replaces variables in your code with other values or expressions at compile time. The <strong>EnvironmentPlugin</strong> is shorthand for using the <strong>DefinePlugin</strong> on <strong>process.env</strong> keys. <strong>We have set the default value of all environment variables to null.</strong></p><p>Observe that we are using the value of the environment variable <strong>APP_ENV </strong>to decide which <strong>.env</strong> file has to be used by <strong>dotenv.config().</strong></p><pre>dotenv.config({<br>path:`./docker/environments/${process.env.APP_ENV}.env`<br>});</pre><p>The<strong> environment.ts</strong> and <strong>environment.development.ts</strong> hold the same content, since nothing is hardcoded. We are accessing the value of the environment variables using the <strong>process.env</strong> object in these 2 files.</p><pre>export const environment = {<br>“VAR1”:process.env[‘VAR1’],<br>“VAR2”:process.env[‘VAR2’],<br>“APP_ENV”:process.env[‘APP_ENV’]<br>};</pre><p>Finally, you can access the content of the environment variables in the <strong>AppComponent </strong>or any other part of the application from the <strong>environment.ts</strong> or <strong>environment.development.ts </strong>file.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { environment } from &#39;src/environments/environment&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent {<br>  title = &#39;envVar&#39;;<br><br>  ngOnInit(){<br>    console.log(environment.APP_ENV,environment.VAR1,environment.VAR2);<br>  }<br>}</pre><p><strong>III. Docker image build and execution</strong></p><p>Lets now proceed to execute the below commands to build the docker image and run the container for development environment.</p><pre>docker compose -p nginx-dev-proj -f docker/docker-compose.yml -f docker/docker-compose.dev.yml build<br>docker compose -p nginx-dev-proj -f docker/docker-compose.yml -f docker/docker-compose.dev.yml up -d — remove-orphans — no-build</pre><p>Observe below that the runtime environment variables have been picked up correctly from the <strong>dev.env</strong> file by <strong>docker-compose.dev.yml</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*8FvmzKz7iEKsgszjH_Q-yw.png" /></figure><p>When I open <strong>localhost:3000 </strong>in the browser, observe that the <strong>value of all environment variables have been printed as null</strong>. Recall that we had set the default value of all environment variables as null in the <strong>custom-webpack.js</strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytxz9YnonrfcgJBxMak-Iw.png" /></figure><p>The reason for this is that the environment variables from <strong>dev.env</strong> were not available at buildtime. There were available in the container only at runtime. <strong>The dotenv.config() in the custom-webpack.js file requires the value of APP_ENV environment variable at buildtime to load the correct .env file.</strong></p><pre>dotenv.config({<br>path:`./docker/environments/${process.env.APP_ENV}.env`<br>});</pre><p>So lets make some changes in the <strong>Dockerfile </strong>and update it as below</p><pre>FROM node:alpine as node<br>ENV APP_ENV=dev<br>WORKDIR /app<br>COPY package.json package-lock.json ./<br>RUN npm cache clean — force<br>RUN npm install<br>COPY . .<br>RUN npm run build<br><br>#Stage 2<br>FROM nginx:alpine<br>VOLUME /var/cache/nginx<br>RUN rm -r /usr/share/nginx/html/*<br>COPY — from=node /app/dist/env-var /usr/share/nginx/html/<br>CMD [“nginx”, “-g”, “daemon off;”]</pre><p>I have added the below line of code so the <strong>ENV </strong>instruction sets an environment variable <strong>APP_ENV</strong> to the value “dev” at build time. It will be available at runtime as well.</p><pre>ENV APP_ENV=dev</pre><p>If we now re-build the docker image and run the container for development.</p><p>There is no change in the environment variables available in the container at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*47YyCYe1HXuPgz3dvOkmdg.png" /></figure><p>If we now refresh <strong>localhost:3000</strong> in the browser, the values of the environment variables have been printed correctly. This is because the <strong>APP_ENV </strong>was set to “dev” at build time and thus <strong>dotenv.config() </strong>in the <strong>webpack.config.js</strong> was able to pick up the <strong>dev.env </strong>file and load the environment variables from that file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UP8XLtnOEjiRE8eqiqv64Q.png" /></figure><p>Lets now proceed to execute the below command to use the same docker image and run the container for production environment.</p><pre>docker compose -p nginx-prod-proj -f docker/docker-compose.yml -f docker/docker-compose.prod.yml up -d — remove-orphans — no-build</pre><p>Observe that the runtime variables in the docker container picked by the <strong>docker-compose.prod.yml</strong> from <strong>prod.env </strong>are correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*9uhXzxlmGHs74oB0-pBRTQ.png" /></figure><p>Opening <strong>localhost:3200</strong> in the browser. Note that its printing the environment variables from the <strong>dev.env</strong> file and not from <strong>prod.env</strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tepWiHa6jZDN7wWKMr8RLw.png" /></figure><p>What is the reason for this behavior ?</p><p>=&gt;We build the docker image only once and promote the same image to higher environments.</p><p>=&gt; The docker image was built setting <strong>APP_ENV</strong> to “dev”.</p><p>=&gt;The <strong>dotenv </strong>npm package used the <strong>dev.env </strong>file to load the environment variables during the angular app build.</p><p>=&gt;At runtime, <strong>docker-compose.prod.yml</strong> picked up the environment variables from <strong>prod.env, </strong>but runtime update of the environment variables had no impact.</p><p>=&gt;Environment variables like APP_ENV, VAR1 and VAR2 set by <strong>DefinePlugin </strong>in Webpack, are hardcoded into the bundled JS during the app build process. <strong>This means their values are fixed at the time of compilation and cannot be changed without rebuilding the application. We do not want to rebuild the app because we are going with the approach of a single docker image for all environments.</strong></p><p>=&gt;Custom webpack configurations cannot directly inject variables that are meant to be read and changed dynamically at runtime. This is because webpack’s main function is to bundle and optimize code for deployment, and this process occurs before the application is run in a browser.</p><p>=&gt;Custom webpack configurations are only meant for customizing the build process (e.g., adding loaders, plugins, or optimizing assets) and operate on the source code before it becomes a runnable application.</p><p>This proves that to achieve runtime update of environment variables without hacky solutions, we require other methods. I have demonstrated 2 such methods for passing non-sensitive runtime data to angular app running in a docker container in the below story.</p><p><a href="https://blog.stackademic.com/angular-passing-runtime-data-to-the-application-running-in-a-docker-container-88115d0fcfe5">Angular: Passing Runtime Data to the Application Running in a Docker Container</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a892da32919" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angular-is-angular-builders-custom-webpack-effective-to-access-environment-variables-updated-at-7a892da32919">Angular: Is @angular-builders/custom-webpack effective to access environment variables updated at…</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[Angular: How I understood Server Sent Events with NodeJs Express]]></title>
            <link>https://blog.stackademic.com/angular-how-i-understood-server-sent-events-with-nodejs-express-7ef34632dcc3?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ef34632dcc3</guid>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[event-stream]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 03:17:04 GMT</pubDate>
            <atom:updated>2025-07-11T15:54:55.429Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, would like you to walk you through an example I used to understand how a <strong>Server Sent Events(SSE)</strong> connection between an Angular app and a Node Express application server actually works. This example covers most of the aspects of SSE.</p><p>Its first important to understand the difference between just a plain Http request and a Http request with SSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Nh-zWomoGvOdgBszsnYldg.png" /></figure><ol><li>As we all know, HTTP is the fundamental protocol for communication on the WWW, to transfer resources between clients and servers.</li><li>It’s a request-response protocol where the client initiates a request, and the server responds with the requested data. Thus we have a new connection with the server for each request from the client.</li><li>Used frequently for general web communication, data transfer</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Ueij3CGilX44hwt6RCOLKA.png" /></figure><ol><li>SSE is a unidirectional data streaming protocol built on top of HTTP. <strong>Unidirectional here means from data flows only from server to client.</strong></li><li>The client just initiates the connection, and the server sends a stream of events over a persistent HTTP connection. Persistent HTTP connection is required for continuous data flow. The event stream is a simple stream of text data which must be encoded using <a href="https://developer.mozilla.org/en-US/docs/Glossary/UTF-8">UTF-8</a>. Messages in the event stream are separated by a pair of newline characters.</li><li>SSE is suitable for scenarios where the server needs to notify the client of updates, such as real-time notifications, live dashboards, or stock tickers.</li></ol><p>Below is a short demonstration of the example. On the left side, we have the angular app running in the browser and on the right side, we have the vscode terminal showing the Node server logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eRZ8l4PDTUjn-DrGQis1g.gif" /></figure><p>In this example, the Node Express server <strong>sends alphabets from A-Z every 1 second to the angular application</strong>. In the above demonstration, there are no disconnections from the client/server side. However we will take up that scenario as well at the end of the story.</p><ol><li>I have 2 buttons to trigger the reception and to stop receiving alphabets from the Node Express server. Clicking on the <strong>“Receive alphabets”</strong> button opens an <strong>EventSource connection</strong> with the server to start receiving messages from it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Luwevx-uZXkwQ8LFZpVag.png" /></figure><p>2. Below is a screenshot of how the server response looks like. We are sending 2 messages per second.</p><p><strong>These 2 messages could have been a single message as well. The purpose of this example is to understand the concept of server sent events. Please structure the messages in a manner most suitable to your application requirements.</strong></p><p>The first message comes under a custom <strong>event timestamp </strong>and the 2nd message comes under a custom <strong>event</strong> <strong>character</strong>. The<strong> data field</strong> for the <strong>timestamp event</strong> stores the timestamp of the message and the <strong>data field</strong> for the<strong> character event</strong> stores the alphabet. The <strong>id field</strong> for the <strong>timestamp event</strong> stores the milliseconds for the date and the <strong>id field</strong> for the <strong>character event </strong>stores the ASCII code of the alphabet being sent. The <strong>retry field</strong> for both the events contains 2000 which means if the server closes the connection deliberately or due to network issue, the browser will retry restoring the connection after <strong>2000ms</strong>. We will discuss these fields in more detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7ByqyFpxddMFtnNFCNJ_Q.png" /></figure><p><strong>Note: Its not required to send the timestamp and the alphabet in different messages. It would have been better to send in the same message as highlighted below with multiple data fields under a single event. The client will receive the value of the data fields concatenated into a single string separated by a line break. You can use the line break to your advantage to split the string and access the alphabet and timestamp separately.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yN9QpbUwIJAjywyeVKkGYA.png" /></figure><p>3. Once the server has sent all the alphabets, observe that it sends a custom event <strong>done </strong>and closes the connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TI9N0seWpFFvD8iZnMKbg.png" /></figure><p>The angular app can listen to this <strong>custom event done</strong> and do some cleanup work or any other action if required. In this example, we have just logged the below highlighted message to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-6LOdqcbzI9dJqnWi-PIw.png" /></figure><p>When the server closes the connection, the browser retries after 2000ms, but it receives a<strong> 204 response</strong> from the server. This is an indication to the browser to stop retrying the connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1ZC5f_laIj1n8V4jmecOA.png" /></figure><p>Another important point to note when the browser retries the connection is the <strong>last-event-id</strong> request header that is being sent to the server. <strong>This request header is only sent on connection retries</strong>. This header contains <strong>id field </strong>of the last message successfully received by the client from the server. The request header value can be used on the Node server to send all messages that follows the message with this particular id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3OAt7W7bhQrRqIBzRabWA.png" /></figure><p>As already mentioned, the <strong>id field</strong> in a message contains the ASCII code of the alphabet being sent by the server to the client. In the above screenshot, the <strong>Last-Event-Id</strong> header contains the value <strong>90</strong>. The alphabet corresponding to this code is <strong>Z</strong>. This means that the client has already received the alphabet Z and thus all alphabets before it. There are no more alphabets that the server can send. Thus the server has responded back with a<strong> 204 status response </strong>and indicated to the browser to stop retrying.</p><p>4. Clicking on the <strong>“Stop Receiving alphabets”</strong> button terminates the connection between the client and server. <strong>Its important to note here that only the client will stop receiving the messages but the server can continue to send messages.</strong></p><p>We have not shown this in the demonstration. We will cover this scenario at the end of the story.</p><p><strong>Node Express</strong> project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*SVuYxlDEbnxZC_AEoYbC2A.png" /></figure><p>Lets begin with the <strong>src/app.js. </strong>The node server is listening for requests on port 8085.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e93f682c688ac64c6a72b9b16622b04/href">https://medium.com/media/5e93f682c688ac64c6a72b9b16622b04/href</a></iframe><p>We have defined a<strong> /random</strong> GET route. We begin by logging the time at which the new request was received from the angular app and we are also checking if the browser has sent the<strong> ‘last-event-id’ </strong>request header. If yes, we are printing its value.</p><pre>//logging request details<br>console.log(`new request received at ${new Date()}`);<br>console.log(`last-event-id header present ? ${req.headers[‘last-event-id’]}`);</pre><p>Next, we have initialised few variables and constants</p><pre>//initialize variables<br>const minAsciiCode=65;<br>const maxAsciiCode=90;<br>const responseInterval=1000;<br>const retryInterval=2000;<br>let lastSentEventId=req.headers[‘last-event-id’];<br>let asciiCode = lastSentEventId ? parseInt(lastSentEventId)+1: minAsciiCode;<br>// let j=0; //this variable is responsible for triggering random disconnections from the server</pre><p>The server is supposed to send alphabets having ASCII code in the range 65–90. Hence we have set 2 constants <strong>minAsciiCode </strong>and <strong>maxAsciiCode</strong>.</p><p>The server will send 1 alphabet every 1 sec. Hence we have set the constant: <strong>responseInterval</strong>.</p><p>The constant <strong>retryInterval </strong>is for setting the <strong>retry field </strong>in a message. Its basically the time interval after a failed connection, when the browser will try to re-establish a stable new connection.</p><p>The variable <strong>lastSentEventId </strong>holds the value of the request header:<strong> ‘last-send-id’. </strong>The browser sends this request header only when it retries a connection. So only in those scenarios the <strong>lastSentEventId </strong>variable will hold the ASCII code of the last successfully received alphabet by the client, otherwise it will be undefined.</p><p>The variable <strong>asciiCode </strong>will hold the ASCII code for which the server needs to send the corresponding alphabet in a message to the client. <strong>If its a retry connection</strong>, the variable <strong>asciiCode </strong>will hold the ASCII code which comes after the ASCII code stored in <strong>lastSendEventId </strong>variable. This is because the client has already successfully received the alphabet with ASCII code stored in the <strong>lastSendEventId </strong>variable. We need to send the alphabet for the next ASCII code.</p><pre>let asciiCode = lastSentEventId ? parseInt(lastSentEventId)+1: minAsciiCode;</pre><p><strong>If its not a retry connection</strong>, it means that the server has to send all alphabets, starting from <strong>minAsciiCode </strong>i.e 65.</p><p>I have commented out the below line code for now. It will be required later in the story.</p><pre>// let j=0; //this variable is responsible for triggering random disconnections from the server</pre><p>Next, we have defined the response headers as below. It is essential to set the below 3 response headers because the client receives events from the server only in <strong>text/event-stream</strong> format.</p><pre>res.header(‘Content-Type’,’text/event-stream’);<br>res.header(‘Cache-Control’,’no-cache’);<br>res.header(‘Connection’,’keep-alive’);</pre><p>Finally, we are executing the below logic every <strong>responseInterval </strong>seconds i.e 1 sec. This means the server is sending a new alphabet and its timestamp every 1 second. The entire logic is enclosed within the <strong>setInterval block</strong>.</p><pre>  let clear=setInterval(()=&gt;{<br>        //j++;<br>        // Once reached an ascii code exceeding the max, terminate the connection with a 204 status code.<br>        if(asciiCode &gt; maxAsciiCode){<br>            clearInterval(clear);<br>            res.status(204).end(); //so that the client does not send anymore requests<br>            return;<br>        }<br>        <br>        //Below piece of code is for demonstrating reconnection from the client, if the server ends the connection randomly<br>        // if(j &gt; Math.floor(Math.random()*10)){<br>        //     clearInterval(clear);<br>        //     res.end();<br>        //     return;<br>        // }<br>        // sending out events to the client<br>        sendMessage();<br>        <br>        if(asciiCode==maxAsciiCode){<br>            //send out a done event once all ascii codes are covered<br>            res.write(&#39;event:done\n&#39;);<br>            res.write(&#39;data:Sent out all alphabets\n\n&#39;)<br>        }<br>        asciiCode++;<br>    },responseInterval)</pre><p>Note that we are incrementing the value of the ASCII code stored in the <strong>asciiCode </strong>variable every 1 second at the end of the <strong>setInterval </strong>block. In the below lines of code, we are checking if the value of the ASCII code stored in <strong>asciiCode </strong>variable is more than the value of the <strong>maxAsciiCode </strong>variable. If yes, it implies that the server has already sent all the alphabets. Thus it closes the connection, sending back a 204 status response to indicate to the browser not to retry establishing a new connection.</p><pre>if(asciiCode &gt; maxAsciiCode){<br>clearInterval(clear);<br>res.status(204).end(); //so that the client does not send anymore requests<br>return;<br>}</pre><p>Next, if the ASCII code stored in the <strong>asciiCode </strong>variable is valid and not exceeding the value of <strong>maxAsciiCode </strong>variable, we are calling the function <strong>sendMessage() </strong>to send 2 messages per second to the client.</p><pre> function sendMessage(){<br>        let date=new Date();<br>        let alphabet=String.fromCharCode(asciiCode); //get the alphabet from the ascii code<br>        console.log(`sending ${alphabet} at ${date}`);<br>        res.write(&#39;event:timestamp\n&#39;);<br>        res.write(`data:${date}\n`);<br>        res.write(`id:${date.getMilliseconds()}\n`);<br>        res.write(`retry:${retryInterval}\n\n`)<br>        res.write(`event:character\n`);<br>        res.write(`data:${alphabet}\n`);<br>        res.write(`id:${asciiCode}\n`);<br>        res.write(`retry:${retryInterval}\n\n`);<br>    }</pre><p><strong>‘\n’ indicates the end of a part of the message and ‘\n\n’ indicates the end of the complete message.</strong></p><p>The format of the message is extremely important.Each message sent by the server has some combination of the following fields, one per line:</p><ol><li><strong>event: </strong>The value of the event field describes the type of event. The specified event will be dispatched on the browser. The angular app must be configured to listen for dispatched event. The<strong> event field</strong> must come before the <strong>data field</strong>.</li><li><strong>data</strong>: The data field for the message.</li><li><strong>id</strong>: A unique id is assigned to the message. This id is used by the browser to populate the <strong>‘last-event-id’</strong> request header when retrying a connection.</li><li><strong>retry</strong>: This field specifies the ms after which the browser must retry a connection.</li></ol><p>Thus the below lines are considered as 1 message which will be captured under <strong>timestamp event</strong>. The <strong>event field</strong> stores the name of the event i.e <strong>timestamp</strong>. The<strong> data field</strong> stores the current date. The <strong>id field </strong>stores the milliseconds for this date and <strong>retry field</strong> stores the retry interval i.e 2000 ms.</p><pre>  res.write(&#39;event:timestamp\n&#39;);<br>  res.write(`data:${date}\n`);<br>  res.write(`id:${date.getMilliseconds()}\n`);<br>  res.write(`retry:${retryInterval}\n\n`)</pre><p>The below lines are considered as 1 message, captured under the <strong>character event</strong>. The <strong>event field</strong> stores the name of the event i.e <strong>character</strong>. The<strong> data field</strong> stores the alphabet corresponding to the ASCII code stored in <strong>asciiCode </strong>variable. The <strong>id field </strong>stores the ASCII code stored in <strong>asciiCode </strong>variable and <strong>retry field</strong> stores the retry interval i.e 2000 ms.</p><pre>res.write(`event:character\n`);<br>res.write(`data:${alphabet}\n`);<br>res.write(`id:${asciiCode}\n`);<br>res.write(`retry:${retryInterval}\n\n`);</pre><p><strong>Note: Since its preferrable to send the timestamp and alphabet as a single message, you can go for sending multiple data fields under a single event approach, rather than sending multiple events. Below is an example implementation.</strong></p><pre>function sendMessage(){<br>let date=new Date();<br>let alphabet=String.fromCharCode(asciiCode); //get the alphabet from the ascii code<br>console.log(`sending ${alphabet} at ${date}`);<br>res.write(`event:character\n`);<br>res.write(`data:${alphabet}\n`);<br>res.write(`data:${date}\n`);<br>res.write(`id:${asciiCode}\n`);<br>res.write(`retry:${retryInterval}\n\n`);<br>}</pre><p>Back to the example. Finally, post sending the 2 messages, we are checking if the value of the ASCII code stored in <strong>asciiCode </strong>variable equals the value of <strong>maxAsciiCode </strong>i.e 95. If yes, it implies that all alphabets have been successfully sent and the server sends a message captured under a <strong>custom done event</strong>.</p><pre>if(asciiCode==maxAsciiCode){<br>//send out a done event once all ascii codes are covered<br>res.write(‘event:done\n’);<br>res.write(‘data:Sent out all alphabets\n\n’)<br>}</pre><p>Before we proceed to discuss the disconnection from client/server scenarios, lets check the Angular project.</p><p><strong>Angular Project</strong></p><p>Beginning with the service which establishes an <strong>EventSource </strong>connection with the server.</p><p><strong>RandomSseService</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1062aab5c893c5176b60b02f5a2ac40/href">https://medium.com/media/e1062aab5c893c5176b60b02f5a2ac40/href</a></iframe><p>=&gt;<strong>charSub$</strong> is a subject used to communicate the messages received by the service from the server to the <strong>AppComponent</strong>. The below method is called by the <strong>AppComponent class </strong>and the observable returned by the method is subscribed to, in the <strong>AppComponent </strong>template via the <strong>async pipe</strong> to display the messages.</p><pre>getMessages(){<br>    return this.charSub$.asObservable();<br>  }</pre><p>=&gt;The <strong>openConnection()</strong> is called, when we click on the “Receive alphabets” button in the <strong>AppComponent</strong>. This method might looks little huge so lets breakdown and see what it does.</p><pre> openConnection(){<br>     this.evtSource=new EventSource(`${environment.backend}/random`);<br><br>     this.evtSource.onopen=function(){<br>      console.log(`Opening an EventSource connection with the server at ${new Date()}. ReadyState is ${this.readyState}`);<br>     }<br><br>     this.evtSource.onmessage=function(result){<br>      console.log(`Received a default message from the server: ${result}`);<br>     }<br><br>     this.evtSource.onerror=function(err){<br>      if(this.readyState === 0){<br>      console.log(`${new Date()}Reconnecting....`)<br>      }<br><br>     }<br><br>     this.evtSource?.addEventListener(&#39;done&#39;,()=&gt;{<br>      console.log(&quot;Received all the data !!!&quot;);<br>   })<br><br>     let obsv1$=fromEventPattern((handler)=&gt;{<br>      this.evtSource?.addEventListener(&#39;character&#39;,(result)=&gt;{<br>        handler(result.data)<br>     })<br>     });<br><br>     let obsv2$=fromEventPattern((handler)=&gt;{<br>       this.evtSource?.addEventListener(&#39;timestamp&#39;,(result)=&gt;{<br>         handler(result.data)<br>      })<br>      });<br><br>     zip([obsv1$,obsv2$]).pipe(<br>      scan((acc:Message[],curr:any[])=&gt;{<br>        let [char,timestamp]=[curr[0],curr[1]];<br>        acc=acc.concat({<br>            character:char,<br>            timestamp:timestamp<br>        });<br>        return acc;<br>      },[])<br>     ).<br>     subscribe((result:Message[])=&gt;{<br>        this.charSub$.next(result);<br>      })<br><br>  }</pre><ol><li>To open a connection to the server to begin receiving events from it, we have created a new <strong>EventSource </strong>object with the server url. The<strong> EventSource()</strong> constructor returns a newly-created <strong>EventSource</strong>, which represents the Nodejs Express server.</li></ol><pre>this.evtSource=new EventSource(`${environment.backend}/random`);</pre><p><strong>environment.ts</strong> and <strong>environment.development.ts</strong>.</p><pre>export const environment = {<br>backend:’/sse’<br>};</pre><p><strong>proxy.conf.json</strong></p><pre>{<br>“/sse”: {<br>“target”: “http://localhost:8085&quot;,<br>“secure”: false,<br>“logLevel”:”debug”,<br>“pathRewrite”: {<br>“^/sse”: “”<br>}<br>}<br>}</pre><p>2. The <strong>open </strong>event of the <strong>EventSource API</strong> is fired when a connection with an EventSource is opened. As mentioned earlier, an <strong>EventSource </strong>in this example represents the Node Express server sending messages.</p><p>The <strong>error </strong>event of the <strong>EventSource API</strong> is fired when a connection with an <strong>EventSource </strong>fails to be opened.</p><p>The <strong>message </strong>event of the <strong>EventSource API</strong> fires whenever the messages received from the server don’t have an <strong>event </strong>field. Although we dont have any such messages from the server in this example, I have just included for information purpose.</p><p>Please note that the <strong>done event</strong> is a custom event and not an inbuilt event of the <strong>EventSource API. </strong>This event fires once the server has completed sending all the alphabets to the client.</p><pre>  this.evtSource.onopen=function(){<br>      console.log(`Opening an EventSource connection with the server at ${new Date()}. ReadyState is ${this.readyState}`);<br>     }<br><br>     this.evtSource.onmessage=function(result){<br>      console.log(`Received a default message from the server: ${result}`);<br>     }<br><br>     this.evtSource.onerror=function(err){<br>      if(this.readyState === 0){<br>      console.log(`${new Date()}Reconnecting....`)<br>      }<br><br>     }<br><br>     this.evtSource?.addEventListener(&#39;done&#39;,()=&gt;{<br>      console.log(&quot;Received all the data !!!&quot;);<br>   })</pre><p>3. We are expecting alphabets A-Z from the server under a custom event <strong>‘character’</strong>. We have added an event listener for this event and converted it into an observable using the <strong>fromEventPattern </strong>rxjs operator.</p><pre>  let obsv1$=fromEventPattern((handler)=&gt;{<br>      this.evtSource?.addEventListener(&#39;character&#39;,(result)=&gt;{<br>        handler(result.data)<br>     })<br>     });</pre><p>Next, we are expecting the timestamp information from the server under a custom event <strong>‘timestamp’.</strong> We have added an event listener for this event and converted it into an observable using the <strong>fromEventPattern </strong>rxjs operator.</p><pre>let obsv2$=fromEventPattern((handler)=&gt;{<br>this.evtSource?.addEventListener(‘timestamp’,(result)=&gt;{<br>handler(result.data)<br>})<br>});</pre><p>Since we want to display the alphabet and its corresponding timestamp information together in the <strong>AppComponent </strong>template, we need to combine this information using the<strong> rxjs zip operator. </strong>We have have combined these 2 pieces of information into an object <strong>{character:char,timestamp:timestamp}. </strong>We will also keep accumulating objects for upcoming messages from the server into an array using the <strong>scan rxjs operator</strong> and send it to the <strong>AppComponent </strong>via the subject <strong>charSub$.</strong></p><pre>  zip([obsv1$,obsv2$]).pipe(<br>      scan((acc:Message[],curr:any[])=&gt;{<br>        let [char,timestamp]=[curr[0],curr[1]];<br>        acc=acc.concat({<br>            character:char,<br>            timestamp:timestamp<br>        });<br>        return acc;<br>      },[])<br>     ).<br>     subscribe((result:Message[])=&gt;{<br>        this.charSub$.next(result);<br>      })</pre><p>4. When I click on the <strong>“Stop Receiving alphabets”</strong> button, the <strong>closeConnection() </strong>is called, which calls the <strong>close()</strong> on the <strong>EventSource object</strong>, to terminate the connection between the client and server. This means, even if the server continues to send messages, the client application will not receive it.</p><pre>closeConnection(){<br>this.evtSource?.close();<br>}</pre><p><strong>AppComponent</strong></p><p>In this component class, we have written the implementation for the methods called, when the buttons are clicked. Within the <strong>ngOnInit()</strong> lifecycle hook, we are calling<strong> getMessages() </strong>in the <strong>RandomSseService </strong>and assigning the returned observable to the property <strong>char$</strong>. We will be subscribing to<strong> char$ </strong>in the template via <strong>async pipe </strong>to display the alphabet and timestamp information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a87aa7382d7b2132de5a69c01fd071c/href">https://medium.com/media/7a87aa7382d7b2132de5a69c01fd071c/href</a></iframe><p><strong>AppComponent Template</strong></p><p>The template is self-explanatory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d36c068568a95b580403b36b575da62/href">https://medium.com/media/4d36c068568a95b580403b36b575da62/href</a></iframe><p><strong>Client Disconnects</strong></p><p>Lets now explore disconnection from the client scenario and check how the server responds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0q-CXUHWMNUnUkahA3SyQ.gif" /></figure><p>In the above demonstration, the client received alphabets uptill K, after which I clicked on the <strong>“Stop Receiving alphabets” </strong>button. Observe that the client stopped receiving any alphabets after K because the <strong>EventSource </strong>connection was terminated. But the server continued to send alphabets uptill Z.</p><p><strong>Server Disconnects</strong></p><p>Let’s now explore the last scenario, where the <strong>EventSource </strong>connection between the client and server gets disconnected from the server side, but the browser attempts a retry 2secs from the disconnection.</p><p>To demonstrate this, we need to uncomment below lines of code in the <strong>app.js</strong> in the Node Express project. Below is final <strong>app.js</strong>. I have uncommented lines 18,41 and 50–54. We have initialized a <strong>variable j,</strong> incrementing it every second in the <strong>setInterval </strong>block and in case value of the <strong>variable j </strong>is greater than a random number between 0–10, we are ending the connection. Its a random disconnection for demonstration purpose and there is no logic behind it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bebc674c248c95baff6f8dbe4e3b4fe3/href">https://medium.com/media/bebc674c248c95baff6f8dbe4e3b4fe3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdMYPP4eoEDcY5YYSx78cw.gif" /></figure><p>In the above demonstration, we make the below observations:</p><ol><li>When the browser makes a <strong>new request(not a retry) </strong>for the first time, the value of the <strong>last-event-id</strong> request header received by the server is <strong>undefined </strong>because the browser has not sent this request header. The client has successfully received alphabets A-F in this initial request.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttS2G7TTYG_Q7SwmCiTTlA.png" /></figure><p>2. The server has now closed the connection, after which the browser has retried the connection sending the request header: <strong>last-event-id</strong> with the value 70. This is the ASCII code of the last alphabet received successfully by the client i.e F.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*sLXuqXe2j0P1nWUEJVPC_w.png" /></figure><p>When the server receives this request header, it will increment the ASCII code from 70 to 71 and send the alphabet corresponding to 71 i.e G and so on, as evident in the screenshot below. In the 1st retry, the client has received the alphabets G-K.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*N1oFR96scbDIGXYEFNeKVQ.png" /></figure><p>3. After alphabet K was sent, the server has closed the connection again. Thus the browser retries for the 2nd time, this time with <strong>last-event-id</strong> request header bearing the value: 75, which is nothing but the ASCII code of K.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbvUSMhqKQ240vQkSvGlGw.png" /></figure><p>The server on receiving 75 in the last-event-id request header, will increment the ASCII code by 1 i.e from 75 to 76 and send the alphabet from L onwards as shown in the screenshot below. Unfortunately, in this retry, the browser received only L and M and the server has closed the connection again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igVXK8123xFcjbrOaZTSmA.png" /></figure><p>4. This process goes on and on with multiple random disconnections from the server. Finally in the 8th retry by the browser, the client has received all characters till Z and the server has sent the <strong>done event </strong>to mark the completion. Server also closes the connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_Av9p43KK5t2ffpeQJ2jw.png" /></figure><p>5. But the browser retries again for the 9th time with the <strong>last-event-id</strong> request header bearing the value: 90 i.e the ASCII code of Z. In the Node project, we have written a logic, wherein if the <strong>last-event-id </strong>bears the maximum ASCII code: 90, then the server will respond with 204 status code to indicate to the browser to stop retrying again because it has sent all the messages. As expected, the server has responded with 204 status code and the browser doesn’t try to establish a new connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCc9z6LIYckIzFwIAxHplQ.png" /></figure><p>Below are the links to the git repositories.</p><ul><li><a href="https://github.com/ramyabala221190/SSE-NodeExpress">GitHub - ramyabala221190/SSE-NodeExpress: A NodeJS Express project to demonstrate Server Sent Events</a></li><li><a href="https://github.com/ramyabala221190/SSE-Angular.git">GitHub - ramyabala221190/SSE-Angular: Angular project to demonstrate Server Sent Events</a></li></ul><h3>Thank you for being a part of the community</h3><p><em>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://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ef34632dcc3" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/angular-how-i-understood-server-sent-events-with-nodejs-express-7ef34632dcc3">Angular: How I understood Server Sent Events with NodeJs Express</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Node Express app to a remote server using Docker Compose and using Nginx as reverse…]]></title>
            <link>https://javascript.plainenglish.io/deploying-a-node-express-app-to-a-remote-server-using-docker-compose-and-using-nginx-as-reverse-0cac6caf6c0b?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cac6caf6c0b</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 14:06:36 GMT</pubDate>
            <atom:updated>2025-08-24T16:42:28.690Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a Node Express app to a remote server using Docker Compose and using Nginx as reverse proxy</h3><p>In this story, we will achieve the below objectives:</p><p>=&gt;We are using 2 Ubuntu remote servers: <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-dev.brazilsouth.cloudapp.azure.com</a> and <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-prod.brazilsouth.cloudapp.azure.com</a>.</p><p>=&gt;We will be deploying the <strong>development version </strong>of the app to <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-dev.brazilsouth.cloudapp.azure.com</a> and the <strong>production version</strong> of the app to <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-prod.brazilsouth.cloudapp.azure.com</a>. The Node Express application will be running on<strong> port 3004 in development environment</strong> and <strong>port 8084 in production environment</strong>. The ports could have been the same as well since the development and production versions of app are being deployed to different servers.</p><p>=&gt;We will be using <strong>nginx </strong>as a reverse proxy server listening on <strong>port 80 </strong>for the <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-dev.brazilsouth.cloudapp.azure.com</a> and on <strong>port 80/443</strong> for <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-prod.brazilsouth.cloudapp.azure.com</a>. Nginx will function as reverse proxy server to receive the client requests and forward them to the respective Node Express applications.</p><p>=&gt;This means that on each server, we will be running 2 docker containers- one for the Node Express app and the other for nginx.</p><p>Hitting <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/</a> will route the request to the development version of the app running on <strong>port 3004</strong>. The development version of the node express app is running on port 3004. The Nginx server is running on port 80. Nginx server will route all client requests on port 80 to the Node express app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9W30dxsMUxwrnLRvNPTS9Q.png" /></figure><p>Hitting <a href="https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/">https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/</a> will route the request to the production version of the app running on <strong>port 8084</strong>. The production version of the node express app is running on port 8084. The Nginx server is running on port 80 and 443. Nginx server will redirect all client requests on port 80 to port 443 and finally route the request on port 443 to the Node express app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8R-01nlOMWd3X1NAT1HJ8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuGTA-axMH5-jSgI1RXqxA.png" /></figure><p><strong>I. Configuring the Remote Servers.</strong></p><p>Before we begin with the Node Express app, we need to ensure the Ubuntu Servers are well configured to host the applications.</p><p>We are authenticating to the 2 servers via SSH public key. Ensure that you have provided your public key when configuring the virtual machine.</p><ol><li><strong>Install Docker on both the Ubuntu Servers</strong></li></ol><p>Connect via SSH to the 2 servers separately on 2 command line windows.</p><pre>ssh azureuser@191.235.235.158<br><br>ssh azureuser@20.206.106.236</pre><p>Post successful login, execute the below commands one by one for both the servers. This will successfully install docker on both the Ubuntu VM’s.</p><pre>sudo apt-get update<br>sudo apt-get install ca-certificates curl<br>sudo install -m 0755 -d /etc/apt/keyrings<br>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc<br>sudo chmod a+r /etc/apt/keyrings/docker.asc<br><br># Add the repository to Apt sources:<br>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br>  $(. /etc/os-release &amp;&amp; echo &quot;${UBUNTU_CODENAME:-$VERSION_CODENAME}&quot;) stable&quot; | \<br>  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br>sudo apt-get update<br><br>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p><strong>2. Resolve the remote docker daemon permission issues.</strong></p><p>Post docker installation, execute below commands on the same SSH session for both the servers, to avoid permission issues with docker daemon.</p><pre>sudo groupadd docker<br>sudo usermod -aG docker $USER<br>sudo chown root:docker /var/run/docker.sock<br>sudo chmod g+w /var/run/docker.sock<br>newgrp docker</pre><p><strong>3. Connecting to the docker daemon on the remote VM.</strong></p><p>In case you have a docker daemon running locally and on your remote VM, you need to connect to the remote docker daemon and not local docker daemon.</p><p>Below commands will help configure the Docker daemon in the VM to allow remote connections.</p><pre>sudo systemctl edit docker.service<br><br># Now make it look like this and save the file when you&#39;re done:<br>[Service]<br>ExecStart=<br>ExecStart=/usr/bin/dockerd -H unix:// -H tcp://0.0.0.0:2375<br><br>#To update and save the file=&gt; CTRL+O to save and then Enter and CTRL+X to Exit<br><br># Reload the systemd daemon.<br>sudo systemctl daemon-reload<br># Restart Docker.<br>sudo systemctl restart docker</pre><p><strong>4</strong>. Ensure that your <strong>Inbound Firewall rules </strong>are configured on both the VM’s to allow incoming requests on ports 80(for nginx),443(nginx in case of using ssl), 2375(for docker daemon) and then restart the VM for the changes to take effect. <strong>Please note that we are not exposing the ports: 3034 and 8084 on which the development and production versions of the application will run. Nginx, as the reverse proxy server will be responsible for routing the client request to the application on the correct environment.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDrhuj_okjK4rmHG586jrA.png" /></figure><p>5. We will install the SSL certificates only on the <a href="https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/">mynodeapp-prod.brazilsouth.cloudapp.azure.com</a> server hosting the production version of the Node express app, so that we can access the application on a secure connection.</p><p><strong>Installing Snap</strong></p><p><strong>Certbot </strong>recommends using their <em>snap</em> package for installation.</p><pre>sudo snap install core; sudo snap refresh core</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dEIWn1mfuQXC-Y3sPdjIw.png" /></figure><p><strong>Install Certbot package</strong></p><pre>sudo snap install --classic certbot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wh3VJrTXpe3vksJrDnSyzg.png" /></figure><p>Link the <strong>certbot </strong>command from the <strong>snap </strong>install directory to your path, so you’ll be able to run it by just typing <strong>certbot</strong>.</p><pre>sudo ln -s /snap/bin/certbot /usr/bin/certbot</pre><p>Certbot provides a variety of ways to obtain SSL certificates through plugins. The Nginx plugin will take care of reconfiguring Nginx and reloading the config whenever necessary. To use this plugin, type the following.</p><pre>sudo certbot --nginx -d mynodeapp-prod.brazilsouth.cloudapp.azure.com</pre><p>This runs <strong>certbot </strong>with the <strong>— nginx </strong>plugin, using <strong>-d </strong>to specify the domain names we’d like the certificate to be valid for.</p><p>If nginx or any other webserver is not installed, we can run certbot to get the certificates in standalone mode using the below command. We’ll use the --standalone option to tell <strong>Certbot </strong>to handle the challenge using its own built-in web server</p><pre>sudo certbot certonly --standalone --preferred-challenges http -d mynodeapp-prod.brazilsouth.cloudapp.azure.com</pre><p>I have used the first command. When running the command, you will be prompted to enter an email address and agree to the terms of service. After doing so, you should see a message telling you the process was successful and where your certificates are stored. Your certificates are downloaded, installed, and loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JD8-5lF6sA_dtfw-HY15Kg.png" /></figure><p><strong>Please note down the location where certificate and key have been installed on your server. </strong>From the above screenshot,</p><pre>Certificate is saved at: /etc/letsencrypt/live/mynodeapp-prod.brazilsouth.cloudapp.azure.com/fullchain.pem<br>Key is saved at: /etc/letsencrypt/live/mynodeapp-prod.brazilsouth.cloudapp.azure.com/privkey.pem</pre><p><strong>Let’s Encrypt’s</strong> certificates are only valid for <strong>ninety days</strong>. The <strong>certbot </strong>package we installed takes care of this for us by adding a <strong>systemd </strong>timer that will run twice a day and automatically renew any certificate that’s within <strong>thirty days</strong> of expiration.</p><p>You can query the status of the timer with the below command:</p><pre>sudo systemctl status snap.certbot.renew.service</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRJLn10IJANcRX1lNRp5HA.png" /></figure><p><strong>II. Node Express App.</strong></p><p>Below is the structure of the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*8L7x5ysKH12GeJGLKaM90g.png" /></figure><p>Within the docker folder, we have a <strong>Dockerfile </strong>for the Express application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd30c010c0aaaf331659ffafeed25ab1/href">https://medium.com/media/fd30c010c0aaaf331659ffafeed25ab1/href</a></iframe><p>We are starting the application within the <strong>startup.sh</strong> shell script.</p><pre>#!/bin/bash<br>echo “Starting container. Run time environment:${APP_ENV} on ${APP_PORT}”<br>npm run start</pre><p>Executing “npm run start” will execute the “start” script in the <strong>package.json</strong>.</p><pre>“start”:”node src/app.js”</pre><p>Within the <strong>docker/environment</strong> folder, we have defined 2 .env files for development and production environment. These 2 .env files do not contain any sensitive information like passwords or API keys. <strong>Environment variables containing sensitive information are best stored on the remote server. Since these .env files do not contain any sensitive information, I have included them into the git source control.</strong></p><p><strong>dev.env</strong></p><pre>APP_ENV=development<br>NODE_ENV=production<br>APP_PORT=3004<br>NGINX_PORT=80<br>NGINX_SSL_PORT=443<br>SERVER_NAME=mynodeapp-dev.brazilsouth.cloudapp.azure.com</pre><p><strong>prod.env</strong></p><pre>APP_ENV=production<br>NODE_ENV=production<br>APP_PORT=8084<br>NGINX_PORT=80<br>NGINX_SSL_PORT=443<br>SERVER_NAME=mynodeapp-prod.brazilsouth.cloudapp.azure.com</pre><p>Within the docker folder, we have defined a base <strong>docker-compose.yml</strong> which contains configuration details common to all environments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7d9c446d7c01edaac159b546c0500ad/href">https://medium.com/media/b7d9c446d7c01edaac159b546c0500ad/href</a></iframe><p>Both the <strong>docker-nginx</strong> and <strong>docker-node</strong> services use the appropriate .env file(based on the target environment) from the <strong>docker/environment</strong> folder. Its essential to specify the environment file for the <strong>docker-nginx</strong> service as well because we are accessing some of these environment variables in the <strong>nginx-dev.config/nginx-prod.config</strong>. Please note that <strong>targetEnv </strong>is an environment variable set in the jenkins pipeline definition.</p><p>Both the services use the<strong> “restart:always”</strong> restart policy to ensure that the existing docker containers are automatically up and running, when the remote server reboots. The <strong>“depends_on”</strong> field ensures that compose creates services in dependency order. This means that docker-nginx service will be created before the docker-node service.</p><p>The base <strong>docker-compose.yml </strong>will be overridden by environment specific compose files.</p><p><strong>docker-compose.dev.yml </strong>is for development environment. We have defined the ports for the 2 services.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bc21129e36b99569ead2907315ec953/href">https://medium.com/media/3bc21129e36b99569ead2907315ec953/href</a></iframe><p>=&gt;<strong>DOCKER_HUB_CRED_USR</strong> is username for <strong>DockerHub </strong>account, which is stored as a secret in the Jenkins CI CD server and exposed as an environment variable in the pipeline definition. <strong>DockerHub </strong>simplifies development with the world’s largest container registry for storing, managing, and sharing Docker images.</p><p>=&gt; <strong>toNodeRepo </strong>and <strong>toNginxRepo </strong>are again environment variables exposed from Jenkins pipeline, containing repository names in Dockerhub for storing the node and nginx docker images respectively. <strong>A repository serves as a dedicated space where you can store images associated with a particular application, microservice, or project.</strong> <strong>A repository stores all the versions/tags of a docker image.</strong></p><p>=&gt;<strong>buildNumber </strong>is the build number generated when I run the Jenkins pipeline job. The value of the <strong>buildNumber </strong>serves as a tag for the docker image. Docker images are organized by tags in a repository. The tags represent different versions of the same application, allowing users to pull the right version when needed.</p><p><strong>docker-compose.prod.yml </strong>is for production environment. We have defined the ports for both the services. In the <strong>docker-nginx</strong> service, we have mounted the SSL certificate and key onto the <strong>/etc/nginx/ssl </strong>path in the container. The <strong>tag </strong>variable is a value input by the user to the jenkins pipeline prior to executing the build. The value is the tag of the docker image built when deploying to development. This helps to pull the exact same docker image for production deployment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09b6d9bdf2a5d4a9784eed7010c2c127/href">https://medium.com/media/09b6d9bdf2a5d4a9784eed7010c2c127/href</a></iframe><p>Lets now move to the nginx server configuration. Within the nginx folder, we have defined another <strong>Dockerfile </strong>with the below contents. Based on the target environment input by the user in the Jenkins pipeline, the <strong>nginx-dev.config</strong> or the <strong>nginx-prod.config</strong> will be used.</p><pre>FROM nginx:alpine<br><br>ARG targetEnv<br><br>COPY nginx/nginx-${targetEnv}.config /etc/nginx/templates/default.conf.template</pre><p>Below is the <strong>nginx-dev.config</strong> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/366c8b140345582bf45047c9cf7aa348/href">https://medium.com/media/366c8b140345582bf45047c9cf7aa348/href</a></iframe><p>We have used the <strong>NGINX_PORT </strong>and the<strong> SERVER_NAME </strong>environment variable from the <strong>dev.env</strong> file to populate the port and server name, the nginx server will be listening for requests.</p><pre> server_name ${SERVER_NAME};<br> listen ${NGINX_PORT};</pre><p>We have also used the <strong>APP_PORT</strong> environment variable from the <strong>dev.env</strong> file to proxy the client requests to the node application on the correct port. Here, <strong>docker-node </strong>is the docker compose service name for the express app.</p><pre>location / {<br>proxy_pass http://docker-node:${APP_PORT};<br>}</pre><p>Below is the <strong>nginx-prod.config </strong>file. We have used the <strong>SERVER_NAME</strong>, <strong>NGINX_SSL_PORT,NGINX_PORT</strong> and <strong>APP_PORT</strong> variables from the <strong>prod.env</strong> file. We have 2 server blocks listening on port 443 and 80. We have referenced the SSL certificate and key from the <strong>/etc/nginx/ssl</strong> path in the container. We have also added a logic to redirect to a secure <a href="https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/">https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/</a> incase of any request to <a href="https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/">http://mynodeapp-prod.brazilsouth.cloudapp.azure.com/</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40becb0bea4bbc2184ba583ba6b3bfa8/href">https://medium.com/media/40becb0bea4bbc2184ba583ba6b3bfa8/href</a></iframe><p>Moving to the <strong>src/app.js. </strong>The <strong>APP_PORT</strong> and <strong>APP_ENV</strong> environment variables get their value from the .env file(dev.env or prod.env based on target environment)we passed to the <strong>docker-compose.yml</strong></p><pre>import express from ‘express’;<br>const app=express();<br><br>app.get(‘/’,(req,res)=&gt;{<br>res.send(`Welcome to Express application running in ${process.env.APP_ENV} on port ${process.env.APP_PORT}`)<br>})<br><br>app.listen(process.env.APP_PORT,()=&gt;{<br>console.log(`Node Express app listening on ${process.env.APP_PORT}`)<br>})</pre><p><strong>III. Jenkins Pipeline</strong></p><p>I have written 2 simple pipeline definitions to automate the deployment. The definitions follow the below steps in brief:</p><ol><li>Clone the git repository containing the express source code.</li><li>If development is the target environment, below is the sequence of events:</li></ol><p>=&gt; Build the docker images for node and nginx</p><p>=&gt;Login into DockerHub or any other registry you are using.</p><p>=&gt;Push the docker images to the repositories dedicated for node and nginx respectively.</p><p>=&gt;SSH into the remote server and run the docker images to create 2 running containers for node and nginx in development.</p><p>3. If production is the target environment, below is the sequence of events:</p><p>=&gt;Pull the docker image for node and nginx, already built when deploying to development.</p><p>=&gt;Rename and tag the pulled images appropriately.</p><p>=&gt;Login into DockerHub registry.</p><p>=&gt;Push the newly tagged docker images to the repositories dedicated for node and nginx respectively.</p><p>=&gt;SSH into the remote server and run the docker images to create 2 running containers for node and nginx in production.</p><p>Below is the definition for development deployment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5798ae45b904ce326a56c680416a63bd/href">https://medium.com/media/5798ae45b904ce326a56c680416a63bd/href</a></iframe><p>Below is the definition for production deployment</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/734e0a83b62c40493a4aa616f8306685/href">https://medium.com/media/734e0a83b62c40493a4aa616f8306685/href</a></iframe><p>Below is the git repository for the Node Express app.</p><p><a href="https://github.com/ramyabala221190/nodejs-express-docker-nginx.git">GitHub - ramyabala221190/nodejs-express-docker-nginx: A simple nodejs project to demonstrate deployment to a remote server using docker and nginx as reverse proxy</a></p><h3>Thank you for being a part of the community</h3><p><em>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://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cac6caf6c0b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/deploying-a-node-express-app-to-a-remote-server-using-docker-compose-and-using-nginx-as-reverse-0cac6caf6c0b">Deploying a Node Express app to a remote server using Docker Compose and using Nginx as reverse…</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[Deploying a Node Express app to a remote server using PM2 and configuring Nginx as reverse proxy]]></title>
            <link>https://javascript.plainenglish.io/deploying-a-node-express-app-to-a-remote-server-using-pm2-and-configuring-nginx-as-reverse-proxy-1c4a2d152ebb?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c4a2d152ebb</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[pm2]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 09:03:13 GMT</pubDate>
            <atom:updated>2025-06-16T00:19:54.357Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, we will achieve the below objectives:</p><p>=&gt;We will be using 2 Ubuntu remote servers: <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-dev.brazilsouth.cloudapp.azure.com</a> and <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-prod.brazilsouth.cloudapp.azure.com</a>.</p><p>=&gt;We will be using PM2 to deploy the <strong>development version </strong>of the app to <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-dev.brazilsouth.cloudapp.azure.com</a> and the <strong>production version</strong> of the app to <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">mynodeapp-prod.brazilsouth.cloudapp.azure.com</a>.</p><p>=&gt;The development version of the app will be running on <strong>port 3000</strong> and the production version of the app will be running on <strong>port 8080</strong>. We will initially access the applications in the browser directly on these ports.</p><p>=&gt;As we progress in the story, we will be configuring <strong>nginx </strong>as a reverse proxy listening on <strong>port 80 </strong>in the 2 servers. Nginx will function as reverse proxy server to receive the client requests and forward them to the respective Node Express applications. Hitting <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/</a> will route the request to the development version of the app running on <strong>port 3000. </strong>Hitting <a href="https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/">http://mynodeapp-prod.brazilsouth.cloudapp.azure.com/</a> will route the request to the production version of the app running on <strong>port 8080.</strong></p><p>=&gt;We will also be installing SSL certificates at the end of the story to access the application securely in the browser.</p><p><strong>I. Configure the Remote Server</strong></p><p>SSH into both the servers on separate command line windows.</p><pre>ssh azureuser@191.235.235.158<br><br>ssh azureuser@20.206.106.236</pre><p>Ensure you have Node and NPM installed on both the servers. I have used the below commands for the same.</p><pre>sudo apt-get update<br>sudo apt-get install nodejs<br>sudo apt-get install npm</pre><p>After Node and NPM is installed, the next step will be to install PM2 globally on both servers. Before you begin the installation, ensure you give the required permissions to write into the below folders.</p><pre>sudo chmod +777 /usr/local/lib/<br>sudo chmod +777 /usr/local/bin/</pre><p>Execute the below command to install PM2 globally.</p><pre>npm install -g pm2</pre><p>After PM2 is installed, execute the below command to ensure that, in case the server shuts down, on restart, all existing PM2 processes will also restart.</p><pre>pm2 startup</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uwBw0N2WRjsirnVBHComw.png" /></figure><p>Finally, it is essential to configure the <strong>Inbound Firewall </strong>rules on both the servers to allow inbound connections to the server.</p><p>For the server hosting the development version of the app, we have added a rule to allow connections on port <strong>3000 </strong>highlighted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYetZiPUPefm4FLVQMsCgA.png" /></figure><p>For the server hosting the production version of the application, we have added a rule to allow inbound connections on port <strong>8080 </strong>highlighted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWEFM5vwg3E-muCePqnY4Q.png" /></figure><p>Note that, we are directly exposing the application ports on the firewall. Ideally, we should use <strong>Nginx </strong>as reverse proxy server to forward the client requests to the application port and just expose the port on which the Nginx server will be listening on, in the firewall rules.</p><p>We will complete the Nginx configuration and the firewall rules update as we progress.</p><p><strong>II. Node Express Project</strong></p><p>Lets now check the NodeJs Project. This is the project structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*0pGskxS1WJMzhb_fl8VGSA.png" /></figure><p>We initially installed <strong>pm2 npm package</strong> on the 2 remote servers for deployment. For testing the node app locally , we need to install pm2 globally on the local system as well.</p><p>So lets go ahead and execute the below command on local system.</p><pre>npm install -g pm2</pre><p>Once pm2 is installed, we need to create a configuration file in the project, which can be generated using the below command.</p><pre>pm2 ecosystem</pre><p>This will generate a <strong>ecosystem.config.js</strong> file in the root of the project. I have renamed it to <strong>ecosystem.config.cjs </strong>to declare it as a <strong>CommonJS </strong>module.</p><p>In the <strong>package.json</strong>, I have added the below field to ensure that all .js files are treated as <strong>ES6 modules</strong>.</p><pre>“type”: “module”,</pre><p>Below is the initial content of the <strong>ecosystem.config.cjs</strong> file.</p><pre>module.exports = {<br>apps : [{<br>script: ‘index.js’,<br>watch: ‘.’<br>}, {<br>script: ‘./service-worker/’,<br>watch: [‘./service-worker’]<br>}],<br>deploy : {<br>production : {<br>user : ‘SSH_USERNAME’,<br>host : ‘SSH_HOSTMACHINE’,<br>ref : ‘origin/master’,<br>repo : ‘GIT_REPOSITORY’,<br>path : ‘DESTINATION_PATH’,<br>‘pre-deploy-local’: ‘’,<br>‘post-deploy’ : ‘npm install &amp;&amp; pm2 reload ecosystem.config.js — env production’,<br>‘pre-setup’: ‘’<br>}<br>}<br>};</pre><p>This has been updated to the below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2c6788141359dff7c9f8d04bfe10c79/href">https://medium.com/media/d2c6788141359dff7c9f8d04bfe10c79/href</a></iframe><p>Lets go through each field in this file to understand its purpose:</p><ol><li>The <strong>“name”</strong> field describes the name of the application.</li></ol><pre>name:’my-app’,</pre><p>2. The <strong>“append_env_to_name”</strong> field is very useful, if you are running Node applications of different environments on the same server/system. PM2 will ensure that it will append the environment to the “name” field so that the application names for different environments are unique. This is not of much use to us post deployment because the development and production version of the app is deployed to 2 different servers. Its very useful for local system testing because you can run the development and production versions of the app together on the same system. There will be no conflict because the names of the app’s are unique.</p><pre>append_env_to_name: true,</pre><p>3. The <strong>“script”</strong> field is the path of the file to execute. It is nothing but our main <strong>app.js </strong>within the <strong>src </strong>folder.</p><pre>script: ‘src/app.js’,</pre><p>4. The <strong>“watch”</strong> field will enable the watch and reload feature. This is useful for local testing. If there are any changes in the <strong>src </strong>folder, the application will automatically reload to reflect the changes.</p><pre>watch: ‘src/’,</pre><p>5. The <strong>“env”</strong> field will contain the environment variables which can be accessed in your Node project. <strong>The variables you define here will be applicable to all environments.</strong></p><pre>env:{<br>NODE_ENV:’production’<br>},</pre><p>6. The <strong>“env_”</strong> field is useful to specify environment specific variables. Thus the <strong>“env_development”</strong> will list out the environment variables for development environment and the <strong>“env_production” </strong>will list out the environment variables for production environment.</p><pre>env_development:{<br>DOTENV_CONFIG_PATH:’.env.development’,<br>PORT:3000,<br>APP_ENV:’development’<br>},<br>env_production:{<br>DOTENV_CONFIG_PATH:’.env.production’,<br>PORT:8080,<br>APP_ENV:’production’<br>},</pre><p>The PORT and APP_ENV variables define the application port and the target environment. What is DOTENV_CONFIG_PATH ?</p><p>To understand why we need this, we need to understand how and why environment variables should be handled.</p><p>The <strong>ecosystem.config.cjs</strong> file provides the ability to create environment variables which can be accessed anywhere in the application. <strong>You need to ensure here that you are not providing variables containing sensitive information like passwords or keys since this file will be checked into the git repository.</strong></p><p><strong>Any sensitive information must be stored securely as environment variables on the remote server and not in the code.</strong></p><p>I have added 2 .env files: <strong>.env.development </strong>and <strong>.env.production.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGI3zmLLCEivCBv2Hj_yFA.png" /></figure><p>These 2 files will not be checked into the git repository and are included in the <strong>.gitignore</strong> file as you see below.</p><pre>node_modules/<br>.env.*</pre><p>What is the purpose of these 2 .env files then ? <strong>These .env files are only for supplying environment variables required for local run of application. Thus these .env files can contain sensitive information only for the local run of the application.</strong></p><p>In order to access the content of these 2 <strong>.env</strong> files in the application for local testing, we are using the <strong>dotenv </strong>npm package. This package is installed as a dev dependency.</p><pre>npm install — save-dev dotenv</pre><p>Lets now get back to the purpose of the DOTENV_CONFIG_PATH variable. By setting this environment variable, we are configuring the <strong>dotenv </strong>package to look for a particular .env file</p><p>Thus for development environment, the <strong>dotenv </strong>package must use the<strong> .env.development</strong> file to set the environment variables.</p><pre>env_development:{<br>DOTENV_CONFIG_PATH:’.env.development’,<br>PORT:3000,<br>APP_ENV:’development’<br>},</pre><p>For production environment, the <strong>dotenv </strong>package must use the<strong> .env.production </strong>file to set the environment variables.</p><pre>env_production:{<br>DOTENV_CONFIG_PATH:’.env.production’,<br>PORT:8080,<br>APP_ENV:’production’<br>}</pre><p>7. We are using the — require (-e) command line option to preload <strong>dotenv</strong>. By doing this, you do not need to require and load <strong>dotenv </strong>in your application code. The <strong>“node_args”</strong> field enables to provide additional arguments when executing the<strong> “script”</strong> field.</p><pre>node_args:`-r dotenv/config`</pre><p>8. Finally, lets move to the <strong>“deploy”</strong> field which contains all details PM2 requires for deploying the development and production versions of the app to the 2 remote servers.</p><pre>deploy : {<br>production : {<br>“user” : “azureuser”,<br>“host” : [“191.235.235.158”],<br>“ref” : “origin/master”,<br>“repo” : “https://github.com/ramyabala221190/nodejs-express-pm2-withoutDocker&quot;,<br>“path” : “/var/prod/onlypm2/”,<br>“pre-setup”:”sudo chmod +777 /var/”,<br>“post-deploy” : “npm run pm2-prod-start”<br>},<br>development:{<br>“user” : “azureuser”,<br>“host” : [“20.206.106.236”],<br>“ref” : “origin/master”,<br>“repo” : “https://github.com/ramyabala221190/nodejs-express-pm2-withoutDocker&quot;,<br>“path” : “/var/dev/onlypm2/”,<br>“pre-setup”:”sudo chmod +777 /var/”,<br>“post-deploy” : “npm run pm2-dev-start”<br>}<br>}</pre><p>Under the “deploy” field, you can have as many fields as the no of the environments available. In this example, we have considered only “development” and “production”. Lets now see the configuration fields under each environment.</p><p>=&gt; The <strong>“user”</strong> and the <strong>“host” </strong>field refers to SSH user on the remote host we need to connect to.</p><pre>“user” : “azureuser”,<br>“host” : [“20.206.106.236”],</pre><p>=&gt; <strong>“ref”</strong> refers to the branch in the <strong>“repo”</strong> repository that needs to be cloned. Its the repository containing the Node app code.</p><pre>“ref” : “origin/master”,<br>“repo” : “https://github.com/ramyabala221190/nodejs-express-pm2-withoutDocker&quot;,</pre><p>=&gt;<strong> “path” </strong>is the path on the remote server, where the application needs to be deployed.</p><pre>“path” : “/var/dev/onlypm2/”,</pre><p>=&gt; The<strong> “pre-setup”</strong> field is required to give appropriate permissions for updating /var/ folder. We will see the significance of this step as we progress in the story.</p><pre>“pre-setup”:”sudo chmod +777 /var/”</pre><p>=&gt; The <strong>“post-deploy”</strong> field contains the command to be executed post deployment.</p><pre>“post-deploy” : “npm run pm2-dev-start”</pre><p>We are executing the “pm2-dev-start” or “pm2-prod-start” script in the <strong>package.json</strong> based on the environment.</p><pre>“pm2-dev-start”: “pm2 startOrReload ecosystem.config.cjs — env development”,<br>“pm2-prod-start”: “pm2 startOrReload ecosystem.config.cjs — env production”,</pre><p>Both the scripts execute the<strong> “pm2 startOrReload”</strong> command passing the path of the configuration file and also the <strong>env flag</strong> which specifies the target environment. The value of the <strong>env flag</strong> decides which deployment configuration and which environment variables will be used in the application. <strong>This command will start a new process or reload an existing process.</strong></p><p>Lets now check our main <strong>src/app.js. </strong>We have referenced the environment variables set in the <strong>ecosystem.config.cjs</strong> and also in the<strong> .env files</strong>. I have logged the value of<strong> “api-key” </strong>environment variable just to demonstrate the working of <strong>dotenv </strong>npm package locally.</p><pre>import express from ‘express’;<br>const app=express();<br><br>app.get(‘/’,(req,res,next)=&gt;{<br>res.status(200).send(`Welcome to the Node Express Application in ${process.env.APP_ENV} environment on port ${process.env.PORT}`);<br>})<br><br>app.listen(process.env.PORT,()=&gt;{<br>console.log(process.env[‘api-key’]);// just logged so that we confirm that the key from the correct file is logged<br>console.log(`server in ${process.env.APP_ENV} environment listening on port ${process.env.PORT}`);<br>})</pre><p><strong>III. Local run of application</strong></p><p>To run the development version of the application, execute the <strong>“pm2-dev-start”</strong> script.</p><pre>“pm2-dev-start”: “pm2 startOrReload ecosystem.config.cjs — env development”,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8vNMfJ7uaJ10dKyJCAQQQ.png" /></figure><p>If you observe the name of the application is not just “my-app”. The environment has also been appended to the application name.</p><p>Hitting <a href="http://localhost:3000/"><strong>http://localhost:3000</strong></a> in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHb4M8pMDHA6xRJGsOu7Tg.png" /></figure><p>Lets now check the PM2 and application logs on the local system by executing <strong>“pm2 logs”</strong>. Observe the value of the environment variables correctly getting printed from the app.js file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIAM4ZwtwHzK00OYx-uqIw.png" /></figure><p>To run the production version of the application, execute the <strong>“pm2-prod-start”</strong> script.</p><pre>“pm2-prod-start”: “pm2 startOrReload ecosystem.config.cjs — env production”,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4iauvbQUujfJ8jMAHbXIw.png" /></figure><p>We are able to execute both production and development versions of the application on the same system because of the unique naming of the apps.</p><p>Hitting <strong>http://localhost:8080</strong> in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yy2gZadU2OLWEn92G4RugQ.png" /></figure><p>Lets now check the PM2 and application logs on the local system using <strong>“pm2 logs”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OISyf1Y93CT8uID2Fs3PoA.png" /></figure><p><strong>IV. Deployment</strong></p><p>Let us review the scripts we have in the <strong>package.json</strong>.</p><pre>“pm2-dev-start”: “pm2 startOrReload ecosystem.config.cjs — env development”,<br>“pm2-prod-start”: “pm2 startOrReload ecosystem.config.cjs — env production”,<br>“pm2-prod-deploy”:”pm2 deploy ecosystem.config.cjs production”,<br>“pm2-dev-deploy”:”pm2 deploy ecosystem.config.cjs development”,<br>“pm2-dev-setup”:”pm2 deploy ecosystem.config.cjs development setup”,<br>“pm2-prod-setup”:”pm2 deploy ecosystem.config.cjs production setup”</pre><p>The <strong>“pm2-dev-start”</strong> or the<strong> “pm2-prod-start” </strong>scripts are to used to start the Node Express app. We have already used these 2 scripts to locally run the applications.</p><p>The<strong> “pm2-dev-setup”</strong> or the <strong>“pm2-prod-setup”</strong> setup scripts are used to run the remote setup commands.</p><p>Finally the <strong>“pm2-dev-deploy” </strong>or the <strong>“pm2-prod-deploy”</strong> deploy scripts are used to complete the deployment.</p><p><strong>Note: The deploy and setup scripts must be executed on GitBash</strong>, else you will face the below error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GwN_CqbiJnKAeMz0Kf5yw.png" /></figure><ol><li><strong>Deployment of Development version</strong></li></ol><p>Lets execute the<strong> “pm2-dev-deploy”</strong> script in <strong>GitBash </strong>on your local system, to deploy the development version of the application. We face the below error which says that the deployment path : <strong>/var/dev/onlypm2</strong> does not exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vidUHJriWC2BRHKlQRetnw.png" /></figure><p>In order to avoid this error, it is essential to perform 1 time setup before any deployments. Thus we execute the<strong> “pm2-dev-setup” </strong>setup script in GitBash on the local system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U2tYfQOgtxFRVElvyJXg5Q.png" /></figure><p>Let me now, point out the importance of the below step in the <strong>ecosystem.config.cjs</strong></p><pre>“pre-setup”:”sudo chmod +777 /var/”,</pre><p>In the absence of the above step, you will face the below error when executing the<strong> “pm2-dev-setup” </strong>or the<strong> “pm2-prod-setup” </strong>setup script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acSY_hbnKadaPlfCBcsG9Q.png" /></figure><p>Note that its only a 1 time step and executing it again will result in the below error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGzIF_eQ7Je4aZsodBjUmQ.png" /></figure><p>Now that the setup is complete, we can proceed to deployment. We execute the <strong>“pm2-dev-deploy” </strong>deploy script in GitBash on the local system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhoqCxHIQ0k1o15ncpcaYg.png" /></figure><p>Utilize the existing SSH session or create a new one on command line with the remote server hosting the development version of the app and execute <strong>“pm2 list”</strong> to display all the PM2 managed processes on the remote server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Adx8bPDb6_g_2dugsREL3w.png" /></figure><p>Executing <strong>“pm2 logs” </strong>in the same SSH session to view the PM2 and the Node Express app logs on the remote server. Observe that the value of the <strong>process.env[‘api-key’]</strong> is <strong>undefined </strong>in the logs below. This is because we have not checked in the <strong>.env files</strong> into the git repository and thus the value of this environment variable will be undefined. <strong>Thus it is important that all the variables defined in the .env files must be set on the remote server.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1UjMUUPGarcczUFXpk5Fw.png" /></figure><p>Opening <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com:3000/">http://mynodeapp-dev.brazilsouth.cloudapp.azure.com:3000/</a> in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KufNEgR12n7PU9SVU9PkFw.png" /></figure><p><strong>2. Deployment of Production version</strong></p><p>Execute the 1 time setup script <strong>“pm2-prod-setup” </strong>in GitBash on your local system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWNjUe9GJgHWJ0Lt7bGoPw.png" /></figure><p>This is only 1 time step, because if you try to execute it again, you will face the below error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNyiLIta83ymItiZ2KPDhA.png" /></figure><p>Lets now execute the deployment script <strong>“pm2-prod-deploy” </strong>in GitBash on your local system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhN3vz_PNLJBpHzTiyfalg.png" /></figure><p>Utilize the existing SSH session or create a new one with the remote server hosting the production version of the app on command line and execute <strong>“pm2 list”</strong> to view all the PM2 managed processes on the remote server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGlyuUF99yV1btMM0uAKvQ.png" /></figure><p>Executing <strong>“pm2 logs” </strong>in the same SSH session, to view the PM2 and the Node Express app logs on the remote server. Here again, observe that the value of the <strong>process.env[‘api-key’]</strong> is <strong>undefined </strong>in the logs below. This is because we have not checked in the <strong>.env files</strong> into the git repository and thus the value of this environment variable will be undefined. <strong>Thus it is important that all the variables defined in the .env files must be set on the remote server.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_yCjLKgLjCQQnlovg5l0g.png" /></figure><p>Hitting <a href="http://mynodeapp-prod.brazilsouth.cloudapp.azure.com:8080/">http://mynodeapp-prod.brazilsouth.cloudapp.azure.com:8080/</a> in the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4w92r0fcucaNgXpnzVG-A.png" /></figure><p>Below is the git repository for the Node Express app.</p><p><a href="https://github.com/ramyabala221190/nodejs-express-pm2-withoutDocker.git">GitHub - ramyabala221190/nodejs-express-pm2-withoutDocker: A simple Nodejs project using pm2 but without docker</a></p><p>Here is the list of available PM2 commands that could be useful.</p><p><a href="https://pm2.io/docs/runtime/reference/pm2-cli/">PM2 - CLI | Reference | PM2 Documentation</a></p><p><strong>V. Configuring NGINX</strong></p><p>We need to execute the below steps for both the remote servers so that nginx can act as the <strong>reverse proxy server</strong> and route client requests to the node express application.</p><ol><li>Begin by installing nginx on the ubuntu server.</li></ol><pre>sudo apt update<br>sudo apt install nginx</pre><p>2. Execute the below command to ensure that nginx starts up automatically on server reboot.</p><pre>sudo systemctl enable nginx</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rr-gP4mPxeiOHFzC5Mc7Pg.png" /></figure><p>3. Create a new configuration file for the node express application in the <strong>/etc/nginx/sites-available</strong> directory.</p><pre>sudo nano /etc/nginx/sites-available/node-express-pm2</pre><p>Adding the following content to the configuration file for <a href="http://mynodeapp-prod.brazilsouth.cloudapp.azure.com:8080/">mynodeapp-dev.brazilsouth.cloudapp.azure.com</a>. Replace the domain name following the “server_name” with your server’s IP address/domain name. <strong>Observe the proxy_pass directive which is used to redirect any client requests on port 80 to port 3000.</strong></p><pre>server {<br> listen 80;<br> server_name mynodeapp-dev.brazilsouth.cloudapp.azure.com;<br><br> location / {<br> proxy_pass http://localhost:3000;<br> proxy_http_version 1.1;<br> proxy_set_header Upgrade $http_upgrade;<br> proxy_set_header Connection ‘upgrade’;<br> proxy_set_header Host $host;<br> proxy_cache_bypass $http_upgrade;<br> }<br>}</pre><p>Below is a screenshot of the same. To save the content to the file. Hit <strong>Ctrl+O</strong> followed by <strong>Enter </strong>and finally <strong>Ctrl+x </strong>to Exit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puKbDk4HNdAF4NKeVEpylg.png" /></figure><p>For the remote server <a href="http://mynodeapp-prod.brazilsouth.cloudapp.azure.com:8080/">mynodeapp-prod.brazilsouth.cloudapp.azure.com</a>, the below content will be used.<strong>Observe the proxy_pass directive which is used to redirect any client requests on port 80 to port 8080.</strong></p><pre>server {<br> listen 80;<br> server_name mynodeapp-prod.brazilsouth.cloudapp.azure.com;<br> <br> location / {<br> proxy_pass http://localhost:8080;<br> proxy_http_version 1.1;<br> proxy_set_header Upgrade $http_upgrade;<br> proxy_set_header Connection ‘upgrade’;<br> proxy_set_header Host $host;<br> proxy_cache_bypass $http_upgrade;<br> }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aemmem1q2wc27bAur6yGlQ.png" /></figure><p>4. Enable the configuration by creating a symbolic link to the sites-enabled directory in both the servers.</p><pre>sudo ln -s /etc/nginx/sites-available/node-express-pm2 /etc/nginx/sites-enabled/</pre><p>5. Test the Nginx configuration for syntax errors.</p><pre>sudo nginx -t</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-nh30PGdGq5CZ3GXLE8FA.png" /></figure><p>6. Reload Nginx in both the servers to apply the changes.</p><pre>sudo systemctl reload nginx</pre><p>7. Finally, please remove the inbound firewall rule we initially added for allowing inbound connections to<strong> port 3000 and 8080 </strong>in the development and production servers respectively. Now, all we have are the below rules in both the servers. After deleting the rule, please restart the servers for the firewall changes to take effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUHQsrq6dEZ4LxOpG6Tv1w.png" /></figure><p>8. Thus, all inbound connections to <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com:3000/">http://mynodeapp-dev.brazilsouth.cloudapp.azure.com:3000/</a>will be blocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*us1IQwFLuj64LBDCtcbFow.png" /></figure><p>Hitting <a href="http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">http://mynodeapp-dev.brazilsouth.cloudapp.azure.com/</a> will automatically route to the development version of the app running on port 3000 because nginx is listening on port 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXX_-ddSX6oLFAfHgFNP8Q.png" /></figure><p>Similarly, all inbound connections to <a href="http://mynodeapp-prod.brazilsouth.cloudapp.azure.com/">http://mynodeapp-prod.brazilsouth.cloudapp.azure.com</a>:8080 will be blocked and all client requests to <a href="http://mynodeapp-prod.brazilsouth.cloudapp.azure.com/">http://mynodeapp-prod.brazilsouth.cloudapp.azure.com/</a> will be routed by nginx to the production version of the app running on port 8080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIkMIWariRIhqUOhLx_MEQ.png" /></figure><p><strong>VI. Securing with SSL connection</strong></p><p>Lets now proceed to install the SSL certificates on the <a href="https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/">mynodeapp-prod.brazilsouth.cloudapp.azure.com</a> server so that we can access the production version of the application on a secure connection.</p><ol><li><strong>Installing Snap</strong></li></ol><p>Certbot recommends using their <em>snap</em> package for installation.</p><pre>sudo snap install core; sudo snap refresh core</pre><p><strong>2. Install Certbot package</strong></p><pre>sudo snap install --classic certbot</pre><p><strong>3. </strong>Link the <strong>certbot </strong>command from the <strong>snap </strong>install directory to your path, so you’ll be able to run it by just typing <strong>certbot</strong>.</p><pre>sudo ln -s /snap/bin/certbot /usr/bin/certbot</pre><p><strong>4. </strong>Certbot provides a variety of ways to obtain SSL certificates through plugins. The Nginx plugin will take care of reconfiguring Nginx and reloading the config whenever necessary. To use this plugin, type the following:</p><pre>sudo certbot --nginx -d mynodeapp-prod.brazilsouth.cloudapp.azure.com</pre><p>This runs <strong>certbot </strong>with the <strong>— nginx </strong>plugin, using <strong>-d </strong>to specify the domain names we’d like the certificate to be valid for.</p><p>When running the command, you will be prompted to enter an email address and agree to the terms of service. After doing so, you should see a message telling you the process was successful and where your certificates are stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*JD8-5lF6sA_dtfw-HY15Kg.png" /></figure><p>Your certificates are downloaded, installed, and loaded, and your Nginx configuration will now automatically redirect all requests from <a href="https://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">http://mynodeapp-prod.brazilsouth.cloudapp.azure.com/</a> to <a href="https://mynodeapp-dev.brazilsouth.cloudapp.azure.com/">https://mynodeapp-prod.brazilsouth.cloudapp.azure.com/</a></p><p>If you now recheck your custom nginx configuration, it has been automatically updated by <strong>Certbot </strong>to use the new certificates. <strong>We have an additional server block listening on 443 port for client requests. There is also a logic which redirects any client requests on port 80 to port 443 automatically. The requests on port 443 will be routed to the node application.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gw26U0z3R5cMIKq3JnmfrQ.png" /></figure><p>Reloading the application in the browser. Nginx automatically redirects the application running on port 80 to 443.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wxXacHOqq6DSkz53ilAmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BonikDRX-px6GbjH-3nGg.png" /></figure><p><strong>5. Certificate Renewal</strong></p><p>Let’s Encrypt’s certificates are only valid for <strong>ninety days</strong>. The <strong>certbot </strong>package we installed takes care of this for us by adding a <strong>systemd </strong>timer that will run twice a day and automatically renew any certificate that’s within <strong>thirty days</strong> of expiration.</p><p>You can query the status of the timer with the below command:</p><pre>sudo systemctl status snap.certbot.renew.service</pre><h3>Thank you for being a part of the community</h3><p><em>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://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c4a2d152ebb" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/deploying-a-node-express-app-to-a-remote-server-using-pm2-and-configuring-nginx-as-reverse-proxy-1c4a2d152ebb">Deploying a Node Express app to a remote server using PM2 and configuring Nginx as reverse proxy</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[Angular: This is how I understood using the ControlValueAccessor interface — Part-II]]></title>
            <link>https://ramya-bala221190.medium.com/angular-this-is-how-i-understood-using-the-controlvalueaccessor-interface-part-ii-845158546696?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/845158546696</guid>
            <category><![CDATA[controlvalueaccessor]]></category>
            <category><![CDATA[formgroup]]></category>
            <category><![CDATA[formarray]]></category>
            <category><![CDATA[ngvalueaccessor]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 12:21:35 GMT</pubDate>
            <atom:updated>2025-04-24T12:27:25.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular: This is how I understood using the ControlValueAccessor interface — Part-II</h3><p>In the first part of this series, we saw a simple shopping cart example. Below is the link.</p><p><a href="https://ramya-bala221190.medium.com/angular-this-is-how-i-understood-using-the-controlvalueaccessor-interface-part-i-49999c6c112a">Angular: This is how I understood using the ControlValueAccessor interface — Part-I</a></p><p>In this story, we will implement a slightly more complex example involving nested FormGroup and FormArray.</p><p>Consider a Contact Form, where you are can update the details of 2 contacts you have. For each contact, you can update certain basic details like name,email, dob etc. Along with that, you can also add multiple addresses and phone numbers. You also have an option to select a profile image for the contact from a list of available images.</p><p>We will be moving the functionality to add multiple addresses, phone numbers and profile image selection to separate components and linking these components to the parent component form using <strong>ControlValueAccessor</strong>.</p><p>Below is a short demo of the example, where the user can update the details of 2 contacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*otr3kxXDnZVntxbtpMn9kQ.gif" /></figure><p>Lets begin with the parent <strong>ContactFormComponent, </strong>which you see in the above demo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65fe28c0c95031f8235428e332c9d127/href">https://medium.com/media/65fe28c0c95031f8235428e332c9d127/href</a></iframe><p>Its a simple reactive form with <strong>root FormGroup userForm</strong>. This <strong>userForm </strong>has a<strong> FormArray userList. </strong>This <strong>FormArray userList</strong> is an array of FormGroups, where each FormGroup describes the user contact.</p><p>Below is the sample JSON data for a user contact.</p><pre>{<br>“id”: 1,<br>“name”: “Leanne Graham”,<br>“profile”:””,<br>“dob”:new Date(“10–21–1992”),<br>“username”: “Bret”,<br>“email”: “Sincere@april.biz”,<br>“favourite”:0,<br>“address”: [{<br>“street”: “Kulas Light”,<br>“suite”: “Apt. 556”,<br>“city”: “Gwenborough”,<br>“zipcode”: “92998–3874”,<br>}],<br>“phone”: [<br>{“phoneNumber”:”1–770–736–8031 x56442&quot;,”preferred”:false,”phoneType”:”home”}<br>],<br>“website”: “hildegard.org”,<br>“company”: {<br>“name”: “Romaguera-Crona”,<br>“catchPhrase”: “Multi-layered client-server neural-net”,<br>“bs”: “harness real-time e-markets”<br>}<br>}</pre><p>Each user contact models the below structure.</p><pre>export interface UserModel {<br>id: number;<br>name: string;<br>dob:Date;<br>profile:string;<br>username: string;<br>email: string;<br>address: AddressModel[];<br>phone: Phone[];<br>website: string;<br>company: CompanyModel;<br>favourite:number<br>}</pre><p>Each FormGroup within the <strong>userList FormArray </strong>is structured as below. I will not be going into details of how the <strong>userList FormArray</strong> is being created. This is out of the scope of the story. But it is essential to understand the structure of each FormGroup. <strong>Observe that all the FormControls, except for id,address and phone, have some in-built/custom validators. </strong>We will be adding validators for the <strong>address and phone FormControls</strong> within the custom components, which will be discussed shortly.</p><pre> createUserGroup(user:UserModel){<br>    return this.fb.group({<br>      id:[user.id],<br>      name:[user.name,[Validators.required]],<br>      dob:[user.dob,[Validators.required]],<br>      email:[user.email,[Validators.required,Validators.email]],<br>      address:[user.address],<br>      phone:[user.phone],<br>      website:[user.website,[Validators.required]],<br>      favourite:[user.favourite,[favValidator]],<br>      profile:[user.profile,[Validators.required]]<br>    })<br>  }</pre><p>Lets get back to the <strong>ContactFormComponent </strong>template.</p><p>We have moved the functionality to display the phone details of the user, adding/removing phone details to a separate component : <strong>CustomPhoneComponent </strong>with selector <strong>&lt;app-custom-phone&gt;</strong>.</p><p>The <strong>formControlName </strong>attribute binds the <strong>&lt;app-custom-phone&gt;</strong> element to the <strong>FormControl phone </strong>in the FormGroup.</p><pre>&lt;div class=”form-group”&gt;<br>&lt;label class=”form-label”&gt;Phone Numbers&lt;/label&gt;<br>&lt;app-custom-phone formControlName=”phone”&gt;&lt;/app-custom-phone&gt;<br>&lt;/div&gt;</pre><p>Similarly, we have the moved the functionality of displaying the address details of the user, adding/removing addresses to a seperate component: <strong>CustomAddressComponent </strong>with selector<strong>&lt; app-custom-address&gt;</strong>. The <strong>formControlName </strong>attribute binds the <strong>&lt;app-custom-address&gt;</strong> element to the <strong>FormControl address </strong>in the FormGroup.</p><pre> &lt;div class=”form-group”&gt;<br>&lt;label class=”form-label”&gt;Addresses&lt;/label&gt;<br>&lt;app-custom-address formControlName=”address”&gt;&lt;/app-custom-address&gt;<br>&lt;/div&gt;</pre><p>Finally, we have also moved the functionality to select a profile picture to a separate component: <strong>ProfileImageSelectorComponent </strong>with selector: <strong>&lt;profile-image-selector&gt;. </strong>The <strong>formControlName </strong>attribute binds the <strong>&lt;profile-image-selector&gt;</strong> element to the <strong>FormControl profile </strong>in the FormGroup.</p><pre>&lt;div class=”form-group”&gt;<br>&lt;label class=”form-label”&gt;Profile&lt;/label&gt;<br>&lt;profile-image-selector formControlName=”profile” [imageList]=”imageList”&gt;&lt;/profile-image-selector&gt;<br>&lt;/div&gt;</pre><p>I. Lets begin with the <strong>CustomAddressComponent.</strong></p><p><strong>CustomAddressComponent Template</strong></p><pre>&lt;form [formGroup]=”addressForm” &gt;<br>&lt;div formArrayName=”addressLineList” class=”address-list-container”&gt;<br>&lt;div *ngFor=”let address of addressControls;let i=index;” [formGroupName]=”i” class=”address-container”&gt;<br><br>&lt;label class=”form-label”&gt;Street&lt;/label&gt;&lt;textarea formControlName=”street” class=”form-control” (blur)=”onTouched()”&gt;&lt;/textarea&gt;<br>&lt;label class=”form-label”&gt;Suite&lt;/label&gt;&lt;textarea formControlName=”suite” class=”form-control” (blur)=”onTouched()”&gt;&lt;/textarea&gt;<br>&lt;label class=”form-label”&gt;City&lt;/label&gt;&lt;textarea formControlName=”city” class=”form-control” (blur)=”onTouched()”&gt;&lt;/textarea&gt;<br>&lt;label class=”form-label”&gt;Zipcode&lt;/label&gt;&lt;textarea formControlName=”zipcode” class=”form-control” (blur)=”onTouched()”&gt;&lt;/textarea&gt;<br>&lt;button type=”button” class=”btn-close” aria-label=”Close” (click)=”removeAddress(i)”&gt;&lt;/button&gt;<br>&lt;/div&gt;<br><br>&lt;/div&gt;<br>&lt;button class=”btn btn-primary” (click)=”addAddress()”&gt;Add Address&lt;/button&gt;<br>&lt;/form&gt;</pre><p>We have a simple reactive form with <strong>root FormGroup addressForm. </strong>This FormGroup <strong>addressForm </strong>has a <strong>FormArray addressLineList</strong>. The <strong>FormArray addressLineList </strong>is an array of FormGroups, where each FormGroup describes a single address.</p><p>Every single address models the below structure.</p><pre>export interface AddressModel {<br>street: string;<br>suite: string;<br>city: string;<br>zipcode: string;<br>}</pre><p>From the <strong>UserModel </strong>interface and the FormGroup structure, it is clear that the value of the <strong>FormControl address </strong>in the <strong>ContactFormComponent </strong>is an array.Thus, we are mapping the <strong>FormControl address</strong> within the <strong>userForm </strong>inside the <strong>ContactFormComponent </strong>to the <strong>FormArray addressLineList</strong> within the <strong>addressForm </strong>inside the <strong>CustomAddressComponent </strong>using the ControlValueAccessor interface.</p><p>Below is the <strong>CustomAddressComponent Class, </strong>where we will check how the value and status of the <strong>FormControl address</strong> within the <strong>userForm </strong>and the value of the <strong>FormArray addressLineList</strong> within the <strong>addressForm </strong>are kept in sync. We have also ensured that if the <strong>addressForm </strong>in the <strong>CustomAddressComponent </strong>is invalid, then the <strong>parent userForm</strong> in the <strong>ContactFormComponent </strong>also remains invalid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d81c0f12fa934421c4e707d220a866fd/href">https://medium.com/media/d81c0f12fa934421c4e707d220a866fd/href</a></iframe><ol><li>Beginning with the <strong>providers </strong>within the @Component. We have registered the <strong>NG_VALUE_ACCESSOR</strong> and the <strong>NG_VALIDATORS</strong> injection tokens with the <strong>providers</strong>. The former provides a <strong>ControlValueAccessor </strong>for the <strong>FormControl address</strong> and latter is for providing additional synchronous validators for the <strong>FormControl address</strong>.</li></ol><pre>@Component({<br>selector: ‘app-custom-address’,<br>templateUrl: ‘./custom-address.component.html’,<br>styleUrls: [‘./custom-address.component.scss’],<br>providers:[{<br>provide:NG_VALUE_ACCESSOR,<br>useExisting:forwardRef(()=&gt;CustomAddressComponent),<br>multi:true<br>},{<br>provide:NG_VALIDATORS,<br>useExisting:forwardRef(()=&gt;CustomAddressComponent),<br>multi:true<br>}]<br>})</pre><p>2. The component implements the <strong>ControlValueAccessor </strong>and the <strong>Validator </strong>interfaces. The former requires 3 mandatory methods and 1 optional method to be implemented. The latter requires 1 mandatory and 1 optional method to be implemented.</p><pre>export class CustomAddressComponent implements ControlValueAccessor,Validator {<br><br>}</pre><p>3. We next move to the 4 methods of the <strong>ControlValueAccessor </strong>interface. The <strong>writeValue</strong>, <strong>registerOnChange</strong>,<strong>registerOnTouched </strong>methods are mandatory to be implemented. The <strong>setDisabledState </strong>method is optional.</p><pre> //ControlValueAccessor methods<br><br>  writeValue(addresses:AddressModel[]): void {<br>    console.log(&quot;writeValue&quot;);<br>    this.addressForm.setControl(&#39;addressLineList&#39;, this.fb.array(addresses.map(addr=&gt;this.loadSingleAddress(addr))),{emitEvent:false})<br>  }<br>  registerOnChange(fn: (value:AddressModel[])=&gt;void): void {<br>    this.addressForm.valueChanges.pipe(takeUntil(this.destroy$)).subscribe((address:{addressLineList:AddressModel[]})=&gt;{<br>      console.log(address.addressLineList)<br>      console.log(&quot;registerOnChange: callback function called&quot;)<br>      fn(address.addressLineList)<br>    });<br>  }<br>  registerOnTouched(fn: ()=&gt;void): void {<br>    this.onTouched=()=&gt;{<br>      console.log(&quot;registerOnTouched: callback function called&quot;)<br>      fn();<br>    }<br>  }<br><br>  setDisabledState(isDisabled: boolean): void { <br>    //optional method. Can be removed if no requirement to implement<br>  }</pre><p>The <strong>writeValue()</strong> updates the value of the <strong>FormArray addressLineList </strong>in the <strong>addressForm </strong>within the <strong>CustomAddressComponent </strong>with the latest value of the <strong>FormControl address </strong>in the <strong>userForm </strong>within the parent <strong>ContactFormComponent. So the changes are propagating from the parent userForm to the child addressForm.</strong></p><p>The <strong>registerOnChange </strong>method receives a callback function as argument. Within the <strong>registerOnChange(), </strong>we are listening to changes in the value of the <strong>addressForm. </strong>Note that we are creating a new subscription, everytime the <strong>registerOnChange()</strong> is called. Hence it is necessary to clear the subscriptions when the component is destroyed(hence the usage of <strong>takeUntil </strong>rxjs).</p><pre>this.addressForm.valueChanges.pipe(takeUntil(this.destroy$)).subscribe((address:{addressLineList:AddressModel[]})=&gt;{<br>console.log(“registerOnChange: callback function called”)<br>fn(address.addressLineList)<br>});</pre><p>For every change in the <strong>addressForm</strong>, we are calling the callback function, passing the latest value of the <strong>FormArray addressLineList </strong>in the <strong>addressForm </strong>within the <strong>CustomAddressComponent </strong>as argument. Calling the callback function updates the value of the <strong>FormControl address </strong>in the <strong>userForm </strong>within the parent <strong>ContactFormComponent </strong>with the latest value. <strong>So the changes are propagating from the child addressForm to the parent userForm.</strong></p><p>The<strong> registerOnTouched() </strong>also accepts a callback function as argument. We are storing the callback function within a property <strong>onTouched</strong>. We will call the <strong>onTouched()</strong> from the template, everytime we want to mark the <strong>FormControl address</strong> within the <strong>userForm </strong>inside the parent <strong>ContactFormComponent</strong> as touched.</p><pre>this.onTouched=()=&gt;{<br>console.log(“registerOnTouched: callback function called”)<br>fn();<br>}</pre><p>The <strong>onTouched()</strong> is called everytime the <strong>blur </strong>event triggers on any <strong>FormControl </strong>within the <strong>addressForm </strong>as highlighted below. So it means that when any FormControl has been touched and when the focus is lost, the <strong>blur </strong>event has triggered. Thus we need to mark the <strong>address FormControl</strong> within the <strong>userForm </strong>inside the <strong>ContactFormComponent </strong>as touched, whenever any FormControl within the <strong>addressForm </strong>is touched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vW5K8eQhMYBnzxAieVTE4g.png" /></figure><p>In the below demonstration, the <strong>touched </strong>status of the<strong> FormControl address</strong> in the<strong> parent userForm</strong> remains false. When I add a new address using the “Add Address” button too ,it remains false. When I started typing in the <strong>Street </strong>field and then moved to the <strong>Suite </strong>field, a blur event triggered on the Street field and marks the <strong>FormControl address</strong> as touched.</p><p>We are not implementing anything in the <strong>setDisabledState() </strong>in this example. But you can enable/disable the complete <strong>addressForm </strong>or a particular control within the form inside the <strong>CustomAddressComponent, </strong>by enabling/disabling the <strong>FormControl address</strong> in the parent <strong>ContactFormComponent</strong>. I have already demonstrated this in Part-I of this series.</p><p>4. Lets now move to 2 methods under the <strong>Validator </strong>interface. We have not implemented the <strong>registerOnValidatorChange </strong>because the current example has no use-case to show its implementation. We will take it up in another story. Since its not a mandatory method, you can remove it, if you have no need to implement it.</p><pre>registerOnValidatorChange(fn: () =&gt; void): void {}<br><br>validate(control: AbstractControl&lt;any, any&gt;): ValidationErrors | null {<br>return this.addressForm.valid ? null : {&quot;error&quot;:true}<br>}</pre><p>The <strong>validate() </strong>takes the <strong>FormControl address</strong> in the <strong>parent userForm </strong>as argument. Here we are checking if the <strong>addressForm </strong>is valid. If yes, it returns null. If the <strong>addressForm </strong>is not valid, then the<strong> parent userForm</strong> will also be invalid.</p><p>Consider the below demonstration, where I am updating the first user’s contact. I have filled up all mandatory fields and the “Update User” button is enabled. When I add a new address using the “Add Address” button, the <strong>addressForm </strong>is invalid because all the fields of the new address are blank. Hence the <strong>parent userFrom </strong>is invalid and the “Update User” button is disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*f3RY8AC_9t0Ix8We9sVBog.gif" /></figure><p>The <strong>CustomPhoneComponent </strong>is implemented the same way as the <strong>CustomAddressComponent</strong>. Hence we will not discuss it here.</p><p>II. Moving to the <strong>ProfileImageSelectorComponent</strong></p><p>As you can see in the demo below, the component, basically displays a list of images. We can click on the image to select it as the profile picture for the user. If a profile picture already exists for a user, clicking on the selected picture, allows you to reset to a new profile picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*p_RIsSoeI-iRC8tPmfShmQ.gif" /></figure><p><strong>ProfileImageSelectorComponent Template</strong></p><p>If there is no profile picture currently available for the user, determined by the <strong>selectedImage </strong>property, then we are showing the list of profile pictures, the user can select from. If no profile image currently exists, clicking on a picture, calls <strong>selectImage()</strong> to set the image for the particular user. If a profile image already exists for the user, we are showing the selected image only. Clicking on the selected image, resets the current selection via <strong>resetSelection()</strong> and allows the user to reselect his profile image.</p><pre>&lt;ul *ngIf=”!selectedImage.length”&gt;<br>&lt;li *ngFor=”let image of imageList” (click)=”selectImage(image)” &gt;<br>&lt;img class=”img-fluid” [src]=”’assets/images/superheroes/’+image” [alt]=”’assets/images/superheroes/’+image”&gt;<br>&lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;img class=”selected img-fluid” *ngIf=”selectedImage.length” [src]=”’assets/images/superheroes/’+ selectedImage” (click)=”resetSelection()”&gt;</pre><p><strong>ProfileImageSelectorComponent Class.</strong></p><p>The component, also implements the <strong>ControlValueAccessor </strong>interface. It has not implemented the <strong>Validator </strong>interface, unlike the <strong>CustomAddressComponent </strong>which we just discussed. This is because the validations are already in place for the <strong>profile FormControl</strong> in the parent <strong>ContactFormComponent </strong>and there are no additional validations required here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a11e9e276a44833a86adfffffb579a97/href">https://medium.com/media/a11e9e276a44833a86adfffffb579a97/href</a></iframe><ol><li>The component accepts a list of image names as @Input from the parent <strong>ContactFormComponent</strong>.</li></ol><pre>@Input(‘imageList’)imageList:string[]=[];</pre><p>2. The <strong>selectedImage </strong>property stores the name of the selected profile image for the user. By default, its an empty string if no there is no selected profile image.</p><pre>selectedImage:string=””;</pre><p>3. When the user clicks on one of the images, the <strong>selectImage()</strong> is called, passing the name of the image as argument. The <strong>selectedImage </strong>property is set to the image name. When I click on the currently selected profile image, we are calling <strong>resetSelection() </strong>and resetting the value of the <strong>selectedImage </strong>property to an empty string.</p><pre>selectImage(image:string){<br>this.selectedImage=image;<br>this.onChange(image);<br>this.onTouched();<br>}<br><br>resetSelection(){<br>   this.selectedImage=&quot;&quot;;<br>   this.onChange(this.selectedImage);<br>   this.onTouched();<br>  }</pre><p>In both <strong>selectImage()</strong> and <strong>resetSelection()</strong>, the<strong> onChange()</strong> and the <strong>onTouched()</strong> are being called. How are the <strong>onChange()</strong> and <strong>onTouched()</strong> defined ?</p><pre>onTouched!:()=&gt;void;<br>onChange!:(value:string)=&gt;void;</pre><p>Within the <strong>registerOnChange</strong>, method, the <strong>onChange </strong>property is defined as a function which accepts the image name as argument. Within the <strong>onChange </strong>function definition, we are calling the callback function, passing the image name as argument. Calling the callback function ensures that the value of the <strong>FormControl profile</strong> within the<strong> </strong>parent <strong>userForm</strong>, inside the <strong>ContactFormComponent</strong>, also is updated to the latest selected image name.</p><pre>registerOnChange(fn:(value:string)=&gt;void): void {<br><br>this.onChange=(image:string)=&gt;{<br>console.log(“registerOnChange callback function called”)<br>fn(image)<br>}<br>}</pre><p>Within the <strong>registerOnTouched()</strong>, we have defined the <strong>onTouched </strong>property as a function, which simply calls the callback function. The purpose of calling the<strong> onTouched()</strong> is to ensure that when an image is selected/re-selected, the <strong>FormControl profile</strong> in the parent <strong>userform </strong>in the <strong>ContactFormContact </strong>is marked as touched.</p><pre>registerOnTouched(fn: ()=&gt;void): void {<br><br>this.onTouched=()=&gt;{<br>console.log(“registerOnTouched callback function called”)<br>fn();<br>}<br>}</pre><p>In the below demonstration, please observe how the <strong>touched </strong>and <strong>valid </strong>status of the <strong>FormControl profile</strong> changes when an image is selected for a user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SfpPkAWyZ9673pXVTLB6Ug.gif" /></figure><p>Below is the git link to the complete example.</p><p><a href="https://github.com/ramyabala221190/AngularControlValueAccessor">GitHub - ramyabala221190/AngularControlValueAccessor: A simple project to demonstrate different scenarios for using ControlValueAccessor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=845158546696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: This is how I understood using the ControlValueAccessor interface — Part-I]]></title>
            <link>https://ramya-bala221190.medium.com/angular-this-is-how-i-understood-using-the-controlvalueaccessor-interface-part-i-49999c6c112a?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/49999c6c112a</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ngvalidators]]></category>
            <category><![CDATA[controlvalueaccessor]]></category>
            <category><![CDATA[validator]]></category>
            <category><![CDATA[ngvalueaccessor]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 12:17:20 GMT</pubDate>
            <atom:updated>2025-04-24T13:53:23.522Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular: This is how I understood using the ControlValueAccessor interface — Part-I</h3><p>The angular documentation defines the <strong>ControlValueAccessor </strong>interface as below:</p><p><strong>“Defines an interface that acts as a bridge between the Angular forms API and a native element in the DOM.”</strong></p><p>This basically means that the <strong>ControlValueAccessor </strong>interface helps to <strong>create a link between a DOM element and an angular form, containing that element.</strong> The DOM element could even be a custom component, which contains some reusable functionality to be used in multiple forms or multiple times in the same form.</p><p><strong>Example use-case:</strong> Consider a scenario in your angular app, where you require the user to enter multiple addresses or phone numbers in a section of the form and you have a similar requirement in another form as well. <strong>Why not move this capability to a separate component with selector say, &lt;add-multiple-controls-dynamic&gt; to make it reusable and somehow link this component selector to the form ? ControlValueAccessor </strong>interface makes this possible.</p><p>The example I gave is a bit complex and was just for you to get an idea how useful this interface can be. We will implement this example in Part-II of this story(link below).</p><p><a href="https://ramya-bala221190.medium.com/angular-this-is-how-i-understood-using-the-controlvalueaccessor-interface-part-ii-845158546696">Angular: This is how I understood using the ControlValueAccessor interface — Part-II</a></p><p><strong>How does ControlValueAccessor interface work ?</strong></p><p>In this story, we will take a very simple example of a shopping cart with multiple products.</p><p>Below is a short demo of what we are trying to achieve.</p><p>=&gt;We have 5 products in the cart for purchase in an application.We have displayed the<strong> name, description,price and quantity </strong>of each product. A product may or may not currently have stock.</p><p>=&gt;The quantity of a product can be increased/decreased using the +/- button.</p><p>=&gt;You need to have at least 1 quantity of each product in the cart.</p><p>=&gt;If the product has no stock, the +/- buttons are disabled.</p><p>=&gt;On clicking on the “Checkout” button, we are printing the reactive form value in the console. <strong>(Normally, no application will allow to checkout a cart with one of the products having no stock. This is simply an example to demonstrate different aspects of ControlValueAccessor interface.).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*S3fNqZ83G_b0yZnHtWBHlQ.gif" /></figure><p>I. Lets now look at the <strong>ShoppingCartComponent </strong>template, which is exactly what we see in the demo and the screenshot above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c21e28f26f395fdc9add27a02e567de/href">https://medium.com/media/2c21e28f26f395fdc9add27a02e567de/href</a></iframe><p>Its a very basic reactive form with root <strong>FormGroup</strong>: <strong>cartForm. </strong>This root Form Group <strong>cartForm </strong>has a <strong>FormArray</strong>: <strong>products</strong>. This <strong>FormArray products </strong>is an array of FormGroups, where each FormGroup describes a product. Below is the screenshot which describes the structure of the <strong>cartForm FormGroup</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vBb6ekN5cyE1OIjtP12BQ.png" /></figure><p>The increment/decrement functionality for the product quantity is moved to a separate component: <strong>QuantityControlComponent </strong>with selector<strong> &lt;app-quantity-control&gt;. </strong>The <strong>formControlName </strong>attribute binds the <strong>&lt;app-quantity-control&gt;</strong> element to the <strong>FormControl quantity</strong> in the FormGroup.</p><pre>&lt;app-quantity-control formControlName=”quantity”&gt;&lt;/app-quantity-control&gt;</pre><p>II. Moving to the <strong>ShoppingCartComponent </strong>class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c68614f765d15113f350f4d6db84c1ae/href">https://medium.com/media/c68614f765d15113f350f4d6db84c1ae/href</a></iframe><p>Let me discuss just the 2 main points here.</p><ol><li>This is the structure of each <strong>FormGroup </strong>within the <strong>products FormArray</strong>. We are not going into detail on how the FormArray products is formed. This is out of the scope of the story. But it is essential to understand the structure of each FormGroup within the <strong>products FormArray</strong>.</li></ol><pre>createProductGroup(product:Product){<br>return new FormGroup({<br>id:new FormControl(product.id),<br>name: new FormControl(product.title),<br>price:new FormControl(product.price),<br>description:new FormControl(product.description),<br>brand: new FormControl(product.brand),<br>rating: new FormControl(product.rating),<br>stock:new FormControl(product.stock),<br>quantity:new FormControl({value:product.quantity,disabled:product.stock == 0})<br>})<br>}</pre><p>Observe the <strong>quantity FormControl</strong>. If the stock for a product is 0, then <strong>quantity FormControl</strong> is disabled.</p><p>2. On clicking on the <strong>“Checkout”</strong> button, the <strong>submit()</strong> is called, where we are printing the value of the <strong>cartForm FormGroup </strong>and we are also printing all the 5 FormGroups within the <strong>products FormArray</strong>.</p><pre>submit(){<br>console.log(this.cartForm.value);<br>console.log((&lt;FormArray&gt;this.cartForm.get(‘products’)).controls);<br>}</pre><p><strong>III. QuantityControlComponent</strong></p><p>Lets now discuss the custom component we have created to implement the increment/decrement functionality of each product’s quantity.</p><p><strong>QuantityControlComponent </strong>template.</p><pre>&lt;div class=&quot;qty-control-container&quot;&gt;<br>    &lt;button [disabled]=&quot;disableAction&quot; class=&quot;btn btn-primary&quot; type=&quot;button&quot; (click)=&quot;addQuantity()&quot;&gt;+&lt;/button&gt;<br>    &lt;span&gt;{{quantity}}&lt;/span&gt;<br>    &lt;button [disabled]=&quot;disableAction&quot; class=&quot;btn btn-warning&quot; type=&quot;button&quot; (click)=&quot;removeQuantity()&quot;&gt;-&lt;/button&gt;<br>&lt;/div&gt;</pre><p>We have created a property <strong>quantity, </strong>which stores the quantity of a product in the cart. We have +/- buttons to increment/decrement the quantity of a product.</p><p>We will now see how the <strong>ControlValueAccessor </strong>interface helps us to the keep the value and status of the <strong>FormControl quantity</strong> within the <strong>cartForm </strong>inside the <strong>ShoppingCartComponent</strong> in sync with<strong> </strong>the <strong>property quantity</strong> within the <strong>QuantityControlComponent.</strong></p><p>We are also ensuring that that the value of the <strong>property quantity</strong> for every product(with stock) must be atleast 1. If it is set to 0, then the parent <strong>cartForm </strong>will no longer will be valid and the “Checkout” button will be disabled.</p><p>Lets now check the <strong>QuantityControlComponent </strong>class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1733fb0a8fb800a9686ba02076834690/href">https://medium.com/media/1733fb0a8fb800a9686ba02076834690/href</a></iframe><ol><li>The first step is to register the <strong>NG_VALUE_ACCESSOR</strong> injection token to provide a <strong>ControlValueAccessor </strong>for form controls. We are also registering the <strong>NG_VALIDATORS</strong> injection token, to provide additional synchronous validators for the <strong>FormControl quantity</strong> within the<strong> cartForm </strong>in the parent <strong>ShoppingCartComponent</strong>.</li></ol><pre>@Component({<br>  selector: &#39;app-quantity-control&#39;,<br>  templateUrl: &#39;./quantity-control.component.html&#39;,<br>  styleUrls: [&#39;./quantity-control.component.scss&#39;],<br>  providers:[{<br>    provide:NG_VALUE_ACCESSOR,<br>    useExisting:forwardRef(()=&gt;QuantityControlComponent),<br>    multi:true<br>  },<br>{<br>  provide:NG_VALIDATORS,<br>  useExisting:forwardRef(()=&gt;QuantityControlComponent),<br>  multi:true<br>}]<br>})</pre><p>2. The <strong>QuantityControlComponent </strong>class implements the <strong>ControlValueAccessor </strong>interface, which is defined as below.</p><pre>interface ControlValueAccessor { <br>writeValue(obj: any): void; <br>registerOnChange(fn: any): void; <br>registerOnTouched(fn: any): void; <br>optional setDisabledState(isDisabled: boolean): void;<br>}</pre><p>It also implements the <strong>Validator </strong>interface, which is defined as below.</p><pre>interface Validator { <br>validate(control: AbstractControl&lt;any, any&gt;): ValidationErrors | null; <br>optional registerOnValidatorChange(fn: () =&gt; void): void;<br>}</pre><p>Lets now understand how these methods work using the <strong>QuantityControlComponent </strong>as reference.</p><p>3. As discussed earlier, we have created a property <strong>quantity</strong>, whose default value is 0. If you recall, this is the same property <strong>quantity </strong>which we are displaying in the template.</p><pre>quantity:number=0;</pre><p>4. The <strong>writeValue()</strong> is called when the value of the <strong>FormControl quantity </strong>for any FormGroup in the parent <strong>ShoppingCartComponent </strong>changes. The argument passed to the <strong>writeValue()</strong> is the latest value of the <strong>FormControl quantity</strong> in the parent component. In this method, we are setting the value of the<strong> property quantity</strong> in the <strong>QuantityControlComponent </strong>to the latest value of the <strong>FormControl quantity </strong>in the parent component.</p><pre>writeValue(qty:number): void {<br>    console.log(&quot;writeValue called&quot;);<br>    this.quantity=qty;<br>  }</pre><p>5. We have declared a property <strong>onChange </strong>which is a function that accepts a number as argument and returns nothing. Lets see how this will be used inside the <strong>registerOnChange()</strong>.</p><pre> private onChange!:(value:number)=&gt;void;</pre><p>The <strong>registerOnChange </strong>method can be slightly tricky to understand.</p><pre>registerOnChange(fn: (value:number)=&gt;void): void {<br>    this.onChange=(qty:number)=&gt;{<br>      console.log(&quot;registerOnChange: callback function called&quot;)<br>      fn(qty);<br>    }<br>  }</pre><p>=&gt;The <strong>registerOnChange </strong>method receives a callback function as argument.</p><p>=&gt;This callback function should be called everytime the value of the <strong>property quantity</strong> in the child <strong>QuantityControlComponent </strong>changes. This change needs to be propagated to the<strong> FormControl quantity</strong> in the parent <strong>ShoppingCartComponent</strong>.</p><p>=&gt; The callback function accepts the latest value of the <strong>property quantity</strong> in the child <strong>QuantityControlComponent </strong>as argument.</p><p>=&gt; What is the purpose of the <strong>registerOnChange </strong>method ? Its purpose is to save the callback function inside a private component property i.e <strong>onChange </strong>in this example, so that this callback function(stored in <strong>onChange </strong>property) can be called by the child <strong>QuantityControlComponent </strong>everytime the value of the <strong>property quantity </strong>changes.</p><p>=&gt; The value of the <strong>property quantity</strong> in the <strong>QuantityControlComponent </strong>changes everytime we click on the +/- buttons. When we click on the +/- buttons, we call the <strong>addQuantity()</strong> and <strong>removeQuantity()</strong> respectively.</p><pre>addQuantity(){<br>    this.quantity++;<br>    this.onChange(this.quantity);<br>    this.onTouched();<br>  }<br><br>  removeQuantity(){<br>    if(this.quantity &gt; 0){<br>    this.quantity--;<br>    this.onChange(this.quantity);<br>    }<br>    this.onTouched();<br>  }</pre><p>In these 2 methods, we have incremented/decremented the value of the property <strong>quantity</strong>. In order to propagate the latest changes in value of the <strong>property quantity </strong>in the <strong>QuantityControlComponent </strong>to the <strong>FormControl quantity</strong> in the parent <strong>ShoppingCartComponent</strong>, we need to call the callback function stored within the <strong>onChange </strong>property. We are calling the<strong> onChange()</strong> passing the latest value of the <strong>property quantity</strong> as argument.</p><p>If you observe, we have also called <strong>onTouched()</strong> whenever we are updating the value of the <strong>property quantity</strong> in the <strong>QuantityControlComponent</strong>. Lets understand, how the <strong>onTouched()</strong> function is defined.</p><p>6. We have declared a property <strong>onTouched, </strong>which is a function that returns nothing. Lets see how this will be used inside the <strong>registerOnTouched()</strong>.</p><pre>  private onTouched!:()=&gt;void;</pre><p>The<strong> registerOnTouched()</strong> is very similar to the <strong>registerOnChange().</strong></p><pre>registerOnTouched(fn: ()=&gt;void): void {<br>    this.onTouched=()=&gt;{<br>      console.log(&quot;registerOnTouched: callback function called&quot;)<br>      fn();<br>    }<br>  }</pre><p>=&gt;The<strong> registerOnTouched() </strong>accepts a callback function as argument. This callback function should be called everytime, the <strong>FormControl quantity</strong> in the parent <strong>ShoppingCartComponent </strong>needs to be marked as <strong>touched</strong>.</p><p>=&gt; The callback function doesnt take any arguments.</p><p>=&gt;What is the purpose of the <strong>registerOnTouched </strong>method ? Its purpose is to save the callback function inside a private component property i.e <strong>onTouched </strong>in this example, so that this callback function(stored in <strong>onTouched </strong>property) can be called everytime the <strong>FormControl quantity</strong> in the parent <strong>ShoppingCartComponent </strong>needs to be marked as <strong>touched</strong>.</p><p>=&gt;We are calling the <strong>onTouched()</strong>, everytime the <strong>addQuantity()</strong> <strong>/removeQuantity()</strong> is called. This means <strong>onTouched() </strong>is called whenever there is a change in the value of the <strong>property quantity</strong> in the <strong>QuantityControlComponent</strong>. This ensures that the the <strong>FormControl quantity</strong> in the parent <strong>ShoppingCartComponent </strong>is marked as <strong>touched.</strong></p><p>7. Finally, we come to the optional<strong> setDisabledState()</strong>.</p><p>We have created a boolean property <strong>disableAction, </strong>whose default is false. <strong>The purpose of this property is to disable the +/- buttons of those products whose current stock is 0.</strong></p><pre>disableAction:boolean=false;</pre><p>This is how <strong>disableAction </strong>property is used in the template.</p><pre>&lt;div class=”qty-control-container”&gt;<br>&lt;button [disabled]=”disableAction” class=”btn btn-primary” type=”button” (click)=”addQuantity()”&gt;+&lt;/button&gt;<br>&lt;span&gt;{{quantity}}&lt;/span&gt;<br>&lt;button [disabled]=”disableAction” class=”btn btn-warning” type=”button” (click)=”removeQuantity()”&gt;-&lt;/button&gt;<br>&lt;/div&gt;</pre><p>The <strong>setDisabledState()</strong> accepts a boolean argument, which is nothing but the<strong> disabled state</strong> of the <strong>FormControl quantity </strong>in the <strong>ShoppingCartComponent</strong>. We are setting property <strong>disableAction </strong>to this boolean value so that the +/- buttons are disabled in the <strong>QuantityControlComponent </strong>for those products, whose <strong>FormControl quantity </strong>is disabled. The <strong>FormControl quantity</strong> is disabled only if the product stock is 0.</p><pre>setDisabledState(isDisabled:boolean){<br>this.disableAction=isDisabled;<br>}</pre><p>The purpose of the <strong>setDisabledState() </strong>is to communicate the disabled status of the <strong>FormControl quantity </strong>in the parent component to the child component <strong>QuantityControlComponent</strong>.</p><p>8. We have not implemented the <strong>registerOnValidatorChange() </strong>because there is no use case in this example to explain how this method works. We can take it up in another story. The <strong>validate()</strong>, accepts the <strong>FormControl quantity </strong>from the parent <strong>cartForm </strong>as argument. If the property quantity in the <strong>QuantityControlComponent </strong>is set to 0, we are returning a validation error to make the <strong>cartForm invalid </strong>and disable the “Checkout” button , else we are simply returning null.</p><pre>validate(control: AbstractControl&lt;any, any&gt;): ValidationErrors | null {<br>return this.quantity == 0 ? {“errors”:”Product quantity is 0&quot;}:null;<br>}<br><br>registerOnValidatorChange?(fn: () =&gt; void): void {<br>//optional method. if not implemented, can be removed<br>}</pre><p><strong>IV. Demonstration</strong></p><p>Lets now check how these methods defined within the interface execute when we interact with the application.</p><ol><li>When the application loads for the first time, observe that the <strong>writeValue()</strong> is called 5 times for the 5 products. The <strong>writeValue()</strong> communicates the latest value of the<strong> FormControl quantity</strong> in each of the 5 FormGroups(i.e 5 products) in the <strong>ShoppingCartComponent </strong>to the corresponding <strong>property quantity</strong> in the <strong>QuantityControlComponent</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alt9P888r1S3xb6exsXSnQ.png" /></figure><p>2. Lets now increase the quantity of the first product and decrement the quantity of the 2nd product.</p><p>In the demo below, when I increase the quantity of the first product, the callback functions: <strong>onChange()</strong> and <strong>onTouched()</strong> are called. These 2 methods are again called, when I decrease the quantity of the 2nd product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*3f3zWXZBKqpHZmjmm9NXLA.gif" /></figure><p>At this stage, we need to verify the below 3 points to check if the <strong>ControlValueAccessor </strong>and <strong>Validator </strong>interfaces have done their job as expected:</p><p>=&gt; Has the value of <strong>FormControl quantity </strong>for the first product updated from 2 to 3 and for the 2nd product from 1 to 0 ?</p><p>=&gt;Has the <strong>FormControl quantity</strong> for the first 2 FormGroups, been marked as <strong>touched </strong>?</p><p>=&gt; How has the <strong>validity </strong>of the <strong>FormControl quantity</strong> changed for the 2 products ?</p><p>In the below screenshot, the <strong>touched </strong>status of the <strong>FormControl quantity</strong> in the first 2 FormGroups(or products) has been set to true. The <strong>FormControl quantity </strong>in the first FormGroup/product remains <strong>valid </strong>but since the value of the <strong>FormControl quantity</strong> in the 2nd FormGroup/product is 0, it is <strong>invalid </strong>as highlighted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sq6Ih_YpKsiXIRVhjW4rZQ.png" /></figure><p>Thus the <strong>cartForm </strong>is invalid and the <strong>“Checkout”</strong> button is disabled as shown in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoo8KHJrCVRE2WpHCTXXew.png" /></figure><p>3. The <strong>setDisabledState()</strong> has worked as expected. This has been proved by the disabled +/- buttons for the last product with no stock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiZlkSK6HaHBu8uqRHL6HQ.png" /></figure><p>4. Lets now make the <strong>cartForm </strong>valid to enable the “Checkout” button by increasing the value of the <strong>FormControl quantity</strong> for the 2nd FormGroup/product from 0 to 2.</p><p>When we click on the <strong>“Checkout”</strong> button, we are printing the value of the <strong>root FormGroup</strong> <strong>cartForm </strong>and also printing all the <strong>5 FormGroups </strong>inside the <strong>products FormArray</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yxg7IM7VcFyuhPzjCGcE3A.gif" /></figure><p>The value of the <strong>FormControl quantity</strong> in the first FormGroup matches the value of <strong>property quantity, </strong>as highlighted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yg5rvpytCKROp2qmG5keVA.png" /></figure><p>Similarly, the value of the<strong> FormControl quantity</strong> in the 2nd FormGroup matches the value of the <strong>property quantity</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrPKkriU17bNWH3OjUQjQw.png" /></figure><p>Below is the git link to the complete example.</p><p><a href="https://github.com/ramyabala221190/AngularControlValueAccessor">GitHub - ramyabala221190/AngularControlValueAccessor: A simple project to demonstrate different scenarios for using ControlValueAccessor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49999c6c112a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular for Beginners: Combining different sets of related data for display using RXJS]]></title>
            <link>https://javascript.plainenglish.io/angular-for-beginners-combining-different-sets-of-related-data-for-display-using-rxjs-b2392edc713b?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2392edc713b</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[forkjoin]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 15:25:10 GMT</pubDate>
            <atom:updated>2025-04-14T05:02:04.480Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, sharing a very simple scenario found in most applications, where you have 2 different but related sets of data, that need to be fetched from different API’s, and has to be displayed together. Displaying together does not mean just dump the 2 data sets into the template. It means that you need to display it such that, relation between the 2 sets of data is clearly visible.</p><p>Consider an example, where you have 10 users, whose basic details you need to display in a table. This data is available from a dummy API: <a href="https://jsonplaceholder.typicode.com/todos">https://jsonplaceholder.typicode.com/</a>users. Now, I also want to display the Todos created by each user in the same table. The details of the Todos created by each user is available from the 2nd dummy API:<a href="https://jsonplaceholder.typicode.com/todos">https://jsonplaceholder.typicode.com/todos</a>.</p><p>We have modelled each user detail using the <strong>UserModel </strong>interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4ozAvrGxpfAp-EWEGvaNA.png" /></figure><pre>export interface UserModel {<br>  id: number,<br>  name: string,<br>  username: string,<br>  email: string,<br>  address: AddressModel,<br>  phone: string,<br>  website: string,<br>  company: CompanyModel<br>}</pre><p>We have modelled each ToDo item created by a user using the <strong>ToDoModel </strong>interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezrnnv5S_2lATBHxZYd7fg.png" /></figure><pre>export interface ToDoModel {<br>userId: number,<br>id: number,<br>title: string,<br>completed: boolean<br>}</pre><p>If you observe,<strong> the link between the 2 sets of data is the the id of the user.</strong> We will display few details of the user: <strong>id and name field</strong> in the <strong>UserModel. </strong>We will use the <strong>userId field</strong> in the <strong>ToDoModel </strong>to extract all the ToDo items created by each user.</p><p>Below is a screenshot of what we are trying to achieve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHyrfAjpWAuFBP0v5Xun0w.png" /></figure><p><strong>DataService</strong></p><pre>export class DataService{<br><br>constructor(private http:HttpClient){}<br><br>getUsers():Observable&lt;UserModel[]&gt;{<br>return this.http.get &lt; UserModel[]&gt;(‘https://jsonplaceholder.typicode.com/users&#39;)<br>}<br><br>getToDos(): Observable&lt;ToDoModel[]&gt;{<br>return this.http.get&lt;ToDoModel[]&gt;(‘https://jsonplaceholder.typicode.com/todos&#39;)<br>}<br><br>}</pre><p><strong>AppComponent Class</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/817a076e7ca46f00d4cd6ff4ebbae271/href">https://medium.com/media/817a076e7ca46f00d4cd6ff4ebbae271/href</a></iframe><ol><li>Since, we want to display all the users data and each user’s corresponding ToDo details, we will use the <strong>forkJoin </strong>RXJS operator to call the 2 dummy API’s in parallel within the <strong>ngOnInit </strong>lifecycle hook.</li></ol><pre>this.data$ = forkJoin([<br>this.service.getUsers().pipe(this.handleError().bind(this)),<br>this.service.getToDos().pipe(this.handleError().bind(this)),<br>])</pre><p>2. It is essential to ensure that when using, <strong>forkJoin</strong>, any possible errors corresponding to the API’s must be handled gracefully. We have created the <strong>handleError()</strong> for that.</p><pre>handleError() {<br>let that = this;<br>return function (observable: Observable&lt;any&gt;) {<br>return observable.pipe(<br>catchError((err: HttpErrorResponse) =&gt; {<br>that.errorSub$.next(err.message);<br>return of(null);<br>}),<br>takeUntil(that.destroy$)<br>);<br>};<br>}</pre><p>3. Observe that within the <strong>map operator</strong>, we have used the responses of the 2 API’s to construct a new array of objects, where each object models a new <strong>UserToDoModel </strong>interface.</p><pre>map(([users, todos]) =&gt; {<br>let result: UserToDoModel[] = users.map((user: UserModel) =&gt; {<br>return {<br>userDetail: user,<br>todos: todos.filter((x: ToDoModel) =&gt; x.userId == user.id),<br>};<br>});<br>return result;<br>}),</pre><p>Below is the <strong>UserToDoModel </strong>interface.</p><pre>export interface UserToDoModel {<br>userDetail: UserModel;<br>todos: ToDoModel[];<br>}</pre><p>Thus we have successfully been able to link each user with the list of ToDo items they have created.</p><p>4. Thus <strong>data$</strong> is an observable which emits an array of objects, where each object models the <strong>UserToDoModel </strong>interface. We will be subscribing to the <strong>data$</strong> observable in the template using <strong>async pipe </strong>and display the user details and each user’s ToDo items.</p><p><strong>AppComponent Template</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/660cd1af1659825962486e58c12144a7/href">https://medium.com/media/660cd1af1659825962486e58c12144a7/href</a></iframe><p>Below is the link to the working example.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-dfb3ktpm%3Fembed%3D1%26file%3Dsrc%252Fmain.ts&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-dfb3ktpm%3Ffile%3Dsrc%252Fmain.ts&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-dfb3ktpm%2Fc11116c2d1bf7f2befeebb52d78fe052&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3898af85254fa96a42f043f5cb74df66/href">https://medium.com/media/3898af85254fa96a42f043f5cb74df66/href</a></iframe><h3>Thank you for being a part of the community</h3><p><em>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://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2392edc713b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angular-for-beginners-combining-different-sets-of-related-data-for-display-using-rxjs-b2392edc713b">Angular for Beginners: Combining different sets of related data for display using RXJS</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[How can you approach a complex table with rowspan and colspan in Angular ?]]></title>
            <link>https://javascript.plainenglish.io/how-can-you-approach-a-complex-table-with-rowspan-and-colspan-in-angular-635e9169234a?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/635e9169234a</guid>
            <category><![CDATA[row-span]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[colspan]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Sat, 08 Feb 2025 12:23:22 GMT</pubDate>
            <atom:updated>2025-02-10T02:44:33.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>How can you approach a complex table with rowspan and colspan in Angular ?</h3><p>Designing tables with <strong>rowspan</strong> and <strong>colspan</strong> can get really crazy at times, if you are a beginner. The first time, I faced such a scenario, I wasted so many hours directly trying to design it with Angular templates and components. This is because it can be tricky to decide how many &lt;tr&gt; elements are needed, how much should each &lt;td&gt; or &lt;th&gt; span and so many more aspects, especially when doing it along with angular structural directives like <strong>*ngFor</strong>.</p><p>With experience, I would like to share few steps before you begin designing such tables:</p><ol><li>The first step should be to make a skeleton of the table on paper or in a word document. If a mock is already provided to you, then you can skip this step. A simple skeleton of how the headers should look like and how a single row in the table should look like.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*6IB5Fw3W0LF3HHRSB2RJ3A.png" /></figure><p>2. The second step should be to <strong>create a new html file in some folder,</strong> separate from your angular project. Now you can construct the table design for 1 or 2 rows max using some simple dummy data(or the actual data itself if its simple enough) in this new html file.</p><p>3. Once you are able to replicate the table using a plain html file, observe the pattern in the &lt;tr&gt;,&lt;th&gt; and &lt;td&gt; elements. This is required to decide if the data needs to be modified to fit this pattern. Translate that into a table in the angular template.</p><p><strong>Let me share a real example of these 3 steps can be applied.</strong></p><p>Below is the dummy data of 11 athletes, the country they hail from, the medals they have won and the year in which the athlete won the medals. If you observe the data closely, we have multiple records for a single athlete. <strong>In those multiple records for a single athlete, the</strong> <strong>fields: id, name and country are always the same. The changes can be seen only in the gold, silver, bronze and year fields.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/297c79bd345f682edba7afc50be1bef8/href">https://medium.com/media/297c79bd345f682edba7afc50be1bef8/href</a></iframe><p><strong>Step-I</strong></p><p>Below is a mock for 1 athlete. We need to do something similar for all 11 athletes. <strong>We are displaying the medals won by a single athlete in all years in a single row. Thus for 11 athletes, we will have 11 rows. If you observe, each row in turn as multiple sub-rows. Each sub-row tells us about the year and the no of medals won in that particular year.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zX1-EXo_-K1tciMhYQBcfQ.png" /></figure><p><strong>Step-II</strong></p><p>I have created a simple <strong>index.html </strong>file and a <strong>styles.css</strong> file inside a folder separate from the angular project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*yXXZLdn8oe17ta_uSqpLCA.png" /></figure><p>Lets design the table headers first. The<strong> ID,Name,Country and Year</strong> headers look pretty straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*PwgiTTQd-yxZkGTo50_AtA.png" /></figure><p>The <strong>Medals</strong> header looks a bit different. It seems as if the header internally has 2 rows. In the first row, we have <strong>Medals</strong>. In the 2nd row, there are 3 columns. We have <strong>Gold, Silver and Bronze</strong> in the 3 columns respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*HA632m2ofppvVAII5DzDMA.png" /></figure><p>Thus, this is my initial design.</p><pre> &lt;table&gt;<br>        &lt;thead&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;ID&lt;/th&gt;<br>                &lt;th &gt;Name&lt;/th&gt;<br>                &lt;th &gt;Country&lt;/th&gt;<br>                &lt;th &gt;Year&lt;/th&gt;<br>                &lt;th&gt;Medals&lt;/th&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;Gold&lt;/th&gt;<br>                &lt;th&gt;Silver&lt;/th&gt;<br>                &lt;th&gt;Bronze&lt;/th&gt;<br>            &lt;/tr&gt;<br>        &lt;/thead&gt;<br>&lt;/table&gt;</pre><p>This design produces a slightly strange UI. To correct this, we need to ensure that the<strong> ID, Name, Country and Year </strong>heading cells, should span <strong>2 rows</strong>. The <strong>Medals</strong> heading cell should <strong>span 3 columns </strong>to accommodate the <strong>Gold, Silver and Bronze</strong> sub-heading cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmJLGwLAZ2KOH-lJUE0S8g.png" /></figure><p>We have made the required corrections as below.</p><pre>&lt;table&gt;<br>        &lt;thead&gt;<br>            &lt;tr&gt;<br>               &lt;th rowspan=&quot;2&quot;&gt;ID&lt;/th&gt;<br>                &lt;th rowspan=&quot;2&quot;&gt;Name&lt;/th&gt;<br>                &lt;th rowspan=&quot;2&quot;&gt;Country&lt;/th&gt;<br>                &lt;th rowspan=&quot;2&quot;&gt;Year&lt;/th&gt;<br>                &lt;th colspan=&quot;3&quot;&gt;Medals&lt;/th&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;Gold&lt;/th&gt;<br>                &lt;th&gt;Silver&lt;/th&gt;<br>                &lt;th&gt;Bronze&lt;/th&gt;<br>            &lt;/tr&gt;<br>        &lt;/thead&gt;<br>&lt;/table&gt;</pre><p>The table heading structure now looks exactly like the mock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLHcoxCneI5S_UNuwd5leA.png" /></figure><p>Moving to the table body, if you observe the mock ,we have data of the athlete for 3 years:2008,2012 and 2016. The data for these 3 years appear as sub-rows within a single row. To make this possible, we need to ensure that the static data in the <strong>ID, Name and Country </strong>columns <strong>span 3 rows</strong>. This gives the appearance of 3 sub-rows within a single row.</p><p>The <strong>&lt;tbody&gt;</strong> element has thus been structured as below.</p><pre>&lt;tbody&gt;<br>&lt;tr&gt;<br>&lt;td rowspan=”3&quot;&gt;1&lt;/td&gt;<br>&lt;td rowspan=”3&quot;&gt;Usain Bolt&lt;/td&gt;<br>&lt;td rowspan=”3&quot;&gt;Jamaica&lt;/td&gt;<br>&lt;td&gt;2008&lt;/td&gt;<br>&lt;td&gt;3&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;/tr&gt;<br><br>&lt;tr&gt;<br>&lt;td&gt;2012&lt;/td&gt;<br>&lt;td&gt;3&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;/tr&gt;<br><br>&lt;tr&gt;<br>&lt;td&gt;2016&lt;/td&gt;<br>&lt;td&gt;3&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;/tr&gt;<br>&lt;/tbody&gt;</pre><p>The table structure looks exactly as expected now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQCAjPrCF8_FbqHVW7zKUQ.png" /></figure><p>Our final <strong>index.html</strong> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51f29649d7312769d71db4e51be59355/href">https://medium.com/media/51f29649d7312769d71db4e51be59355/href</a></iframe><p><strong>Step-III</strong></p><p>We know now exactly how to arrive at the mock table for 1 athlete. We can now move to our angular project.</p><p>We have created<strong> 2 interfaces</strong> to model the athlete data.</p><pre>export interface Athelete {<br>id: number;<br>name: string;<br>}<br><br>export interface AtheleteList {<br>athlete: Athelete;<br>year: number;<br>gold: number;<br>silver: number;<br>bronze: number;<br>country: string;<br>}</pre><p><strong>Component Class:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05e65f152c77c97f512d5817ec77adc6/href">https://medium.com/media/05e65f152c77c97f512d5817ec77adc6/href</a></iframe><p>=&gt; In the beginning of the story, I have shared the gist of the athelete data we will be using in the story. In the angular project, this data is exported from a file <strong>data.ts. </strong>Each object in the array of objects exported from <strong>data.ts</strong> models the <strong>AtheleteList</strong> interface.</p><pre>{<br>athlete: { id: 1, name: ‘Usain Bolt’ },<br>year: 2008,<br>gold: 3,<br>silver: 0,<br>bronze: 0,<br>country: ‘Jamaica’,<br>},</pre><p>=&gt;We cannot consume this array of objects directly to populate the table. Instead we will be grouping the athletes based on their unique <strong>id</strong> and we will create a single array which contains multiple sub-arrays. Each sub-array is an array of objects describing a single athlete and each object models the <strong>AtheleteList </strong>interface as we already know. This means since there are 11 atheletes, we will have 11 sub-arrays.</p><p>=&gt;<strong>athletesList$ </strong>is an observable of the array of sub-arrays, we discussed in the earlier point. We we will subscribe to <strong>athletesList$ </strong>in the template using <strong>async</strong> pipe to construct the table.</p><pre>athletesList$?: Observable&lt;AtheleteList[][]&gt;;</pre><p>=&gt;Within the <strong>ngOnInit</strong> lifecycle hook, we are getting hold of the array of objects exported from <strong>data.ts </strong>and converting it into a cold observable using the <strong>from</strong> operator. We are then using the <strong>groupBy</strong> operator to group the objects based on the unique <strong>athlete.id</strong> key. The output of the <strong>mergeMap</strong> operator will be 11 arrays of objects. Each array contains multiple objects, all related to a single athlete. The <strong>scan</strong> operator pushes all the 11 arrays into another array. <strong>So we get a single array containing 11 sub-arrays.</strong></p><pre>this.athletesList$ = from(data).pipe(<br>groupBy((item) =&gt; item.athlete.id),<br>mergeMap((group$) =&gt;group$.pipe(reduce((acc: AtheleteList[], curr) =&gt; […acc, curr], []))<br>),<br>scan((acc: AtheleteList[][], curr: AtheleteList[]) =&gt; {acc.push(curr);return acc;}, []),<br>takeLast(1)<br>);</pre><p>Below is the screenshot of the final array which contains 11 sub-arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgR_pnIhmMAC9-zPxuOEmA.png" /></figure><p><strong>Component Template: </strong>In the template, we have subscribed to the <strong>athletesList$ </strong>observable using async pipe and constructed the table in the same fashion as <strong>index.html.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7efbc93e4afd9b73b578f2e2e437b0c/href">https://medium.com/media/c7efbc93e4afd9b73b578f2e2e437b0c/href</a></iframe><p>The <strong>&lt;thead&gt;</strong> is exactly the same as what we had in <strong>index.html.</strong></p><pre>&lt;thead&gt;<br>&lt;tr&gt;<br>&lt;th rowspan=”2&quot;&gt;ID&lt;/th&gt;<br>&lt;th rowspan=”2&quot;&gt;Name&lt;/th&gt;<br>&lt;th rowspan=”2&quot;&gt;Country&lt;/th&gt;<br>&lt;th rowspan=”2&quot;&gt;Year&lt;/th&gt;<br>&lt;th colspan=”3&quot;&gt;Medals&lt;/th&gt;<br>&lt;/tr&gt;<br>&lt;tr&gt;<br>&lt;th&gt;Gold&lt;/th&gt;<br>&lt;th&gt;Silver&lt;/th&gt;<br>&lt;th&gt;Bronze&lt;/th&gt;<br>&lt;/tr&gt;<br>&lt;/thead&gt;</pre><p>Coming to the <strong>&lt;tbody&gt;</strong> element, lets compare the <strong>index.html</strong> and the component template.</p><p><strong>First &lt;tr&gt; element in the index.html</strong></p><pre>&lt;tr&gt;<br>&lt;td rowspan=”3&quot;&gt;1&lt;/td&gt;<br>&lt;td rowspan=”3&quot;&gt;Usain Bolt&lt;/td&gt;<br>&lt;td rowspan=”3&quot;&gt;Jamaica&lt;/td&gt;<br>&lt;td&gt;2008&lt;/td&gt;<br>&lt;td&gt;3&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;/tr&gt;</pre><p><strong>First &lt;tr&gt; element in the component template</strong>.</p><p><strong>athleteGroupList</strong> refers to each of the 11 sub-arrays. Each sub-array contains multiple objects detailing the medals won by a single athelete. In the first &lt;tr&gt; element, we are going to display only the first object in the sub-array. We have set the <strong>rowspan</strong> attribute of the <strong>ID,Name and Country </strong>columns to the <strong>length of the sub-array. </strong>This is because the data in these 3 columns is going to common for all the objects in the sub-array. So we want the data in these 3 columns to span as many rows as the no of objects in the sub-array.</p><pre>&lt;ng-container *ngFor=”let athleteGroupList of athletesList$|async;”&gt;<br>&lt;tr&gt;<br>&lt;td [attr.rowspan]=”athleteGroupList.length”&gt;{{athleteGroupList[0].athlete.id}}&lt;/td&gt;<br>&lt;td [attr.rowspan]=”athleteGroupList.length”&gt;{{athleteGroupList[0].athlete.name}}&lt;/td&gt;<br>&lt;td [attr.rowspan]=”athleteGroupList.length”&gt;{{athleteGroupList[0].country}}&lt;/td&gt;<br>&lt;td&gt;{{athleteGroupList[0].year}}&lt;/td&gt;<br>&lt;td&gt;{{athleteGroupList[0].gold}}&lt;/td&gt;<br>&lt;td&gt;{{athleteGroupList[0].silver}}&lt;/td&gt;<br>&lt;td&gt;{{athleteGroupList[0].bronze}}&lt;/td&gt;<br>&lt;/tr&gt;<br><br>&lt;!---other &lt;tr&gt; elements---&gt;<br><br>&lt;/ng-container&gt;</pre><p><strong>Remaining &lt;tr&gt; elements in the index.html. </strong>Observe that in the remaining &lt;tr&gt; elements <strong>we have skipped the ID, Name and Country </strong>columns because the data in the columns is common and it will span 3 rows for the 1st athelete. In the remaining &lt;tr&gt; elements, you only need to display the data for the<strong> Year and Medals</strong> column</p><pre>&lt;tr&gt;<br>&lt;td&gt;2012&lt;/td&gt;<br>&lt;td&gt;3&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;/tr&gt;<br><br>&lt;tr&gt;<br>&lt;td&gt;2016&lt;/td&gt;<br>&lt;td&gt;3&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;td&gt;0&lt;/td&gt;<br>&lt;/tr&gt;</pre><p><strong>Remaining &lt;tr&gt; elements in the component template.</strong></p><p>Here we are <strong>iterating through each object in the sub-array except for the first one</strong> and <strong>displaying only the data in the Year and Medals column</strong>.</p><pre>&lt;ng-container *ngFor=”let athelete of athleteGroupList;let j=index”&gt;<br>&lt;tr *ngIf=”j &gt; 0&quot;&gt;<br>&lt;td&gt;{{athelete.year}}&lt;/td&gt;<br>&lt;td&gt;{{athelete.gold}}&lt;/td&gt;<br>&lt;td&gt;{{athelete.silver}}&lt;/td&gt;<br>&lt;td&gt;{{athelete.bronze}}&lt;/td&gt;<br>&lt;/tr&gt;<br>&lt;/ng-container&gt;</pre><p>Our final table in the angular template looks like this. I understand it doesn’t look stylish. Here the focus is more on how you can easily arrive at the expected table structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ftldjs_1vaCAUx6Onp5uJw.png" /></figure><p>From the above example its clear that you can save a lot of time designing tables using <strong>rowspan</strong> and <strong>colspan</strong> if you follow the below points:</p><ol><li>Take single object from the actual data or create your own dummy data to design the table in a simple .html file.</li><li>Once you are able to construct the table as expected for 1 or 2 rows in the .html file, the next important step is to observe the patterns of the &lt;tr&gt;,&lt;th&gt; and &lt;td&gt; elements.</li><li>Now all you need to do is follow the same pattern and construct the table in the angular component.</li></ol><p>Below is the link to the working example.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-i4y69mig%3Fembed%3D1%26file%3Dsrc%252Fmain.ts&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-i4y69mig%3Ffile%3Dsrc%252Fmain.ts&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-i4y69mig%2Feede753718923a7d04d72b32f5f6cd6a&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8f3e939369b80373d05ac15c4b00f98/href">https://medium.com/media/b8f3e939369b80373d05ac15c4b00f98/href</a></iframe><h3>Thank you for being a part of the community</h3><p><em>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://x.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://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=635e9169234a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-can-you-approach-a-complex-table-with-rowspan-and-colspan-in-angular-635e9169234a">How can you approach a complex table with rowspan and colspan in Angular ?</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[2 Different ways you can process .css/.scss files in TS Project using Webpack 5]]></title>
            <link>https://javascript.plainenglish.io/2-different-ways-you-can-process-css-scss-files-in-ts-project-using-webpack-5-af6b04ddd5b4?source=rss-f2cd68202ac6------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6b04ddd5b4</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[loader]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[plugins]]></category>
            <dc:creator><![CDATA[Angular&NodeEnthusiast]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 09:35:00 GMT</pubDate>
            <atom:updated>2025-02-10T02:32:16.730Z</atom:updated>
            <content:encoded><![CDATA[<h3>2 Different ways you can process .css/.scss files in TS Project using Webpack 5</h3><p>To copy the style content in the <strong>.css/.scss</strong> files in the source code of your project to the <strong>distribution folder</strong>, we can use either of the 2 ways:</p><p>=&gt; Dump all style content into the <strong>.js</strong> <strong>bundle</strong> within the <strong>dist</strong> folder.</p><p>=&gt;Create a seperate <strong>.css bundle </strong>within the <strong>dist</strong> folder for all the style content in the project.</p><p>Finally at the end</p><p>I have already created a TS project with webpack configured in the below story. Please check the below link.</p><p><a href="https://ramya-bala221190.medium.com/few-easy-steps-to-run-and-test-your-typescript-code-in-the-browser-using-webpack-5-90c63ffa36cd">Few easy steps to Run and Test your Typescript Code in the browser using WebPack 5</a></p><p>This is how the TS project, with webpack 5 configured currently looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*ugsDFS-LE6sDSKf_nRbilg.png" /></figure><p><strong>index.html</strong> within the project root.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;body&gt;<br>&lt;h4&gt;Welcome to Webpack&lt;/h4&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>styles.scss </strong>within the project root.</p><pre>$color:red;<br>$underline:underline;<br><br>h4{<br>text-decoration: $underline;<br>color:$color;<br>}</pre><p><strong>src/index.ts</strong></p><pre>import ‘../styles.scss’;<br>console.log(“Hello World”);</pre><p><strong>It is very important to import the styles.scss within the index.ts file, for webpack to identify and process the styles.scss file.</strong></p><p>The <strong>webpack.config.js </strong>looks like below currently, with no rules to process<strong> .scss/.css </strong>files. We just have a “<strong>ts-loader”</strong> to transpile .ts into .js files and a <strong>html-webpack-plugin</strong> package to automatically generate an <strong>index.html </strong>within the <strong>dist</strong> folder with every build. The <strong>dist/index.html </strong>file is generated using the<strong> index.html within the project root </strong>as the template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc37a4ced9eb96b7425512bb9b22ea8/href">https://medium.com/media/4cc37a4ced9eb96b7425512bb9b22ea8/href</a></iframe><p><strong>I. Method-A</strong></p><p>To dump all the style content into the <strong>.js </strong>file within the <strong>dist</strong> folder, we need to install the below dev dependencies in case you are using <strong>.scss files</strong>.</p><pre>npm install --save-dev css-loader style-loader sass sass-loader</pre><p>In case you are using only <strong>.css </strong>files in your project, you can omit installing <strong>sass</strong> and <strong>sass-loader</strong>. Just install the below dev dependencies.</p><pre>npm install --save-dev css-loader style-loader</pre><p>Next, you need to update the <strong>webpack.config.js </strong>to include an additional rule under <strong>module.rules</strong>.</p><p>This rule below will target <strong>.scss </strong>files and execute loaders in the sequence:<strong> sass-loader →css-loader → style-loader. </strong>The <strong>style-loader</strong> will finally dump all the style content into the <strong>output.js</strong> file within the <strong>dist</strong> folder.</p><pre>{<br>test:/\.scss$/,<br>exclude:/node_modules/,<br>use:[“style-loader”,”css-loader”,”sass-loader”], //executes from right to left<br>},</pre><p>For<strong> .css files</strong>, you can update the rule as below:</p><pre>{<br>test:/\.css$/,<br>exclude:/node_modules/,<br>use:[“style-loader”,”css-loader”], //executes from right to left<br>},</pre><p>Below is the updated <strong>webpack.config.js </strong>looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c87a96023d475e93ee947d999a9a8f/href">https://medium.com/media/96c87a96023d475e93ee947d999a9a8f/href</a></iframe><p>Executing <strong>“npm run build”,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deLvbLdL1yPRkMUWFxU2bg.png" /></figure><p>This is how the <strong>dist</strong> folder looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*HjSSXMfxdJ3dn2BZEPo3yw.png" /></figure><p>Contents of <strong>dist/index.html</strong></p><pre>&lt;head&gt;&lt;script defer=”defer” src=”output.js”&gt;&lt;/script&gt;&lt;/head&gt;&lt;!doctype html&gt;&lt;body&gt;&lt;h4&gt;Welcome to Webpack&lt;/h4&gt;&lt;/body&gt;</pre><p>Contents of <strong>dist/output.js. </strong>Observe that the style content within the <strong>styles.scss</strong> file is now available within the <strong>dist/output.js</strong> file.</p><pre>(()=&gt;{“use strict”;var e={83:(e,t,n)=&gt;{n.d(t,{A:()=&gt;i});var r=n(354),o=n.n(r),a=n(314),c=n.n(a)()(o());c.push([e.id,”h4{text-decoration:underline;color:red}”,””,{version:3,sources:[“webpack://./styles.scss”],names:[],mappings:”AAGA,GACI,yBAHO,CAIP,SALG”,sourcesContent:[“$color:red;\r\n$underline:underline;\r\n\r\nh4{\r\n text-decoration: $underline;\r\n color:$color;\r\n}\r\n”],sourceRoot:””}]);const i=c},314:e=&gt;{e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=””,r=void 0!==t[5];return t[4]&amp;&amp;(n+=”@supports (“.concat(t[4],”) {“)),t[2]&amp;&amp;(n+=”@media “.concat(t[2],” {“)),r&amp;&amp;(n+=”@layer”.concat(t[5].length&gt;0?” “.concat(t[5]):””,” {“)),n+=e(t),r&amp;&amp;(n+=”}”),t[2]&amp;&amp;(n+=”}”),t[4]&amp;&amp;(n+=”}”),n})).join(“”)},t.i=function(e,n,r,o,a){“string”==typeof e&amp;&amp;(e=[[null,e,void 0]]);var c={};if(r)for(var i=0;i&lt;this.length;i++){var s=this[i][0];null!=s&amp;&amp;(c[s]=!0)}for(var u=0;u&lt;e.length;u++){var l=[].concat(e[u]);r&amp;&amp;c[l[0]]||(void 0!==a&amp;&amp;(void 0===l[5]||(l[1]=”@layer”.concat(l[5].length&gt;0?” “.concat(l[5]):””,” {“).concat(l[1],”}”)),l[5]=a),n&amp;&amp;(l[2]?(l[1]=”@media “.concat(l[2],” {“).concat(l[1],”}”),l[2]=n):l[2]=n),o&amp;&amp;(l[4]?(l[1]=”@supports (“.concat(l[4],”) {“).concat(l[1],”}”),l[4]=o):l[4]=””.concat(o)),t.push(l))}},t}},354:e=&gt;{e.exports=function(e){var t=e[1],n=e[3];if(!n)return t;if(“function”==typeof btoa){var r=btoa(unescape(encodeURIComponent(JSON.stringify(n)))),o=”sourceMappingURL=data:application/json;charset=utf-8;base64,”.concat(r),a=”/*# “.concat(o,” */”);return[t].concat([a]).join(“\n”)}return[t].join(“\n”)}},978:(e,t,n)=&gt;{n.r(t),n.d(t,{default:()=&gt;h});var r=n(72),o=n.n(r),a=n(825),c=n.n(a),i=n(659),s=n.n(i),u=n(56),l=n.n(u),d=n(540),p=n.n(d),f=n(113),v=n.n(f),m=n(83),y={};y.styleTagTransform=v(),y.setAttributes=l(),y.insert=s().bind(null,”head”),y.domAPI=c(),y.insertStyleElement=p(),o()(m.A,y);const h=m.A&amp;&amp;m.A.locals?m.A.locals:void 0},72:e=&gt;{var t=[];function n(e){for(var n=-1,r=0;r&lt;t.length;r++)if(t[r].identifier===e){n=r;break}return n}function r(e,r){for(var a={},c=[],i=0;i&lt;e.length;i++){var s=e[i],u=r.base?s[0]+r.base:s[0],l=a[u]||0,d=””.concat(u,” “).concat(l);a[u]=l+1;var p=n(d),f={css:s[1],media:s[2],sourceMap:s[3],supports:s[4],layer:s[5]};if(-1!==p)t[p].references++,t[p].updater(f);else{var v=o(f,r);r.byIndex=i,t.splice(i,0,{identifier:d,updater:v,references:1})}c.push(d)}return c}function o(e,t){var n=t.domAPI(t);return n.update(e),function(t){if(t){if(t.css===e.css&amp;&amp;t.media===e.media&amp;&amp;t.sourceMap===e.sourceMap&amp;&amp;t.supports===e.supports&amp;&amp;t.layer===e.layer)return;n.update(e=t)}else n.remove()}}e.exports=function(e,o){var a=r(e=e||[],o=o||{});return function(e){e=e||[];for(var c=0;c&lt;a.length;c++){var i=n(a[c]);t[i].references — }for(var s=r(e,o),u=0;u&lt;a.length;u++){var l=n(a[u]);0===t[l].references&amp;&amp;(t[l].updater(),t.splice(l,1))}a=s}}},659:e=&gt;{var t={};e.exports=function(e,n){var r=function(e){if(void 0===t[e]){var n=document.querySelector(e);if(window.HTMLIFrameElement&amp;&amp;n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}t[e]=n}return t[e]}(e);if(!r)throw new Error(“Couldn’t find a style target. This probably means that the value for the ‘insert’ parameter is invalid.”);r.appendChild(n)}},540:e=&gt;{e.exports=function(e){var t=document.createElement(“style”);return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},56:(e,t,n)=&gt;{e.exports=function(e){var t=n.nc;t&amp;&amp;e.setAttribute(“nonce”,t)}},825:e=&gt;{e.exports=function(e){if(“undefined”==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(n){!function(e,t,n){var r=””;n.supports&amp;&amp;(r+=”@supports (“.concat(n.supports,”) {“)),n.media&amp;&amp;(r+=”@media “.concat(n.media,” {“));var o=void 0!==n.layer;o&amp;&amp;(r+=”@layer”.concat(n.layer.length&gt;0?” “.concat(n.layer):””,” {“)),r+=n.css,o&amp;&amp;(r+=”}”),n.media&amp;&amp;(r+=”}”),n.supports&amp;&amp;(r+=”}”);var a=n.sourceMap;a&amp;&amp;”undefined”!=typeof btoa&amp;&amp;(r+=”\n/*# sourceMappingURL=data:application/json;base64,”.concat(btoa(unescape(encodeURIComponent(JSON.stringify(a)))),” */”)),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},113:e=&gt;{e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var a=t[r]={id:r,exports:{}};return e[r](a,a.exports,n),a.exports}n.n=e=&gt;{var t=e&amp;&amp;e.__esModule?()=&gt;e.default:()=&gt;e;return n.d(t,{a:t}),t},n.d=(e,t)=&gt;{for(var r in t)n.o(t,r)&amp;&amp;!n.o(e,r)&amp;&amp;Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=&gt;Object.prototype.hasOwnProperty.call(e,t),n.r=e=&gt;{“undefined”!=typeof Symbol&amp;&amp;Symbol.toStringTag&amp;&amp;Object.defineProperty(e,Symbol.toStringTag,{value:”Module”}),Object.defineProperty(e,”__esModule”,{value:!0})},n.nc=void 0,n(978),console.log(“Hello World”)})();<br>//# sourceMappingURL=output.js.map</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4F1dNu1LRajMc6zHKRMVQ.png" /></figure><p>Running <strong>“npm run start”</strong>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJDMPbbCY0O3JF7_q2F7qQ.png" /></figure><p>Hitting <strong>localhost:8080</strong> in the browser. Works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y79NGlD_DRiPYozU2PwALg.png" /></figure><p><strong>II. Method-B</strong></p><p>To create a seperate <strong>.css</strong> file within the <strong>dist</strong> folder for dumping all the style content, we need to install an additional dev dependency: <strong>mini-css-extract-plugin</strong></p><pre>npm install --save-dev mini-css-extract-plugin</pre><p>Lets create a new configuration file: <strong>webpack.config.1.js</strong> in the project root. It will be a replica of the <strong>webpack.config.js</strong> but with few changes.</p><p>Within the <strong>webpack.config.1.js</strong>, we need to first require the <strong>mini-css-extract-plugin </strong>npm package.</p><pre>const miniCssExtractPlugin=require(‘mini-css-extract-plugin’);</pre><p>For <strong>.scss files</strong>, We need to update FROM</p><pre>{<br>test:/\.scss$/,<br>exclude:/node_modules/,<br>use:[“style-loader”,”css-loader”,”sass-loader”], //executes from right to left<br>},</pre><p>TO</p><pre>{<br>test:/\.scss$/,<br>exclude:/node_modules/,<br>use:[miniCssExtractPlugin.loader,”css-loader”,”sass-loader”], //executes from right to left<br>},</pre><p>For <strong>.css files</strong>, We need to update FROM</p><pre>{<br>test:/\.css$/,<br>exclude:/node_modules/,<br>use:[“style-loader”,”css-loader”], //executes from right to left<br>},</pre><p>TO</p><pre>{<br>test:/\.css$/,<br>exclude:/node_modules/,<br>use:[miniCssExtractPlugin.loader,”css-loader”], //executes from right to left<br>},</pre><p>Finally, we need to add the below to the <strong>plugins</strong> key. We want the style content in all the<strong> .css/.scss</strong> files in the project to be dumped into a single <strong>output.css </strong>file within the <strong>dist</strong> folder.</p><pre>new miniCssExtractPlugin({filename:’output.css’})</pre><p>This is how our <strong>webpack.config.1.js</strong> looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3609a446d8b218d141399ff6e1ce390d/href">https://medium.com/media/3609a446d8b218d141399ff6e1ce390d/href</a></iframe><p>To run the <strong>build </strong>for the<strong> </strong>the project and <strong>start </strong>the webpack dev server using the new configuration file, I have added 2 additional scripts in the <strong>package.json</strong> with the <strong>config</strong> flag.<strong> We are passing the name of the configuration file to be used, to the config flag.</strong></p><pre>“build-1”:”webpack --env production --config webpack.config.1.js”,<br>“start-1”:”webpack serve --config webpack.config.1.js”</pre><p>Lets run<strong> “npm run build-1”,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVzlH2vF0sTkZYeKGrc0Ww.png" /></figure><p>Contents of <strong>dist</strong> folder. Observe the additional <strong>output.css</strong> file within the dist folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*LqCJusF-EEUSKsgQVBrlHA.png" /></figure><p>Contents of<strong> dist/index.html. </strong>Observe that <strong>output.css </strong>has been automatically referenced in the <strong>dist/index.html</strong> via <strong>&lt;link&gt;</strong> element.</p><pre>&lt;head&gt;&lt;script defer=”defer” src=”output.js”&gt;&lt;/script&gt;&lt;link href=”output.css” rel=”stylesheet”&gt;&lt;/head&gt;&lt;!doctype html&gt;&lt;body&gt;&lt;h4&gt;Welcome to Webpack&lt;/h4&gt;&lt;/body&gt;</pre><p>Contents of<strong> dist/output.css</strong></p><pre>h4{text-decoration:underline;color:red}<br>/*# sourceMappingURL=output.css.map*/</pre><p>Running<strong> “npm run start-1”,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkYXghde-IwceFnP-sk-wA.png" /></figure><p>Hitting in <strong>localhost:8080</strong> in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3URZukZJGOiCNshpddtU9Q.png" /></figure><p>Below is the github link to the project.</p><p><a href="https://github.com/ramyabala221190/baseForTSProject/tree/css-processing">GitHub - ramyabala221190/baseForTSProject at css-processing</a></p><p>If you want to understand how assets like images can be processed in a TS project, using Webpack, do check the below story.</p><p><a href="https://ramya-bala221190.medium.com/3-different-ways-you-can-process-image-assets-in-ts-project-using-webpack-5-41e7c219915a">3 Different ways you can process image assets in TS Project using Webpack 5</a></p><h3>Thank you for being a part of the community</h3><p><em>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://x.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://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6b04ddd5b4" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/2-different-ways-you-can-process-css-scss-files-in-ts-project-using-webpack-5-af6b04ddd5b4">2 Different ways you can process .css/.scss files in TS Project using Webpack 5</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>