<?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 Selim on Medium]]></title>
        <description><![CDATA[Stories by Selim on Medium]]></description>
        <link>https://medium.com/@slmens?source=rss-2cf0d1b4b6d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lMrH7UjhgWdwY07MwJYcGg.jpeg</url>
            <title>Stories by Selim on Medium</title>
            <link>https://medium.com/@slmens?source=rss-2cf0d1b4b6d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:11:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@slmens/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[From Containers to Clusters: Building Your First Kubernetes Environment from Scratch]]></title>
            <link>https://slmens.medium.com/from-containers-to-clusters-building-your-first-kubernetes-environment-from-scratch-dc743f8076d3?source=rss-2cf0d1b4b6d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc743f8076d3</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Selim]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 04:03:16 GMT</pubDate>
            <atom:updated>2025-01-05T04:03:16.917Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! In this article, I’ll be exploring what Kubernetes is, why and how it’s used, and answering some common questions about it. Since this will be quite an extensive piece, I’d like to start with a brief overview of what each section will cover.</p><p><strong><em>Sections of the Article:</em></strong></p><ol><li><strong>Section 1:</strong> Before diving into Kubernetes, we’ll quickly go over the essential concepts you need to understand, like containers and Docker. I won’t delve too deeply into these topics, so if you’re already familiar with them, feel free to skip ahead to Section 2.</li><li><strong>Section 2:</strong> Here, we’ll discuss what Kubernetes is, how it works, and in what scenarios it can be beneficial. This section will be more theoretical, and I’ll use diagrams to explain what’s happening behind the scenes in Kubernetes and its underlying logic.</li><li><strong>Section 3:</strong> Finally, after learning the theory, we’ll move on to practice. In this part, we’ll set up a Kubernetes cluster from scratch and run a pre-built full-stack project on it. You can find the GitHub link to the completed project at the end of the article.</li></ol><p>Let’s get started!</p><h4><strong><em>Section 1 — What Are Containers and Docker?</em></strong></h4><p>To understand Kubernetes, we first need to grasp what Docker is and the concept of containers. In this section, I’ll focus on these topics without going too deep.</p><p><strong><em>What Is a Container?</em></strong></p><p>You’ve likely experienced this before: the code you wrote runs flawlessly on your computer, but when you try to execute it on a friend’s machine or any other computer, it doesn’t work, and you say, “But it worked on my computer!” Containers were created precisely to solve this problem. They provide an isolated environment containing all the dependencies necessary for your code to run. So, no matter where you run this isolated environment, the code will function correctly because everything it needs is bundled with the code inside the container.</p><p>This ensures that an application runs the same way in production as it does on a developer’s machine. Unlike virtual machines, containers use fewer resources and operate faster because they provide isolation at the operating system level. This creates lighter and more portable application environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*mbi82DvnoWKMwimI15BoaQ.png" /></figure><p><strong><em>Why Containers?</em></strong></p><p>The traditional way of developing and deploying applications often leads to issues due to differences in environments. These discrepancies can cause significant time loss and errors during deployment. Containers address these challenges by:</p><ol><li><strong>Ensuring Consistency Across Environments</strong>: By encapsulating an application and its dependencies, containers eliminate environment-related inconsistencies.</li><li><strong>Enhancing Efficiency</strong>: Containers are lightweight because they share the host OS kernel, making them faster to start and requiring fewer resources than virtual machines.</li><li><strong>Portability and Flexibility</strong>: Containers can run anywhere, whether on a developer’s laptop, on-premises data center, or in the cloud, ensuring seamless deployment across platforms.</li></ol><p>Containers have become a standard in modern software development, enabling faster development cycles, consistent operations, and more reliable deployments. By understanding containers, you’ll be better equipped to grasp the orchestration and scalability capabilities that Kubernetes offers.</p><p><strong><em>What Is Docker?</em></strong></p><p>Now that you know what containers do and why they are so widely used, it’s clear that containers simplify many aspects of software development. However, they also introduce their own challenges, which lead to the need for additional solutions. Managing, organizing, and keeping containers up to date are tasks that require efficient solutions, and one of the most popular tools for this is Docker.</p><p>At its core, Docker is a container management tool. It helps us create, manage, update, and distribute containers. Docker streamlines these processes, making it easier for developers and operations teams to work seamlessly across environments.</p><p><strong><em>Why Do We Need Docker?</em></strong></p><p>Containers alone provide the isolation and consistency needed to run applications smoothly across different environments. However, managing containers manually can become complex and error-prone, especially when dealing with numerous containers or when frequent updates are necessary. Docker addresses these issues by providing:</p><ol><li><strong>Automation and Efficiency</strong>: Docker automates the process of container creation and deployment, reducing manual overhead and minimizing the risk of human error.</li><li><strong>Portability</strong>: Docker containers can be easily moved between different environments, ensuring that applications run consistently anywhere.</li><li><strong>Version Control and Rollback</strong>: With Docker, you can track changes to your container images and easily roll back to previous versions if necessary.</li><li><strong>Resource Management</strong>: Docker optimizes resource usage by ensuring that containers share resources efficiently without interfering with each other.</li></ol><p><strong><em>How Does Docker Work?</em></strong></p><p>Docker uses a client-server architecture. The Docker client communicates with the Docker daemon, which performs the heavy lifting of building, running, and distributing containers. The process revolves around Docker images, which are lightweight, standalone packages that include everything needed to run a piece of software: code, runtime, libraries, and settings.</p><p><strong><em>Dockerfile</em></strong></p><p>A Dockerfile is a text document that contains a set of instructions for assembling a Docker image. It defines the application environment and lists all dependencies, configurations, and commands needed to build and run the application. By using a Dockerfile, you can create a consistent environment for your application, ensuring that it behaves the same way across different systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*ig-liT0pe5pWmY_PgZ532A.png" /><figcaption>Dockerfile</figcaption></figure><p><strong><em>Docker Images</em></strong></p><p>Docker images are built from Dockerfiles. They are read-only templates that serve as a blueprint for creating Docker containers. When you build an image from a Dockerfile, the image captures the application and its entire environment in a single package. This includes the operating system, application code, libraries, and any other files needed to run the application.</p><ul><li><strong>Creating Images</strong>: The Docker daemon processes the instructions in the Dockerfile to create an image. Each command in the Dockerfile corresponds to a layer in the image, making it possible to reuse layers and optimize image size.</li><li><strong>Image Repositories</strong>: Docker images can be stored and shared using Docker registries, such as Docker Hub. This allows developers to distribute their applications easily and ensures that the same image can be used consistently in different environments.</li></ul><p><strong><em>Docker Containers</em></strong></p><p>Once you have a Docker image, you can use it to create one or more Docker containers. Containers are runtime instances of Docker images. They run in isolated environments on the host system, ensuring that each container has its own filesystem, network, and process space.</p><ul><li><strong>Running Containers</strong>: To run a container, Docker uses the image to create a separate, isolated environment on the host. This environment includes all the components defined in the image, allowing the application to run exactly as specified.</li><li><strong>Container Management</strong>: Docker provides tools for managing containers, including starting, stopping, and monitoring their performance. Containers can be easily scaled, replicated, and managed, making Docker a powerful solution for deploying applications in a consistent and reliable manner.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Knxbz_BI_QYFgxdW76BPg.png" /><figcaption>An excellent visual I obtained from <a href="https://cto.ai/blog/docker-image-vs-container-vs-dockerfile/">https://cto.ai/blog/docker-image-vs-container-vs-dockerfile/</a></figcaption></figure><p><strong><em>What Problems Does Docker Solve?</em></strong></p><p>Before Docker, deploying applications across different environments was a cumbersome process prone to compatibility issues. Docker solves this by:</p><ul><li><strong>Eliminating “It Works on My Machine” Syndrome</strong>: With Docker, the same environment is replicated across all machines, ensuring consistency.</li><li><strong>Simplifying Deployment</strong>: Docker enables fast and straightforward deployment processes, reducing the time and effort needed to get applications up and running.</li><li><strong>Facilitating Collaboration</strong>: By standardizing the environment, Docker makes it easier for development and operations teams to collaborate efficiently.</li></ul><p>In summary, Docker not only simplifies container management but also enhances the overall software development lifecycle by making it more reliable, portable, and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*PqiXMsfhohjan6zZYbjb9Q.png" /></figure><h4><strong><em>Section 2 — Kubernetes</em></strong></h4><p>Now that we have a grasp of Docker and containers, we can delve into Kubernetes: what it is, how it works, and why it’s essential.</p><p><strong><em>What is Kubernetes?</em></strong></p><p>Kubernetes (often abbreviated as K8s) is a container orchestration system developed by Google. It helps manage and automate the lifecycle of containers in a distributed environment. In simpler terms, Kubernetes is a system that automatically manages the containers created from Docker images for you.</p><p><strong><em>Why is it Useful?</em></strong></p><p>The core feature of Kubernetes is its ability to manage the lifecycle of containers. But what exactly is a lifecycle? The lifecycle of a container includes its creation, running state, and termination. Kubernetes ensures that containers are automatically managed throughout this lifecycle.</p><p>For instance, if you have 1000 containers and some of them fail for any reason, you might not even be aware of it. Imagine a container responsible for authentication fails; in this scenario, users would be unable to log in to your application. Without Kubernetes, you would need to manually check if that container is running and take action to restart it.</p><p>However, with Kubernetes, if a container fails or stops for any reason, Kubernetes automatically restarts it. This self-healing capability is one of Kubernetes’ fundamental features. It ensures that your application remains resilient and operational, even in the face of individual container failures.</p><p>Here are some of the key features of Kubernetes:</p><ol><li><strong>Automated Management and Self-Healing:</strong></li></ol><ul><li><strong>Automatic Restart: </strong>Like I mention above<strong> </strong>Kubernetes automatically restarts containers that have failed or stopped. This ensures that the application remains operational without manual intervention.</li><li><strong>Self-Healing:</strong> If a Pod or container is marked as unhealthy, Kubernetes detects this and either restarts the faulty component or replaces it with a new one. This maintains the overall health of the application.</li></ul><p><strong>2. Automatic Scaling:</strong></p><ul><li><strong>Horizontal Scaling:</strong> Kubernetes can automatically adjust the number of running Pods based on the current load or demand. This means it can increase the number of Pods when traffic rises and decrease them when traffic falls, optimizing resource utilization.</li><li><strong>Vertical Scaling:</strong> Kubernetes allows for the dynamic adjustment of resource requests for Pods, such as increasing or decreasing CPU or memory allocation, to better meet application demands.</li></ul><p><strong>3. Load Balancing and Service Discovery:</strong></p><ul><li><strong>Load Balancing:</strong> Kubernetes distributes network traffic across multiple Pods to ensure high performance and reliability. This helps in maintaining balanced workloads and preventing any single Pod from being overwhelmed.</li><li><strong>Service Discovery:</strong> Kubernetes provides a stable network endpoint for communication between different components of an application. This abstraction allows services to find and interact with each other seamlessly without needing to manage IP addresses and port numbers manually.</li></ul><p><strong>4. Secrets and Configuration Management:</strong></p><ul><li><strong>Secrets:</strong> Kubernetes securely stores and manages sensitive information such as passwords, API keys, and certificates. This ensures that confidential data is handled securely and can be provided to Pods as needed.</li><li><strong>ConfigMaps:</strong> Kubernetes manages configuration data centrally, allowing you to separate configuration settings from application code. This makes it easier to manage and update configurations without redeploying the application.</li></ul><p><strong>5. Automated Rollouts and Rollbacks:</strong></p><ul><li><strong>Rollouts:</strong> Kubernetes can automatically roll out updates to applications in a controlled manner. It ensures that updates are applied gradually, minimizing downtime and potential disruptions.</li><li><strong>Rollbacks:</strong> If an update causes issues, Kubernetes can roll back to a previous stable version of the application, restoring the system to its prior state.</li></ul><p><strong>6. Resource Management and Optimization:</strong></p><ul><li><strong>Resource Requests and Limits:</strong> Kubernetes allows you to define resource requests and limits for each container. This ensures that containers have the necessary resources and prevents them from consuming excessive resources that could affect other containers.</li><li><strong>Node Affinity and Anti-Affinity:</strong> Kubernetes can schedule Pods based on specific requirements or constraints, such as ensuring certain Pods are co-located or separated for performance and reliability reasons.</li></ul><p><strong>7. Persistent Storage:</strong></p><ul><li><strong>Persistent Volumes (PVs):</strong> Kubernetes provides a way to manage storage resources independently of individual Pods. This ensures that data persists across container restarts and is available to different Pods as needed.</li><li><strong>Storage Classes:</strong> Kubernetes allows you to define different types of storage based on performance and availability requirements, providing flexibility in how storage is provisioned and managed.</li></ul><p>Overall, Kubernetes offers a comprehensive set of features that simplify the management of containerized applications, enhance their reliability, and optimize resource usage, making it a crucial tool for modern cloud-native deployments.</p><p><strong><em>How It’s Works?</em></strong></p><p>Kubernetes consists of many resources. I’ll dive into these resources in more detail in the next section, but to understand how Kubernetes works, we need to learn about a few of them now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rojb4jGDZIL8qW33OO93kQ.png" /><figcaption>Kubernetes Cluster Example</figcaption></figure><p>In a Kubernetes cluster, there is one master node and as many worker nodes as you define. Worker nodes act like large containers themselves, and within them, they run pods as well as other components that handle the node’s system tasks, as shown in the diagram.</p><p><strong><em>What is a Pod?</em></strong><br>Pods are the smallest deployable units in Kubernetes, representing a single instance of a running process in your cluster. They encapsulate one or more containers, along with storage resources, a unique network IP, and options that govern how the container(s) should run. While it’s common to run a single container in a pod, pods can also contain multiple containers that need to share resources, such as a web server container and a logging container working together.</p><p>Pods are designed to be ephemeral, meaning they can be created, destroyed, and replicated quickly. If a pod fails, Kubernetes can automatically create a new one to maintain the desired state of your application. This flexibility makes pods ideal for scalable and resilient microservices architectures.</p><p>Additionally, each pod in Kubernetes has its own IP address within the cluster, which means containers in different pods can communicate with each other directly using these IP addresses. This networking model simplifies the way services are exposed and consumed within the cluster</p><p><strong><em>What is a Master Node?</em></strong><br>The master node is the control center of a Kubernetes cluster. It manages the cluster’s overall state and orchestrates the deployment, scaling, and management of your applications. The master node runs several critical components:</p><ol><li><strong>API Server:</strong> This is the central hub for communication between users, the cluster, and its components. All requests (made with CLI or UI)to the Kubernetes API are handled by the API server, making it the main interface for interacting with the cluster.</li><li><strong>Scheduler:</strong> The scheduler decides which worker nodes should run the newly created or scaled pods. It takes into account various factors such as resource requirements, affinity rules, and the current load on the nodes to ensure efficient utilization of resources.</li><li><strong>Controller Manager:</strong> This component ensures that the cluster’s desired state matches its actual state. It manages tasks like replication (ensuring the correct number of pods are running), node health, and endpoint management.</li><li><strong>etcd:</strong> A key-value store that persists all cluster data. It stores the entire configuration and state of the cluster, making it crucial for maintaining consistency and reliability.</li></ol><p>The master node continuously monitors the state of the worker nodes and the applications running on them. It ensures that the desired state of the cluster, as defined by the user, is maintained, and it takes corrective actions when necessary, such as rescheduling pods or scaling applications up or down. In essence, the master node is the brain of the Kubernetes cluster, orchestrating everything that happens within it.</p><p><strong><em>Summary</em></strong></p><p>To summarize how Kubernetes works: At the core, Kubernetes uses containers, which are built from images, to package our code along with all necessary dependencies. These containers are run inside pods, which are the smallest deployable units in Kubernetes. A pod can contain one or more containers and has its own network IP, storage, and other resources.</p><p>Pods run on nodes, which are essentially machines (either physical or virtual) within the Kubernetes cluster. Each node acts like an individual computer that manages the pods assigned to it. The cluster itself, which is a collection of nodes, is responsible for managing these nodes and ensuring that the pods are running as desired. The master node oversees the entire cluster, orchestrating the deployment, scaling, and management of all the pods across the nodes.</p><h4><strong>Section 3 — Kubernetes Cluster from Scratch</strong></h4><p>Thank you for reading this far; you’ve reached the most important part! In this section, we’ll take a pre-built to-do application and deploy it on a Kubernetes cluster. Currently, the application doesn’t have a database; all to-dos are stored in an array on the server. This means that all data is lost whenever the server restarts. To address this, we’ll run a MongoDB instance locally and connect the application to it, making the necessary adjustments. By the end of this section, we’ll have a cluster capable of handling millions of requests and automatically managing our backend, frontend, database, and many more components like ingress. You can find the GitHub link to the final version of the application at the end of the article.</p><p>We are setting up this Kubernetes cluster on a Windows machine using Docker Desktop, but there are many different ways to install a Kubernetes cluster. First, you’ll need Docker Desktop. Download it from Docker’s official website and install it. After installation, you’ll need to enable the Kubernetes feature within Docker Desktop. To do this, go to the settings, find the Kubernetes option, and enable it. Once Kubernetes is enabled, we’ll have access to the kubectl command, which we’ll use for all of our operations.</p><p>Within a Kubernetes cluster, we manage things like pods and services using YAML files. YAML (Yet Another Markup Language) is used to define the configuration of resources in the cluster, making it easier to manage infrastructure as code.</p><p>For example, let’s say you want to deploy an Nginx web server inside your cluster. You would create a YAML file that defines the deployment and the service, then apply it using kubectl. Here&#39;s a basic example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*CA_Xnid2H32liRNBltSLTQ.png" /></figure><p>This YAML defines a deployment with three replicas of an Nginx container. After creating this file, you would run the following command to deploy it to your Kubernetes cluster: kubectl apply -f example.yaml. Similarly, you can create services, ingress rules, and other Kubernetes resources using YAML files.</p><p>Let’s set up a cluster from scratch for our to-do application.</p><p><strong><em>Cluster Setup</em></strong></p><p>When I say “from scratch,” I assume you’ve already completed the steps of installing Docker Desktop, enabling Kubernetes, and that you have access to the kubectl command.</p><p>Now we have a working Kubernetes cluster, but it’s empty and doesn’t do anything useful yet. To make it work for us, we need to create various resources using YAML files. To keep everything organized, I’ve created a folder called infra/k8s. We&#39;ll write all our YAML files under this folder, which is a common best practice.</p><p><strong><em>What Do We Need?</em></strong></p><p>Let’s think about what we need. We have a Next.js frontend and an Express backend, and we also need a database. So, for each component (frontend, backend, and database), we’ll need:</p><ul><li><strong>A Deployment:</strong> This will define the pods (containers) that run our Docker images.</li><li><strong>A Service:</strong> This will expose the Deployment, enabling communication either within the cluster or externally.</li></ul><p>The Deployment will handle running our containers from Docker images, and the Service will allow these deployments to communicate with each other or with external users.</p><p>However, there is one more thing we need, and that is: Ingress.</p><p><strong><em>Why Do We Need Ingress?</em></strong></p><p>In a Kubernetes cluster, Services allow us to expose our applications, but they are often not enough, especially if you want to manage external traffic in a more sophisticated way. This is where Ingress comes into play.</p><ul><li>Ingress acts as an entry point for external traffic into your cluster, allowing you to define rules that route traffic to different Services based on the requested URL or other conditions.</li><li>In our case, we need Ingress because we want to handle requests from the outside world, such as routing HTTP requests to our frontend or backend services based on the URL path (e.g., / for frontend, /api for backend).</li></ul><p>Without Ingress, we’d have to expose each service individually, which can complicate things, especially in larger applications. Ingress simplifies external access and helps manage SSL/TLS, load balancing, and routing more effectively.</p><p>To summarize why we use Ingress: instead of exposing all our services to the outside of the cluster, we only expose the Ingress service. The Ingress resource, defined in a YAML file, handles routing by directing incoming traffic to the appropriate services based on the routes we specify.</p><p>In addition, Ingress acts as a reverse proxy for our cluster, efficiently managing incoming traffic. It can even handle load balancing between the instances of our services. This not only simplifies external access to our applications but also provides built-in features like SSL/TLS termination and advanced traffic routing, which would otherwise require manual setup for each individual service.</p><p>By centralizing and controlling external access through Ingress, we improve security, scalability, and overall management of traffic into the cluster. This makes Ingress an essential tool for handling more complex applications running in Kubernetes.</p><p>Let’s proceed as follows: First, we will set up deployments and services for the frontend, backend, and database. Then, we will connect these to the Ingress.</p><p><strong><em>Client Side Setup</em></strong></p><p>When a user makes a request to our application through their browser, the request first reaches our Ingress. The Ingress routes the traffic to the appropriate client-side service within our Kubernetes cluster. This service connects to the client deployment, which runs the code in the container to render the frontend and send the response back to the user’s browser. This is the basic flow from the client request to the final rendered page.</p><p><strong><em>Docker Image Creation</em></strong></p><p>Before creating the deployment, we need a Docker image that contains our frontend application. Here’s how you can create and use a Docker image for your application:</p><ol><li><strong>Create a Dockerfile:</strong> Write a Dockerfile that defines how your Docker image is built. For a Next.js application, the Dockerfile might look like this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*yG44aF67G2Y6su0E30YlMw.png" /><figcaption>Dockerfile for client</figcaption></figure><p>2. <strong>Build the Docker Image:</strong> Once the Dockerfile is ready, build the Docker image using the following command:</p><p>docker build -t your-frontend-image:latest .</p><p>This command creates a Docker image named your-frontend-image with the latest tag, based on the instructions in your Dockerfile.</p><p>3. <strong>Push the Docker Image to a Registry:</strong></p><p>After building the image, you need to push it to a Docker registry (such as Docker Hub, AWS ECR, or another private registry) so that Kubernetes can access it:</p><p>docker tag your-frontend-image:latest your-dockerhub-username/your-frontend-image:latest</p><p>docker push your-dockerhub-username/your-frontend-image:latest</p><p>Replace your-dockerhub-username with your Docker Hub username or the appropriate registry URL.</p><p><strong><em>Creating the Deployment and Service</em></strong></p><p>With the Docker image available, you can now create the Kubernetes deployment and service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*p9WO_FIo0cLmI0NRHYyj0A.png" /><figcaption>17.satırı kendinize göre değiştirmeniz gerekiyor.</figcaption></figure><p>In fact, we can write our deployments and services in separate files, but as you saw on line 20, if you use three ---, you can start a new document within the same file. In this case, the document above defines the pod deployment, and the one below defines the service.</p><p><strong><em>Deployment and Service Relationship</em></strong></p><p>You might wonder how a service knows which pod to reach. Services typically use a field called selector to determine which pods they will route traffic to. The selector matches the labels on the pods, and traffic is routed to the pods with those labels. For example, if a service YAML file defines a selector with app: frontend, the service will route traffic only to pods that have the label app: frontend. This ensures that the service correctly directs traffic to the intended pods.</p><p><strong><em>Service Types in Kubernetes</em></strong></p><p>There are different types of Services in Kubernetes, each designed for specific use cases:</p><ol><li><strong>ClusterIP</strong>: Exposes the Service on a cluster-internal IP. It is accessible only within the cluster and is used for internal communication between services. This is the default option for services in Kubernetes. So, our frontend service is a ClusterIP service, meaning it can only be accessed by other services within the same Kubernetes cluster.</li><li><strong>NodePort</strong>: Exposes the Service on each Node’s IP at a static port, allowing access from outside the cluster using &lt;NodeIP&gt;:&lt;NodePort&gt;. Useful for development but not recommended for production.</li><li><strong>LoadBalancer</strong>: The LoadBalancer service type provisions an external load balancer with a public IP, allowing external traffic to access the service. It automatically distributes traffic across the service&#39;s pods and is suitable for production environments where you need reliable, scalable access. Additionally, it often supports SSL/TLS termination, handling encrypted traffic efficiently. Note that Ingress is typically implemented as a LoadBalancer service to manage external traffic and routing to various services within the cluster.</li><li><strong>ExternalName</strong>: Maps a Service to a DNS name, returning a CNAME record. Useful for integrating with external services.</li></ol><p><strong><em>Bringing Frankestein to Life</em></strong></p><p>To deploy and expose your application effectively within your Kubernetes cluster, you’ll follow these steps:</p><ol><li><strong>Apply the Configurations</strong>: Use kubectl apply -f client-depl.yamlto apply the YAML configurations to your cluster. These commands will create or update the resources defined in your YAML files.</li><li><strong>Verify Deployment and Service</strong>: Check the status of your deployment and service with kubectl get deployments and kubectl get services to ensure they are running correctly and are accessible as expected.</li><li><strong>Monitor and Troubleshoot</strong>: Use kubectl logs &lt;pod-name&gt; to view the logs of a specific pod and kubectl describe service &lt;service-name&gt; to get detailed information about a service. These commands will help you monitor the application and troubleshoot any issues if the deployment or service does not behave as expected.</li></ol><p>If you can see that the client is running in the logs, then the deployment is successful, and your client is now running within your cluster.</p><p><strong><em>Server Side Setup</em></strong></p><p>The server-side setup follows a similar approach. First, you need to create a Docker image for your backend application. Once you have the image, you can use it in a Kubernetes Deployment and Service. The backend service will typically be a ClusterIP, used for communication with other components within the cluster. However, if external access is required, you can configure it with NodePort or connect it via Ingress.</p><p>Here’s an example of what your backend Deployment and Service might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5YKqHjS56E98cSy24Yvpg.png" /><figcaption>Server Deployment</figcaption></figure><p><strong>Note:</strong> If your backend requires environment variables, remember to manage them using a ConfigMap or Secret in Kubernetes. This keeps your code clean and makes configuration management easier.</p><p><strong><em>Database Setup</em></strong></p><p>For the database, we typically use a StatefulSet because it’s better suited for maintaining consistency and persistence. However, for simpler projects, a Deployment can suffice. For example, if you’re setting up a PostgreSQL database, your YAML configuration might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*vD6ksqN2Kx_oGizCOq4KWA.png" /></figure><p><strong>Persistent Volumes:</strong> If your database needs to store data persistently, you should also configure a PersistentVolume (PV) and PersistentVolumeClaim (PVC) to ensure data survives pod restarts.</p><p><strong><em>Ingress Setup</em></strong></p><p>Once all deployments and services are configured, the next step is to set up Ingress. As mentioned earlier, Ingress serves as the entry point for external traffic and routes requests to the appropriate services within the cluster.</p><p>Here’s an example of a basic Ingress configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7ye0LxkoLY6jGkOHzS4LA.png" /></figure><p>After setting up the Ingress deployment, you may need to update your local /etc/hosts file to ensure your custom domain (e.g., your-app.example.com) resolves correctly to your cluster&#39;s IP. For example, you can add an entry like 127.0.0.1 your-app.example.com to map the domain to your local machine.</p><p><strong><em>Why Update the </em></strong><strong><em>/etc/hosts File?</em></strong></p><p>The /etc/hosts file allows you to map specific domain names (like your-app.example.com) to an IP address. In our case, this ensures your local machine routes requests for the custom domain to the IP of your Kubernetes cluster (e.g., 127.0.0.1 for local testing). We are going to update our /etc/hosts file in a bit.</p><h4>Deploying Kubernetes Resources</h4><p>Now that all our deployments, services, and the ingress configuration are ready, we need to deploy these resources into the Kubernetes cluster. This involves applying our YAML configuration files using kubectl. Let’s break this process down step by step:</p><p><strong><em>Applying Kubernetes Configurations</em></strong></p><p>Ensure all your YAML files (frontend, backend, database deployments, services, and ingress) are correctly structured and located in your project directory. Here’s an example structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*tjh3HZmzBlD8MV_96rrN6Q.png" /></figure><p>To deploy all resources:</p><ol><li><strong><em>Apply all YAML files in the directory:</em></strong></li></ol><ul><li>kubectl apply -f infra/k8s</li></ul><p>This command applies all YAML files under the infra/k8s directory. Kubernetes will create or update the resources as defined in these files.</p><p><strong>2. Verify the deployments</strong>: After applying the configurations, check the status of the resources to ensure they are running correctly</p><ul><li>kubectl get deployments</li><li>kubectl get services</li><li>kubectl get pods</li><li>kubectl get ingress</li></ul><p>These commands will provide an overview of your deployments, services, pods, and ingress configuration.</p><p><strong><em>Configuring Your Local Hosts File</em></strong></p><p>To test the ingress configuration locally, you may need to update your local hosts file. This maps the domain name (e.g., your-app.example.com) to the IP address of your Kubernetes cluster.</p><ol><li><strong>Find the IP address of your cluster</strong>: If you are running Kubernetes locally (e.g., with Docker Desktop or Minikube), the IP address is likely 127.0.0.1. For Minikube, you can find the IP address using:</li></ol><ul><li>minikube ip</li></ul><p><strong>2. Edit the hosts file</strong>: Open the hosts file on your local machine:</p><ul><li><strong>Mac/Linux</strong>: Use a text editor to open /etc/hosts: sudo nano /etc/hosts</li><li><strong>Windows</strong>: Open C:\Windows\System32\drivers\etc\hosts with administrative privileges using Notepad.</li></ul><p><strong>3. Add an entry for your application</strong>: Append the following line to map your app’s domain to the cluster IP:</p><ul><li>127.0.0.1 your-app.example.com</li></ul><p><strong>4. Save the file</strong> and exit the editor. Now, when you visit your-app.example.com in your browser, the traffic will be routed to your local Kubernetes cluster via the ingress.</p><p><strong><em>Monitoring and Debugging</em></strong></p><p>After deploying the resources, it’s essential to monitor and debug to ensure everything is working as expected:</p><ol><li><strong>Check pod logs</strong>:</li></ol><ul><li>kubectl logs &lt;pod-name&gt;</li><li>Replace &lt;pod-name&gt; with the name of the pod you want to inspect. This helps diagnose issues like failed container startups.</li></ul><p><strong>2. Describe resources</strong>: Use kubectl describe to get detailed information about a specific resource:</p><ul><li>kubectl describe pod &lt;pod-name&gt; kubectl describe service &lt;service-name&gt; kubectl describe ingress &lt;ingress-name&gt;</li></ul><p><strong>3. Monitor resource status</strong>: Keep an eye on your resources with:</p><ul><li>kubectl get pods -w</li><li>The -w flag continuously updates the status, helping you monitor changes in real-time.</li></ul><h4>Testing the Application</h4><p>Once everything is deployed, test your application:</p><ol><li>Open your browser and navigate to the domain you configured in the hosts file (e.g., <a href="http://your-app.example.com)./">http://your-app.example.com).</a></li><li>Verify that the frontend, backend, and database are interacting as expected.</li><li>Test various routes and endpoints to ensure the ingress rules are correctly routing traffic.</li></ol><p>If the application does not behave as expected, revisit your configurations and use the debugging tools mentioned above to identify and resolve issues.</p><h4><strong><em>Conclusion:</em></strong></h4><p>To summarize, Kubernetes becomes truly valuable when managing complex, scalable applications that require orchestration of multiple components. While simpler tools like Docker Compose can handle small projects, Kubernetes excels at providing robust solutions for scaling, fault tolerance, and automated deployments.</p><p>Deciding whether you need Kubernetes depends on your application’s size and complexity. For small, local projects, Docker Compose might be sufficient. However, for production-ready applications with multiple services, Kubernetes is the better choice for ensuring scalability and maintainability.</p><p>By setting up your cluster as described above, you’ve built a solid foundation for running containerized applications efficiently. Whether it’s for development or production, Kubernetes gives you the flexibility and power to manage your applications at scale.</p><p>For the source code:</p><p><a href="https://github.com/slmens/k8sMediumArticle">https://github.com/slmens/k8sMediumArticle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc743f8076d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding NextJS App Router: A Comparison with React Router]]></title>
            <link>https://slmens.medium.com/understanding-nextjs-app-router-a-comparison-with-react-router-ad947e6f760b?source=rss-2cf0d1b4b6d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad947e6f760b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[nextjs-app-router]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[routing]]></category>
            <dc:creator><![CDATA[Selim]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 16:01:05 GMT</pubDate>
            <atom:updated>2024-06-23T16:01:05.203Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, In this article, I will explain what the app router in NextJS is, how it facilitates our projects, and how we can use it. Let’s dive into these questions and discover the benefits and usage of the app router in Next.js.</p><p>In the first part, we will perform a simple routing setup from scratch using the React Router library version 5.3.4. This is intended for readers who may not know what routing is or how it is done in React. I don’t prefer the 6th version, but there aren’t tremendous differences between the 5th and 6th versions, so understanding the 5th version will suffice. This will also allow us to clearly see the differences between the basic routing in React and the App Router in NextJS. In the next part, we will discuss what the App Router is and what benefits it offers. Then, we will build a routing system from scratch using the App Router and dive deeper into its workings through that system.</p><h3>Part 1 — React Router:</h3><p>Let’s start with “What is Routing?”. There are two types of Routing: Network Routing, which is not our topic here, and Application Routing, which is what we will focus on.</p><p>Imagine an e-commerce website. You open the site, and the homepage appears with login/register buttons at the top and products displayed all around. Let’s say you like a product and click on it, or you want to log in and click the login button. The site changes your browser’s URL to “/login” and shows you the login page, right? When you click the login button, you expect it to navigate you to the “/login” route, and as a result, the URL in your browser becomes “/login”. At this point, we render the component that we want to display for this URL, which, in this case, is the Login component. This process is called routing. In simple terms, routing can be understood as the process of determining which page or component to render based on the URL — if the URL is “/login”, render the login page; if it’s “/home”, render the home page, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ip9GDh5HwbdFqlBMPqpsAg.png" /></figure><p>I start by setting up a React project using Vite and then remove the unnecessary parts. Next, I install version 5.3.4 of React Router by running the command npm i react-router-dom@5.3.4. Now, I have a completely empty React application, and I&#39;m ready to start with routing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOLAeBvPOu77aU2fUH188A.png" /></figure><p>The routing system is usually set up in App.jsx, so that&#39;s what I did. The purpose of this is to have a routing system in place as soon as we render App.jsx into our HTML using Main.jsx. While it could technically be done in lower-level components, this would typically be impractical and illogical.</p><p>Inside App.jsx, we start by importing the BrowserRouter tag from React Router and use it to wrap our routing setup. Within this, we use a Switch structure, which is similar to a switch/case statement in programming. Inside the Switch, we use Route tags to specify which component to render for each URL. For example, we can set up the Route so that the Home component is rendered when the URL is &quot;/&quot; (i.e., &quot;<a href="http://localhost:3000/">http://localhost:3000/</a>&quot;).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ll9DThSEYILeHCq5aVEP6A.png" /><figcaption>React Router</figcaption></figure><h3>Exact:</h3><p>However, there’s an important point to understand here. As seen in the first Route tag, there is a keyword called exact. We use this keyword when we want the URL to match exactly with the specified path. I know it might sound confusing, so let me explain with an example.</p><p>Let’s say we remove the exact keyword from the first Route and set our URL to &quot;/about&quot;. What would we expect? We would expect the second Route to match and render the About component, right? However, the Home component will actually be rendered. Why does this happen?</p><p>React Router checks the current URL and starts from the topmost Route within the Switch structure, then goes downwards to find a match. If we don&#39;t use the exact keyword on &quot;/&quot; in the first Route, it essentially means &quot;render the Home component for any URL that contains /&quot;. Therefore, because &quot;/about&quot; contains &quot;/&quot;, the Home component will be rendered since it matches the topmost route.</p><p>To ensure that the About component renders when the URL is &quot;/about&quot;, we need to move the Route for &quot;/about&quot; above the Route for &quot;/&quot;. Alternatively, we can add the exact keyword to the Route for &quot;/&quot; to specify that we want to render the Home component only when the URL is exactly &quot;/&quot;.</p><p>In summary, using exact in React Router specifies that the path must match the URL exactly, without considering partial matches.</p><h3>Navigation (Link):</h3><p>So, how do we change the URL? We don’t manually type “/about” or “/profile” into the browser’s address bar. There are two ways to achieve this. The first method, as you can see in the application, involves using the Link components inside the navigation (Nav). These components come from React Router and allow us to change the URL using the to attribute. This triggers our routers and renders the desired component accordingly.</p><p>You can achieve the same using an &lt;a&gt; tag from HTML, but there&#39;s a crucial difference. If you use an &lt;a&gt; tag instead of the Link component provided by React Router, yes, you can change the URL and trigger the routers to render the desired component. However, the significant point here is that when you change the URL using an &lt;a&gt; tag, you&#39;ll notice the page refreshes. On the other hand, when you navigate using the Link component, the page won&#39;t refresh. You can observe this non-refresh behavior in the top left corner of the video below. I changed the URL to &quot;/about&quot; using an &lt;a&gt; tag, and whenever I click on &quot;About&quot; to go to &quot;/about&quot;, the page refreshes. This doesn&#39;t happen with the Link components, which is what we want.</p><p>The two biggest differences between the Link component and the &lt;a&gt; tag are as follows: First, the &lt;a&gt; tag refreshes the page and sends a new request to the server, whereas Link uses the History API to facilitate transitions between components without making a new request. This efficiency can lead to significant resource savings.</p><p>The second benefit, which is closely related to the first, is that when using the &lt;a&gt; tag, the page refresh and server request cause the loss of current state (such as form input values entered by the user). However, with Link, this state is preserved.</p><p>In essence, when dealing with routing, it’s advisable to use Link for these reasons.</p><h3>useHistory :</h3><p>Now, you might wonder, “Can I only use Link when redirecting users to other routes? For example, after a user fills out a login form, can&#39;t I redirect them to &quot;/&quot; if they successfully log in without clicking any Link ?&quot; As you&#39;ve rightly guessed, of course you can do that. However, there are slight differences between React Router v5 and v6. Since I&#39;m using v5 in this article, I&#39;ll use the useHistory hook. Readers using v6 can refer to the &lt;Redirect /&gt; component in the React Router documentation.</p><p>The useHistory hook is used as follows: In the simple login function depicted in the image below, I&#39;ve written a basic login function. First, to use the useHistory hook, we declare const history = useHistory() on line 6. The useHistory hook returns an instance of history, allowing us to perform operations using history. When the button is clicked, it sends a POST request to &quot;<a href="http://localhost:3000/login">http://localhost:3000/login</a>&quot;. If the backend returns true, we redirect the user to the home page by using history.push(&quot;/&quot;).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ih_1Ok15c5j4QEPooRduA.png" /><figcaption>useHistory</figcaption></figure><h3>Dynamic Routing :</h3><p>Lastly, let’s talk about the third router. Here, there’s something different with “items/:id”. The colon “:” at the beginning of “id” indicates that this word is a placeholder, meaning something will come here (in this case, an item ID), and you can capture that incoming thing with the word “id”. Looking back at our navbar, our last three links are “items/1”, “items/2”, and “items/3”, so in these URLs, :id has been replaced with 1, 2, and 3.</p><p>In this “items/:id” route, we said that if this route is called, the ItemDetails component should be rendered. But I want the content of this component to be dynamic. That is, according to the ID of the item in the URL, the content of ItemDetails should change. For example, I will print the ID of the item on the screen. To achieve this, we will use the useParams hook from React Router. This hook is used as shown in the image to capture a value from the URL. As we mentioned earlier, we will use &quot;:id&quot; to capture this value, and here by saying const {id}, we capture the ID from the URL and render it inside a &quot;p&quot; tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4_ujdRAPXXJeJk6vv-8HQ.png" /><figcaption>useParams</figcaption></figure><p>Why would we need something like this? In fact, we have a great need for it, and we use it every day. For example, imagine you’re browsing an e-commerce site and click on a product. The URL changes, and the corresponding component renders. If we were to create a separate component for each product while managing millions of products, it would not only be incredibly difficult, even impossible, but also highly impractical.</p><p>That’s why we create a single component called “Product” and use useParams to capture the ID of the product from the URL we clicked. This way, instead of creating separate components like &lt;ItemOne /&gt;, &lt;ItemTwo /&gt;, &lt;ItemThree /&gt; for routes like &quot;items/1&quot;, &quot;items/2&quot;, &quot;items/3&quot;, we dynamically render the &lt;Item /&gt; component using the ID from the URL with useParams. This approach allows us to solve the problem dynamically with just one component, handling potentially millions of items.</p><p>While I haven’t covered React Router library in its entirety, I’ve explained everything necessary to understand its general concept. Now, we can move on to the main topic.</p><h3>Part 2 — App Router:</h3><p>The purpose of using NextJS’s App Router is the same: to handle routing within the application. However, NextJS has implemented this functionality uniquely and seamlessly integrated it into the framework itself, rather than offering it as a separate library.</p><p>I’m starting a NextJS project from scratch to examine this. I’m using the command npx create-next-app@latestand answering the questions as shown below. This project is for testing purposes, so I opted not to include ESLint and TypeScript, which I would typically install for a regular NextJS project setup.</p><p>I also chose not to create an “src” folder because I don’t need additional folders like components or services for this demonstration. Our main focus here is on the App file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXLGRjc-2Dws-zSxJuKnHQ.png" /></figure><p>As you can see, here’s a NextJS application in front of me. I’ve emptied the contents of the page.js file inside App and returned an h1 element. When I open the application, this will appear because this page.js corresponds to my “/” URL in the App Router. You’ll understand this in more detail shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jUHmtqJuaoUquaJ0mh_PA.png" /></figure><p>Now, I want you to look into the app folder. What you’re looking at is our router. Yes, you heard that right. Each folder inside the app folder corresponds to a Route within our switch structure. This means that to create a new route, all we need to do is create a new folder under the app folder, such as a folder named “home”.</p><p>When we create the “home” folder, we now have a “/home” route. However, for this route to render something on the screen, we create a file named page.jsx inside the home folder. This follows a rule, so don’t create a file with a different name; the App Router will look for a file named “page” to render output for the “/home” route.</p><p>Creating a route is quite easy, isn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*5_YC_DwC6Lujxn7MklFiyw.png" /><figcaption>Nextjs App Router Tree</figcaption></figure><p>Got it. Let me explain again with another example. When we create a folder named “login” under the app directory, we automatically establish a “/login” route. So, whenever we enter “/login” in the URL, what gets rendered on the screen is determined by the contents of page.jsx inside the “login” folder.</p><h3>Layout:</h3><p>Alright, what about layouts? If you have a piece of code that you’ll use repeatedly under every route within a specific route, you can place that piece of code in a layout. This way, it can affect all routes under that specific route. Each layout file accepts children as a prop, which represents the component underneath it. The layout renders this component on the screen and allows us to add content above or below children. If this sounds confusing, let me explain with an example from below.</p><p>As you can see, under my app directory, there are folders named home, about, and login, each containing a page.jsx file. This means I have routes for “/login”, “/home”, and “/about”.</p><p>Each route can have its own page file as well as its own layout file, but generally, we don’t add a layout to every route unless it’s necessary. In this example, under the app directory (“/”), I’ve added “LAYOUT” above children in layout.jsx. Let me explain what happens in this case. Unless stated otherwise, we&#39;ll see the &quot;LAYOUT&quot; text across all routes under the app directory. For instance, in the page file under the home route, I&#39;ve written &quot;Home&quot; without adding anything like &quot;LAYOUT&quot;, but when navigating to &quot;/home&quot;, &quot;LAYOUT&quot; appears above &quot;Home&quot;. Why? Because in the top-level layout file, which is in the app directory, I&#39;ve returned the text &quot;LAYOUT&quot; above children in its render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6z9SGqZtk-ng3cOMAKTGSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*l0mt9bxI25LlweGDXI01Xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94NsEQtqfV9tar-zBdRJTA.png" /><figcaption>App Router Layout Example</figcaption></figure><p>However, now we have a problem: I want “LAYOUT” to appear across all routes, but specifically for the home route and its children routes (like profile), I want “HOME LAYOUT” to be displayed as well. If I add “HOME LAYOUT” directly to the layout.jsx file under the app directory, it will appear not only for the home route and its children but also across all routes. I only want this for the home and its children routes. Let me explain this with an example.</p><p>As you can see, I’ve created a profile route under the home route. Inside the home folder, I’ve created a layout.jsxfile and added “HOME LAYOUT” above children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDXgnvesN9AGZP0qQNONNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*Y4cTwmR21P9ibYI7DIS4Pg.png" /><figcaption>Profile Layout</figcaption></figure><p>As you can see in the screenshot above, when navigating to “/home/profile” route, first the text “LAYOUT” from the top-level layout in the app route hierarchy was displayed. Then, the layout under the home route displayed “HOME LAYOUT”, and finally, the page.jsx under the profile route returned the text “Profile” to be rendered. As observed, I see three different texts on the screen.</p><p>Where and how can we use this feature? What purpose does it serve? To put it simply, is there a better place than the top-level layout in the hierarchy to place a navbar? Once I write my navbar above children in the top-level layout, I can see this navbar across all routes without needing to write it in each page.jsx. The same can be said for a footer as well.</p><h3>Route Groups :</h3><p>But this might create another issue. While it’s nice to write the navbar once and avoid rewriting it, you might not want a navbar or footer on the login page. So, what do you do?</p><p>There are many ways to handle this, but I’ll show you what I think is the most appropriate, and in doing so, we’ll also discover a new feature. We can solve this problem using what we call “Route groups”.</p><p>Our goal is to prevent the navbar or footer from appearing on the login page, while ensuring they appear on all other pages. We don’t want to add the navbar and footer to every page.jsx file, so we’ll use layouts to achieve this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJ3eD_DzlO8N3p3RCd424g.png" /></figure><p>Here’s how we solved the problem as seen in the above image. What did we do here? Firstly, we see things like “(auth)” and “(others)”. These are called route groups. These parentheses allow us to group routes within routing without creating a route like “/(auth)” — we still have “/login” but within a group.</p><p>Additionally, we took what we wrote in the top-level layout within the “app” folder hierarchy and placed it into the layout we created inside the “login” folder. This way, while we still obtain the same appearance in the home route, we achieve the following appearance in the login route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*l5GF0o7pZ__R2ZL8KraIcQ.png" /></figure><h3>Dynamic Routes:</h3><p>If you remember our example with React Router, I’ll explain how to achieve the same using App Router in Next.js. For those who haven’t read about React Router, let me recap the example we’re going to implement. Imagine we have an e-commerce website with thousands of different products. When a user clicks on a product, we want them to be directed to a page showing the specific details of that product. There are two ways to achieve this:</p><ol><li><strong>Static Routes for Each Product</strong>: We could create separate components and routes for each product, as shown in the first image below.</li><li><strong>Dynamic Route Approach</strong>: Alternatively, as shown in the second image below, we can create a dynamic route where URLs like “/item-details/1”, “/item-details/2”, “/item-details/3” all render the same page component, but the content of the page changes based on the ID provided in the URL.</li></ol><p>This approach allows us to handle potentially thousands of products without creating separate components and routes for each one.</p><p>Now, let’s see how we can implement this using App Router in Next.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*u5w2pXGC4CNps-MUPOCTwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*EMcYKxlm_uN3vhBrpUYDrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5z31jEXcdxp__zZckw3SuQ.png" /><figcaption>useParams</figcaption></figure><p>As seen in the code above, we create the “item-details” route and below it, our [id] route, without creating thousands of components. You can also see “slug” mentioned here, which is a general term. In the page.jsx file under [id], I used the useParams hook to capture the value from the URL and displayed it on the screen. If you used [slug], you should use const {slug}. You need to match what is specified in the route to capture it correctly.</p><p>As shown in the two images below, all we do is change what comes after “/item-details”. This allows us to immediately see the output on the screen change. In other words, there’s no need to create another component or route.</p><p>How can we use this feature on our e-commerce page? After capturing the product’s ID in the URL, we can fetch details like the product’s image, name, price, etc., from the backend using the ID. This enables us to display the product details on the screen without creating individual routes and components for thousands of products. We’ve handled our task with just one route and component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*4m8Lm2WiMuSG_jBKbTLbZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*E7vX2lNTfno47p2oTOk6tw.png" /><figcaption>Dynamic Routing Example</figcaption></figure><h3>Navigation:</h3><p>Alright, we’ve talked about App Router quite a bit, but I still navigate to routes by manually typing URLs into the browser’s address bar. Isn’t there something like Link in React Router? Of course, there is, and it’s named the same.</p><p>As you can see in the code snippet below, we have the usage of Link on line 26. When this link is clicked, we are directed to the “/register” route. However, to navigate to other routes, it’s not necessary to click somewhere. As shown in the handleClick function, I’ve created a mock fetch function for “/api/login”. If this function returns “http status ok”, then we navigate to the home route using the “router.push(“/home”)” command. However, to use this, we need to call the useRouter function at line 6 to create an instance. Through this instance, we handle navigation.</p><blockquote>However, useRouteris only valid for client-side components. If you want to perform navigation in server-side components, you should use the Redirectcomponent. Please visit App Router Docs for more info about Redirect.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRjjQBUClj4zGpnLZIpVAg.png" /><figcaption>useRouter</figcaption></figure><h3>More To Learn:</h3><p>Up to this point, I’ve covered the fundamental and frequently used aspects. In this section, I’ll briefly discuss some remarkable features that I don’t always use but find impressive. For more detailed information, you can refer to the NextJS App Router documentation.</p><h3>Creating Custom Loading, Error and Not Found pages:</h3><p>Creating a route can be as simple as creating a folder named “login”. Thanks to the App Router, setting up custom error and loading screens is equally straightforward. All you need to do is create files named error, not-found, and loading just like you would with a page, and then return the desired view from these files. This makes building custom pages much easier.</p><p>For example, as shown in the images below, when I encounter a “not found” error, I can specify exactly what I want to display in the not-found page. Now, whenever a &quot;not found&quot; error occurs, I see the content I defined.</p><p>The same approach applies to the loading and error pages. Although I&#39;m demonstrating this with the not-found page since it&#39;s the simplest to illustrate, the principle is the same for the others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWqOgHv0EVlgwSs1FgyHsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*TJb5K77k4Srx5D1Te6OqtA.png" /><figcaption>I’m typing “/noooooooo” to URL and it returns me “not found” error</figcaption></figure><h3>Private Folders:</h3><p>Remember Route Groups?<strong> </strong>They allowed us to organize our routes and provided a more structured routing system. Typically, we would place routes like login and register under a group such as (auth), and these would become part of our routing structure.</p><p>But what if we have code that we don’t want to be part of a route? For example, suppose I have a utils.js file where I keep some helper functions. Initially, I might think to store this file in a folder named lib inside the app directory. However, this would unintentionally create a /lib route, even though there&#39;s no page file within it and I don&#39;t intend to display anything from this folder.</p><p>To handle such scenarios, NextJS provides a feature called <strong>private folders</strong>. By prefixing the folder name with an underscore (e.g., _lib instead of lib), the folder and its contents are excluded from the routing system. This means that our utils.js file can be safely stored in _lib, without turning it into a route. This keeps our helper functions private and ensures they don&#39;t interfere with our application&#39;s routing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*rKEwbtx9YV6wBaLuzLvPOQ.png" /></figure><h3>Parallel Routes:</h3><p>Parallel routes are used when we want to render multiple routes on the same screen simultaneously. This might sound a bit complex, so let me break it down with an example.</p><h4>Scenario: Building a Social Media Page</h4><p>Imagine you’re developing a social media site. On your main screen, you have a scrollable feed of posts — let’s call this the home page. Additionally, you have a section for stories at the top and a sidebar on the right showing online friends.</p><p>You could code all these components directly into the home page. That way, when you navigate to the home route, it would display posts, stories, and friends all together.</p><h4>The Challenge of Organizing Code</h4><p>However, this approach might clutter your home page, making it harder to manage. You might want to separate the code into different folders for better organization. But you don&#39;t want to create separate routes like /stories or /friends, as these don&#39;t make sense on their own without the context of the home page.</p><h4>Solution: Using Parallel Routes with Slots</h4><p>Here’s where NextJS’s App Router and <strong>slots</strong> come to the rescue:</p><ol><li><strong>Creating Slots:</strong></li></ol><ul><li>Create a folder named @stories and place a page.jsx file inside it.</li><li>Similarly, create a folder named @friends and add a page.jsx file there.</li><li>By prefixing these folders with @, you designate them as slots. This prevents them from automatically becoming standalone routes like /stories or /friends.</li></ul><p><strong>2. Integration into Layout and Page Components:</strong></p><ul><li>As seen in the images below, I have two slots (@friends and @stories) alongside a layout and a page component. This page file represents my home page.</li><li>In my layout file, I capture these two slots and nest them under the children of the page component.</li><li>As shown in the final image, all components appear together under the /social route, despite being in separate files. This approach enhances code organization and simplifies development.</li></ul><p><strong>3. Benefits of Using Slots:</strong></p><ul><li>When each feature is separated into slots, you don’t need to wait for all slots to load to view the entire site. For instance, upon entering the home route, posts may load first, while stories are still in the loading phase, and the friends section has already loaded.</li><li>If an API error occurs and stories fail to load, a custom error page specific to the stories slot can be rendered. This flexibility enhances application robustness and user experience.</li></ul><p>By leveraging NextJS’s App Router and organizing components into slots, you can effectively manage and enhance the flexibility of your application while maintaining a structured and modular codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*HfZfKgdByV7cZ2mpxLLAmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oabc6pGjERT85Wp2WytDsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*RIRIt8it9rJYCCX2d0zHWg.png" /></figure><h3><strong>Using Intercepting Routes in Modals</strong></h3><p>Intercepting Routes is a powerful feature for creating modals, and I’ll give you an example of where and how it’s used. For detailed implementation, refer to the Intercepting Routes section on the NextJS App Router page.</p><h4>Scenario: Social Media Site Modal Example</h4><p>Imagine you’re on a social media site and you long-press on a photo. Without leaving the current page, the photo enlarges as a modal in the center of the screen, allowing you to view its description. All of this happens without navigating away from the current screen, achieved solely through manipulation of the App Router.</p><h4>Use Case: Modals with Intercepting Routes</h4><p>Intercepting Routes are typically used in scenarios like modals. Here’s how:</p><ul><li><strong>Triggering the Modal:</strong> When a user interacts with a photo (e.g., long-press), intercepting routes allow the application to display the photo details in a modal overlay.</li><li><strong>Modal Behavior:</strong> The modal appears on top of the existing content, providing a focused view of the photo and its description.</li><li><strong>No Page Navigation:</strong> This interaction occurs without navigating away from the current screen, enhancing user experience by maintaining context.</li></ul><h3>Conclusion:</h3><p>We’ve reached the end of the article where I compared App Router and React Router, highlighting the advantages of NextJS’s App Router. I didn’t delve into all the details of React Router, nor did I cover every feature of App Router, but you can continue exploring more in the NextJS App Router documentation.</p><p>In summary NextJS’s App Router offers us several conveniences:</p><ul><li>Integration into the application,</li><li>Ability to quickly create new routes,</li><li>Minimization of repetitive code with layouts,</li><li>Ease of managing routes with route groups,</li><li>Handling loading, not found, and error pages,</li><li>Implementing Intercepting Routes for modals,</li><li>Using Parallel Routes efficiently,</li><li>Utilizing Private Folders for code organization.</li></ul><p>There’s a lot to learn about NextJS. I recommend trying NextJS and discovering its powerful features for yourself. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad947e6f760b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>