<?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[Paktolus Engineering - Medium]]></title>
        <description><![CDATA[Paktolus Engineering is a hub for sharing insights, innovations, and expertise in software development, engineering, and technology. Explore articles on cutting-edge technologies, industry best practices, and creative solutions that drive digital transformation. - Medium]]></description>
        <link>https://medium.com/paktolus-engineering?source=rss----e48f673dd523---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Paktolus Engineering - Medium</title>
            <link>https://medium.com/paktolus-engineering?source=rss----e48f673dd523---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:25:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/paktolus-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Don’t Sacrifice your HI for AI]]></title>
            <link>https://medium.com/paktolus-engineering/dont-sacrifice-your-hi-for-ai-20d8539ed5ef?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/20d8539ed5ef</guid>
            <category><![CDATA[risk-mitigation-strategy]]></category>
            <category><![CDATA[information-technology]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[human-intelligence]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Maya Singh]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 13:17:07 GMT</pubDate>
            <atom:updated>2025-01-06T13:17:07.814Z</atom:updated>
            <content:encoded><![CDATA[<p><em>-by Maya Singh</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*WJVqODz6aDtOHvNaMOlj3Q.png" /></figure><p>According to Forbes, the Artificial Intelligence (AI) market is projected to reach a staggering $1,339 billion by 2030, experiencing substantial growth from its estimated $214 billion revenue in 2024. The primary reason behind this rapid adoption of AI, especially GenAI models, lies in its phenomenal ability to combine automation, intelligence, and prediction to improve daily life and business operations. It addresses increasing demands for faster results, better data analysis, and productivity. Yet, alongside its undeniable benefits, AI presents a spectrum of risks and concerns that must be addressed with vigilance. The desired relationship between Human Intelligence (HI), the creator of AI, and AI, is of mutualism where both parties benefit from each other, and not of parasitism where one thrives at the cost of the other. Like the mutual funds market, AI solutions should also be accompanied by a disclaimer statement, maybe something like, “Irresponsible usage of AI is subject to diverse risks, please be sufficiently aware before using.”</p><p><strong>GenAI</strong></p><p>A category of AI that generates content based on natural language prompts in the form of text, images, or audio is known as Generative AI. All widely used large language models (LLMs) like ChatGPT, Gemini, Claude, Copilot, Llama, etc. fall into this category of AI. These models are trained on vast datasets using self-supervised learning techniques to operate on deep learning principles, leveraging neural network architectures to process and understand human languages. They are enabled to engage in natural linguistic conversations with humans, basically to behave as humans. The end goal of these models is to develop human-level cognition and completely mimic human intelligence and behavior.</p><p>Generative AI learns from teaching, training, and experiences, thus making decisions based on stored memories and thought processes which are generated as per the datasets it got trained upon. It can also remember and perceive its surroundings, allowing it to develop and study patterns and continuously keep learning from them, opening a doorway to numerous risks.</p><p><strong>Risk and Concerns</strong></p><p>1. Misinformation:</p><p>All LLMs are prone to developing a fake sense of intuition wherein they perceive patterns that do not exist and have no real-world context, hence generating nonsensical results, popularly termed “AI Hallucinations.” It will just make things up which often arises due to incorrect or incomplete training data. Research shows that over 75% of consumers are concerned about misinformation from AI.</p><p>This raises serious concerns about reliability and reinforces that one must not solely depend on the results provided by these tools. Human oversight is critical in this case, and all the outcomes must be thoroughly cross verified before using.</p><p>2. Inaccuracy:</p><p>Although these frequently used models are trained on huge petabytes of datasets, this does not guarantee them to be error-free. There are recorded instances of models struggling to perform basic mathematics tasks, providing content with numerous spelling errors, and generating variable inconsistent outputs, largely due to misinterpretation of training data. These incorrect results if used as it is without monitoring, might lead to a domino effect of inaccurate reports.</p><p>It’s vital to ensure a human is always in the loop to double-check outcomes.</p><p>3. Lack of Transparency:</p><p>A wide variety of information is now just a prompt away, but users are often unaware of how these systems collect, process, save, and use their data leading to major violations of privacy expectations. No information is shared whether a proper data life cycle management process/policy is in place or not which raises concerns of trust issues with sensitive personal and company data. We must practice asking ourselves a simple question before uploading any data on these AI platforms — I am providing too much information?</p><p>In addition to this, we are also unable to see how deep learning models arrive at their decisions not allowing us to trace their thinking process, thus making it a mysterious “black box”. This opaqueness prevents users from making well-informed decisions and utilizing these tools with the much-required scrutiny. Drawing necessary boundaries while using AI is essential to maintain trust and accountability.</p><p>4. Surveillance Risks:</p><p>While personalization is useful in industries such as healthcare and hospitality, AI-driven hyper-personalization can be alarming. We all must have experienced receiving product/service recommendations based on our past search history, combined with AI and real-time consumer data, this process is made even more granular by studying consumer moods and patterns to influence decision making.</p><p>This type of unconsented user profiling done on the bedrock of intrusive surveillance, data analytics and constant monitoring is a threat to human agency and conscious decision making. Strong oversight mechanisms and ethical guidelines must be adopted at organization and individual levels to effectively mitigate this risk.</p><p>5. Security and Privacy Threats:</p><p>GenAI solutions are often referred to as a “double-edged sword” as on one hand they offer exemplary innovation, while on the other hand, they also expose users to massive cybersecurity and privacy risks. Owing to its lack of data usage transparency and black box effect, confidential and personally identifying information is susceptible to unwanted disclosures. In addition to this, these widely used platforms are vulnerable to prompt-injection attacks, wherein ill-meaning inputs may cause large language model chatbots to expose data that should be kept private or perform other actions that lead to data compromises. One needs to be extremely careful before uploading files which contain vital information about self or an organization as privacy is truly a myth in the age of AI.</p><p>A thorough risk assessment must be conducted to ensure that chosen AI solutions are in alignment with organizational needs and comply with data regulation policies. Organizations like Apple and Samsung, for instance, have banned the internal use of ChatGPT, especially by the software development team after realizing that potentially sensitive code had been uploaded to the platform, risking the loss of confidential company information.</p><p>Regular audits will help mitigate privacy risks and protect personal and confidential data. Practices like anonymizing and encrypting sensitive user/customer data before uploading it onto the open AI platforms should be followed to prevent privacy breaches and unauthorized access.</p><p>Just like the evolving nature of this technology, these mitigating strategies must also evolve along with creating awareness, GenAI demystifying, and training opportunities for all.</p><p>6. Legal Concerns:</p><p>Prompt-based LLMs seem magical, creating lengthy reports, essays, stunning images, etc. in the blink of an eye. But who owns these outcomes? Several reports suggest that these responses include copyrighted content without permission raising concerns of data ownership and intellectual property rights infringement. Moreover, when AI systems err, determining responsibility becomes a murky territory.</p><p>Implementation of robust data verification and data protection policies is the need of the hour, more than ever.</p><p>7. Misuse:</p><p>Numerous videos are circulating on social media showcasing public figures speaking about something, which they never did! These are known as “Deepfakes” wherein hyper-realistic fabricated media is created using AI, mimicking someone to spread false or misleading information that can influence public opinion. These videos not only discredit individual identity but also are a major threat to public safety due to their persuasive nature. In addition to this, these tools can also be used to create ill-motivated harmful content. Additionally, the weaponization of AI in the form of autonomous drones or military systems raises fears of an arms race where machines, not humans, dictate critical decisions. Such developments could lead to catastrophic consequences if left unchecked.</p><p>The application of human values and ethical principles is vital to protect our social fabric from such incidents.</p><p>8. Biased Outcomes:</p><p>AI systems often inherit biases embedded in their training data, called as “AI Bias”. These biases can result in discriminatory outcomes which can skew decisions towards a particular direction. For instance, algorithms might unfairly disadvantage certain groups based on race, gender, or socioeconomic status, perpetuating systemic inequities. This highlights serious ethical and moral concerns associated with this technology.</p><p>The outcomes generated should always be overlaid by human expertise for objective and fair decision-making.</p><p><strong>Human Factor</strong></p><p>Although AI offers astounding benefits, overdependence on it can erode humans of the very traits that make them human. Essential skills like creativity, communication, language competency, critical thinking, and problem-solving are under threat due to the dopamine kick generated by instant results from these machine systems. Additionally, excessive dependence on digital assistants and automated systems could lead to a society where human effort and ingenuity are undervalued.</p><p>Unrestricted interaction with AI systems also risks fostering emotional detachment, as artificial ones replace human connections. This raises existential questions about the role of AI in shaping human identity and relationships. Just like how a low-calorie diet is followed to achieve certain health goals, it is important to follow a “low prompt diet” to protect ourselves from “prompt addiction.” Also, it must be noted that emotional intelligence is the core of human intelligence that enables collaboration, effective leadership, adaptability, better customer service, and ethical decision-making. No matter how advanced AI becomes, and no matter the safeguards or lack thereof, it can never “truly” replicate or match humanity’s ability to feel, experience, and express emotions.</p><p>HI should not be mortgaged to harness the advantages of AI. Thorough checks and balances must be implemented to ensure that we are the ones using the technology and not getting used by it instead.</p><p><strong>Way Forward</strong></p><p>While Artificial Intelligence promises to revolutionize every aspect of our lives, human intelligence must remain the guiding force for striking the right balance. Used responsibly, guided by ethics and a sense of purpose, it surely is a powerful tool that can be used to augment human capabilities. By proactively addressing risks and concerns, we can harness AI’s potential safely, thus creating a future where technology empowers humanity without overshadowing it. Emphasizing collaboration between humans and machines can maximize benefits while minimizing risks. The eventual goal must be a harmonious coexistence where AI serves as an ally, not a master.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20d8539ed5ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/dont-sacrifice-your-hi-for-ai-20d8539ed5ef">Don’t Sacrifice your HI for AI</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Most commonly found Vulnerabilities in Web Applications.]]></title>
            <link>https://medium.com/paktolus-engineering/most-commonly-found-vulnerabilities-in-web-applications-01dfb54530e2?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/01dfb54530e2</guid>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[web-vulnerabilities]]></category>
            <category><![CDATA[bug-bounty-writeup]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[vapt-services]]></category>
            <dc:creator><![CDATA[Jay Shankar]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 04:40:59 GMT</pubDate>
            <atom:updated>2025-01-03T19:46:16.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGJHB-3n8hAAPTmKx2h5fQ.png" /></figure><p>React.js, Next.js, and Express.js are widely used frameworks for developing dynamic, modern web applications. While these technologies offer powerful tools for developers, they do not inherently guarantee the security of an application. It is essential to understand and address common vulnerabilities within this technology stack to ensure the development of secure and resilient software.</p><blockquote><strong>Cross-Site Scripting (XSS) Attacks:</strong></blockquote><p><strong>Reflected XSS (via GET Parameters):</strong><br> Reflected XSS attacks occur when malicious scripts are injected through URL parameters (GET requests). These scripts can steal sensitive data, such as cookies, or redirect users to attacker-controlled websites with minimal user interaction. This vulnerability is typically considered a medium to high-level threat and is exploited through improperly sanitized GET parameters.</p><p><strong>Stored XSS (via POST Parameters):</strong><br> Stored XSS attacks are more severe, injecting malicious code through POST parameters, which are then stored in a database. When this data is retrieved and displayed on the front end, the malicious payload is executed. This can lead to the theft of cookies, session hijacking, or redirection to malicious websites, often with no user interaction required. Stored XSS is considered a high to critical-level vulnerability and requires strong input validation and output encoding mechanisms to mitigate.</p><p><strong>Example payload to test for Cross-Site Scripting Attacks:</strong></p><p>· To create a popup alert: “&gt;&lt;img src=x onerror=alert(3);//&gt;</p><p>· To redirect a user to other domains: “&gt;&lt;img src=x onerror=location.replace(“https://attacker-controlled-domain”);//&gt;</p><p><strong>Use Case Scenario: Cross-Site Scripting (XSS) Vulnerabilities in GET and POST Parameters</strong></p><p>In both GET and POST request methods, web applications may be vulnerable to Cross-Site Scripting (XSS) attacks if user-supplied data is not properly validated and sanitized. This can occur when an attacker injects malicious script code into a parameter value that is later reflected or stored by the server and executed on the client side.</p><p><strong>Proof Of Concept:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xceyvrhReWQaI1Tx_JYJxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXXvM9cK4LnI5EhJ1dV2OA.png" /><figcaption>Cross Site Payload that is being executed based of the malicious user input.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDLD_PwGWtcQvjdCzdAbaQ.png" /></figure><p><strong>Solution to Prevent Cross-Site Scripting (XSS) Attacks</strong></p><p>The most effective way to mitigate Cross-Site Scripting (XSS) attacks is to <strong>HTML encode</strong> user input before storing it in the database. This process ensures that any potentially harmful scripts are treated as plain text, rather than executable code. By encoding user input, the application safeguards against the execution of malicious payloads when data is retrieved and rendered on the frontend.</p><ul><li><strong>Input Sanitization and Encoding:</strong> When accepting user input, it is crucial to sanitize and encode special characters (e.g., &lt;, &gt;, &amp;, and &quot;), transforming them into their respective HTML entities. This prevents the input from being interpreted as HTML or JavaScript by the browser.</li><li><strong>Storage and Retrieval:</strong> By storing the encoded data in the database, you ensure that any potentially dangerous input is stored as harmless text. When the data is retrieved and rendered on the frontend, the encoded characters are displayed as intended — without triggering any scripts or payloads.</li></ul><p>This approach nullifies the risk of <strong>stored XSS attacks</strong>, as the payloads stored in the database are never executed when the data is displayed to the user.</p><blockquote><strong>Indirect Object Reference (IDOR) Vulnerabilities:</strong></blockquote><p>Indirect Object Reference (IDOR) vulnerabilities occur when an attacker can access or modify data that they should not be authorized to view, typically by manipulating parameters, such as auserId, in the URL or request. These vulnerabilities arise when an application does not properly validate whether the requesting user has permission to access the specified resource.</p><ul><li><strong>Attack Mechanism:</strong> An attacker can often exploit IDOR by modifying the userId parameter (or a similar identifier) to reference the account or data of another user. In many cases, attackers may attempt to brute-force the userId values, particularly when there is no specific target in mind and the attacker is simply trying to access data indiscriminately. This can lead to unauthorized access to sensitive user information.</li><li><strong>Example:</strong> An attacker could change the userId=123 parameter in a request URL to userId=124, allowing them to retrieve another user&#39;s data, if the application does not adequately enforce authorization checks.</li></ul><p><strong>Authentication and Authorization Issues in APIs:</strong></p><p><strong>Lack of Authentication on API Endpoints:</strong></p><p>In many cases, API endpoints are not properly secured, allowing attackers to access sensitive information without proper authentication. This leaves the API exposed, with the potential for unauthorized users to exploit it. If sensitive data, such as personal information or credentials, is exposed through these unprotected endpoints, attackers can easily steal or manipulate this information.</p><p><strong>Authorization Bypass (Privilege Escalation):</strong></p><ul><li>Even if API endpoints require authentication, they may not properly check if the authenticated user has the appropriate authorization to access specific resources. For instance, a normal user might be able to access admin-level endpoints if the application only checks for authentication and not for the user’s roles or privileges.</li><li><strong>Example:</strong> A user who is authenticated could, inappropriately, access an endpoint designed for administrators by simply knowing the endpoint URL, even though they do not have the necessary privileges to perform such actions.</li></ul><p>In this example, we can see that just by changing the userId we are able to fetch data of other users.</p><p><strong>Proof Of Concept:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*cgkZG_5mUDNvzJo60qZLMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Qi-a6QxMNCeyKIGe62h6tw.png" /></figure><p><strong>Solution to Prevent IDOR’s</strong></p><p>To address this issue, developers should ensure that all API endpoints requiring access to sensitive data are protected by authentication mechanisms, such as JWT (JSON Web Tokens). These tokens should encapsulate both the user’s authentication and authorization details, enabling the server to validate not only the identity of the user but also their permissions to access specific endpoints. By enforcing token-based authentication and verifying the user’s roles and privileges, developers can effectively secure API endpoints and prevent unauthorized access.</p><blockquote><strong>Logical Bugs:</strong></blockquote><p>Business logic vulnerabilities are often subtle and challenging to identify, as they typically arise from flaws in the way an application processes input to generate output. In many cases, developers implement logic to automate certain processes without thoroughly validating or sanitizing user input before it is used. This oversight creates opportunities for attackers to exploit the system by providing unexpected input that bypasses intended controls.</p><p><strong>Example of Exploit:</strong> An attacker may manipulate a quantity field by entering a value like “0.1”, which could lead to a pricing error or unintended discount, resulting in financial gain. This is a classic example of faulty business logic, where improper validation allows users to manipulate critical application processes.</p><p><strong>Proof Of Concept:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5DwfnMRJtN29OPq9kW6-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*OWqwrUt7WI45erm519RhEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzIhVTPfuDITBTAixS06tA.png" /></figure><p><strong>A solution to the Problem:</strong></p><p>To address business logic vulnerabilities, developers should implement strict input validation rules to ensure that user-provided data matches the expected data types and formats. By validating input before processing, the application can enforce proper constraints and prevent unintended manipulation of business processes. This simple yet effective check will help eliminate logic flaws and ensure the application generates correct, expected results.</p><blockquote><strong>HTML Injection Attacks:</strong></blockquote><p>HTML injection attacks occur when an application fails to properly sanitize user input, allowing attackers to inject malicious HTML tags — such as &lt;a&gt; (anchor) or &lt;iframe&gt; tags—into the application. These injected tags can redirect users to attacker-controlled websites, expose sensitive information such as IP addresses, or perform other harmful actions. The injected HTML is often stored in the database through POST parameters, and when the affected content is later rendered, the malicious payloads are executed in the browsers of unsuspecting users. This creates significant security risks, as it enables attackers to exploit the application&#39;s trust in user-generated content.</p><p><strong>Payload:</strong> “&gt;&lt;iframe src=”https://attacker-controlled-domain.com”;//&gt;</p><p>Use case scenario: Use the payload in any post parameter where the value of the post parameter will be saved in the database.</p><p><strong>Proof Of Concept:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0ndHAzrn2aQe8-INdWdag.png" /></figure><p><strong>A solution to the Problem:</strong></p><p>To prevent HTML injection attacks, it is crucial to <strong>HTML encode</strong> user input before storing it in the database. This ensures that any potentially harmful HTML tags or scripts are treated as plain text rather than executable code. By following this workflow, the application can safely store and display user input, preventing malicious payloads from being triggered on the front end when the data is rendered.</p><blockquote><strong>Vulnerable and Outdated JavaScript Libraries and Frameworks:</strong></blockquote><p>Vulnerabilities often arise when developers use outdated JavaScript libraries and frameworks, focusing solely on achieving the desired functionality without considering potential security risks. These outdated libraries may contain known vulnerabilities or CVEs (Common Vulnerabilities and Exposures), which can be exploited by attackers to carry out malicious activities. Failure to regularly update and patch these dependencies exposes applications to security threats that can compromise their integrity and safety.</p><p><strong>Proof Of Concept:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwJzjv-ISvEMbinY77t-Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQgU9Sib4TmmMA4b6g2XLg.png" /></figure><p><strong>A solution to the Problem:</strong></p><p>To mitigate the risks associated with outdated JavaScript libraries and frameworks, always use the latest stable release of the framework or library in use. If an older version is necessary due to compatibility or other constraints, ensure that any security patches or updates addressing known CVEs (Common Vulnerabilities and Exposures) are promptly implemented. Regularly monitor for new security advisories and update dependencies as needed to reduce the potential for exploitation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01dfb54530e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/most-commonly-found-vulnerabilities-in-web-applications-01dfb54530e2">Most commonly found Vulnerabilities in Web Applications.</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Containers with a Read-Only Filesystem.]]></title>
            <link>https://medium.com/paktolus-engineering/running-containers-with-a-read-only-filesystem-f2456e0d8da8?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/f2456e0d8da8</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[readonly]]></category>
            <dc:creator><![CDATA[Arun Singh]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 04:38:40 GMT</pubDate>
            <atom:updated>2025-01-03T19:47:01.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yK6mZf3zQz8Yh6OIVg2rLw.png" /></figure><p>Let’s dive into how to run your application on a read-only filesystem container. In this blog article, I will explain how to run your container with the read-only option. Before we start, let’s explore the advantages and disadvantages of running containers with a read-only filesystem.</p><h4>Advantages</h4><p>1. <strong>Reduced Attack Surface</strong>: Running your application inside a container with a read-only filesystem means the application doesn’t have write access to the filesystem. If there’s an exploit in the application that a hacker could use to upload malicious scripts, this will be prevented because the application will fail to write files due to the read-only file system.</p><p>2. <strong>Immutable Infrastructure</strong>: Read-only containers promote the concept of immutable infrastructure, where containers are treated as disposable. Any changes are made by creating new containers rather than modifying existing ones.</p><p>3. <strong>Good for Audit and Reporting</strong>: Running containers with a read-only filesystem can help you pass security requirements. For example, AWS Security Hub checks if containers run with the read-only option. If they are not, your overall security score may be impacted.</p><h4>Disadvantages</h4><p>1. <strong>Debugging</strong>: There aren’t many disadvantages, but one notable issue is the difficulty in debugging containers during runtime. You might not be able to install debugging tools in read-only containers.</p><p>With these points in mind, let’s move on to the steps to run your container with a read-only filesystem.</p><h3>Running Containers with a Read-Only Filesystem</h3><p>Turning on the read-only option for containers across various platforms like Docker, AWS ECS, and Kubernetes is straightforward. You need to pass the correct argument. However, challenges arise when you start the container with a read-only filesystem. Your application might crash due to permission issues, as it won’t be able to access the filesystem to create necessary files during startup.</p><h4>Example with Docker</h4><p>To run a container in Docker with a read-only filesystem, use the — read-only option:</p><pre>docker run - read-only nginx</pre><p>Similarly, in a Docker Compose file, you can set read_only: true:</p><pre>services:<br> test:<br> image: busybox<br> read_only: true</pre><p>Kubernetes and AWS ECS also provide options for creating read-only containers.<br>Challenges and Solutions</p><p>Let’s take a basic container image, such as the Nginx image. Your application container might be more complex than Nginx, but the concepts remain the same.</p><p>When you run the Nginx image with a read-only filesystem, it will fail to start immediately because it cannot access certain temporary files like nginx.pid and client_temp.</p><p><strong>Example Error:</strong> Nginx fails to start as it is unable to create nginx.pid and client_temp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*QqFk0K4GW0US8wyUI2GMuQ.png" /><figcaption>docker run read-only</figcaption></figure><h4>Solution 1: Using –tmpfs</h4><p>You can use the — tmpfs option of the docker run command to provide temporary storage for the container:</p><pre>docker run - read-only - tmpfs /var/cache/nginx/ - tmpfs /var/run/ nginx</pre><p>This allows the Nginx container to start without crashing. However, there might still be errors related to other files, such as /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh being unable to modify /etc/nginx/conf.d/default.conf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*DVFV1IygRnmLuW_my-qxYg.png" /><figcaption>docker run read-only with tempfs</figcaption></figure><p>Since the — tmpfs option mounts tmpfs on the specified directory, it causes any existing files to be overwritten by the mount point. This can result in errors like 10-listen-on-ipv6-by-default.sh: info: /etc/nginx/conf.d/default.conf is not a file or does not exist.</p><h4>Solution 2: Using Dockerfile VOLUME Instruction</h4><p>In such scenarios, you can use the VOLUME instruction in the Dockerfile to build a custom Nginx image, which will mount a volume during startup. This approach prevents existing files from being overwritten.</p><p><strong>Note About Dockerfile Volume Instruction:</strong> Volumes are initialized when a container is created. If the container’s base image contains data at the specified mount point, that existing data is copied into the new volume upon volume initialization. (Note that this does not apply when mounting a host directory.)</p><p><strong>Dockerfile for Nginx with VOLUME Instruction:</strong></p><pre>FROM nginx:latest<br>VOLUME /etc/nginx/conf.d</pre><p><strong>Build and run this custom Nginx image:</strong></p><pre>docker build -t nginx:custom .<br>docker run --read-only --tmpfs /var/cache/nginx/ --tmpfs /var/run/ nginx:custom</pre><p>This ensures that Nginx runs without errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*E-YnRldu3DJtPwuHN1xv0Q.png" /><figcaption>docker run read-only tempfs and cache write directory</figcaption></figure><p><strong>Note:</strong> The — tmpfs option is available with docker run, docker-compose, and AWS ECS. However, AWS ECS with Fargate doesn’t support the — tmpfs option. For Fargate, you can use Docker volumes. <a href="https://github.com/aws/containers-roadmap/issues/736">Fargate option issue link</a>.</p><h4>Solution for Kubernetes: Using emptyDir</h4><p>In Kubernetes, you can use the emptyDir concept to get temporary write access space in a read-only container.</p><p><strong>Sample Kubernetes YAML with emptyDir Implementation:</strong></p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: test<br>spec:<br>  containers:<br>  - name: container<br>    volumeMounts:<br>    - mountPath: /tmp<br>      name: tmp<br>      subPath: tmp<br>    - mountPath: /run<br>      name: tmp<br>      subPath: run<br>  volumes:<br>  - name: tmp<br>    emptyDir:<br>      medium: Memory<br>      sizeLimit: 64Mi</pre><h3>Additional Challenge: Identifying Required Write Access Directories</h3><p>One more challenge arises when you plan to convert your application to a read-only container: how to find which directories are required for your application to write access for it to work properly.</p><p><strong>Solution for This Problem:</strong></p><p>You can use the docker diff command. Docker keeps a record of all files and directories created or modified by your application after the container started. So you can run your application in write mode, use all features, and then run the docker diff command against your container. This will produce a list of all files and directories created and modified. You can use this information to plan your journey to go read-only containers.</p><p>You can use tmpfs and Dockerfile Volume instruction combined to fix issues where your application needs write access to specific directories.</p><p><strong>Example:</strong></p><p>Below is the output of the docker diff command for one of the applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*tkdiVUgGzXY290SCWzbJZw.png" /><figcaption>docker diff command</figcaption></figure><p>You can use this information to adjust your Docker configurations accordingly. As you can see cache folder we can use tmpfs as that is mostly empty folder created after container starts but any folder which might have file already for that we can use Volume in Dockerfile.</p><h3>Conclusion</h3><p>Running containers with a read-only filesystem enhances security and promotes immutable infrastructure. However, it introduces challenges such as permission issues and difficulty in debugging. Using options like — tmpfs, Dockerfile VOLUME instructions, and Kubernetes emptyDir can help overcome these challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2456e0d8da8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/running-containers-with-a-read-only-filesystem-f2456e0d8da8">Running Containers with a Read-Only Filesystem.</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with NEXT.JS 14]]></title>
            <link>https://medium.com/paktolus-engineering/getting-started-with-next-js-14-8178ce875a56?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/8178ce875a56</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[faizan shaikh]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 19:48:16 GMT</pubDate>
            <atom:updated>2025-01-03T19:42:59.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjYc6Ic1UIwb55enWCB1LQ.png" /></figure><p>As we know, Next.js which is built on top of React. So, what sets Next.js apart from React?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*WGAmHyS5IPjuIe2abYGWNg.gif" /></figure><p>Before we dive in, let’s briefly understand the difference.</p><p>When we first start with React, we often come across the statement <em>“React is a library and not a framework”,</em> which may not make sense at first.</p><p>But, this is where all of it begins.</p><p>According to the definitions,</p><blockquote>A library is a pre-written module that a developer can use to accomplish common tasks more efficiently.</blockquote><p>This is exactly what React does. Back in the early days of frontend web development, adding even a single element dynamically to a page required a lot of explicit code and a significant amount of effort. However, with React, this same task can be accomplished swiftly without the need for explicit coding, all thanks to its declarative nature. Just provide the structure and content, and React handles the rest, including DOM manipulation.</p><p>But the issue here is that React is primarily focused on certain aspects of the application, such as front-end UI components. Even basic features like page navigation require an additional package. It only offers solutions for the UI, while the developer has to handle the rest.</p><p>On the other hand,</p><blockquote>A framework provides similar capabilities to libraries, but with added features. It enforces code standards and conventions, abstracting repeated boilerplate code and complex low-level details.</blockquote><p>This is where Next.js comes in. It’s built on top of React, offering access to all of React’s features, along with many additional features. For example, it offers static and dynamic rendering options (basically SSG and SSR), file-system based router, built-in optimization for images and fonts, built-in support for CSS modules, and more. Additionally, it provides a “Route Handler” to create API endpoints and perform server-side logic inside the Next application.</p><p>😅 Yeah, I know all of that feels like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*z8InsfUYiekLUOT-4hp86Q.gif" /></figure><p>In a nutshell, frameworks like Next.js streamline the development process by providing nearly everything out of the box, allowing developers to focus more on building instead of managing all the puzzle pieces, unlike libraries such as React.</p><p>There’s no right or wrong choice between Next.js and React. With React, the developer has more control, while with Next.js, the framework has more control.</p><p>Alright, let’s get started on setting up the Next.js project.</p><h3>Pre-Requisite Knowledge</h3><p>It just require a basic understanding of HTML, CSS, JavaScript, and React.</p><h3>Installation</h3><p>Open the terminal, navigate to the folder where you want to locate your project, and run the following command.</p><pre>npx create-next-app@14.2</pre><p>It will give the following options to choose from</p><pre>What is your project named? my-app<br>Would you like to use TypeScript? No / Yes<br>Would you like to use ESLint? No / Yes<br>Would you like to use Tailwind CSS? No / Yes<br>Would you like to use `src/` directory? No / Yes<br>Would you like to use App Router? (recommended) No / Yes<br>Would you like to customize the default import alias (@/*)? No / Yes<br>What import alias would you like configured? @/*</pre><p>Make sure to select all the options based on your preferences, but be sure to choose “<strong>Yes</strong>” for the “<strong>Would you like to use App Router?</strong>” option. This is the recommended approach for building a Next.js project, as it incorporates all the latest features that Next.js has to offer.</p><p>After completing all the installation steps, navigate to the project folder.</p><h3>Project Structure</h3><p>This is how the project structure will look, including all top-level folders and files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*VIPFYqPwNjF3hTV_alQuTg.jpeg" /></figure><p>We mainly work with only 2–3 folders,</p><ol><li>public — which contains all the static assets.</li><li>app — which is essential as it stores all the page files and handles the routing. Another folder we’ll manually add is</li><li>components— which we add manually, where all the individual component files are stored and later combined to build the UI.</li><li>Lastly, the node_modules directory contains all the dependency package files, and we don’t make changes to this folder. Only the npm command modifies this folder.</li></ol><h3>Let’s build a tiny project to understand things a little better.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5CNtFO1o11hDwBnu7gNOA.jpeg" /></figure><p>This is what we’ll build: a small e-commerce app consisting of four pages.</p><ol><li>Home— where we can view all the products.</li><li>Product Details — where we can view information about a specific product, choose a size and make a purchase or add the product to your bag.</li><li>Bag(basically a cart) — where we can view all the products added, see the total value, and proceed with the order.</li><li>Order Confirmed — where we can see that our order has been confirmed.</li></ol><h3>Creating Reusable Components</h3><p>Let’s start by creating a components folder. Inside the components folder, create a header folder with a header file and a footer folder with a footer file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*ENUuXJd9hYHT65aaoZ1g8w.jpeg" /></figure><p>Add the following code inside Header.tsx</p><pre>import Image from &quot;next/image&quot;;<br>import Link from &quot;next/link&quot;;<br>import bag from &quot;../../public/bag.svg&quot;;<br><br>const Header = () =&gt; {<br>  return (<br>    &lt;header&gt;<br>      &lt;nav className=&quot;header&quot;&gt;<br>        &lt;h1 className=&quot;logo&quot;&gt;<br>          &lt;Link href=&quot;/&quot;&gt;DeMo&lt;/Link&gt;<br>        &lt;/h1&gt;<br>        &lt;div className=&quot;bag&quot;&gt;<br>          &lt;Link href=&quot;/bag&quot;&gt;<br>            &lt;Image src={bag} alt=&quot;shopping bag icon&quot; /&gt;<br>          &lt;/Link&gt;<br>        &lt;/div&gt;<br>      &lt;/nav&gt;<br>    &lt;/header&gt;<br>  );<br>};<br><br>export default Header;</pre><p>and Footer.tsx.</p><pre>import Image from &quot;next/image&quot;;<br>import pc from &quot;../../public/pc.svg&quot;;<br>import next from &quot;../../public/next-logo.svg&quot;;<br><br>const Footer = () =&gt; {<br>  return (<br>    &lt;footer className=&quot;footer&quot;&gt;<br>      &lt;p className=&quot;flex items-center gap-1&quot;&gt;<br>        Made with{&quot; &quot;}<br>        &lt;span&gt;<br>          &lt;Image src={pc} alt=&quot;pc icon&quot; /&gt;<br>        &lt;/span&gt;{&quot; &quot;}<br>        using{&quot; &quot;}<br>        &lt;span&gt;<br>          &lt;Image src={next} alt=&quot;next icon&quot; /&gt;<br>        &lt;/span&gt;<br>      &lt;/p&gt;<br>    &lt;/footer&gt;<br>  );<br>};<br><br>export default Footer;</pre><p>There, we have created our first two component, everything in the code above seems familiar, similar to what we would have done in React. Except two things,</p><ol><li>We are using the next Link component instead of the regular HTML &lt;a&gt; anchor element which is the primary way to navigate between pages in Next.js and it also improves the performance of client-side navigation by prefetching and loading linked routes in the background, when the Link<strong> </strong>component comes into users viewport.</li><li>And, next Image component instead of regular HTML &lt;img&gt; image element, which helps with automatic image optimizations like serving correctly sized images for each device with modern image formats like webp and avif, preventing layout shifts when images are loading, etc.</li></ol><p>Now, we will use both of these components inside a special file called layout.tsx. Navigate to appfolder and you will find the file there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*Pb_D0CMb2ZamiXZxA3JNqw.jpeg" /></figure><p>The file name itself indicates its purpose. The layout file, created in the root of the app, is known as the root layout. It applies to all the routes, is required, and must contain html and body elements. This enables modification of the initial HTML returned from the server. Similarly, if necessary, we can create more nested layouts. Likewise, we can create nested routes in a similar manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*PYQ6ZGEOrqdhR1sfqfS3iw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*nOs4SyCrNqGkZ2zRY8QcNw.jpeg" /></figure><p>Add below code in the layout.tsx file.</p><pre>import type { Metadata } from &quot;next&quot;;<br>import { Inter } from &quot;next/font/google&quot;;<br>import &quot;./globals.css&quot;;<br>import Header from &quot;@/components/header/Header&quot;;<br>import Footer from &quot;@/components/footer/Footer&quot;;<br><br>const inter = Inter({ subsets: [&quot;latin&quot;] });<br><br>export const metadata: Metadata = {<br>  title: &quot;Demo&quot;,<br>  description: &quot;Demo app built using Next.js&quot;,<br>};<br><br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body className={inter.className}&gt;<br>        &lt;Header /&gt;<br>        &lt;main&gt;{children}&lt;/main&gt;<br>        &lt;Footer /&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>This will make the header and footer visible on all the routes.</p><h3>Getting Data For The Application</h3><p>Now, we need to access data for the application, typically located on the server, by making a request. In a traditional web development setup, a separate backend server would be created to handle API requests. This server would then execute the server-side logic and interact with a database to provide the necessary data. However, Next.js changes this approach with its built-in Route Handlerfeature. It allow developers to define server-side logic directly within their frontend application codebase, eliminating the need for a separate backend server.</p><p>We simply need to create a folder named api within the app folder and then add a file named route.ts. However, since we are working on an e-commerce app, we want to improve readability by creating an additional nested folder inside api called products, and then including a route.ts file within it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*dZi8zj2dVtiDFzNaYJxpPw.jpeg" /></figure><p>It supports the following HTTP methods: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.</p><p>To simplify the process, we will stimulate the database by just creating data.ts in the api folder, with the sample code below.</p><pre>export const data = [<br>  {<br>    id: &quot;c27be251-4e69-4aeb-a766-dbc01bde66e5&quot;,<br>    category: &quot;men&quot;,<br>    product_type: &quot;sweater&quot;,<br>    title: &quot;Loose Fit Zip-through hoodie&quot;,<br>    description:<br>      &quot;Zip-through hoodie in lightweight sweatshirt fabric made from a cotton blend with a soft brushed inside. Jersey-lined, drawstring hood, a zip down the front, diagonal, welt side pockets and wide ribbing at the cuffs and hem. Loose fit for a generous but not oversized silhouette.&quot;,<br>    sizes: [&quot;XS&quot;, &quot;S&quot;, &quot;M&quot;, &quot;L&quot;, &quot;XL&quot;, &quot;XXL&quot;],<br>    color: &quot;Blue&quot;,<br>    image:<br>      &quot;https://example.com/zip_through_hoodie_eohged.jpg&quot;,<br>    price: 1499,<br>  },<br>  ...<br>];</pre><p>We will create a handler function for the GET method inside route.ts and return the data array in the response. All the server-side logic goes inside this function.</p><pre>import { data } from &quot;../data&quot;;<br><br>export async function GET() {<br>  return Response.json(data);<br>}</pre><p>Now, within the app folder, you can locate the page.tsx file, this is the root page (basically a homepage) which can be accessed by visiting http://localhost:3000/. Similarly for creating nested pages, we create sub-folders inside app folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*yNTNoOWOh6O1X8cLgf9Esg.jpeg" /></figure><p>where bag can be access by visiting http://localhost:3000/bag and order-confirmed by http://localhost:3000/order-confirmed.</p><p>Now, inside root page.tsx add the following code</p><pre>const fetchProducts = async () =&gt; {<br>  const response = await fetch(&quot;http://localhost:3000/api/products&quot;, {<br>    method: &quot;GET&quot;,<br>  });<br><br>  if (!response.ok) {<br>    throw new Error(&quot;failed to fetch products&quot;);<br>  }<br><br>  return response.json();<br>};<br><br>export default async function Home() {<br>  const products = await fetchProducts();<br><br>  return &lt;div&gt;homepage&lt;/div&gt;;<br>}</pre><p>And, this is where Rendering Methodscome into play. In Next.js 14 terms this will be called a Server Componentand the component will be statically rendered or in older terms, it will be SSG (Static Site Generation). It is considered Static Renderingbecause we have information ahead of the client requesting data. Till now, all the components we saw can be consider as Server Component which renders statically.</p><p>Let’s create a Product Cardcomponent, which we can render on the home page to display the products list. Create a folder called product_card inside the components folder and a page.tsx file within, with the following code.</p><pre>import { IProduct } from &quot;@/types/IProduct&quot;;<br>import Link from &quot;next/link&quot;;<br>import ProductImage from &quot;../product_image/ProductImage&quot;;<br>import ProductDetails from &quot;../product_details/ProductDetails&quot;;<br><br>interface IProductCard {<br>  product: IProduct;<br>}<br><br>const ProductCard = ({ product }: IProductCard) =&gt; {<br>  return (<br>    &lt;Link href={`/products/${product.id}`}&gt;<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;ProductImage image_src={product.image} /&gt;<br>        &lt;ProductDetails product={product} /&gt;<br>      &lt;/div&gt;<br>    &lt;/Link&gt;<br>  );<br>};<br><br>export default ProductCard;</pre><p>We can observe that there are several elements involved here, and the component is made up of several other components. But, we won’t discuss the creation of every single component, as that is not the main focus of the article.</p><p>Let’s use the ProductCard component within the Home component to display all the retrieved products.</p><pre>import ProductCard from &quot;@/components/product_card/ProductCard&quot;;<br>import { IProduct } from &quot;@/types/IProduct&quot;;<br><br>const fetchProducts = async () =&gt; {<br>  const response = await fetch(&quot;http://localhost:3000/api/products&quot;, {<br>    method: &quot;GET&quot;,<br>  });<br><br>  if (!response.ok) {<br>    throw new Error(&quot;failed to fetch products&quot;);<br>  }<br><br>  return response.json();<br>};<br><br>export default async function Home() {<br>  const products = await fetchProducts();<br><br>  return (<br>    &lt;section&gt;<br>      &lt;div className=&quot;grid grid-cols-1 gap-4  md:grid-cols-2  lg:grid lg:grid-cols-4&quot;&gt;<br>        {products.map((product: IProduct) =&gt; (<br>          &lt;ProductCard key={product.id} product={product} /&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/section&gt;<br>  );<br>}</pre><p>This is how the Home component looks after the update and below is the result that we get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ypSrZS8F8mYX9b0Q88asw.png" /></figure><h3>Dynamic Routing</h3><p>In the ProductCard component, the wrapper element is the Next.js Link component, which navigates to /products/${product.id} route and this type of routing is called Dynamic Route. Below is how we define it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*J4MffgWDvtZWHnnxox5aVw.jpeg" /></figure><p>When we don’t know the exact segment names ahead of time and want to create routes from dynamic data, we can use Dynamic Segmentsthat are filled in at request time or prerendered at build time.</p><p>Dynamic Segments can be created by wrapping folder name with [], as we can see above. It passed as the params prop to layout, page, route, and generateMetadata functions.</p><p>Now, let’s take a look at the Product Detailscomponent code in page.tsx inside the [id] folder.</p><pre>import { IProduct } from &quot;@/types/IProduct&quot;;<br>import ProductImage from &quot;@/components/product_image/ProductImage&quot;;<br>import ProductDetails from &quot;@/components/product_details/ProductDetails&quot;;<br><br>const fetchProduct = async (id: string) =&gt; {<br>  const response = await fetch(`http://localhost:3000/api/products/${id}`);<br><br>  if (!response.ok) {<br>    throw new Error(&quot;failed to fetch product&quot;);<br>  }<br><br>  return response.json();<br>};<br><br>const page = async ({ params }: { params: { id: string } }) =&gt; {<br>  const product: IProduct[] = await fetchProduct(params.id);<br><br>  return (<br>    &lt;section className=&quot;grid grid-cols-1 gap-6 md:grid-cols-2&quot;&gt;<br>      &lt;div className=&quot;product_image_complete&quot;&gt;<br>        &lt;ProductImage image_src={product[0].image} /&gt;<br>      &lt;/div&gt;<br>      &lt;ProductDetails type=&quot;complete&quot; product={product[0]} /&gt;<br>    &lt;/section&gt;<br>  );<br>};<br><br>export default page;</pre><p>We are destructing id from params prop, which we passed to the Dynamic Route in ProductCard component.</p><pre>...<br>const ProductCard = ({ product }: IProductCard) =&gt; {<br>  return (<br>    &lt;Link href={`/products/${product.id}`}&gt;...&lt;/Link&gt;<br>  );<br>};<br>...</pre><p>And, we can see in the Products component, that we are fetching individual product data with the use of the id that we received.</p><p>Lets, take a look at the URL we are requesting for a specific products data.</p><pre>http://localhost:3000/api/products/${id}</pre><p>We have three segments: api, products, and ${id}. We already have a products folder with a route.ts file that serves as an endpoint to retrieve all the products. Now, we will add one more folder named [id] with route.ts, similar to what we did for the Product Detailspage, in order to fetch individual product data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*5l1Jb8xClAg4NKMhS3bjZw.jpeg" /></figure><p>And, as we already know, we handle all the server logic inside the route.ts file, even this one is going to be a GET method.</p><pre>import { data } from &quot;../../data&quot;;<br><br>export async function GET(<br>  { params }: { params: { id: string } }<br>) {<br>  const item = data.filter((product) =&gt; params.id === product.id);<br>  if (item.length &lt; 1) {<br>    return new Response(&quot;product not found&quot;);<br>  }<br>  return Response.json(item);<br>}</pre><p>Similarly to our approach for retrieving all products, we do not connect to or query any database for data. We filter mock data based on the id from the params object and send it in the response.</p><p>This is how we get product data for our Product Details page and this is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPC6cxHaZDb2Rhr8bM5c_A.png" /></figure><p>The Product Details page is made up of two components, Product Imagewhich is a Next.js Imagecomponent under the hood, but the ProductDetails is a client component, let’s take a look at its code.</p><pre>&quot;use client&quot;;<br>import { FormEvent, useState } from &quot;react&quot;;<br>import { IProduct } from &quot;@/types/IProduct&quot;;<br>import ProductTitlePrice from &quot;../product_title_price/ProductTitlePrice&quot;;<br>import ProductSize from &quot;../product_size/ProductSize&quot;;<br>import HorizontalRule from &quot;../horizontal_rule/HorizontalRule&quot;;<br>import ProductButtons from &quot;../product_buttons/ProductButtons&quot;;<br>import clsx from &quot;clsx&quot;;<br>import useCart from &quot;@/store/store&quot;;<br><br>interface IProductDetails {<br>  type?: &quot;complete&quot;;<br>  product: IProduct;<br>}<br><br>const ProductDetails = ({ type, product }: IProductDetails) =&gt; {<br>  const [selectedSize, setSelectedSize] = useState&lt;null | string&gt;(null);<br>  const addToBag = useCart((state) =&gt; state.addToBag);<br><br>  const handleFormSubmit = (event: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    event.preventDefault();<br><br>    if (!selectedSize) {<br>      alert(&quot;please select a size.&quot;);<br>      return;<br>    }<br><br>    addToBag({<br>      id: product.id,<br>      image: product.image,<br>      title: product.title,<br>      price: product.price,<br>      sizes: product.sizes,<br>      selectedSize,<br>      quantity: 1,<br>    });<br>  };<br><br>  const getSelectedSize = (size: null | string) =&gt; {<br>    setSelectedSize(size);<br>  };<br><br>  return (<br>    &lt;form<br>      className={clsx(<br>        &quot;product_details&quot;,<br>        type === &quot;complete&quot; &amp;&amp; &quot;product_details_complete&quot;<br>      )}<br>      onSubmit={handleFormSubmit}<br>    &gt;<br>      &lt;ProductTitlePrice title={product.title} price={product.price} /&gt;<br>      {type === &quot;complete&quot; &amp;&amp; (<br>        &lt;&gt;<br>          &lt;ProductSize<br>            sizes={product.sizes}<br>            selectedSize={selectedSize}<br>            getSelectedSize={getSelectedSize}<br>          /&gt;<br>          &lt;HorizontalRule /&gt;<br>          &lt;ProductButtons /&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default ProductDetails;</pre><p>We can see the &quot;use client” directive at the very top of the file. This convention tells Next that it has to be a client component. Rendering a component on the client side may be necessary for tasks such as adding user events or using hooks on the component.</p><p>We can find both cases in this component, state hook to keep track of selected product size, where state and setter function is passed to the ProductSize component is used to toggle product size to change the selected product state and the ProductButtons component consists of two buttons “Buy Now” which adds the selected product to the global state and moves to the Bag page and “Add to Bag” which adds the selected product to global state.</p><p>We’re even using hooks from a third-party library called <a href="https://github.com/pmndrs/zustand">Zustand</a>, which is used for global state management. In our case, we are using it for the cart feature.</p><p>Also, we have a Bag page which is a client component.</p><pre>&quot;use client&quot;;<br>import { useRouter } from &quot;next/navigation&quot;;<br>import ProductCardBag from &quot;@/components/product_card_bag/ProductCardBag&quot;;<br>import EmptyBag from &quot;@/components/empty_bag/EmptyBag&quot;;<br>import useCart from &quot;@/store/store&quot;;<br>import BagTotalCard from &quot;@/components/bag_total_card/BagTotalCard&quot;;<br>import PrimaryButton from &quot;@/components/primary_button/PrimaryButton&quot;;<br><br>const page = () =&gt; {<br>  const { items } = useCart((state) =&gt; ({ items: state.items }));<br>  const clearBag = useCart((state) =&gt; state.clearBag);<br>  const router = useRouter();<br><br>  const handlePlaceOrderClick = () =&gt; {<br>    router.push(&quot;/order-confirmed&quot;);<br>    clearBag();<br>  };<br><br>  return (<br>    &lt;section className=&quot;max-w-96 mx-auto  flex-col-center gap-4&quot;&gt;<br>      {items.length !== 0 ? (<br>        items.map((item, index) =&gt; (<br>          &lt;ProductCardBag key={index} product={item} /&gt;<br>        ))<br>      ) : (<br>        &lt;EmptyBag /&gt;<br>      )}<br><br>      {items.length !== 0 &amp;&amp; (<br>        &lt;&gt;<br>          &lt;BagTotalCard items={items} /&gt;<br>          &lt;PrimaryButton onClick={handlePlaceOrderClick}&gt;<br>            Place Order<br>          &lt;/PrimaryButton&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/section&gt;<br>  );<br>};<br><br>export default page;</pre><p>It consists of three main components and a button: EmptyBag and BagTotalCard, which are static components displaying static data, and the ProductCardBag, which has interactivity, along with the Place Orderbutton.</p><pre>import React from &quot;react&quot;;<br>import ProductImage from &quot;../product_image/ProductImage&quot;;<br>import ProductTitlePrice from &quot;../product_title_price/ProductTitlePrice&quot;;<br>import ProductSizeBag from &quot;../product_size_bag/ProductSizeBag&quot;;<br>import ProductQuantity from &quot;../product_quantity/ProductQuantity&quot;;<br>import useCart from &quot;@/store/store&quot;;<br>import { IProductBag } from &quot;@/types/IProductBag&quot;;<br><br>interface IProductCardBag {<br>  product: IProductBag;<br>}<br><br>const ProductCardBag = ({ product }: IProductCardBag) =&gt; {<br>  const removeFromBag = useCart((state) =&gt; state.removeFromBag);<br><br>  const handleRemoveClick = () =&gt; {<br>    removeFromBag(product.id, product.selectedSize);<br>  };<br><br>  return (<br>    &lt;div className=&quot;product_card_bag&quot;&gt;<br>      &lt;div className=&quot;product_image_bag&quot;&gt;<br>        &lt;ProductImage image_src={product.image} /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;product_details_bag&quot;&gt;<br>        &lt;ProductTitlePrice title={product.title} price={product.price} /&gt;<br><br>        &lt;div className=&quot;flex gap-4&quot;&gt;<br>          &lt;ProductSizeBag product={product} /&gt;<br>          &lt;ProductQuantity product={product} /&gt;<br>        &lt;/div&gt;<br><br>        &lt;button<br>          type=&quot;button&quot;<br>          className=&quot;remove_button&quot;<br>          onClick={handleRemoveClick}<br>        &gt;<br>          Remove<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ProductCardBag;</pre><p>And, the component is composed of the previously discussed components, except of ProductSizeBag,</p><pre>import React, { useState } from &quot;react&quot;;<br>import { IProductBag } from &quot;@/types/IProductBag&quot;;<br>import useCart from &quot;@/store/store&quot;;<br><br>interface IProductSizeBag {<br>  product: IProductBag;<br>}<br><br>const ProductSizeBag = ({ product }: IProductSizeBag) =&gt; {<br>  const [currentSize, setCurrentSize] = useState(product.selectedSize);<br>  const updateSize = useCart((state) =&gt; state.updateSize);<br><br>  const handleChange = (event: React.ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; {<br>    setCurrentSize(event.target.value);<br>    updateSize(product.id, product.selectedSize, event.target.value);<br>  };<br><br>  return (<br>    &lt;select<br>      className=&quot;product_size_bag&quot;<br>      name=&quot;size&quot;<br>      id=&quot;size&quot;<br>      defaultValue={currentSize}<br>      onChange={handleChange}<br>    &gt;<br>      {product.sizes.map((size, index) =&gt; (<br>        &lt;option key={index} value={size}&gt;<br>          {size}<br>        &lt;/option&gt;<br>      ))}<br>    &lt;/select&gt;<br>  );<br>};<br><br>export default ProductSizeBag;</pre><p>and ProductQuantity.</p><pre>import { IProductBag } from &quot;@/types/IProductBag&quot;;<br>import Image from &quot;next/image&quot;;<br>import minus from &quot;../../public/minus.svg&quot;;<br>import plus from &quot;../../public/plus.svg&quot;;<br>import useCart from &quot;@/store/store&quot;;<br><br>interface IProductQuantity {<br>  product: IProductBag;<br>}<br><br>const ProductQuantity = ({ product }: IProductQuantity) =&gt; {<br>  const updateQuantity = useCart((state) =&gt; state.updateQuantity);<br>  const removeFromBag = useCart((state) =&gt; state.removeFromBag);<br>  const decreaseQuantity = product.quantity - 1;<br>  const increaseQuantity = product.quantity + 1;<br><br>  const handleDecreaseQuantityClick = () =&gt; {<br>    product.quantity &gt; 1<br>      ? updateQuantity(product.id, product.selectedSize, decreaseQuantity)<br>      : removeFromBag(product.id, product.selectedSize);<br>  };<br><br>  const handleIncreaseQuantityClick = () =&gt; {<br>    product.quantity &gt;= 10<br>      ? alert(&quot;maximum 10 quantity can be added.&quot;)<br>      : updateQuantity(product.id, product.selectedSize, increaseQuantity);<br>  };<br><br>  return (<br>    &lt;div className=&quot;product_quantity&quot;&gt;<br>      &lt;button<br>        className=&quot;product_quantity_button&quot;<br>        onClick={handleDecreaseQuantityClick}<br>      &gt;<br>        &lt;Image src={minus} alt=&quot;minus icon&quot; /&gt;<br>      &lt;/button&gt;<br>      &lt;div className=&quot;product_quantity_count&quot;&gt;{product.quantity}&lt;/div&gt;<br>      &lt;button<br>        className=&quot;product_quantity_button&quot;<br>        onClick={handleIncreaseQuantityClick}<br>      &gt;<br>        &lt;Image src={plus} alt=&quot;plus icon&quot; /&gt;<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ProductQuantity;</pre><p>This is the outcome when all of the above come together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVZL-eCZTIy-w-vHs2QV1Q.png" /></figure><p>Lastly, Order Confirmed page which is a basic static page.</p><pre>import React from &quot;react&quot;;<br>import Image from &quot;next/image&quot;;<br>import check from &quot;../../public/check.svg&quot;;<br>import ContinueShoppingButton from &quot;@/components/continue_shopping_button/ContinueShoppingButton&quot;;<br><br>const page = () =&gt; {<br>  return (<br>    &lt;section className=&quot;h-[60vh]  flex-row-center&quot;&gt;<br>      &lt;div className=&quot;flex-col-center gap-4&quot;&gt;<br>        &lt;Image src={check} alt=&quot;check icon&quot; /&gt;<br>        &lt;p className=&quot;font-semibold&quot;&gt;Order Confirmed&lt;/p&gt;<br>        &lt;ContinueShoppingButton /&gt;<br>      &lt;/div&gt;<br>    &lt;/section&gt;<br>  );<br>};<br><br>export default page;</pre><p>And, the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PEwS3D6qXPwnpV4AttTHbQ.png" /></figure><blockquote>Note: Additional tools were used, such as Typescript, Tailwaind CSS and Zustand.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*VrhtQCozAz676XrnuHYe5A.gif" /></figure><h3>Summary</h3><p>In summary, Next.js extends React by adding features like server-side rendering, file-system routing, and built-in API handling, streamlining development with more out-of-the-box functionality compared to React’s focus on UI components and flexibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8178ce875a56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/getting-started-with-next-js-14-8178ce875a56">Getting started with NEXT.JS 14</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging AI Power: A Comprehensive Guide to Integrating OpenAI with NestJS]]></title>
            <link>https://medium.com/paktolus-engineering/leveraging-ai-power-a-comprehensive-guide-to-integrating-openai-with-nestjs-1c7c772e96fd?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/1c7c772e96fd</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Shiddhant Behera]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 12:28:47 GMT</pubDate>
            <atom:updated>2025-01-03T19:44:29.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3VxDva1BJCbEcua-g6MwQ.png" /></figure><h3><strong>Introduction</strong></h3><p>Artificial intelligence (AI) technology is advancing quickly, with OpenAI leading the way. OpenAI’s powerful models can mimic human writing, answer questions, and write code. This makes OpenAI very useful for developers who want to add advanced AI features to their apps.</p><p>NestJS is a progressive NodeJS framework that is efficient, scalable, and well-structured. It uses TypeScript and supports modern JavaScript features, making it a top choice for building server-side applications.</p><p>When you combine OpenAI with NestJS, you get the best of both worlds: the smart capabilities of OpenAI’s models and the reliable structure and scalability of NestJS applications. This combination is great for creating smart APIs that need secure access and efficient processing.</p><p>Next, let’s explore the step-by-step process of setting up and securing your NestJS project with OpenAI integration.</p><h3>Prerequisites</h3><p>Before we dive in, ensure you have the following tools installed:</p><ul><li>NodeJS</li><li>npm or yarn</li><li>NestJS CLI</li></ul><h3>Step 1: Setting Up the NestJS Project</h3><p>First, create a new NestJS project using the NestJS CLI.</p><pre>nest new &lt;your-app-name&gt;<br>cd &lt;your-app-name&gt;</pre><h3>Step 2: Installing Required Packages</h3><p>We’ll need to install the OpenAI SDK package.</p><pre>npm install openai</pre><h3>Step 3: Setting Up Environment Variables</h3><p>Create a .env file in the root of your project to store the OpenAI API key.</p><pre>OPENAI_API_KEY=&lt;your-openai-key&gt;</pre><h3>Step 4: Setting Up the OpenAI Service and Controller</h3><h4>1. Create a service to handle OpenAI API requests.</h4><p>In this service, we use the GPT-3.5-turbo model to process user queries. The service sends user prompts to the OpenAI API and returns the generated response from the assistant.</p><pre>// src/open-ai/open-ai.service.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import OpenAI from &#39;openai&#39;;<br>import { ChatCompletionMessage } from &#39;openai/resources/chat/completions&#39;;<br>import { OpenAIRequestDto } from &#39;./dtos/open-ai-req.dto&#39;;<br><br>@Injectable()<br>export class OpenAIService {<br>  private openai = new OpenAI({<br>    apiKey: process.env.OPENAI_API_KEY,<br>  });<br>  constructor() {}<br><br>  async chatCompletion(<br>    request: OpenAIRequestDto,<br>  ): Promise&lt;ChatCompletionMessage&gt; {<br>    const completion = await this.openai.chat.completions.create({<br>      messages: [<br>        {<br>          role: &#39;user&#39;,<br>          content: request.prompt,<br>        },<br>      ],<br>      model: &#39;gpt-3.5-turbo&#39;,<br>    });<br><br>    return completion.choices[0].message;<br>  }<br>}</pre><h4>2. Create a controller to handle requests to the OpenAI service.</h4><p>Here, we create an API endpoint that takes a user query and generates a response using the OpenAI service. This endpoint is secured with JWT authentication to ensure only authorized users can access it.</p><pre>// src/open-ai/open-ai.controller.ts<br><br>import { Body, Controller, Post, UseGuards } from &#39;@nestjs/common&#39;;<br>import { OpenAIService } from &#39;./open-ai.service&#39;;<br>import { ChatCompletionMessage } from &#39;openai/resources/chat/completions&#39;;<br>import { ApiBearerAuth, ApiTags } from &#39;@nestjs/swagger&#39;;<br>import { OpenAIRequestDto } from &#39;./dtos/open-ai-req.dto&#39;;<br>import { JwtAuthGuard } from &#39;src/auth/guards/jwt-guard&#39;;<br><br>@ApiTags(&#39;Open AI&#39;)<br>@ApiBearerAuth(&#39;AUTHORIZATION-JWT&#39;)<br>@UseGuards(JwtAuthGuard)<br>@Controller(&#39;open-ai&#39;)<br>export class OpenAIController {<br>  constructor(private readonly service: OpenAIService) {}<br><br>  @Post(&#39;generate&#39;)<br>  async generateResponse(<br>    @Body() request: OpenAIRequestDto,<br>  ): Promise&lt;ChatCompletionMessage&gt; {<br>    return this.service.chatCompletion(request);<br>  }<br>}</pre><h4>3. Create the DTO for the user request.</h4><pre>// src/open-ai/dto/open-ai-request.dto.ts<br><br>import { ApiProperty } from &#39;@nestjs/swagger&#39;;<br><br>export class OpenAIRequestDto {<br>  @ApiProperty()<br>  prompt!: string;<br>}</pre><h4>4. Register the OpenAI service and controller.</h4><pre>// src/open-ai/open-ai.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { OpenAIController } from &#39;./open-ai.controller&#39;;<br>import { OpenAIService } from &#39;./open-ai.service&#39;;<br><br>@Module({<br>  controllers: [OpenAIController],<br>  providers: [OpenAIService],<br>})<br>export class OpenAIModule {}</pre><h3>Step 5: Testing the API with Postman</h3><p>We’ll test our API using Postman to ensure everything is set up correctly</p><h4>Postman Configuration:</h4><ul><li><strong>URL:</strong> <a href="http://localhost:3000/open-ai/generate">http://localhost:3000/open-ai/generate</a></li><li><strong>Method:</strong> POST</li><li><strong>Headers:</strong></li><li>Authorization: Bearer &lt;your-jwt-token&gt;</li><li>Content-Type: application/json</li></ul><p>Below is a screenshot of the Postman setup for hitting the POST request to generate a response from OpenAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jU1v5tCS7ORaHosnoD6YQ.png" /></figure><h3>Step 6: Implementing Unit Tests</h3><p>We’ll write comprehensive unit tests to verify the functionality and reliability of our OpenAI service and controller. These tests will help ensure our application behaves as expected under various conditions.</p><h4>Testing the controller method</h4><pre>// src/open-ai/open-ai.controller.spec.ts<br><br>import { Test, TestingModule } from &#39;@nestjs/testing&#39;;<br>import { OpenAIController } from &#39;./open-ai.controller&#39;;<br>import { OpenAIService } from &#39;./open-ai.service&#39;;<br>import { OpenAIRequestDto } from &#39;./dtos/open-ai-req.dto&#39;;<br>import { ChatCompletionMessage } from &#39;openai/resources/chat/completions&#39;;<br><br>describe(&#39;OpenAIController&#39;, () =&gt; {<br>  let controller: OpenAIController;<br>  let service: OpenAIService;<br><br>  beforeEach(async () =&gt; {<br>    const module: TestingModule = await Test.createTestingModule({<br>      controllers: [OpenAIController],<br>      providers: [<br>        {<br>          provide: OpenAIService,<br>          useValue: {<br>            chatCompletion: jest.fn(),<br>          },<br>        },<br>      ],<br>    }).compile();<br><br>    controller = module.get&lt;OpenAIController&gt;(OpenAIController);<br>    service = module.get&lt;OpenAIService&gt;(OpenAIService);<br>  });<br><br>  it(&#39;should be defined&#39;, () =&gt; {<br>    expect(controller).toBeDefined();<br>  });<br><br>  describe(&#39;Method - generateResponse&#39;, () =&gt; {<br>    it(&#39;should call service function with the provided request&#39;, async () =&gt; {<br>      const request: OpenAIRequestDto = { prompt: &#39;Test prompt&#39; };<br>      const expectedResponse: ChatCompletionMessage = {<br>        role: &#39;assistant&#39;,<br>        content: &#39;Test response&#39;,<br>      };<br><br>      const spyOnChatCompletion = jest<br>        .spyOn(service, &#39;chatCompletion&#39;)<br>        .mockResolvedValue(expectedResponse);<br><br>      const result = await controller.generateResponse(request);<br><br>      expect(spyOnChatCompletion).toHaveBeenCalledWith(request);<br>      expect(result).toEqual(expectedResponse);<br>    });<br>  });<br>});</pre><h4>Testing the service method</h4><pre>// src/open-ai/open-ai.service.spec.ts<br><br>import { Test, TestingModule } from &#39;@nestjs/testing&#39;;<br>import { OpenAIService } from &#39;./open-ai.service&#39;;<br>import { OpenAIRequestDto } from &#39;./dtos/open-ai-req.dto&#39;;<br>import {<br>  ChatCompletion,<br>  ChatCompletionMessage,<br>} from &#39;openai/resources/chat/completions&#39;;<br>import OpenAI from &#39;openai&#39;;<br><br>jest.mock(&#39;openai&#39;);<br><br>describe(&#39;OpenAIService&#39;, () =&gt; {<br>  let service: OpenAIService;<br>  let mockOpenAI: jest.Mocked&lt;OpenAI&gt;;<br><br>  beforeEach(async () =&gt; {<br>    mockOpenAI = {<br>      chat: {<br>        completions: {<br>          create: jest.fn(),<br>        },<br>      },<br>    } as unknown as jest.Mocked&lt;OpenAI&gt;;<br><br>    const module: TestingModule = await Test.createTestingModule({<br>      providers: [<br>        OpenAIService,<br>        {<br>          provide: OpenAI,<br>          useValue: mockOpenAI,<br>        },<br>      ],<br>    }).compile();<br><br>    service = module.get&lt;OpenAIService&gt;(OpenAIService);<br>    service[&#39;openai&#39;] = mockOpenAI;<br>  });<br><br>  it(&#39;should be defined&#39;, () =&gt; {<br>    expect(service).toBeDefined();<br>  });<br><br>  describe(&#39;Method - chatCompletion&#39;, () =&gt; {<br>    it(&#39;should call OpenAI API and return the response&#39;, async () =&gt; {<br>      const request: OpenAIRequestDto = { prompt: &#39;Test prompt&#39; };<br>      const mockResponse = {<br>        choices: [<br>          {<br>            message: {<br>              role: &#39;assistant&#39;,<br>              content: &#39;Test response&#39;,<br>            } as ChatCompletionMessage,<br>          },<br>        ],<br>      };<br><br>      const spyOnOpenAICreate = jest<br>        .spyOn(mockOpenAI.chat.completions, &#39;create&#39;)<br>        .mockResolvedValue(mockResponse as ChatCompletion);<br><br>      const result = await service.chatCompletion(request);<br><br>      expect(spyOnOpenAICreate).toHaveBeenCalledWith({<br>        messages: [{ role: &#39;user&#39;, content: request.prompt }],<br>        model: &#39;gpt-3.5-turbo&#39;,<br>      });<br>      expect(result).toEqual(mockResponse.choices[0].message);<br>    });<br>  });<br>});</pre><h3>What Next?</h3><p>Once you’ve integrated OpenAI with NestJS, the next step is to bring your AI-powered features to life. This means creating a user-friendly interface using your favorite frontend framework. Users can then interact directly with your AI tools. For example, you could design a simple chat interface or a tool that generates text to show off OpenAI’s abilities.</p><p>Using OpenAI with NestJS opens up many possibilities, allowing you to use advanced AI features in a structured and manageable way. It’s important to make sure your API is secure and thoroughly tested so users can rely on your AI services. This approach ensures users get the full benefit of your AI capabilities in a strong and efficient system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c7c772e96fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/leveraging-ai-power-a-comprehensive-guide-to-integrating-openai-with-nestjs-1c7c772e96fd">Leveraging AI Power: A Comprehensive Guide to Integrating OpenAI with NestJS</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing your Web Apps by AI integration using Next.js and OpenAI.]]></title>
            <link>https://medium.com/paktolus-engineering/enhancing-your-web-apps-by-ai-integration-using-next-js-and-openai-2eb56f9e9a5e?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/2eb56f9e9a5e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-apps]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Shawaiz Siddiqui ]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 14:04:23 GMT</pubDate>
            <atom:updated>2025-01-03T19:41:27.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hdi49UnLzObcYFiAo6iCFA.png" /></figure><blockquote>Leveraging the power of AI to make your web apps more attractive and powerful.</blockquote><p><strong>Artificial Intelligence (AI)</strong> is revolutionizing various industries, offering unprecedented opportunities for innovation. You can seamlessly incorporate AI into your web applications by harnessing the power of advanced <strong>Large Language Models (LLMs)</strong> through APIs. In this article, I’ll show you how to supercharge your <strong>Next.js</strong> app with the capabilities of <strong>OpenAI</strong>. We’ll explore creating dynamic chat completions using the <strong>OpenAI API</strong> and managing streaming responses on the front end, bringing your app to the next level of interactivity and intelligence.</p><h3>Introduction to OpenAI APIs :</h3><p>You’ve likely heard of <strong>ChatGPT</strong>, a chat assistant created by <strong>OpenAI </strong>that responds to user queries through prompts, sending sequences of tokens in response. <strong>OpenAI </strong>also offers APIs that you can integrate into your applications to receive responses from different <strong>LLM </strong>models that are available at <strong>OpenAI</strong>.</p><h3>Getting Started</h3><p>To begin, let&#39;s create a new <strong>Next.js</strong> project</p><pre>npx create-next-app@latest ai-nextjs-integration</pre><p>For demonstration purposes, we will create a basic app that generates a short note on a topic provided by the user.<br>Open the project directory in any IDE like VS Code. I am using VS Code for this example. Clean the boilerplate provided by <strong>Next.js</strong> and create custom components to build a basic UI.</p><h3>Project Structure</h3><p>I am using <strong>Next.js 14 </strong>(App router) in this project and my project folder structure looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*r068RqKVfT8QTL_x9nSm7A.png" /><figcaption>folder-structure</figcaption></figure><h3>Creating UI Elements</h3><p>Let’s first create basic UI elements, and then we will go for AI integration by creating <strong>Next.js </strong>API routes.</p><p>I have created a components directory inside <strong>src/ </strong>directory and there I have created UI components like form, button, select-input, etc, imported from <strong>shadcn/ui</strong> as you can see in the folder structure. I have also created a <strong>Home</strong> component where we will set up some states and structure the page.</p><h4>Home Component</h4><pre>//src/components/home/index.tsx<br><br>&#39;use client&#39;;<br>import styles from &quot;./style.module.scss&quot;;<br>import SelectForm from &quot;../select-form&quot;;<br>import ContentArea from &quot;../content-area&quot;;<br>import { useState } from &quot;react&quot;;<br>import { Button } from &quot;../ui/button&quot;;<br><br>const Home = () =&gt; {<br>  //state to set response from AI<br>  const[aiResponse, setAiResponse] = useState(&quot;&quot;);<br><br>  return (<br>    &lt;&gt;<br>    &lt;h1 className={styles.title}&gt;Generate AI Powered Short Notes, In Just One Click&lt;/h1&gt;<br>    &lt;div className={styles.container}&gt;<br>        &lt;h3 className={styles.subtitle}&gt;Choose a Topic: &lt;/h3&gt;<br>        &lt;SelectForm setAiResponse={setAiResponse}/&gt;<br>        &lt;ContentArea aiResponse={aiResponse}/&gt;<br>        &lt;Button onClick={()=&gt;setAiResponse(&quot;&quot;)} disabled={!aiResponse} className={styles.reset_button}&gt;Reset&lt;/Button&gt;<br>    &lt;/div&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default Home</pre><p>The two main components i.e., <strong>SelectForm </strong>and <strong>ContentArea </strong>are responsible for their respective tasks. <strong>SelectForm</strong> is responsible for handling the submission of the title and sending it to the backend endpoint that we will create to set up the <strong>OpenAI </strong>connection.</p><h4>SelectForm Component</h4><pre>//src/components/select-form/index.tsx<br><br>&#39;use client&#39;;<br><br>import { Button } from &#39;@/components/ui/button&#39;;<br>import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from &#39;@/components/ui/form&#39;;<br>import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from &#39;@/components/ui/select-input&#39;;<br>import { zodResolver } from &#39;@hookform/resolvers/zod&#39;;<br>import { useForm } from &#39;react-hook-form&#39;;<br>import { z } from &#39;zod&#39;;<br>import styles from &#39;./style.module.scss&#39;;<br>import { Dispatch, FC, SetStateAction } from &#39;react&#39;;<br><br>const FormSchema = z.object({<br>    topic: z<br>        .string({<br>            required_error: &#39;Please select an topic.&#39;,<br>        })<br>});<br><br>interface Props {<br>    setAiResponse: Dispatch&lt;SetStateAction&lt;string&gt;&gt;;<br>}<br><br>const SelectForm: FC&lt;Props&gt; = ({ setAiResponse }) =&gt; {<br>    const form = useForm&lt;z.infer&lt;typeof FormSchema&gt;&gt;({<br>        resolver: zodResolver(FormSchema),<br>    });<br><br>    const onSubmit = async (data: z.infer&lt;typeof FormSchema&gt;) =&gt; {<br>        //nothing to do here for now, will implement this later. <br>    };<br><br>    return (<br>        &lt;Form {...form}&gt;<br>            &lt;form onSubmit={form.handleSubmit(onSubmit)} className={styles.form}&gt;<br>                &lt;FormField<br>                    control={form.control}<br>                    name=&#39;topic&#39;<br>                    render={({ field }) =&gt; (<br>                        &lt;FormItem&gt;<br>                            &lt;FormLabel&gt;{form.getValues().topic ? `topic selected: ${form.getValues().topic}` : &quot;Select Topic&quot;}&lt;/FormLabel&gt;<br>                            &lt;Select onValueChange={field.onChange} defaultValue={field.value}&gt;<br>                                &lt;FormControl&gt;<br>                                    &lt;SelectTrigger&gt;<br>                                        &lt;SelectValue placeholder=&#39;Select a topic to generate short notes&#39; /&gt;<br>                                    &lt;/SelectTrigger&gt;<br>                                &lt;/FormControl&gt;<br>                                &lt;SelectContent&gt;<br>                                    &lt;SelectItem value=&#39;Artificial Intelligence&#39;&gt;Artificial Intelligence&lt;/SelectItem&gt;<br>                                    &lt;SelectItem value=&#39;Javascript&#39;&gt;Javascript&lt;/SelectItem&gt;<br>                                    &lt;SelectItem value=&#39;Machine Learning&#39;&gt;Machine Learning&lt;/SelectItem&gt;<br>                                &lt;/SelectContent&gt;<br>                            &lt;/Select&gt;<br>                            &lt;FormMessage /&gt;<br>                        &lt;/FormItem&gt;<br>                    )}<br>                /&gt;<br>                &lt;Button disabled={!form.getValues().topic} type=&#39;submit&#39;&gt;Generate Short Note!&lt;/Button&gt;<br>            &lt;/form&gt;<br>        &lt;/Form&gt;<br>    );<br>};<br><br>export default SelectForm;</pre><p>In this component, we have created a form that takes a topic from the list of available topics from the user as input and handles the submission. Additionally, I have used some libraries like <strong>zod</strong> and <strong>react-hook-form </strong>to handle the form submission and validations. For now, we have kept the <strong>onSubmit</strong> function empty and will implement it later.</p><h4>ContentArea Component</h4><p>Now, the other component which is <strong>ContentArea</strong>, is responsible for displaying the AI-generated content on the screen.<br>The response that we get from AI is in markdown format, so to display it properly as text, we will be using a library. There is a number of libraries which does the same, but I have used <strong>react-markdown </strong>along with<strong> remark-gfm </strong>to<strong> </strong>display the markdown as text.</p><p>Let&#39;s install both of these:</p><pre>npm i react-markdown remark-gfm</pre><pre>//src/components/content-area/index.tsx<br><br>import React, { FC } from &#39;react&#39;<br>import styles from &#39;./style.module.scss&#39;;<br>import Markdown from &#39;react-markdown&#39;<br>import remarkGfm from &#39;remark-gfm&#39;<br><br>interface Props {<br>    aiResponse: string;<br>}<br><br>const ContentArea:FC&lt;Props&gt; = ({aiResponse}) =&gt; {<br>  return (<br>    &lt;div className={styles.content_root}&gt;<br>    { aiResponse ? <br>        (&lt;Markdown remarkPlugins={[remarkGfm]}&gt;{aiResponse}&lt;/Markdown&gt;)<br>        : <br>        (&lt;div className={styles.no_response}&gt;Response from Ai Will Appear Here!&lt;/div&gt;)}<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default ContentArea</pre><h3>Frontend Layout</h3><p>Now we are done with designing the basic layout. It looks like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OIjyhuakoEFQ2F30pbX3A.png" /></figure><h3>Creating Next.js API route to set up OpenAI connection</h3><p>Now, Let&#39;s create a route named ‘<strong>message</strong>’ as <strong>/app/api/message/route.ts.</strong> Here, we will write server-side logic to connect <strong>OpenAI API </strong>generate the response based on the prompt provided by the user, and send it back as the streaming response. <br>It is optional to create a streaming response, you can directly just send the final output to the user, but if you want the user to know as and when the AI model is sending the output, you can generate the streaming response and the user will see the response in a way as the typewriter is writing it. This effect is also seen in <strong>ChatGPT </strong>and other AI models like <strong>Claude. AI</strong>.</p><p>To generate a streaming response, <strong>Next.js </strong>offers a very easy way to generate streaming responses as described in the docs: <a href="https://nextjs.org/docs/app/building-your-application/routing/route-handlers#streaming">click to see</a><br>To set up the <strong>OpenAI API </strong>and generate a streaming response, you need to install the following libraries :</p><pre>npm i openai ai</pre><h4>‘message’ Route Handler</h4><pre>//src/app/api/message/route.ts<br><br>//import the necessary libraries.<br>import OpenAI from &quot;openai&quot;;<br>import { OpenAIStream, StreamingTextResponse } from &#39;ai&#39;<br> <br>const openai = new OpenAI(); <br>// in newer version, you don&#39;t need to pass the api key manually,<br>// you just need to add the Api key as a value of this env variable <br>// OPENAI_API_KEY into your project. <br> <br>export const runtime = &#39;edge&#39;<br> <br>export async function POST(req: Request) {<br>  const { topic } = await req.json();<br>  //here, we are manually generating a prompt based on topic selected by user,<br>  // but the prompt solely can be provided by the user also.<br><br>const prompt = `generate a short note between 150 to 200 words on topic: ${topic}`;<br>  const response = await openai.chat.completions.create({<br>    model: &#39;gpt-3.5-turbo&#39;, //define the model of your choice from available openai models<br>    stream: true, // flag this true to get streamed response<br>    messages:[{role:&quot;user&quot;, content:prompt}],<br>    max_tokens: 150, // limit the no. of tokens to avoid high billing costs.<br>  })<br> <br>  const stream = OpenAIStream(response)<br> <br>  return new StreamingTextResponse(stream)<br>}</pre><p>So, we have set up the route handler which will generate the streaming response and will return it back to the front end where we can handle this.</p><h3>Creating a custom hook for handling the streaming response on frontend</h3><p>Now, let&#39;s get back to the frontend interface, call the API endpoint there, and handle the AI-generated streaming response.<br>Handling the streaming response is a bit tricky, but here’s how you can do it.</p><h4>useFetchAiResponse Hook</h4><pre>//src/hooks/use-fetch-ai-response/index.tsx: <br><br>import { useState, Dispatch, SetStateAction } from &#39;react&#39;;<br>import { toast } from &#39;sonner&#39;;<br>import styles from &#39;./style.module.scss&#39;;<br><br>const useFetchAiResponse = (setAiResponse: Dispatch&lt;SetStateAction&lt;string&gt;&gt;) =&gt; {<br>    const [loading, setLoading] = useState(false);<br><br>    const showToastError = (message: string) =&gt; {<br>        toast(<br>            &lt;div className={styles.toast__wrapper}&gt;<br>                &lt;div className={styles.toast__title}&gt;{message}&lt;/div&gt;<br>            &lt;/div&gt;,<br>            {<br>                duration: 5000,<br>            }<br>        );<br>    };<br><br>    const fetchAiResponse = async (data: { topic: string }) =&gt; {<br>        setLoading(true);<br>        setAiResponse(&quot;&quot;);<br>        try {<br>            const response = await fetch(&#39;/api/message&#39;, {<br>                method: &#39;POST&#39;,<br>                body: JSON.stringify(data),<br>                headers: { &#39;Content-type&#39;: &#39;application/json&#39; },<br>            });<br><br>            if (!response.ok || !response.body) {<br>                showToastError(&#39;Error Occurred&#39;);<br>                setLoading(false);<br>                return;<br>            }<br><br>            //logic for handling the streaming response starts here<br>            const reader = response.body.getReader();<br>            const decoder = new TextDecoder();<br>            let done = false;<br><br>            // run a loop while the reader has not stopped reading the streaming response.<br>            while (!done) {<br>                const { value, done: readerDone } = await reader.read();<br>                done = readerDone;<br>                if (value) {<br>                    const text = decoder.decode(value, { stream: true });<br>                    const cleanText = text.replace(/0:&quot;/g, &#39;&#39;).replace(/&quot;,/g, &#39;&#39;).replace(/&quot;/g, &#39;&#39;);<br>                    setAiResponse((prev) =&gt; prev + cleanText);<br>                }<br>            }<br>        } catch (error) {<br>            showToastError(&#39;Error Occurred&#39;);<br>        } finally {<br>            setLoading(false);<br>        }<br>    };<br><br>    return { fetchAiResponse, loading };<br>};<br><br>export default useFetchAiResponse;</pre><p>For the separation of concerns, we have separated the logic of handling the AI streaming response inside a custom hook in <strong>src/hooks/use-fetch-ai-response/index.tsx</strong> file.</p><h3>Finally, complete the ‘onSubmit’ function in the ‘SelectForm’ component</h3><p>Also, we have completed the <strong>onSubmit </strong>function, which previously we have left incomplete. here’s the updated code for it :</p><pre>// src/components/select-form/index.tsx<br><br>import useFetchAiResponse from &#39;@/hooks/use-fetch-ai-response&#39;;<br><br>const SelectForm: FC&lt;Props&gt; = ({ setAiResponse }) =&gt; {<br>  const form = useForm&lt;z.infer&lt;typeof FormSchema&gt;&gt;({<br>    resolver: zodResolver(FormSchema),<br>  });<br><br>  const { fetchAiResponse } = useFetchAiResponse(setAiResponse);<br><br>  const onSubmit = async (data: z.infer&lt;typeof FormSchema&gt;) =&gt; {<br>    await fetchAiResponse(data);<br>    form.reset();<br>    form.resetField(&quot;topic&quot;);<br>  };<br><br>  return (<br>    &lt;Form {...form}&gt;<br>      &lt;form onSubmit={form.handleSubmit(onSubmit)} className={styles.form}&gt;<br>        // rest of the form content<br>      &lt;/form&gt;<br>    &lt;/Form&gt;<br>  );<br>};<br><br>export default SelectForm;</pre><h3>Testing the Project</h3><p>Now, we have set up everything for the project, and it&#39;s now working as expected. You just need to enter a topic on which you want to generate the short note and AI will send you the response. <br>Here’s a screenshot of the application where the AI has generated the response based on the user prompt :</p><p>Select the topic and click Generate Short Note!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xg223RI6wH6OEQQXvxDIjw.png" /><figcaption>selecting the topic</figcaption></figure><p>Here’s the generated content displayed below the form :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NjD8lafjz3K34_CRWMTGw.png" /><figcaption>generated content</figcaption></figure><h3>Conclusion:</h3><p>Integrating AI into your web apps can significantly enhance their functionality and user experience. By leveraging APIs like those offered by <strong>OpenAI</strong>, you can achieve remarkable use cases and elevate your web applications to new heights.</p><p>I hope this article was useful in demonstrating how you can integrate <strong>OpenAI </strong>into your <strong>Next.js</strong> app and build amazing AI-powered web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb56f9e9a5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/enhancing-your-web-apps-by-ai-integration-using-next-js-and-openai-2eb56f9e9a5e">Enhancing your Web Apps by AI integration using Next.js and OpenAI.</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Your .NET]]></title>
            <link>https://medium.com/paktolus-engineering/securing-your-net-87b44195663f?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/87b44195663f</guid>
            <category><![CDATA[license]]></category>
            <category><![CDATA[license-key]]></category>
            <category><![CDATA[licensing]]></category>
            <dc:creator><![CDATA[Naeem Quraishi]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 00:40:54 GMT</pubDate>
            <atom:updated>2025-01-03T19:49:18.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xkp5L9TpYur0THIY-X7tdA.png" /></figure><h3><strong>Securing Your .NET Application: A Step-by-Step Guide to Implement Licensing with .NET Reactor and Standard.Licensing</strong></h3><p>In the world of software development, protecting your hard work is crucial. One effective way to safeguard your .NET application is by implementing licensing mechanisms. In this blog post, we’ll explore two approaches — using the paid tool .NET Reactor and the free library Standard.Licensing — to help you secure your application and ensure that only authorized users can access it.</p><p><strong>1.</strong> <strong>.NET Reactor</strong></p><p>.NET Reactor is a powerful and popular tool that provides code protection and licensing features for .NET applications. Follow these steps to implement licensing using .NET Reactor:</p><p><strong>Step 1: Obtain .NET Reactor</strong><br> Visit the .NET Reactor website and download the latest version. Install it on your development machine.</p><p><strong>Step 2: Configure .NET Reactor</strong><br> Launch .NET Reactor and open your project. Navigate to the “Settings” tab and configure the settings according to your preferences, including the type of protection and licensing parameters such as expiration date, usage restrictions, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UzF7tziRKMeXEuypmxvZig.png" /></figure><p><strong>Step 3: Protect Your Application</strong><br> Click on “Protect” to secure your application. .NET Reactor will generate a protected version of your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1KbbxkT96U5d3mjHr9uPug.png" /></figure><p><strong>Step 4: Generate License Key</strong><br> Use .NET Reactor to generate a license key for your application. This key will be used to validate the license during runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*EU0nVK2EQvmphg2yuTyeEQ.png" /></figure><p><strong>Step 5: Integrate Licensing Code</strong><br> Integrate the generated license file into your code using the provided API. In your licensing project, add the necessary code to validate the license key during application startup. This may involve checking the key’s validity, expiration date, and other relevant details.</p><p><strong>2.</strong> <strong>Standard.Licensing</strong></p><p>If you’re looking for a free and open-source alternative, Standard. Licensing is a robust library that simplifies licensing implementation in .NET applications. Here’s how to get started:</p><p><strong>Step 1: Install Standard.Licensing</strong><br> Install the Standard. Licensing NuGet package in your Visual Studio project. You can do this using the NuGet Package Manager or by adding the package reference directly to your project file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*WsEccpwKbsEGQiUrxrdv2w.png" /></figure><p><strong>Step 2: Create a License File</strong><br> Generate a license file that contains information about your application, such as the license key, expiration date, and any custom data you want to include.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*ulq8PPa51tOObeVAZXpg9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Ld3-DxT75Rm2-wqXMyK6zw.png" /></figure><p><strong>Step 3: Integrate Licensing Code</strong><br> In your application, add code to validate the license during startup. Utilize the Standard licensing library to check the license file’s integrity and extract relevant information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*fNqtVN0wzJsOrFrDi6eNbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*uppwf9uE52IYKLZs77k1Mg.png" /></figure><p><strong>Conclusion:<br></strong>Securing your .NET application through licensing is crucial for safeguarding your hard work. Whether you opt for the robust features of “.NET Reactor” or the flexibility of “Standard Licensing,” both methods offer effective ways to control access to your software. Choose the one that best suits your project’s requirements and ensure a smooth, protected user experience for your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87b44195663f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/securing-your-net-87b44195663f">Securing Your .NET</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All that you need to know about POM structure in Cypress automation:]]></title>
            <link>https://medium.com/paktolus-engineering/all-that-you-need-to-know-about-pom-structure-in-cypress-automation-16d030853619?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/16d030853619</guid>
            <category><![CDATA[cypress-automation]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[test-automation-framework]]></category>
            <category><![CDATA[page-object-model]]></category>
            <dc:creator><![CDATA[Ajay Sutar]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 00:34:02 GMT</pubDate>
            <atom:updated>2025-01-03T19:45:24.573Z</atom:updated>
            <content:encoded><![CDATA[<p>Page Object Model (POM) is a design pattern widely used in test automation frameworks to enhance the maintainability and reusability of automated test scripts. It is a JavaScript based end-to-end testing framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENziWufcrP-8MW4RspR8rw.png" /></figure><h4><strong>Here’s what makes the implementation of Page Objects in Cypress different from other frameworks:</strong></h4><ul><li>Reusability: Page Objects help to reuse code and maintainability by encapsulating page-specific logic of modules within separate classes.</li><li>Readability: Page Objects make your tests more readable and maintainable by hiding the complexities of how elements are found and interacted with on the page.</li><li>Easy Maintenance: When UI changes occur in a project, then only need to update the methods or locators of the corresponding Page Object class, rather than modifying entire tests throughout your spec file.</li></ul><h4><strong>Structure of Page Object Model:</strong></h4><figure><img alt="page-object-model-framework-structure-in-cypress" src="https://cdn-images-1.medium.com/max/363/1*Gxz72tnqu30n_iGA-scAXw.png" /><figcaption>Page Object framework structure</figcaption></figure><h4><strong>Steps to create POM framework:</strong></h4><p><strong>Step 1. Create a Page Objects Directory:</strong></p><p>First, create a directory to hold your Page Objects. You can name this directory as ‘page-objects’ or ‘pages’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*DeIfNhUlfZQJTqEpKoD-yg.png" /></figure><p><strong>Step 2. Create Page Object Files and define:</strong></p><p>Inside the page_objects directory, create a separate JavaScript file for each page or component you are testing. Each page of the application should have its own Page Object class. These classes encapsulate the elements and actions related to that specific page and functionality. Each class of page object contains.</p><ol><li>Locators of elements on the webpage (CSS selectors, XPath, etc.)</li><li>And methods to interact with that element (e.g., click, select, type, etc).</li></ol><p>Example:</p><pre>class registerPage {<br>  firstName = &quot;#input-firstname&quot;;<br>  lastName = &quot;#input-lastname&quot;;<br>  email = &quot;#input-email&quot;;<br>  telephone = &quot;#input-telephone&quot;;<br>  password = &quot;#input-password&quot;;<br>  passwordConfirm = &quot;#input-confirm&quot;;<br>  policyCheckbox = &#39;input[type=&quot;checkbox&quot;]&#39;;<br>  continue = &quot;.btn.btn-primary&quot;;<br><br>  firstNameField(FN) {<br>    cy.get(this.firstName).type(FN);<br>  }<br>  lastNameField(LN) {<br>    cy.get(this.lastName).type(LN);<br>  }<br>  emailField(Email) {<br>    cy.get(this.email).type(Email);<br>  }<br>  telephoneField(Phn) {<br>    cy.get(this.telephone).type(Phn);<br>  }<br>  passwordField(Pwd) {<br>    cy.get(this.password).type(Pwd);<br>  }<br>  confirmPasswordField(ConfirmPwd) {<br>    cy.get(this.passwordConfirm).type(ConfirmPwd);<br>  }<br>  checkBox() {<br>    cy.get(this.policyCheckbox).check();<br>  }<br>  continueButton() {<br>    cy.get(this.continue).click();<br>  }<br>}<br>export default registerPage;</pre><p><strong>Step 3. Using Page Objects in Tests:</strong></p><p>In Cypress test files (*.spec.js), we can import and use the Page Objects to interact with elements on the page.</p><p>Example:</p><pre>import registerPage from &quot;../pages/registerPage&quot;;<br><br>describe(&quot;User registration flow&quot;, () =&gt; {<br>  const registObjects = new registerPage();<br><br>  it(&quot;Launch register url&quot;, () =&gt; {<br>    cy.visit(Cypress.env(&quot;URL&quot;));<br>  });<br><br>  it(&quot;Registration flow&quot;, () =&gt; {<br>    cy.fixture(&quot;registrationDetails&quot;).then((data) =&gt; {<br>      registObjects.firstNameField(data.firstName);<br>      registObjects.lastNameField(data.lastName);<br>      registObjects.emailField(data.email);<br>      registObjects.telephoneField(data.contact);<br>      registObjects.passwordField(data.password);<br>      registObjects.confirmPasswordField(data.confirmPassword);<br>    });<br>  });<br>});</pre><p><strong>Fixture file:</strong> Contains sample data or files that can be used in tests.</p><pre>{<br>    &quot;firstName&quot;: &quot;John&quot;,<br>    &quot;lastName&quot;:&quot;Wick&quot;,<br>    &quot;email&quot;:&quot;johnwick@yopmail.com&quot;,<br>    &quot;contact&quot;:&quot;15166184623&quot;,<br>    &quot;password&quot;:&quot;John@123&quot;,<br>    &quot;confirmPassword&quot;:&quot;John@123&quot;<br>}</pre><p>By following these steps we can effectively build project structure using the Page Objects model in Cypress automation, making tests more maintainable and scalable.</p><p><strong>You can find end-to-end code here- </strong><a href="https://github.com/ajay-s99/Cypress-POM-Structure">https://github.com/ajay-s99/Cypress-POM-Structure</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d030853619" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/all-that-you-need-to-know-about-pom-structure-in-cypress-automation-16d030853619">All that you need to know about POM structure in Cypress automation:</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionising Information Retrieval with Generative AI (Text-to-SQL)]]></title>
            <link>https://medium.com/paktolus-engineering/revolutionising-information-retrieval-with-generative-ai-text-to-sql-d61e69702648?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/d61e69702648</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[text-to-sql]]></category>
            <dc:creator><![CDATA[Sandeep Chavan]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 00:18:08 GMT</pubDate>
            <atom:updated>2025-01-03T19:48:01.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Rg8DgOzKv9vZaG9NFYb3g.png" /></figure><h3>Introduction</h3><p>The constant evolution of artificial intelligence has given rise to innovative solutions, and our latest project is at the forefront of this revolution. Combining the capabilities of Generative AI with Text Generation, we’ve developed an Information Retrieval system in Python that aims to redefine the way users interact with databases. This blog post provides an in-depth exploration of the project’s architecture, key functionalities, and the significance it holds in the realm of AI-driven information retrieval.</p><h3>Important Features</h3><h4>Bridging the Gap: Text Generation and Information Retrieval</h4><p>The convergence of text generation and information retrieval is a pivotal development that empowers systems to understand and respond to natural language queries effectively. Our project harnesses advanced techniques from Natural Language Processing (NLP) and Generative AI to create an intelligent system that seamlessly interprets user prompts and retrieves relevant information.</p><h4>Streamlining Queries with Pattern Matching and Lemmatisation</h4><p>The heart of our project lies in the <strong>nlp_search</strong> function, a powerful tool that takes user prompts and refines them using sophisticated techniques. By employing pattern matching and lemmatization, the function ensures that user inputs are processed into structured SQL queries with precision and accuracy. The integration of the Pattern Matcher and spaCy library enhances the system’s ability to understand and respond to diverse queries.</p><h4>Database Connectivity and Schema Design</h4><p>Flexibility is key in any robust information retrieval system. To cater to diverse database structures, we’ve provided users with the ability to define their schema in an SQL file. The <strong>get_data_from_db</strong> function establishes a connection to the specified database, executes the generated SQL query, and organizes the retrieved data into a 2D array. This modular approach allows users to seamlessly integrate our project with their existing data structures.</p><h3>Flow Diagram:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lop5dOJcNcXZkFFGk5tpRg.png" /></figure><h3>Project in Action: Code Walkthrough</h3><p>The <strong>nlp_search</strong> function in “main.py” is the starting point. It executes other sub-functions to generate the final response.</p><pre>def nlp_search(prompt): <br>try: <br>  #step 1: <br>  final_prompt = clean_prompt(prompt, nlp, matcher) <br>  #step 2: <br>  sql_query = prepare_sql_statement(final_prompt, ln2sql_obj) <br>  #step 3: <br>  data = get_data_from_db(sql_query) <br>  #step 4: <br>  response = nlp_generate_response(prompt, data, nlp) <br>  return response <br>except: <br>  print(&quot;nlp_search failed. error.&quot;) <br>  return &quot;Failed to get result.&quot;</pre><p>The “main.py” also loads global AI models at startup</p><pre>if __name__ == &quot;__main__&quot;:<br>    nltk.download(&quot;punkt&quot;)<br>    nltk.download(&#39;wordnet&#39;)<br>    nlp = spacy.load(&#39;en_core_web_sm&#39;)<br>    matcher = Matcher(nlp.vocab)<br>    add_spacy_matcher(matcher)<br>    ln2sql_obj = Ln2sql(<br>        database_path=os.path.dirname(__file__) + &quot;/database_store/insurance.sql&quot;,<br>        language_path=os.path.dirname(__file__) + &quot;/lang_store/english.csv&quot;,<br>        json_output_path=&quot;&quot;,<br>        thesaurus_path=&quot;&quot;,<br>        stopwords_path=&quot;&quot;,<br>    )</pre><h4>Step 1: Cleaning the Prompt (NLU)</h4><p>The <strong>clean_prompt</strong> function serves as the first step in preparing user queries for efficient retrieval. This multifaceted function replaces words from a predefined dictionary, handles date-related queries by converting them into actual dates, and incorporates additional language operations. The result is a cleaned and refined prompt that sets the stage for accurate information retrieval.</p><pre>def clean_prompt(prompt, nlp, matcher): <br>  final_prompt = re.sub(r&#39;\s+&#39;, &#39; &#39;, prompt) <br>  final_prompt = lookup_dates(final_prompt, nlp) <br>  final_prompt = lookup_words_nlp(final_prompt, nlp, matcher) <br>  doc = nlp(final_prompt) <br>  final_prompt = lemmatize_text(final_prompt, nlp) <br>return final_prompt</pre><p>It uses a matcher to train the model to fine-tune the “prompt”. In the below code, this function will add the ability to the matcher to replace “policy #”, “policy number” or “policy no” (with or without space or special char) with the “policy_number” word which is the database entity field.</p><pre>def add_spacy_matcher(matcher):<br>    patterns = []<br>    patterns.append([{&#39;LOWER&#39;: &#39;policynumber&#39;}])<br>    patterns.append([{&#39;LOWER&#39;: &#39;policy&#39;}, {&#39;LOWER&#39;: &#39;number&#39;}])<br>    patterns.append([{&#39;LOWER&#39;: &#39;policy&#39;}, {&#39;IS_PUNCT&#39;: True, &#39;OP&#39;:&#39;*&#39;}, {&#39;LOWER&#39;: &#39;number&#39;}])<br>    patterns.append([{&#39;LOWER&#39;: &#39;policyno&#39;}])<br>    patterns.append([{&#39;LOWER&#39;: &#39;policy&#39;}, {&#39;LOWER&#39;: &#39;no&#39;}])<br>    patterns.append([{&#39;LOWER&#39;: &#39;policy&#39;}, {&#39;IS_PUNCT&#39;: True, &#39;OP&#39;:&#39;*&#39;}, {&#39;LOWER&#39;: &#39;no&#39;}])<br>    patterns.append([{&#39;LOWER&#39;: &#39;policy#&#39;}])<br>    patterns.append([{&#39;LOWER&#39;: &#39;policy&#39;}, {&#39;LOWER&#39;: &#39;#&#39;}])<br>    matcher.add(&#39;policy_number&#39;, patterns)</pre><h4>Step 2: SQL Query Generation (Text-to-SQL)</h4><p>The <strong>prepare_sql_statement</strong> function utilizes the Ln2Sql library to convert the cleaned prompt into a structured SQL query. This step is critical in ensuring that user intent is accurately translated into a format understandable by the database. The generated SQL query lays the groundwork for effective data retrieval.</p><pre>def prepare_sql_statement(prompt, ln2sql_obj): <br>  sql_query = ln2sql_obj.get_query(prompt) <br>  sql_query = &quot; &quot;.join(sql_query.split()) <br>  return sql_query</pre><h4>Step 3: Database Interaction</h4><p>The <strong>get_data_from_db</strong> function establishes a connection to the specified database and executes the generated SQL query. The retrieved data is organized into a 2D array, where the 0th array contains column headers, and subsequent arrays represent data values. This organized structure is pivotal for creating a human-readable response.</p><pre>def get_data_from_db(sql_query): <br>  data = [] <br>  con = sqlite3.connect(&quot;./database_store/sample.db&quot;) <br>  #connect to the database and fetch result in 2d List <br>  cur = con.cursor() <br>  cur.execute(sql_query) <br>  # Fetch the column names from the cursor&#39;s description <br>  column_names = [member[0] for member in cur.description] <br>  data.append(column_names)<br>  myresult = cur.fetchall() <br>  for x in myresult: <br>    data.append(list(x)) <br>  return data</pre><h4>Step 4: Generating Human-like Text Response (NLG)</h4><p>The <strong>nlp_generate_response</strong> function transforms the fetched data into a coherent and human-like text response. Whether the user is querying a single data point or multiple values, this function ensures that the response is informative, structured, and easily comprehensible. We have used a Hugging face transformer to generate human-like text by providing original prompts and answer hints as input to the model.</p><pre>import re<br>#import hugging face transformers<br>from transformers import T5Tokenizer, T5ForConditionalGeneration</pre><pre># step 4: This function sould generate human readable response<br>def nlp_generate_response(prompt: str, data, nlp):<br>    prompt = re.sub(r&#39;\s+&#39;, &#39; &#39;, prompt)</pre><pre>    data_string = &quot;&quot;<br>    if len(data) &gt; 1:<br>        data_count = len(data[0])<br>        if data_count == 1:<br>            data_string = str(data[1][0])<br>        elif data_count &gt; 1:<br>            index = 0<br>            for labal in data[0]:<br>                data_string += f&quot;{labal.replace(&#39;_&#39;, &#39; &#39;).title()} is {data[1][index]}&quot;<br>                if index == data_count - 2:<br>                    data_string += &quot; and &quot;<br>                elif index != data_count - 1:<br>                    data_string += &quot;, &quot;<br>                index += 1</pre><pre>    #initialize model from Hugging face<br>    tokenizer = T5Tokenizer.from_pretrained(&quot;google/flan-t5-base&quot;)<br>    model = T5ForConditionalGeneration.from_pretrained(&quot;google/flan-t5-base&quot;)</pre><pre>    input_text = f&quot;Create statement from question and answer. {prompt} \n Answer: {data_string}&quot;<br>    input_ids = tokenizer(input_text, return_tensors=&quot;pt&quot;, max_new_tokens=50).input_ids</pre><pre>    outputs = model.generate(input_ids)<br>    return tokenizer.decode(outputs[0])</pre><h3>Conclusion</h3><p>In conclusion, our Information Retrieval project represents a significant leap forward in leveraging Generative AI and text generation for database interactions. By incorporating advanced NLP techniques, database connectivity, and SQL query generation, we aim to revolutionize the way users interact with and extract information from databases. This project not only showcases the capabilities of modern AI but also sets the stage for future advancements in intelligent information retrieval systems. The fusion of Generative AI and information retrieval is a potent force, and our project stands as a testament to the endless possibilities that emerge at this intersection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61e69702648" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/revolutionising-information-retrieval-with-generative-ai-text-to-sql-d61e69702648">Revolutionising Information Retrieval with Generative AI (Text-to-SQL)</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iText 7 ASP.NET Core : Solve “FontProvider and FontSet are Empty” Error]]></title>
            <link>https://medium.com/paktolus-engineering/itext-7-asp-net-core-solve-fontprovider-and-fontset-are-empty-error-0ae081f1853e?source=rss----e48f673dd523---4</link>
            <guid isPermaLink="false">https://medium.com/p/0ae081f1853e</guid>
            <category><![CDATA[itext7]]></category>
            <category><![CDATA[fontprovider-error]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Sandeep Chavan]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 00:16:27 GMT</pubDate>
            <atom:updated>2025-01-03T19:37:05.993Z</atom:updated>
            <content:encoded><![CDATA[<h3>iText 7 ASP.NET Core: <strong>Solve “FontProvider and FontSet are Empty” Error</strong></h3><p>In the realm of web development, PDF generation is a crucial aspect, often requiring the integration of third-party libraries. When working with ASP.NET 6 and iText 7 for PDF creation, developers may encounter the perplexing “FontProvider and FontSet are Empty” error. This blog post aims to shed light on this issue and provide a step-by-step guide on how to resolve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRmPAhiY2w2LM7PU1bP0Ew.png" /></figure><h4><strong>Understanding the Error</strong></h4><p>The “FontProvider and FontSet are Empty” error can be a stumbling block for developers attempting to generate PDF content using iText 7 in an ASP.NET 6 application. This error typically indicates a lack of font information for the PDF document, causing the library to struggle with font resolution during the rendering process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RHx6NLII0SOtYc7Rsh7ag.png" /><figcaption>Application will break at “document.add(item)”</figcaption></figure><h4><strong>Identifying the Root Cause</strong></h4><p>To address this error, it’s crucial to delve into its origins. Often, it stems from font properties not being properly set within the HTML content that you are attempting to convert into a PDF. Fonts play a pivotal role in the appearance of the document, and iText 7 requires accurate font information for seamless PDF generation.</p><p>When we checked the “Font” property of every “item”, we found that it is set to the “times” string and there is no font available in the “StandardFonts” constants as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLnS79O60E2iNqSIRTvXEg.png" /><figcaption>Notice that “item” has “times” as font property.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*L0Z7g7Z13znyEUYcHKn1wQ.png" /><figcaption>In the “StandardFonts” class “times” is not defined.</figcaption></figure><h4><strong>Solving the Issue — A DIY Approach</strong></h4><p>One effective solution to the “FontProvider and FontSet are Empty” error involves creating a function to remove font properties from all nested elements in the HTML content. By systematically cleaning up the font-related attributes, developers can ensure a clean slate for the PDF generation process. It will follow the parent element/document font style. This DIY approach tackles the issue head-on, providing a workaround while maintaining the structural integrity of the HTML content.</p><pre>if (element.HasProperty(Property.FONT))<br>{<br>    element.DeleteOwnProperty(Property.FONT);<br>}</pre><h4><strong>Step-by-Step Guide</strong></h4><p>In this section, we will provide a step-by-step guide on implementing the function to remove font properties. This guide will empower developers to address the error efficiently, allowing for a smooth PDF generation process in their ASP.NET 6 applications using iText 7.</p><p>Step 1: Create a Windows/Web project in .Net 6 (We have created an Asp.Net MVC project)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*bMWG3_mkrxbpB-rT_hNzVg.png" /></figure><p>Step 2: Add “itext7”, “itext7.pdfhtml”, “itext.bouncy-castle-adapter” Nuget libraries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*MY_UddxuOmRX3QFaVVhtLA.png" /></figure><p>Step 3: Add the below code in the “HomeController” class and add the “var data = CreatePdf();” code in the “Index()” method.</p><pre>private string CreatePdf()<br>        {<br>            try<br>            {<br>                string destFileName = @&quot;C:\temp\test.pdf&quot;;<br>                using (PdfWriter writer = new PdfWriter(destFileName))<br>                {<br>                    using (PdfDocument pdfDocument = new PdfDocument(writer))<br>                    {<br>                        Document document = new Document(pdfDocument);<br>                        document.Add(new Paragraph(&quot;Hello World!&quot;));<br>                        string customHtml = &quot;&lt;div&gt;&lt;p&gt;&lt;span&gt;Test Para 1&lt;/span&gt;&lt;/p&gt;&gt;&lt;p&gt;&lt;span&gt;Test Para 2&lt;/span&gt;&lt;/p&gt;&lt;/div&gt;&quot;;<br>                        var elements = HtmlConverter.ConvertToElements(customHtml);<br>                        List&lt;Paragraph&gt; paraList = GetParagraphs(elements);<br>                        foreach (var item in paraList)<br>                        {<br>                            document.Add((Paragraph)item);<br>                        }<br>                    }<br>                }<br>                return destFileName;<br>            }<br>            catch (Exception ex)<br>            {<br>                throw;<br>            }<br>        }<br>        private List&lt;Paragraph&gt; GetParagraphs(IList&lt;IElement&gt; elements)<br>        {<br>            List&lt;Paragraph&gt; list = new List&lt;Paragraph&gt;();<br>            foreach (IElement element in elements)<br>            {<br>                if (element is Paragraph)<br>                {<br>                    list.Add((Paragraph)element);<br>                }<br>                else if (element is IBlockElement)<br>                {<br>                    var tempList = GetParagraphs(((IBlockElement)element).GetChildren());<br>                    if (tempList.Count &gt; 0)<br>                    {<br>                        list.AddRange(tempList);<br>                    }<br>                }<br>            }<br>            return list;<br>        }</pre><p>Step 4: Now run the project. You will face the “FontProvider and FontSet are Empty” error.</p><p>Step 5: Stop the debugging and add the below code. Also add “ClearUnwantedProperties(elements);” this code after “HtmlConverter.ConvertToElements(customHtml);” in “CreatePdf()” function.</p><pre>private void ClearUnwantedProperties(IList&lt;IElement&gt; elements)<br>        {<br>            foreach (IElement element in elements)<br>            {<br>                if (element.HasProperty(Property.FONT))<br>                {<br>                    element.DeleteOwnProperty(Property.FONT);<br>                }<br>                if (element is IBlockElement)<br>                {<br>                    var childs = ((IBlockElement)element).GetChildren();<br>                    if (childs.Count &gt; 0)<br>                    {<br>                        ClearUnwantedProperties(childs);<br>                    }<br>                }<br>            }<br>        }</pre><p>Now run the code. The issue is resolved! Happy Coding!</p><h4><strong>Alternative Solution:</strong></h4><p>Another approach is you add FontProvider for font “times” so you will not need to remove Font property. But we have not followed this approach because today “HtmlConverter.ConvertToElements” applies the “times” string and it may be different for other elements or in the future. So instead we removed the font property and followed our standard fonts.</p><h4><strong>Best Practices for PDF Generation in ASP.NET 6</strong></h4><p>To prevent similar font-related issues in the future, adopting best practices for PDF generation is essential. This section will explore recommendations for handling fonts, styling, and other nuances that contribute to a seamless and error-free PDF generation experience.</p><h4><strong>Conclusion:</strong></h4><p>Resolving the “FontProvider and FontSet are Empty” error in iText 7 for PDF generation in ASP.NET 6 requires a strategic approach. By understanding the error, identifying its root cause, and implementing a practical solution, developers can overcome this obstacle and enhance the reliability of their PDF generation process. This blog post aims to equip developers with the knowledge and tools needed to tackle font-related challenges and deliver polished PDF documents in their ASP.NET 6 applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ae081f1853e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paktolus-engineering/itext-7-asp-net-core-solve-fontprovider-and-fontset-are-empty-error-0ae081f1853e">iText 7 ASP.NET Core : Solve “FontProvider and FontSet are Empty” Error</a> was originally published in <a href="https://medium.com/paktolus-engineering">Paktolus Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>