<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ German Cocca - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ German Cocca - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 18 May 2026 10:46:44 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/GerCocca/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Event-Based Architectures in JavaScript: A Handbook for Devs ]]>
                </title>
                <description>
                    <![CDATA[ In modern software development, event-driven architectures have become one of the most powerful ways to build scalable, decoupled, and responsive systems. Instead of relying on direct calls between components, event-driven systems communicate through... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/event-based-architectures-in-javascript-a-handbook-for-devs/</link>
                <guid isPermaLink="false">690b87a7da01ae579df92085</guid>
                
                    <category>
                        <![CDATA[ software architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ event-driven-architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Wed, 05 Nov 2025 17:21:43 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762296111539/a47bf1c2-1d4d-4c3b-8006-4f3479647f75.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In modern software development, <strong>event-driven architectures</strong> have become one of the most powerful ways to build scalable, decoupled, and responsive systems.</p>
<p>Instead of relying on direct calls between components, event-driven systems communicate through events – messages that signal that something has happened.</p>
<p>JavaScript, with its inherently asynchronous nature and built-in event loop, is a natural fit for this paradigm. From browser interactions to backend microservices, event-based communication enables flexibility, performance, and maintainability across the entire stack.</p>
<p>This handbook explores how event-driven architectures work, how they can be implemented in JavaScript (both in Node.js and in the browser), and why they are foundational to building modern distributed applications.</p>
<h3 id="heading-prerequisites-what-you-should-already-know">Prerequisites: What you should already know</h3>
<ul>
<li><p>JavaScript fundamentals (ES6+): modules, classes, closures, <code>this</code></p>
</li>
<li><p>Asynchronous JS: callbacks, Promises, <code>async</code>/<code>await</code>, and the event loop</p>
</li>
<li><p>Node.js basics</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-introduction">1. Introduction</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-an-event-driven-architecture">What Is an Event-Driven Architecture?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-javascript-naturally-fits-this-paradigm">Why JavaScript Naturally Fits This Paradigm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-event-driven-vs-request-driven-architectures">Event-Driven vs. Request-Driven Architectures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-it-makes-sense-to-use-an-event-driven-architecture">When It Makes Sense to Use an Event-Driven Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-it-might-not-be-the-right-choice">When It Might Not Be the Right Choice</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-typical-business-use-cases">Typical Business Use Cases</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-2-fundamentals-of-the-event-model-in-javascript">2. Fundamentals of the Event Model in JavaScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-event-loop-task-queue-and-call-stack">The Event Loop, Task Queue, and Call Stack</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-eventemitter-and-the-pubsub-pattern">EventEmitter and the Pub/Sub Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-eventtarget-customevent-and-browser-events">EventTarget, CustomEvent, and Browser Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-putting-it-all-together">Putting It All Together</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-3-publishersubscriber-pubsub-pattern">3. Publisher–Subscriber (Pub/Sub) Pattern</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-concept-and-advantages-of-decoupling">Concept and Advantages of Decoupling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-basic-implementation-in-plain-javascript">Basic Implementation in Plain JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitations-and-when-to-use-a-library">Limitations and When to Use a Library</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-4-implementations-in-nodejs">4. Implementations in Node.js</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-native-events-module">How to Use the Native events Module</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-example-event-oriented-microservice">Real Example: Event-Oriented Microservice</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-error-handling-and-backpressure">Error Handling and Backpressure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-an-event-bus-across-services">How to Build an Event Bus Across Services</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-1">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-5-event-driven-microservices-architecture">5. Event-Driven Microservices Architecture</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-asynchronous-communication-via-message-brokers">Asynchronous Communication via Message Brokers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-order-inventory-notification-flow">Example: Order → Inventory → Notification Flow</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-designing-event-contracts-event-schemas">Designing Event Contracts (Event Schemas)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-an-event-driven-microservice-architecture">When to Use an Event-Driven Microservice Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-2">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-6-frontend-applications-and-events">6. Frontend Applications and Events</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-custom-events-in-the-browser">Custom Events in the Browser</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-event-communication-in-modern-frameworks">Event Communication in Modern Frameworks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-time-architectures-websockets-and-server-sent-events">Real-Time Architectures: WebSockets and Server-Sent Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-3">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-7-event-sourcing-and-cqrs-command-query-responsibility-segregation">7. Event Sourcing and CQRS (Command Query Responsibility Segregation)</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-event-sourcing-the-core-idea">Event Sourcing: The Core Idea</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-reconstructing-state-from-events">Example: Reconstructing State from Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cqrs-command-query-responsibility-segregation">CQRS: Command Query Responsibility Segregation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-difference-between-event-sourcing-and-pubsub">Difference Between Event Sourcing and Pub/Sub</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-event-sourcing-and-cqrs">When to Use Event Sourcing and CQRS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-4">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-8-benefits-and-challenges">8. Benefits and Challenges</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-benefits-of-eda">Benefits of EDA</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-challenges-of-eda">Challenges of EDA</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-5">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-9-real-world-use-cases">9. Real-World Use Cases</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-financial-and-banking-systems">1. Financial and Banking Systems</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-e-commerce-platforms">2. E-commerce Platforms</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-iot-and-sensor-networks">3. IoT and Sensor Networks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-real-time-analytics-and-monitoring">4. Real-Time Analytics and Monitoring</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-social-networks-and-messaging-apps">5. Social Networks and Messaging Apps</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-workflow-automation-and-orchestration">6. Workflow Automation and Orchestration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-6">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-10-best-practices-and-conclusions">10. Best Practices and Conclusions</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-version-and-validate-events">1. Version and Validate Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-design-for-idempotency">2. Design for Idempotency</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-keep-events-meaningful-and-self-contained">3. Keep Events Meaningful and Self-Contained</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-implement-robust-error-handling-and-dead-letter-queues">4. Implement Robust Error Handling and Dead-Letter Queues</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-ensure-observability-and-traceability">5. Ensure Observability and Traceability</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-use-patterns-for-reliability">6. Use Patterns for Reliability</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-choose-the-right-broker-for-the-job">7. Choose the Right Broker for the Job</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-balance-event-driven-and-request-driven-approaches">8. Balance Event-Driven and Request-Driven Approaches</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-educate-and-align-the-team">9. Educate and Align the Team</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-start-small-then-evolve">10. Start Small, Then Evolve</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-1-introduction">1. Introduction</h2>
<p>Software systems are becoming increasingly distributed, asynchronous, and complex. Traditional <strong>request–response</strong> architectures – where one component directly calls another and waits for a reply – often create tight coupling and limit scalability.</p>
<p>In contrast, <strong>event-driven architectures (EDA)</strong> embrace asynchrony by letting components communicate through events (messages that represent a change or an occurrence in the system). When an event happens (for example, <em>“Order Created”</em>), other parts of the system that care about that event can react to it independently, without knowing who triggered it or when.</p>
<p>This simple shift from <strong>commands</strong> to <strong>events</strong> has profound implications for scalability, resilience, and system design. It allows applications to evolve as loosely coupled collections of independent components that listen for and emit events, rather than monolithic blocks of code that depend directly on each other.</p>
<h3 id="heading-what-is-an-event-driven-architecture">What Is an Event-Driven Architecture?</h3>
<p>An event-driven architecture is a software design pattern where the flow of the program is determined by events. An <strong>event</strong> can be any significant change in state, like a user action, a message from another system, a sensor reading, or even an internal trigger like a database update.</p>
<p>In this model:</p>
<ul>
<li><p><strong>Producers</strong> (also called emitters or publishers) generate and broadcast events.</p>
</li>
<li><p><strong>Consumers</strong> (or listeners or subscribers) react to those events asynchronously.</p>
</li>
</ul>
<p>Unlike traditional request-driven systems, producers and consumers don’t directly call each other. Instead, they communicate through a <strong>mediator</strong> (like an event bus, queue, or topic), achieving loose coupling and higher flexibility.</p>
<h3 id="heading-why-javascript-naturally-fits-this-paradigm">Why JavaScript Naturally Fits This Paradigm</h3>
<p>JavaScript was built around an event-driven model from its very beginning. In the browser, every user interaction – clicks, scrolls, network responses – is handled through events. The <strong>event loop</strong>, <strong>callback queue</strong>, and <strong>non-blocking I/O</strong> make JavaScript particularly well-suited for systems where many things happen concurrently.</p>
<p>In Node.js, this model extends to the backend. The <code>EventEmitter</code> API, asynchronous I/O, and the single-threaded event loop allow developers to write scalable services that handle thousands of concurrent connections efficiently. This makes JavaScript a natural language for implementing and experimenting with event-driven systems across the full stack, from the UI to distributed microservices.</p>
<h3 id="heading-event-driven-vs-request-driven-architectures">Event-Driven vs. Request-Driven Architectures</h3>
<p>Here’s a quick summary of the main features and differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Request-Driven</td><td>Event-Driven</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Communication</strong></td><td>Direct, synchronous (A calls B)</td><td>Indirect, asynchronous (A emits event, B reacts)</td></tr>
<tr>
<td><strong>Coupling</strong></td><td>Tight (services know each other)</td><td>Loose (services only know event types)</td></tr>
<tr>
<td><strong>Scalability</strong></td><td>Limited by synchronous blocking</td><td>Naturally scalable with asynchronous flows</td></tr>
<tr>
<td><strong>Failure handling</strong></td><td>Errors propagate directly</td><td>Components fail independently</td></tr>
<tr>
<td><strong>Typical example</strong></td><td>REST API call chain</td><td>Message bus or event broker (Kafka, RabbitMQ)</td></tr>
</tbody>
</table>
</div><p>Event-driven systems tend to perform better in environments that require real-time updates, asynchronous workflows, or high concurrency, such as financial transaction systems, IoT platforms, and analytics pipelines.</p>
<p>But adopting an Event-Driven Architecture is not a universal solution. It introduces its own complexities and is best suited to problems where loose coupling, scalability, and reactivity are primary goals.</p>
<h3 id="heading-when-it-makes-sense-to-use-an-event-driven-architecture">When It Makes Sense to Use an Event-Driven Architecture</h3>
<ul>
<li><p><strong>Asynchronous or real-time requirements</strong>: When the system needs to react to changes instantly (for example, new data, user interactions, or external triggers).</p>
</li>
<li><p><strong>High scalability and resilience</strong>: When services must handle variable workloads independently, without blocking or waiting for each other.</p>
</li>
<li><p><strong>Microservices or distributed systems</strong>: When independent services must communicate without strong dependencies or shared state.</p>
</li>
<li><p><strong>Extensibility and flexibility</strong>: When you expect the system to evolve over time, adding new consumers without modifying existing producers.</p>
</li>
<li><p><strong>Data streaming or continuous processing</strong>: When the system processes streams of events (for example, telemetry, logs, or payments) rather than discrete requests.</p>
</li>
</ul>
<h3 id="heading-when-it-might-not-be-the-right-choice">When It Might <em>Not</em> Be the Right Choice</h3>
<ul>
<li><p><strong>Simple, synchronous applications</strong>: For small systems where interactions are linear (for example, a CRUD API or a small monolith), introducing an event bus may be unnecessary overhead.</p>
</li>
<li><p><strong>Strong consistency requirements</strong>; When the system must maintain a strict order of operations or immediate transactional integrity, asynchronous event flows can complicate data coherence.</p>
</li>
<li><p><strong>Limited observability or operational tooling</strong>: Debugging distributed events is harder – tracing and replaying events requires good logging and monitoring infrastructure.</p>
</li>
<li><p><strong>Team inexperience</strong>: If the development team is not familiar with asynchronous systems, event versioning, or message brokers, the cognitive load may outweigh the benefits.</p>
</li>
</ul>
<h3 id="heading-typical-business-use-cases">Typical Business Use Cases</h3>
<ol>
<li><p><strong>E-commerce platforms:</strong> Events like <em>OrderPlaced</em>, <em>PaymentProcessed</em>, <em>ItemShipped</em> trigger workflows across inventory, billing, and logistics services.</p>
</li>
<li><p><strong>Financial and banking systems:</strong> Real-time updates of transactions, fraud detection, and asynchronous settlement processing.</p>
</li>
<li><p><strong>IoT and telemetry processing:</strong> Devices emit data continuously. The backend aggregates, filters, and reacts to these events asynchronously.</p>
</li>
<li><p><strong>Streaming analytics and monitoring:</strong> Continuous event ingestion from applications or sensors to update dashboards and trigger alerts.</p>
</li>
<li><p><strong>Social networks and messaging apps:</strong> Notifications, chat updates, and activity feeds naturally map to event streams that multiple consumers can subscribe to.</p>
</li>
<li><p><strong>Workflow orchestration systems:</strong> Each step in a process (for example, document signed, email sent, approval granted) triggers subsequent actions automatically.</p>
</li>
</ol>
<p>Event-driven architectures change the way we think about program flow. Instead of pulling data or waiting for responses, components <strong>react</strong> to what’s happening in the system.</p>
<p>By leveraging JavaScript’s asynchronous foundations, like the event loop, promises, and non-blocking I/O, developers can build architectures that are more responsive, resilient, and scalable than traditional request-driven designs.</p>
<p>In the next section, we’ll dive deeper into how JavaScript’s event model works, exploring the event loop, the task queue, and the key mechanisms (like <code>EventEmitter</code>) that make this paradigm possible.</p>
<h2 id="heading-2-fundamentals-of-the-event-model-in-javascript">2. Fundamentals of the Event Model in JavaScript</h2>
<p>JavaScript is inherently event-driven. From its earliest days in the browser to its modern incarnation on the server with Node.js, the language has been designed to handle asynchronous operations gracefully through events – signals that something has happened.</p>
<p>Understanding how this works under the hood is essential before applying event-driven principles to large systems.</p>
<h3 id="heading-the-event-loop-task-queue-and-call-stack">The Event Loop, Task Queue, and Call Stack</h3>
<p>At the heart of JavaScript’s concurrency model lies the <strong>event loop</strong>, a mechanism that enables asynchronous, non-blocking behavior in a single-threaded environment.</p>
<p>Let’s break it down:</p>
<ol>
<li><p><strong>Call Stack</strong>: This is where JavaScript executes code line by line. Each function call creates a new frame on the stack.</p>
</li>
<li><p><strong>Task Queue (or Callback Queue)</strong>: When asynchronous operations finish (like a <code>setTimeout</code> or a network request), their callbacks are queued here for later execution.</p>
</li>
<li><p><strong>Event Loop</strong>: Constantly checks if the call stack is empty. When it is, the loop dequeues a task and pushes it onto the stack to execute.</p>
</li>
</ol>
<p>This cycle repeats indefinitely – hence the term <em>“event loop.”</em></p>
<pre><code class="lang-typescript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"A"</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"B"</span>);
}, <span class="hljs-number">0</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"C"</span>);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// A</span>
<span class="hljs-comment">// C</span>
<span class="hljs-comment">// B</span>
</code></pre>
<p>Even though the timeout is <code>0</code>, the callback runs <strong>after</strong> the synchronous code because it’s queued in the task queue and executed only when the call stack is clear.</p>
<p>This model allows JavaScript to remain responsive and non-blocking, even while performing I/O operations or waiting for user input.</p>
<h3 id="heading-eventemitter-and-the-pubsub-pattern">EventEmitter and the Pub/Sub Pattern</h3>
<p>Node.js exposes its event-driven core through the <code>EventEmitter</code> class – one of its most fundamental building blocks.</p>
<p>An <code>EventEmitter</code> lets objects emit events and subscribe to them. This mechanism forms the foundation for countless Node.js APIs, from HTTP servers to file streams.</p>
<p>Here’s a simple example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-comment">// Subscriber (listener)</span>
emitter.on(<span class="hljs-string">'dataReceived'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Data received: <span class="hljs-subst">${data}</span>`</span>);
});

<span class="hljs-comment">// Publisher (emitter)</span>
emitter.emit(<span class="hljs-string">'dataReceived'</span>, <span class="hljs-string">'User profile loaded'</span>);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-typescript">Data received: User profile loaded
</code></pre>
<p>Each event has:</p>
<ul>
<li><p>A <strong>name</strong> (string or symbol)</p>
</li>
<li><p>A set of <strong>listeners</strong> (functions) that react to it</p>
</li>
</ul>
<p>This is the classic <strong>Publisher–Subscriber</strong> pattern (Pub/Sub): components publish events, while others subscribe to react – without direct references to each other.</p>
<h3 id="heading-eventtarget-customevent-and-browser-events">EventTarget, CustomEvent, and Browser Events</h3>
<p>In the browser, the same concept exists through the <code>EventTarget</code> API. Every DOM element can listen for or dispatch events.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>);

button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked!'</span>);
});
</code></pre>
<p>We can also create <strong>custom events</strong> to simulate our own event-driven behavior:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> userEvent = <span class="hljs-keyword">new</span> CustomEvent(<span class="hljs-string">'userLoggedIn'</span>, {
  detail: { name: <span class="hljs-string">'Alice'</span> }
});

<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'userLoggedIn'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Welcome, <span class="hljs-subst">${e.detail.name}</span>!`</span>);
});

<span class="hljs-built_in">document</span>.dispatchEvent(userEvent);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-typescript">Welcome, Alice!
</code></pre>
<p>This lightweight mechanism allows front-end applications to coordinate behavior across components without tight coupling.</p>
<h3 id="heading-putting-it-all-together">Putting It All Together</h3>
<p>Whether in the browser or Node.js, JavaScript’s asynchronous runtime and event-driven APIs form a natural foundation for building reactive, modular, and scalable systems.</p>
<p>In Node.js, nearly everything is an event emitter – HTTP requests, streams, process signals, and even errors. In the browser, events are how users and systems interact through clicks, network responses, and state changes.</p>
<p>This unified model across client and server is what makes JavaScript uniquely powerful for implementing end-to-end event-driven architectures.</p>
<p>In the next section, we’ll explore the Pub/Sub pattern in depth: we’ll understand its advantages, pitfalls, and how to implement it cleanly in plain JavaScript before scaling up to distributed systems.</p>
<h2 id="heading-3-publishersubscriber-pubsub-pattern">3. Publisher–Subscriber (Pub/Sub) Pattern</h2>
<p>The Publisher–Subscriber pattern, often abbreviated as Pub/Sub, is one of the most common and powerful foundations of event-driven systems. It defines how components can communicate asynchronously without knowing each other directly – a principle known as <strong>loose coupling</strong>.</p>
<p>In a Pub/Sub model:</p>
<ul>
<li><p><strong>Publishers</strong> (or emitters) broadcast events.</p>
</li>
<li><p><strong>Subscribers</strong> (or listeners) register interest in those events.</p>
</li>
<li><p>A <strong>broker</strong> (or event bus) acts as a mediator between the two.</p>
</li>
</ul>
<p>This separation allows systems to evolve and scale independently: new subscribers can be added without changing the publishers, and vice versa.</p>
<h3 id="heading-concept-and-advantages-of-decoupling">Concept and Advantages of Decoupling</h3>
<p>In traditional architectures, one component often depends directly on another:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processOrder</span>(<span class="hljs-params">order</span>) </span>{
  sendInvoice(order);
  notifyWarehouse(order);
}
</code></pre>
<p>Here, <code>processOrder</code> is tightly coupled to the functions it calls. If we later need to send a shipping confirmation or trigger analytics, we must modify <code>processOrder</code> again. This violates the <strong>Open/Closed Principle</strong> (open for extension, closed for modification).</p>
<p>In a Pub/Sub model, the same logic becomes event-driven:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> bus = <span class="hljs-keyword">new</span> EventEmitter();

bus.on(<span class="hljs-string">'order:created'</span>, sendInvoice);
bus.on(<span class="hljs-string">'order:created'</span>, notifyWarehouse);

bus.emit(<span class="hljs-string">'order:created'</span>, { id: <span class="hljs-number">42</span>, items: <span class="hljs-number">3</span> });
</code></pre>
<p>Now, <code>processOrder</code> doesn’t need to know who’s listening. It simply emits an event (<code>order:created</code>), and any number of subscribers can react to it – even ones that didn’t exist when the code was written.</p>
<p><strong>Advantages:</strong></p>
<ul>
<li><p>✅ <strong>Loose coupling</strong> between components</p>
</li>
<li><p>⚙️ <strong>Easier extensibility</strong>: add new behaviors by adding listeners</p>
</li>
<li><p>🚀 <strong>Parallel evolution</strong>: teams can work on producers and consumers independently</p>
</li>
<li><p>🧩 <strong>Greater testability</strong>: events can be simulated in isolation</p>
</li>
</ul>
<h3 id="heading-basic-implementation-in-plain-javascript">Basic Implementation in Plain JavaScript</h3>
<p>While Node.js provides a ready-to-use <code>EventEmitter</code>, you can easily build a minimal event bus in plain JavaScript. This helps illustrate the underlying logic:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createEventBus</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> listeners = {};

  <span class="hljs-keyword">return</span> {
    subscribe(event, callback) {
      <span class="hljs-keyword">if</span> (!listeners[event]) listeners[event] = [];
      listeners[event].push(callback);
    },
    publish(event, data) {
      (listeners[event] || []).forEach(<span class="hljs-function">(<span class="hljs-params">callback</span>) =&gt;</span> callback(data));
    },
    unsubscribe(event, callback) {
      listeners[event] = (listeners[event] || []).filter(<span class="hljs-function">(<span class="hljs-params">cb</span>) =&gt;</span> cb !== callback);
    }
  };
}

<span class="hljs-comment">// Example usage</span>
<span class="hljs-keyword">const</span> bus = createEventBus();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onUserRegistered</span>(<span class="hljs-params">user</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Welcome, <span class="hljs-subst">${user.name}</span>!`</span>);
}

bus.subscribe(<span class="hljs-string">'user:registered'</span>, onUserRegistered);
bus.publish(<span class="hljs-string">'user:registered'</span>, { name: <span class="hljs-string">'Alice'</span> });
bus.unsubscribe(<span class="hljs-string">'user:registered'</span>, onUserRegistered);
</code></pre>
<p>This simple implementation already captures the essence of Pub/Sub:</p>
<ul>
<li><p>You can <strong>subscribe</strong> to an event.</p>
</li>
<li><p>You can <strong>publish</strong> events with data.</p>
</li>
<li><p>You can <strong>unsubscribe</strong> dynamically.</p>
</li>
</ul>
<h3 id="heading-limitations-and-when-to-use-a-library"><strong>Limitations and When to Use a Library</strong></h3>
<p>While the above implementation works for small-scale use, real-world systems often require:</p>
<ul>
<li><p>Wildcard or hierarchical event names (for example, <code>order.*</code> or <code>user.created</code>)</p>
</li>
<li><p>Asynchronous delivery (with message queues or brokers)</p>
</li>
<li><p>Error handling and retries</p>
</li>
<li><p>Event persistence or replay</p>
</li>
<li><p>Cross-process or distributed communication</p>
</li>
</ul>
<p>In those cases, using a dedicated library or broker is more appropriate.</p>
<p>Popular options include Node.js’s built-in <code>EventEmitter</code> for in-process events, <code>RxJS</code> for reactive programming and stream composition, and message brokers like RabbitMQ, Kafka, or Redis Streams for distributed, scalable architectures</p>
<p>Each of these tools extends the Pub/Sub model to handle larger scale, fault tolerance, and observability – essential features in modern distributed systems.</p>
<h3 id="heading-summary">Summary</h3>
<p>The Publisher–Subscriber pattern is the backbone of event-driven design. It transforms direct, synchronous function calls into indirect, asynchronous communications, allowing systems to evolve gracefully and handle change without friction.</p>
<p>In JavaScript, this pattern is everywhere – from browser DOM events to Node.js streams and microservice architectures.</p>
<p>In the next section, we’ll dive deeper into practical implementations in Node.js, exploring how the <code>events</code> module powers many of the platform’s most important features and how it can be extended to build robust, event-oriented systems.</p>
<h2 id="heading-4-implementations-in-nodejs">4. Implementations in Node.js</h2>
<p>Node.js was designed from the ground up around the <strong>event-driven paradigm</strong>. Its single-threaded, non-blocking I/O model allows it to handle thousands of concurrent operations efficiently – not by running code in parallel, but by reacting to events as they occur.</p>
<p>At the heart of this model lies the <code>events</code> module, which exposes the <code>EventEmitter</code> class used throughout Node’s core APIs, from HTTP servers to file streams.</p>
<h3 id="heading-how-to-use-the-native-events-module">How to Use the Native <code>events</code> Module</h3>
<p>The <code>EventEmitter</code> class provides a standard way to <strong>emit</strong> and <strong>listen for</strong> events within a Node.js process.<br>It’s a lightweight yet powerful abstraction for asynchronous communication between components.</p>
<p>Let’s look at a simple example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-comment">// Register an event listener</span>
emitter.on(<span class="hljs-string">'user:login'</span>, <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`User logged in: <span class="hljs-subst">${user.name}</span>`</span>);
});

<span class="hljs-comment">// Emit the event</span>
emitter.emit(<span class="hljs-string">'user:login'</span>, { name: <span class="hljs-string">'Alice'</span> });
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-typescript">User logged <span class="hljs-keyword">in</span>: Alice
</code></pre>
<p>Each <code>EventEmitter</code> instance maintains an internal map of event names to listener functions. Listeners can be added using <code>.on()</code> or <code>.once()</code> (for one-time execution), and events are triggered asynchronously with <code>.emit()</code>.</p>
<h3 id="heading-real-example-event-oriented-microservice">Real Example: Event-Oriented Microservice</h3>
<p>To see this in action, imagine a simplified order-processing microservice:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> bus = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createOrder</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Order created: <span class="hljs-subst">${order.id}</span>`</span>);
  bus.emit(<span class="hljs-string">'order:created'</span>, order);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendInvoice</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Invoice sent for order <span class="hljs-subst">${order.id}</span>`</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateInventory</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Inventory updated for order <span class="hljs-subst">${order.id}</span>`</span>);
}

<span class="hljs-comment">// Subscribe listeners</span>
bus.on(<span class="hljs-string">'order:created'</span>, sendInvoice);
bus.on(<span class="hljs-string">'order:created'</span>, updateInventory);

<span class="hljs-comment">// Simulate an order</span>
createOrder({ id: <span class="hljs-number">123</span>, items: [<span class="hljs-string">'Book'</span>, <span class="hljs-string">'Pen'</span>] });
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-typescript">Order created: <span class="hljs-number">123</span>
Invoice sent <span class="hljs-keyword">for</span> order <span class="hljs-number">123</span>
Inventory updated <span class="hljs-keyword">for</span> order <span class="hljs-number">123</span>
</code></pre>
<p>Here, the microservice emits an <code>order:created</code> event whenever a new order is placed. Multiple listeners (invoice and inventory handlers) react independently – a miniature event-driven architecture in a single process.</p>
<p>This approach scales naturally as the system grows. New behaviors, like sending notifications or analytics tracking, can be added by simply subscribing new listeners.</p>
<h3 id="heading-error-handling-and-backpressure">Error Handling and Backpressure</h3>
<p>In event-driven systems, error management is crucial because unhandled exceptions inside event listeners can crash the entire Node.js process.</p>
<p>To prevent this, Node provides built-in mechanisms:</p>
<ol>
<li><p><strong>Error events</strong>: You can emit and handle errors explicitly.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
 <span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> EventEmitter();

 emitter.on(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'An error occurred:'</span>, err.message);
 });

 emitter.emit(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Database connection failed'</span>));
</code></pre>
<p> If an <code>'error'</code> event is emitted without at least one listener, Node.js will throw it as an uncaught exception and terminate the process.</p>
</li>
<li><p><strong>Backpressure management</strong>: In streaming scenarios, producers can emit data faster than consumers can handle.</p>
<p> Node.js Streams solve this through <strong>backpressure</strong>, where consumers signal when they are ready for more data.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
 <span class="hljs-keyword">const</span> readable = fs.createReadStream(<span class="hljs-string">'large-file.txt'</span>);
 <span class="hljs-keyword">const</span> writable = fs.createWriteStream(<span class="hljs-string">'copy.txt'</span>);

 readable.pipe(writable); <span class="hljs-comment">// Automatically manages flow control</span>
</code></pre>
<p> Under the hood, streams use event-based coordination (<code>data</code>, <code>drain</code>, <code>end</code>) to ensure stability even under heavy load.</p>
</li>
</ol>
<h3 id="heading-how-to-build-an-event-bus-across-services">How to Build an Event Bus Across Services</h3>
<p>While <code>EventEmitter</code> works within a single process, real-world architectures often span multiple microservices or containers. In such cases, an external message broker (like RabbitMQ, Kafka, or Redis Streams) acts as a distributed event bus.</p>
<p>Each service becomes either:</p>
<ul>
<li><p>a <strong>producer</strong> (publishing events), or</p>
</li>
<li><p>a <strong>consumer</strong> (subscribing and reacting).</p>
</li>
</ul>
<p>Node.js integrates seamlessly with these systems using community libraries:</p>
<ul>
<li><p><a target="_blank" href="https://www.npmjs.com/package/amqplib"><code>amqplib</code></a> for RabbitMQ</p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/kafkajs"><code>kafkajs</code></a> for Apache Kafka</p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/redis"><code>redis</code></a> for Redis Pub/Sub</p>
</li>
</ul>
<p>Example (simplified with Redis):</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> { createClient } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'redis'</span>);
<span class="hljs-keyword">const</span> publisher = createClient();
<span class="hljs-keyword">const</span> subscriber = createClient();

<span class="hljs-keyword">await</span> publisher.connect();
<span class="hljs-keyword">await</span> subscriber.connect();

subscriber.subscribe(<span class="hljs-string">'user:created'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`New user event received: <span class="hljs-subst">${message}</span>`</span>);
});

<span class="hljs-keyword">await</span> publisher.publish(<span class="hljs-string">'user:created'</span>, <span class="hljs-built_in">JSON</span>.stringify({ id: <span class="hljs-number">1</span>, name: <span class="hljs-string">'Alice'</span> }));
</code></pre>
<p>This pattern allows <strong>cross-service communication</strong> without tight coupling. Each service reacts to events asynchronously, whether it’s hosted locally or across a cluster.</p>
<h3 id="heading-summary-1">Summary</h3>
<p>The Node.js <code>EventEmitter</code> encapsulates the essence of event-driven design at the process level: lightweight, decoupled, and asynchronous. Combined with external message brokers, it becomes a powerful tool for building scalable, distributed event-driven systems.</p>
<p>Through events, Node.js applications can handle multiple concurrent workflows efficiently, maintain clear separation of concerns, and grow organically as the system evolves.</p>
<p>In the next section, we’ll extend this idea beyond a single application. We’ll explore <strong>Event-Driven Microservices Architecture</strong>, where multiple independent services communicate entirely through asynchronous event flows.</p>
<h2 id="heading-5-event-driven-microservices-architecture">5. Event-Driven Microservices Architecture</h2>
<p>As applications grow, a single event bus inside one process is no longer enough. When your system consists of multiple independently deployed services – each owning its own data and responsibilities – the Event-Driven Architecture becomes a natural fit for enabling asynchronous, decoupled communication.</p>
<p>In an event-driven microservice ecosystem, services don’t call each other directly through HTTP or RPC.<br>Instead, they publish and consume events through a <strong>message broker</strong> – a central medium that handles delivery, queuing, and persistence of messages between services.</p>
<h3 id="heading-asynchronous-communication-via-message-brokers">Asynchronous Communication via Message Brokers</h3>
<p>In a request-driven microservice system, one service directly invokes another via REST or gRPC:</p>
<pre><code class="lang-typescript">Order Service  →  Inventory Service  →  Notification Service
</code></pre>
<p>Each call is synchronous, meaning the caller waits for a response. This creates coupling and potential cascading failures if one service is down or slow.</p>
<p>In an event-driven model, communication happens asynchronously through events:</p>
<pre><code class="lang-typescript">Order Service  →  [Event Bus]  →  Inventory Service, Notification Service
</code></pre>
<p>The event bus becomes the backbone of the system. Each service publishes events and subscribes to those it needs, without knowing who will consume them.</p>
<p>This brings several advantages:</p>
<ul>
<li><p>⚙️ <strong>Loose coupling:</strong> services don’t depend on each other’s availability</p>
</li>
<li><p>📈 <strong>Scalability:</strong> new consumers can subscribe without changing existing code</p>
</li>
<li><p>🔁 <strong>Resilience:</strong> temporary outages are absorbed by the broker’s queues</p>
</li>
<li><p>🧩 <strong>Extensibility:</strong> new workflows can be added just by listening to existing events</p>
</li>
</ul>
<h3 id="heading-example-order-inventory-notification-flow">Example: Order → Inventory → Notification Flow</h3>
<p>Let’s consider a practical scenario in an e-commerce platform:</p>
<ol>
<li><p><strong>Order Service</strong> publishes an <code>order:created</code> event when a user places an order.</p>
</li>
<li><p><strong>Inventory Service</strong> subscribes to <code>order:created</code> and decrements stock.</p>
</li>
<li><p><strong>Notification Service</strong> also subscribes to <code>order:created</code> and sends a confirmation email.</p>
</li>
</ol>
<pre><code class="lang-typescript">          ┌──────────────────────┐
          │   Order Service      │
          │ emits <span class="hljs-string">"order:created"</span>│
          └──────────┬───────────┘
                     │
          ┌──────────▼───────────┐
          │     Event Bus        │
          │ (Kafka, RabbitMQ...) │
          └──────┬───────────────┘
      ┌──────────┴───────────┐   ┌────────────────────┐
      │ Inventory Service    │   │ Notification Service│
      │ updates stock        │   │ sends email         │
      └──────────────────────┘   └────────────────────┘
</code></pre>
<p><strong>Node.js example (simplified with Redis):</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// order-service.js</span>
<span class="hljs-keyword">const</span> { createClient } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'redis'</span>);
<span class="hljs-keyword">const</span> publisher = createClient();
<span class="hljs-keyword">await</span> publisher.connect();

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createOrder</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Order created: <span class="hljs-subst">${order.id}</span>`</span>);
  <span class="hljs-keyword">await</span> publisher.publish(<span class="hljs-string">'order:created'</span>, <span class="hljs-built_in">JSON</span>.stringify(order));
}

createOrder({ id: <span class="hljs-number">42</span>, items: [<span class="hljs-string">'Book'</span>, <span class="hljs-string">'Pen'</span>] });
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// inventory-service.js</span>
<span class="hljs-keyword">const</span> { createClient } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'redis'</span>);
<span class="hljs-keyword">const</span> subscriber = createClient();
<span class="hljs-keyword">await</span> subscriber.connect();

<span class="hljs-keyword">await</span> subscriber.subscribe(<span class="hljs-string">'order:created'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> order = <span class="hljs-built_in">JSON</span>.parse(message);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Updating inventory for order <span class="hljs-subst">${order.id}</span>`</span>);
});
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// notification-service.js</span>
<span class="hljs-keyword">const</span> { createClient } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'redis'</span>);
<span class="hljs-keyword">const</span> subscriber = createClient();
<span class="hljs-keyword">await</span> subscriber.connect();

<span class="hljs-keyword">await</span> subscriber.subscribe(<span class="hljs-string">'order:created'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> order = <span class="hljs-built_in">JSON</span>.parse(message);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Sending confirmation email for order <span class="hljs-subst">${order.id}</span>`</span>);
});
</code></pre>
<p>Each service is now independent. They communicate only through <strong>events</strong>, not direct calls.</p>
<h3 id="heading-designing-event-contracts-event-schemas">Designing Event Contracts (Event Schemas)</h3>
<p>In a distributed system, events are <strong>contracts</strong> – they define what information producers share and consumers rely on. Defining and maintaining these contracts carefully is crucial to avoid breaking downstream consumers.</p>
<p>A good event should:</p>
<ul>
<li><p>Contain enough context for consumers to act independently</p>
</li>
<li><p>Use a <strong>versioned schema</strong> to evolve safely over time</p>
</li>
<li><p>Include metadata like <code>eventId</code>, <code>timestamp</code>, and <code>source</code></p>
</li>
</ul>
<p><strong>Example event schema (JSON):</strong></p>
<pre><code class="lang-typescript">{
  <span class="hljs-string">"event"</span>: <span class="hljs-string">"order:created"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"timestamp"</span>: <span class="hljs-string">"2025-10-29T18:45:00Z"</span>,
  <span class="hljs-string">"data"</span>: {
    <span class="hljs-string">"orderId"</span>: <span class="hljs-number">42</span>,
    <span class="hljs-string">"userId"</span>: <span class="hljs-number">123</span>,
    <span class="hljs-string">"items"</span>: [
      { <span class="hljs-string">"sku"</span>: <span class="hljs-string">"BOOK-001"</span>, <span class="hljs-string">"quantity"</span>: <span class="hljs-number">2</span> },
      { <span class="hljs-string">"sku"</span>: <span class="hljs-string">"PEN-003"</span>, <span class="hljs-string">"quantity"</span>: <span class="hljs-number">1</span> }
    ],
    <span class="hljs-string">"total"</span>: <span class="hljs-number">39.90</span>
  }
}
</code></pre>
<p>Best practices:</p>
<ul>
<li><p>Use namespaced event types (<code>order:created</code>, <code>payment:failed</code>)</p>
</li>
<li><p>Include a version number (<code>v1</code>, <code>v2</code>) to avoid schema drift</p>
</li>
<li><p>Store events in a central registry (for example, JSON Schema repository)</p>
</li>
<li><p>Log all events for auditing and debugging</p>
</li>
</ul>
<h3 id="heading-when-to-use-an-event-driven-microservice-architecture">When to Use an Event-Driven Microservice Architecture</h3>
<p>Event-driven microservices are especially valuable when:</p>
<ul>
<li><p>Systems require real-time updates (for example, notifications, analytics)</p>
</li>
<li><p>Components must operate independently and asynchronously</p>
</li>
<li><p>The platform needs to scale horizontally across services</p>
</li>
<li><p>New capabilities should be added without touching existing code</p>
</li>
</ul>
<p>But this architecture also brings challenges:</p>
<ul>
<li><p>Harder to trace flows across multiple asynchronous hops</p>
</li>
<li><p>Requires observability tools (logs, traces, metrics) to debug issues</p>
</li>
<li><p>Event ordering and exact-once delivery can be complex</p>
</li>
<li><p>Increased operational overhead from managing brokers and message queues</p>
</li>
</ul>
<h3 id="heading-summary-2">Summary</h3>
<p>Event-driven microservices take the principles of the Pub/Sub pattern and scale them across distributed systems. By communicating exclusively through asynchronous events, services become autonomous, resilient, and extensible. This is ideal for modern cloud architectures and high-throughput applications.</p>
<p>In the next section, we’ll shift our focus to the front end and explore how event-driven principles power reactivity in browsers and frameworks like React and Vue, and how technologies like <strong>WebSockets</strong> and <strong>Server-Sent Events</strong> enable real-time user experiences.</p>
<h2 id="heading-6-frontend-applications-and-events">6. Frontend Applications and Events</h2>
<p>While backend systems use event-driven architectures to coordinate between services, frontend applications have relied on event-based programming since JavaScript’s creation. And again, every user interaction is handled through events.</p>
<p>Understanding how events flow in the browser, and how modern frameworks like React and Vue build upon this model, is key to creating responsive, decoupled, and real-time user interfaces.</p>
<h3 id="heading-custom-events-in-the-browser">Custom Events in the Browser</h3>
<p>In vanilla JavaScript, every DOM element can emit and listen to events through the <code>EventTarget</code> API.<br>This mechanism is the foundation of how browsers handle user interaction and component communication.</p>
<p><strong>Example – Basic Event Handling:</strong></p>
<pre><code class="lang-typescript">&lt;button id=<span class="hljs-string">"subscribeBtn"</span>&gt;Subscribe&lt;/button&gt;
&lt;script&gt;
  <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'subscribeBtn'</span>);
  btn.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User subscribed!'</span>);
  });
&lt;/script&gt;
</code></pre>
<p>Here, the button acts as an <strong>event emitter</strong>. When the <code>click</code> event occurs, the listener function reacts. This is a simple example of publish-subscribe behavior within the DOM.</p>
<p>You can also define <strong>custom events</strong> to allow decoupled communication between components:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> userEvent = <span class="hljs-keyword">new</span> CustomEvent(<span class="hljs-string">'user:registered'</span>, {
  detail: { name: <span class="hljs-string">'Alice'</span>, email: <span class="hljs-string">'alice@example.com'</span> }
});

<span class="hljs-comment">// Listen for the event</span>
<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'user:registered'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Welcome <span class="hljs-subst">${e.detail.name}</span>!`</span>);
});

<span class="hljs-comment">// Dispatch it</span>
<span class="hljs-built_in">document</span>.dispatchEvent(userEvent);
</code></pre>
<p>Output:</p>
<pre><code class="lang-typescript">Welcome Alice!
</code></pre>
<p>This approach allows different parts of the UI to react to user actions or system changes without directly calling each other.</p>
<h3 id="heading-event-communication-in-modern-frameworks">Event Communication in Modern Frameworks</h3>
<p>Modern JavaScript frameworks like React, Vue, and Angular abstract the native event system, but the core idea remains the same: <strong>components react to events</strong>.</p>
<h4 id="heading-react-example">React Example</h4>
<p>React’s synthetic event system wraps the browser’s native events, providing a unified interface across browsers.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NewsletterSignup</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleSubmit</span>(<span class="hljs-params">e</span>) </span>{
    e.preventDefault();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Newsletter form submitted!'</span>);
  }

  <span class="hljs-keyword">return</span> (
    &lt;form onSubmit={handleSubmit}&gt;
      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"email"</span> placeholder=<span class="hljs-string">"Your email"</span> /&gt;
      &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;Subscribe&lt;/button&gt;
    &lt;/form&gt;
  );
}
</code></pre>
<p>Behind the scenes, React uses an <strong>event delegation</strong> model: it attaches a single listener at the root and dispatches events down the component tree efficiently.</p>
<p>For cross-component communication, React developers often use:</p>
<ul>
<li><p>Context or state managers (like Redux, Zustand, or Recoil)</p>
</li>
<li><p>Event emitter utilities (like <code>mitt</code> or <code>nanoevents</code>)</p>
</li>
<li><p>Custom hooks for modular event handling</p>
</li>
</ul>
<p>Example using a lightweight emitter (<code>mitt</code>):</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> mitt <span class="hljs-keyword">from</span> <span class="hljs-string">'mitt'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bus = mitt();
</code></pre>
<p>Then anywhere in your app:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Component A</span>
bus.emit(<span class="hljs-string">'theme:changed'</span>, <span class="hljs-string">'dark'</span>);

<span class="hljs-comment">// Component B</span>
bus.on(<span class="hljs-string">'theme:changed'</span>, <span class="hljs-function">(<span class="hljs-params">theme</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Theme updated to <span class="hljs-subst">${theme}</span>`</span>);
});
</code></pre>
<p>This simple event bus decouples components that don’t share a direct parent-child relationship.</p>
<h4 id="heading-vue-example">Vue Example</h4>
<p>Vue provides a native event system for <strong>child-to-parent</strong> communication and also supports global event buses.</p>
<pre><code class="lang-typescript">&lt;template&gt;
  &lt;button <span class="hljs-meta">@click</span>=<span class="hljs-string">"notify"</span>&gt;Notify Parent&lt;/button&gt;
&lt;/template&gt;

&lt;script&gt;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  methods: {
    notify() {
      <span class="hljs-built_in">this</span>.$emit(<span class="hljs-string">'user-registered'</span>, { name: <span class="hljs-string">'Alice'</span> });
    }
  }
};
&lt;/script&gt;
</code></pre>
<p>The parent component can listen for <code>user-registered</code> and react accordingly. Vue 3 also supports custom event buses via external libraries like <code>mitt</code>, enabling component-to-component events without tight coupling.</p>
<h3 id="heading-real-time-architectures-websockets-and-server-sent-events">Real-Time Architectures: WebSockets and Server-Sent Events</h3>
<p>In modern web applications, the event-driven model extends beyond the client, connecting the front end and back end in real-time.</p>
<h4 id="heading-websockets">WebSockets</h4>
<p>WebSockets provide a full-duplex channel between the browser and the server. This means both sides can send events at any time, enabling instant updates without polling.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> socket = <span class="hljs-keyword">new</span> WebSocket(<span class="hljs-string">'wss://example.com/socket'</span>);

socket.addEventListener(<span class="hljs-string">'open'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Connected to server'</span>);
  socket.send(<span class="hljs-built_in">JSON</span>.stringify({ event: <span class="hljs-string">'user:joined'</span>, name: <span class="hljs-string">'Alice'</span> }));
});

socket.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(msg.data);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'New event from server:'</span>, data);
});
</code></pre>
<p>Use cases:</p>
<ul>
<li><p>Real-time chat applications</p>
</li>
<li><p>Live dashboards</p>
</li>
<li><p>Online multiplayer games</p>
</li>
</ul>
<h4 id="heading-server-sent-events-sse">Server-Sent Events (SSE)</h4>
<p>SSE is a simpler alternative when you only need one-way communication – from server to client – using standard HTTP connections.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> source = <span class="hljs-keyword">new</span> EventSource(<span class="hljs-string">'/events'</span>);

source.addEventListener(<span class="hljs-string">'update'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(e.data);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Received update:'</span>, data);
});
</code></pre>
<p>SSE is ideal for live notifications, monitoring dashboards, and continuous data feeds.</p>
<h3 id="heading-summary-3">Summary</h3>
<p>The frontend world has always been event-driven – from DOM interactions to modern component frameworks and real-time connections.</p>
<p>By treating the UI as a system that <strong>reacts to events rather than polling for changes</strong>, we build interfaces that are more responsive, more modular, and easier to extend and integrate with event-driven back ends.</p>
<p>Whether you use <code>CustomEvent</code>, <code>mitt</code>, WebSockets, or SSE, the principle is the same: emit events, listen for changes, and let your app respond asynchronously.</p>
<p>In the next section, we’ll explore how these same principles extend into Event Sourcing and CQRS (Command Query Responsibility Segregation) – advanced architectural patterns that persist and reconstruct system state entirely through events.</p>
<h2 id="heading-7-event-sourcing-and-cqrs-command-query-responsibility-segregation">7. Event Sourcing and CQRS (Command Query Responsibility Segregation)</h2>
<p>Up to this point, we’ve explored events as <strong>transient messages</strong> that trigger behavior – signals passed between components or services. But in more advanced architectures, events can also become the source of truth for the system’s state itself.</p>
<p>This is where <strong>Event Sourcing</strong> and <strong>CQRS</strong> come into play.</p>
<p>These patterns are fundamental in systems that require auditability, replayability, and scalable state reconstruction, such as banking platforms, e-commerce systems, and workflow engines.</p>
<h3 id="heading-event-sourcing-the-core-idea">Event Sourcing: The Core Idea</h3>
<p>In traditional architectures, a system stores only the current state: for example, a database row representing the latest balance of a user’s account.</p>
<p>In Event Sourcing, the system instead stores a series of events that led to that state. Each event represents a historical change, such as <code>AccountCreated</code>, <code>FundsDeposited</code>, or <code>FundsWithdrawn</code>.</p>
<p>When you need the current state, you don’t query a static record – you <strong>replay</strong> all relevant events in sequence.</p>
<p><strong>Traditional Model:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Account</td><td>Balance</td></tr>
</thead>
<tbody>
<tr>
<td>#001</td><td>$500</td></tr>
</tbody>
</table>
</div><p><strong>Event-Sourced Model:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Timestamp</td><td>Event</td><td>Data</td></tr>
</thead>
<tbody>
<tr>
<td>10:00 AM</td><td>AccountCreated</td><td>{ id: 1, owner: 'Alice' }</td></tr>
<tr>
<td>10:05 AM</td><td>FundsDeposited</td><td>{ id: 1, amount: 300 }</td></tr>
<tr>
<td>10:10 AM</td><td>FundsDeposited</td><td>{ id: 1, amount: 200 }</td></tr>
</tbody>
</table>
</div><p>To calculate the balance, you replay the events:</p>
<pre><code class="lang-typescript"><span class="hljs-number">0</span> + <span class="hljs-number">300</span> + <span class="hljs-number">200</span> = $<span class="hljs-number">500</span>
</code></pre>
<p>This approach provides:</p>
<ul>
<li><p>🧾 <strong>Full audit history</strong>: every state change is recorded</p>
</li>
<li><p>🔁 <strong>Replayability</strong>: rebuild state after crashes or schema changes</p>
</li>
<li><p>🧩 <strong>Temporal queries</strong>: know what the system looked like at any point in time</p>
</li>
</ul>
<h3 id="heading-example-reconstructing-state-from-events">Example: Reconstructing State from Events</h3>
<p>Let’s illustrate with a simple JavaScript implementation.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> events = [
  { <span class="hljs-keyword">type</span>: <span class="hljs-string">'AccountCreated'</span>, data: { id: <span class="hljs-number">1</span>, owner: <span class="hljs-string">'Alice'</span> } },
  { <span class="hljs-keyword">type</span>: <span class="hljs-string">'FundsDeposited'</span>, data: { id: <span class="hljs-number">1</span>, amount: <span class="hljs-number">300</span> } },
  { <span class="hljs-keyword">type</span>: <span class="hljs-string">'FundsDeposited'</span>, data: { id: <span class="hljs-number">1</span>, amount: <span class="hljs-number">200</span> } },
  { <span class="hljs-keyword">type</span>: <span class="hljs-string">'FundsWithdrawn'</span>, data: { id: <span class="hljs-number">1</span>, amount: <span class="hljs-number">100</span> } }
];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rebuildAccount</span>(<span class="hljs-params">events</span>) </span>{
  <span class="hljs-keyword">let</span> balance = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> events) {
    <span class="hljs-keyword">switch</span> (event.type) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">'FundsDeposited'</span>:
        balance += event.data.amount;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'FundsWithdrawn'</span>:
        balance -= event.data.amount;
        <span class="hljs-keyword">break</span>;
    }
  }

  <span class="hljs-keyword">return</span> balance;
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Current balance:'</span>, rebuildAccount(events)); <span class="hljs-comment">// 400</span>
</code></pre>
<p>Here, we never stored a static “balance” field. Instead, we <strong>reconstructed</strong> it from the sequence of past events – the same way a ledger works in accounting.</p>
<p>This technique is powerful for debugging, auditing, or migrating systems: you can replay all events in a new environment to rebuild state exactly as it was.</p>
<h3 id="heading-cqrs-command-query-responsibility-segregation">CQRS: Command Query Responsibility Segregation</h3>
<p><strong>CQRS (Command Query Responsibility Segregation)</strong> is a complementary pattern often used with Event Sourcing.<br>It separates the model for writing data (commands) from the model for reading data (queries).</p>
<ul>
<li><p><strong>Commands</strong> modify system state by producing events (<code>OrderPlaced</code>, <code>PaymentProcessed</code>).</p>
</li>
<li><p><strong>Queries</strong> read data optimized for retrieval (for example, a denormalized “view” of orders).</p>
</li>
</ul>
<p>This separation improves scalability and performance because the read and write sides can evolve independently – even use different databases.</p>
<p><strong>Simplified diagram:</strong></p>
<pre><code class="lang-typescript">[User Action]
      │
      ▼
 ┌────────────┐
 │ Command API│  ---&gt;  emits ---&gt;  [Event Store]
 └────────────┘                      │
                                    ▼
                        ┌────────────────────┐
                        │  Read Model / View │
                        │ (e.g., MongoDB)    │
                        └────────────────────┘
</code></pre>
<p><strong>Example (conceptual):</strong></p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">placeOrder</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-comment">// Write model</span>
  eventStore.push({ <span class="hljs-keyword">type</span>: <span class="hljs-string">'OrderPlaced'</span>, data: order });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getOrdersView</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Read model</span>
  <span class="hljs-keyword">return</span> eventStore
    .filter(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> e.type === <span class="hljs-string">'OrderPlaced'</span>)
    .map(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> e.data);
}
</code></pre>
<p>Here, the <strong>event store</strong> acts as the single source of truth, while <strong>query views</strong> can be rebuilt or optimized as needed.</p>
<h3 id="heading-difference-between-event-sourcing-and-pubsub">Difference Between Event Sourcing and Pub/Sub</h3>
<p>It’s common to confuse Event Sourcing with simple event-driven messaging, but they solve different problems:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Pub/Sub</td><td>Event Sourcing</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Purpose</strong></td><td>Asynchronous communication</td><td>Persistent state representation</td></tr>
<tr>
<td><strong>Event lifetime</strong></td><td>Temporary (in transit)</td><td>Permanent (stored)</td></tr>
<tr>
<td><strong>Consumer type</strong></td><td>Services that react</td><td>Systems that rebuild state</td></tr>
<tr>
<td><strong>Example</strong></td><td>Send email when order created</td><td>Reconstruct order history</td></tr>
</tbody>
</table>
</div><p>You can – and often should – use both together: an event-sourced service emits domain events to notify other systems.</p>
<h3 id="heading-when-to-use-event-sourcing-and-cqrs">When to Use Event Sourcing and CQRS</h3>
<p><strong>Use when:</strong></p>
<ul>
<li><p>You need a <strong>complete audit trail</strong> or historical reconstruction.</p>
</li>
<li><p>The business domain is complex and event-driven by nature (finance, logistics, IoT).</p>
</li>
<li><p>The system requires <strong>high resilience</strong> and state recoverability.</p>
</li>
</ul>
<p><strong>Avoid when:</strong></p>
<ul>
<li><p>You’re building a small, CRUD-oriented app with limited complexity.</p>
</li>
<li><p>You don’t need event replay or full history, as it adds storage and operational overhead.</p>
</li>
<li><p>Your team lacks experience managing distributed consistency and event evolution.</p>
</li>
</ul>
<h3 id="heading-summary-4">Summary</h3>
<p>Event Sourcing and CQRS extend event-driven design to the data layer. Instead of only reacting to events, your system persists them and uses them as the foundation for rebuilding, auditing, and scaling.</p>
<p>This approach transforms your architecture from a static data store into a living timeline, where every change is captured as part of an ongoing story of the system’s behavior.</p>
<p>In the next section, we’ll analyze the benefits and challenges of event-driven architectures. We’ll explore why they scale so effectively, but also why debugging and observability can be tricky in large distributed environments.</p>
<h2 id="heading-8-benefits-and-challenges">8. Benefits and Challenges</h2>
<p>Event-driven architectures offer remarkable scalability, resilience, and flexibility, qualities that make them a cornerstone of modern distributed systems. But these benefits come with trade-offs: debugging becomes more complex, data consistency is harder to guarantee, and operational visibility requires specialized tooling.</p>
<p>In this section, we’ll examine both sides — why EDAs are so powerful and what challenges teams face when implementing them.</p>
<h3 id="heading-benefits-of-eda">Benefits of EDA</h3>
<h4 id="heading-1-scalability-and-responsiveness">1. Scalability and Responsiveness</h4>
<p>Event-driven systems naturally handle high concurrency. Because components react to events asynchronously, they can process workloads in parallel without blocking one another.</p>
<p>For example, in a retail platform:</p>
<ul>
<li><p>The <strong>Order Service</strong> publishes an event.</p>
</li>
<li><p>The <strong>Inventory</strong>, <strong>Billing</strong>, and <strong>Notification</strong> services consume it concurrently.</p>
</li>
</ul>
<p>This decoupling allows systems to scale horizontally, adding new consumers or instances without affecting existing ones.</p>
<p>Also, when combined with brokers like Kafka or RabbitMQ, EDAs can handle massive throughput while maintaining order and reliability.</p>
<h4 id="heading-2-loose-coupling-and-extensibility">2. Loose Coupling and Extensibility</h4>
<p>In a traditional system, integrating new functionality often requires editing existing components. In an event-driven system, new consumers simply subscribe to existing events.</p>
<p>For instance, adding a new Analytics Service that listens for <code>order:created</code> events requires:</p>
<ul>
<li><p>No changes to the Order Service</p>
</li>
<li><p>No disruption to other consumers</p>
</li>
<li><p>No coordination between teams</p>
</li>
</ul>
<p>This makes event-driven systems extensible by design, which is invaluable for large organizations with multiple teams or evolving business logic.</p>
<h4 id="heading-3-resilience-and-fault-isolation">3. Resilience and Fault Isolation</h4>
<p>Since communication is asynchronous, if one service fails, others can continue working. Events are buffered in the broker and delivered later.</p>
<p>This prevents cascading failures typical of tightly coupled, request-response systems. For example, if the Notification Service is down, orders can still be processed, and notifications will be sent once it recovers.</p>
<p>Many brokers also provide durable queues and retries, ensuring no event is lost even under heavy load or downtime.</p>
<h4 id="heading-4-real-time-and-reactive-experiences">4. Real-Time and Reactive Experiences</h4>
<p>Event-driven systems power real-time applications, from chat apps and IoT platforms to fraud detection systems and live analytics dashboards.</p>
<p>Because events represent changes as they happen, they enable instant updates, alerts, and responsive UIs. When combined with technologies like WebSockets, Server-Sent Events, or GraphQL Subscriptions, the same model extends seamlessly to the frontend.</p>
<h4 id="heading-5-auditability-and-traceability">5. Auditability and Traceability</h4>
<p>When paired with Event Sourcing, EDAs provide a complete audit trail of everything that has happened in the system. This is crucial for domains like finance, healthcare, or logistics, where compliance and historical accuracy are mandatory.</p>
<h3 id="heading-challenges-of-eda"><strong>Challenges of EDA</strong></h3>
<h4 id="heading-1-debugging-and-tracing">1. Debugging and Tracing</h4>
<p>Unlike synchronous systems, where a stack trace shows the full call path, event-driven systems are <strong>non-linear</strong>. An event may pass through multiple services, queues, and transformations before triggering an outcome.</p>
<p>This makes it difficult to answer questions like:</p>
<blockquote>
<p>“Why did this event trigger twice?”<br>“Where did this data originate?”<br>“Which services consumed this message?”</p>
</blockquote>
<p>To mitigate this, teams rely on <strong>distributed tracing</strong> tools such as:</p>
<ul>
<li><p>OpenTelemetry</p>
</li>
<li><p>Jaeger</p>
</li>
<li><p>Zipkin</p>
</li>
<li><p>AWS X-Ray</p>
</li>
<li><p>Kafka UI / Conduktor (for message inspection)</p>
</li>
</ul>
<p>Embedding trace IDs in event metadata is a best practice that allows cross-service correlation of events.</p>
<h4 id="heading-2-data-consistency">2. Data Consistency</h4>
<p>Because events are asynchronous, maintaining strict <strong>transactional consistency</strong> is challenging. For example, when an <code>OrderPlaced</code> event triggers multiple actions, those actions may complete at different times – or even fail independently.</p>
<p>To manage this, developers often use:</p>
<ul>
<li><p><strong>Idempotent event handlers</strong> (safe to re-run)</p>
</li>
<li><p><strong>Outbox pattern</strong> (ensuring events are emitted only after successful database commits)</p>
</li>
<li><p><strong>Saga pattern</strong> (for distributed transactions and compensating actions)</p>
</li>
</ul>
<p>These patterns add robustness but also increase system complexity.</p>
<h4 id="heading-3-message-duplication-and-ordering">3. Message Duplication and Ordering</h4>
<p>In distributed systems, you must assume:</p>
<ul>
<li><p>Events may arrive twice (due to retries)</p>
</li>
<li><p>Events may arrive out of order</p>
</li>
</ul>
<p>Because of this, consumers need to be designed for <a target="_blank" href="https://www.freecodecamp.org/news/idempotence-explained/">idempotency</a> and order independence. Many event stores or brokers (like Kafka) provide partitioning and offsets to preserve partial ordering, but global order is rarely guaranteed.</p>
<h4 id="heading-4-operational-complexity">4. Operational Complexity</h4>
<p>While adding a message broker improves decoupling, it also introduces new infrastructure to manage:</p>
<ul>
<li><p>Brokers and topics</p>
</li>
<li><p>Retention policies</p>
</li>
<li><p>Consumer groups</p>
</li>
<li><p>Dead-letter queues (for failed messages)</p>
</li>
</ul>
<p>Monitoring and maintaining these systems requires DevOps expertise and mature observability practices.</p>
<h4 id="heading-5-team-and-mental-model-shift">5. Team and Mental Model Shift</h4>
<p>Event-driven systems require developers to think differently:</p>
<ul>
<li><p>Systems become <strong>reactive</strong>, not procedural.</p>
</li>
<li><p>Data flows are <strong>eventual</strong>, not immediate.</p>
</li>
<li><p>Debugging requires <strong>system-wide visibility</strong>, not local inspection.</p>
</li>
</ul>
<p>For teams used to request-response logic, this transition can be difficult, requiring training, discipline, and careful design reviews.</p>
<h3 id="heading-summary-5">Summary</h3>
<p>Event-driven architectures offer:</p>
<ul>
<li><p>⚙️ Scalability</p>
</li>
<li><p>🧩 Extensibility</p>
</li>
<li><p>🔁 Resilience</p>
</li>
<li><p>⚡ Real-time capabilities</p>
</li>
</ul>
<p>But they demand:</p>
<ul>
<li><p>🧠 Rethinking data flow</p>
</li>
<li><p>🔍 Better observability</p>
</li>
<li><p>🧰 Advanced tooling</p>
</li>
</ul>
<p>When implemented carefully, EDAs unlock new levels of system flexibility and business agility, but success depends on balancing their power with strong governance, well-defined event contracts, and team alignment.</p>
<p>In the next section, we’ll look at <strong>real-world use cases</strong>, examining how leading industries like fintech, e-commerce, and IoT leverage event-driven architectures to achieve scale, responsiveness, and reliability.</p>
<h2 id="heading-9-real-world-use-cases">9. Real-World Use Cases</h2>
<p>Event-driven architectures are not just theoretical patterns. They power many of the systems we use every day. From instant payments to social networks, EDAs provide the backbone for handling real-time data, asynchronous workflows, and massive scalability.</p>
<p>Below are some of the most common and impactful use cases across different industries.</p>
<h3 id="heading-1-financial-and-banking-systems">1. Financial and Banking Systems</h3>
<p>Financial institutions rely heavily on asynchronous, reliable event flows to process millions of operations safely and in real time.</p>
<h4 id="heading-typical-events">Typical Events</h4>
<ul>
<li><p><code>TransactionInitiated</code></p>
</li>
<li><p><code>FundsDeposited</code></p>
</li>
<li><p><code>PaymentProcessed</code></p>
</li>
<li><p><code>FraudAlertTriggered</code></p>
</li>
</ul>
<h4 id="heading-how-it-works">How It Works</h4>
<p>When a user initiates a payment:</p>
<ol>
<li><p>The Payment Service emits a <code>PaymentInitiated</code> event.</p>
</li>
<li><p>The Fraud Detection Service subscribes to it, analyzing risk in parallel.</p>
</li>
<li><p>The Ledger Service records the transaction asynchronously.</p>
</li>
<li><p>The Notification Service sends confirmations.</p>
</li>
</ol>
<p>Each component operates independently, and failures or slow responses in one don’t block others.</p>
<h4 id="heading-benefits">Benefits</h4>
<ul>
<li><p>Real-time fraud detection</p>
</li>
<li><p>Parallel transaction processing</p>
</li>
<li><p>Clear audit trail for compliance (with Event Sourcing)</p>
</li>
</ul>
<p><strong>Example:</strong> Modern payment systems (like Revolut, Stripe, and PayPal) use event-driven microservices to orchestrate transactions securely and at scale.</p>
<h3 id="heading-2-e-commerce-platforms">2. E-commerce Platforms</h3>
<p>E-commerce systems are naturally event-driven. Every customer action generates events that ripple across subsystems.</p>
<h4 id="heading-typical-events-1">Typical Events</h4>
<ul>
<li><p><code>OrderCreated</code></p>
</li>
<li><p><code>ItemAddedToCart</code></p>
</li>
<li><p><code>InventoryUpdated</code></p>
</li>
<li><p><code>ShipmentDispatched</code></p>
</li>
</ul>
<h4 id="heading-event-flow-example">Event Flow Example</h4>
<p>When a user places an order:</p>
<ol>
<li><p>The Order Service emits <code>OrderCreated</code>.</p>
</li>
<li><p>Inventory Service reserves stock.</p>
</li>
<li><p>Billing Service processes the payment.</p>
</li>
<li><p>Shipping Service schedules delivery.</p>
</li>
<li><p>Analytics Service records metrics.</p>
</li>
</ol>
<p>Each step occurs asynchronously, allowing thousands of orders to be processed concurrently.</p>
<h4 id="heading-benefits-1">Benefits</h4>
<ul>
<li><p>High scalability during peak sales (for example, Black Friday)</p>
</li>
<li><p>Fault isolation between modules</p>
</li>
<li><p>Easy integration of new services (for example, loyalty or recommendation engines)</p>
</li>
</ul>
<p><strong>Example:</strong> Amazon and Shopify both use event-based pipelines for order management, tracking, and analytics.</p>
<h3 id="heading-3-iot-and-sensor-networks">3. IoT and Sensor Networks</h3>
<p>In IoT ecosystems, thousands or millions of devices constantly emit data. Event-driven architectures are essential for ingesting, processing, and reacting to these streams efficiently.</p>
<h4 id="heading-typical-events-2">Typical Events</h4>
<ul>
<li><p><code>TemperatureMeasured</code></p>
</li>
<li><p><code>DeviceConnected</code></p>
</li>
<li><p><code>MotionDetected</code></p>
</li>
<li><p><code>BatteryLow</code></p>
</li>
</ul>
<h4 id="heading-event-flow-example-1">Event Flow Example</h4>
<ol>
<li><p>Devices publish sensor data to a message broker (like MQTT, Kafka, or AWS IoT Core).</p>
</li>
<li><p>The Processing Service filters and enriches data.</p>
</li>
<li><p>Alert Services emit notifications if thresholds are crossed.</p>
</li>
<li><p>Analytics Pipelines store aggregated data for insights.</p>
</li>
</ol>
<h4 id="heading-benefits-2">Benefits</h4>
<ul>
<li><p>Real-time monitoring</p>
</li>
<li><p>Predictive maintenance (based on event patterns)</p>
</li>
<li><p>Scalable ingestion from thousands of sources</p>
</li>
</ul>
<p><strong>Example:</strong> Smart cities and connected vehicles use event-driven systems to react to sensor data in milliseconds, adjusting traffic lights, tracking fleets, or monitoring energy grids.</p>
<h3 id="heading-4-real-time-analytics-and-monitoring">4. Real-Time Analytics and Monitoring</h3>
<p>Modern analytics systems depend on <strong>stream processing</strong>, continuously ingesting and analyzing events to derive insights instantly.</p>
<h4 id="heading-typical-events-3">Typical Events</h4>
<ul>
<li><p><code>PageViewed</code></p>
</li>
<li><p><code>UserLoggedIn</code></p>
</li>
<li><p><code>MetricUpdated</code></p>
</li>
</ul>
<h4 id="heading-event-flow-example-2">Event Flow Example</h4>
<ol>
<li><p>Applications emit user interaction events to a message queue.</p>
</li>
<li><p>A Stream Processor (like Apache Flink or Kafka Streams) aggregates events in real time.</p>
</li>
<li><p>Dashboards and alerting systems consume processed results via WebSockets or APIs.</p>
</li>
</ol>
<h4 id="heading-benefits-3">Benefits</h4>
<ul>
<li><p>Live metrics and dashboards</p>
</li>
<li><p>Early anomaly detection</p>
</li>
<li><p>Continuous feedback loops for ML models</p>
</li>
</ul>
<p><strong>Example:</strong> Netflix uses event-driven data pipelines (built on Kafka) to monitor playback quality and deliver adaptive streaming experiences in real time.</p>
<h3 id="heading-5-social-networks-and-messaging-apps">5. Social Networks and Messaging Apps</h3>
<p>Social platforms are fundamentally <strong>event-driven systems</strong>. Every post, like, message, or comment is an event that triggers updates across multiple systems.</p>
<h4 id="heading-typical-events-4">Typical Events</h4>
<ul>
<li><p><code>PostCreated</code></p>
</li>
<li><p><code>MessageSent</code></p>
</li>
<li><p><code>UserMentioned</code></p>
</li>
<li><p><code>NotificationDelivered</code></p>
</li>
</ul>
<h4 id="heading-event-flow-example-3">Event Flow Example</h4>
<p>When a user sends a message:</p>
<ol>
<li><p>The Chat Service emits <code>MessageSent</code>.</p>
</li>
<li><p>The Notification Service alerts the recipient.</p>
</li>
<li><p>The Search Index Service updates conversations.</p>
</li>
<li><p>The Analytics Service logs engagement metrics.</p>
</li>
</ol>
<h4 id="heading-benefits-4">Benefits</h4>
<ul>
<li><p>Instant notifications and updates</p>
</li>
<li><p>Asynchronous scalability across millions of users</p>
</li>
<li><p>Modular and evolvable product features</p>
</li>
</ul>
<p><strong>Example:</strong> Slack, WhatsApp, and Facebook Messenger rely on distributed event buses to coordinate billions of message and presence events per day.</p>
<h3 id="heading-6-workflow-automation-and-orchestration">6. Workflow Automation and Orchestration</h3>
<p>Workflow systems such as document approvals, CI/CD pipelines, or business processes are often built around events.</p>
<h4 id="heading-typical-events-5">Typical Events</h4>
<ul>
<li><p><code>TaskCreated</code></p>
</li>
<li><p><code>TaskCompleted</code></p>
</li>
<li><p><code>ApprovalGranted</code></p>
</li>
<li><p><code>PipelineDeployed</code></p>
</li>
</ul>
<h4 id="heading-how-it-works-1">How It Works</h4>
<p>Each action in a workflow triggers the next step through events, allowing flexible orchestration without hardcoding dependencies. This makes it easy to reconfigure or extend workflows dynamically.</p>
<p><strong>Example:</strong> GitHub Actions and Zapier use event-driven models to execute workflows automatically based on triggers (for example, a commit, file upload, or webhook).</p>
<h3 id="heading-summary-6">Summary</h3>
<p>Event-driven architectures power some of the most demanding digital systems in existence. Across industries, they provide:</p>
<ul>
<li><p>⚙️ <strong>Scalable infrastructure</strong> for handling massive event streams</p>
</li>
<li><p>⏱ <strong>Real-time responsiveness</strong> to user and system actions</p>
</li>
<li><p>🧩 <strong>Modularity and evolution</strong> as systems grow by subscribing to new events</p>
</li>
</ul>
<p>Whether in fintech, IoT, e-commerce, or analytics, EDAs have proven to be a flexible, future-proof foundation for building systems that react intelligently to change.</p>
<p>In the final section, we’ll synthesize the lessons learned, summarizing best practices, common pitfalls, and key takeaways for adopting event-driven architectures successfully in modern JavaScript ecosystems.</p>
<h2 id="heading-10-best-practices-and-conclusions">10. Best Practices and Conclusions</h2>
<p>Event-driven architectures offer a flexible, scalable, and future-proof foundation for modern software systems. But their power comes with complexity: events are easy to emit but hard to manage at scale without discipline and consistency.</p>
<p>This final section distills practical best practices for designing and operating event-driven systems effectively, followed by a summary reflection on when and how to adopt this architecture.</p>
<h3 id="heading-1-version-and-validate-events">1. Version and Validate Events</h3>
<p>Events evolve over time as your system grows. Adding or changing fields can break consumers if versions aren’t managed carefully.</p>
<p><strong>Best practices:</strong></p>
<ul>
<li><p>Use explicit versioning in event names or schemas (for example, <code>order:created.v2</code>).</p>
</li>
<li><p>Validate event payloads using JSON Schema or tools like <code>ajv</code> or <code>Zod</code>.</p>
</li>
<li><p>Maintain a central event catalog or schema registry shared by all services.</p>
</li>
</ul>
<p>This ensures backward compatibility and reduces surprises when consumers update at different times.</p>
<h3 id="heading-2-design-for-idempotency">2. Design for Idempotency</h3>
<p>In distributed systems, <strong>duplicate messages</strong> are inevitable – retries, network hiccups, or failovers can cause events to be processed multiple times.</p>
<p>Make consumers idempotent, meaning they can handle the same event repeatedly without unintended side effects.</p>
<p>For example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span> (!processedEvents.has(event.id)) {
  process(event);
  processedEvents.add(event.id);
}
</code></pre>
<p>Always include a unique event ID and check for duplicates before applying changes.</p>
<h3 id="heading-3-keep-events-meaningful-and-self-contained">3. Keep Events Meaningful and Self-Contained</h3>
<p>Each event should represent a <strong>domain-level change</strong>, not just a technical signal. Avoid overly generic messages like <code>"update"</code> or <code>"dataChanged"</code>, as they make debugging and evolution difficult.</p>
<p>Good events:</p>
<ul>
<li><p>Describe <strong>what happened</strong> (not what to do).</p>
</li>
<li><p>Include <strong>enough context</strong> for consumers to act independently.</p>
</li>
<li><p>Avoid exposing internal database models directly.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-typescript">{
  <span class="hljs-string">"event"</span>: <span class="hljs-string">"user:email:updated"</span>,
  <span class="hljs-string">"data"</span>: { <span class="hljs-string">"userId"</span>: <span class="hljs-number">123</span>, <span class="hljs-string">"oldEmail"</span>: <span class="hljs-string">"a@x.com"</span>, <span class="hljs-string">"newEmail"</span>: <span class="hljs-string">"b@x.com"</span> }
}
</code></pre>
<p>This provides clear, business-oriented semantics.</p>
<h3 id="heading-4-implement-robust-error-handling-and-dead-letter-queues">4. Implement Robust Error Handling and Dead-Letter Queues</h3>
<p>Not every event will be processed successfully. Network failures, schema mismatches, or transient service outages are inevitable.</p>
<p><strong>Mitigation strategies:</strong></p>
<ul>
<li><p>Use <strong>retry policies</strong> with exponential backoff.</p>
</li>
<li><p>Send failed messages to a <strong>dead-letter queue (DLQ)</strong> for inspection.</p>
</li>
<li><p>Build <strong>alerting and monitoring</strong> on DLQ metrics to detect recurring issues.</p>
</li>
</ul>
<p>This ensures resilience and prevents message loss.</p>
<h3 id="heading-5-ensure-observability-and-traceability">5. Ensure Observability and Traceability</h3>
<p>Debugging asynchronous flows requires visibility. Embed tracing and correlation data into your events:</p>
<pre><code class="lang-typescript">{
  <span class="hljs-string">"event"</span>: <span class="hljs-string">"payment:processed"</span>,
  <span class="hljs-string">"eventId"</span>: <span class="hljs-string">"9b7f...c0"</span>,
  <span class="hljs-string">"traceId"</span>: <span class="hljs-string">"c74d...d9"</span>,
  <span class="hljs-string">"timestamp"</span>: <span class="hljs-string">"2025-11-03T13:45:00Z"</span>
}
</code></pre>
<p>Integrate with tools like:</p>
<ul>
<li><p>OpenTelemetry for distributed tracing</p>
</li>
<li><p>Jaeger or Zipkin for visualization</p>
</li>
<li><p>Kafka UI, Redpanda Console, or Conduktor for message inspection</p>
</li>
</ul>
<p>This allows you to reconstruct event lifecycles across services, which is critical for debugging, compliance, and performance tuning.</p>
<h3 id="heading-6-use-patterns-for-reliability">6. Use Patterns for Reliability</h3>
<p>Certain design patterns make large-scale event-driven systems more reliable:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Pattern</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Outbox Pattern</strong></td><td>Ensures events are emitted only after DB transactions succeed</td></tr>
<tr>
<td><strong>Saga Pattern</strong></td><td>Coordinates distributed transactions with compensating actions</td></tr>
<tr>
<td><strong>Event Choreography</strong></td><td>Lets services react naturally without central orchestration</td></tr>
<tr>
<td><strong>Event Carried State Transfer</strong></td><td>Includes enough data in events for consumers to act independently</td></tr>
</tbody>
</table>
</div><p>Applying these patterns reduces race conditions and improves data consistency.</p>
<h3 id="heading-7-choose-the-right-broker-for-the-job">7. Choose the Right Broker for the Job</h3>
<p>Different brokers serve different use cases:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Broker</td><td>Strength</td></tr>
</thead>
<tbody>
<tr>
<td><strong>RabbitMQ</strong></td><td>Simple, reliable queues; easy to use for small systems</td></tr>
<tr>
<td><strong>Kafka</strong></td><td>High throughput, event persistence, replayability</td></tr>
<tr>
<td><strong>Redis Streams</strong></td><td>Lightweight, in-memory stream processing</td></tr>
<tr>
<td><strong>NATS / Pulsar</strong></td><td>Low-latency, cloud-native messaging for microservices</td></tr>
</tbody>
</table>
</div><p>Your choice depends on throughput, durability, and delivery guarantees.</p>
<h3 id="heading-8-balance-event-driven-and-request-driven-approaches">8. Balance Event-Driven and Request-Driven Approaches</h3>
<p>Event-driven systems excel in asynchronous workflows, but not everything should be event-driven.</p>
<p>Use <strong>synchronous APIs</strong> for immediate, transactional actions (for example, authentication, user profile lookup). And use <strong>events</strong> for background or decoupled processes (for example, analytics, notifications, async updates).</p>
<p>Combining both models yields the best balance of responsiveness and reliability.</p>
<h3 id="heading-9-educate-and-align-the-team">9. Educate and Align the Team</h3>
<p>Architecture is as much about people as it is about technology. Ensure developers share a common understanding of event naming conventions, schema versioning policies, error handling and retry rules, and ownership of producer and consumer responsibilities.</p>
<p>Without alignment, even the best tools lead to inconsistent, brittle systems.</p>
<h3 id="heading-10-start-small-then-evolve">10. Start Small, Then Evolve</h3>
<p>You don’t need Kafka clusters or event sourcing to begin. Start small:</p>
<ul>
<li><p>Use Node.js <code>EventEmitter</code> or a simple in-memory bus for decoupling modules.</p>
</li>
<li><p>Gradually evolve toward distributed brokers as complexity increases.</p>
</li>
</ul>
<p>The key is incremental adoption – building understanding before scaling infrastructure.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Event-driven architectures fundamentally change how we design software. By focusing on what happens rather than what to do next, systems become more adaptable, reactive, and aligned with real-world processes.</p>
<p>In JavaScript – a language born from events – this paradigm feels especially natural. From browser interactions to Node.js microservices, event-driven thinking unifies the frontend and backend under a single principle: <strong>react to change</strong>.</p>
<p>When used wisely, EDA is not just a design pattern – it’s an architectural mindset that empowers systems to evolve continuously, communicate fluidly, and stay resilient in the face of complexity.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The NestJS Handbook – Learn to Use Nest with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. Combining the best ideas from OOP (Object-Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming)... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-nestjs-handbook-learn-to-use-nest-with-code-examples/</link>
                <guid isPermaLink="false">684c867db87f779c97f2e509</guid>
                
                    <category>
                        <![CDATA[ nestjs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Fri, 13 Jun 2025 20:13:49 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749830137752/799b050a-f884-4043-9db1-fe2bb860d297.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. Combining the best ideas from OOP (Object-Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming), it gives you a fully-architected, batteries-included platform on top of Express (or Fastify).</p>
<p>If you’re coming from Angular, you’ll feel right at home with its module/controller/service structure and powerful dependency-injection system.</p>
<p>In this article we’ll cover both <strong>theory</strong> – why NestJS exists, how it’s structured, and when to reach for it –and <strong>practice</strong>, with bite-sized code snippets demonstrating how to bootstrap a project, define routes, inject dependencies, and more. Let’s start by understanding what NestJS is and where it came from.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-1-what-is-nestjs">What is NestJS?</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-11-history-and-philosophy">1.1 History and Philosophy</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-2-why-choose-nestjs">Why Choose NestJS?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-21-benefits-and-use-cases">2.1 Benefits and Use Cases</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-22-comparison-with-other-frameworks">2.2 Comparison with Other Frameworks</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-3-getting-started">Getting Started</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-31-installing-the-cli">3.1 Installing the CLI</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-32-creating-your-first-project">3.2 Creating Your First Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-33-project-structure-overview">3.3 Project Structure Overview</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-4-core-nestjs-building-blocks">Core NestJS Building Blocks</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-41-modules">4.1 Modules</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-42-controllers">4.2 Controllers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-43-providers-services">4.3 Providers (Services)</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-5-dependency-injection">Dependency Injection</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-51-how-di-works-in-nestjs">5.1 How DI Works in NestJS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-52-custom-providers-and-factory-providers">5.2 Custom Providers and Factory Providers</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-6-routing-amp-middleware">Routing &amp; Middleware</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-61-defining-routes">6.1 Defining Routes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-62-applying-middleware">6.2 Applying Middleware</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-7-request-lifecycle-amp-pipes">Request Lifecycle &amp; Pipes</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-71-what-are-pipes">7.1 What Are Pipes?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-72-built-in-vs-custom-pipes">7.2 Built-In vs. Custom Pipes</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-8-guards-amp-authorization">Guards &amp; Authorization</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-81-implementing-guards">8.1 Implementing Guards</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-82-role-based-access-control">8.2 Role-Based Access Control</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-9-exception-filters">Exception Filters</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-91-handling-errors-gracefully">9.1 Handling Errors Gracefully</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-92-creating-custom-filters">9.2 Creating Custom Filters</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-10-interceptors-amp-logging">Interceptors &amp; Logging</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-101-transforming-responses">10.1 Transforming Responses</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-102-logging-and-performance-metrics">10.2 Logging and Performance Metrics</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-11-database-integration">Database Integration</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-111-typeorm-with-nestjs">11.1 TypeORM with NestJS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-112-mongoose-mongodb">11.2 Mongoose (MongoDB)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-113-prisma">11.3 Prisma</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-12-configuration-management">Configuration Management</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-121-nestjsconfig-module">12.1 @nestjs/config Module</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-122-environment-variables">12.2 Environment Variables</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-13-authentication">Authentication</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-131-jwt-strategy">13.1 JWT Strategy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-132-oauth2-social-login">13.2 OAuth2 / Social Login</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion-amp-further-resources">Conclusion &amp; Further Resources</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-official-docs-and-community-links">Official Docs and Community Links</a></p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-1-what-is-nestjs">1. What is NestJS?</h2>
<p>NestJS is a framework for building server-side applications in Node.js. It’s written in TypeScript (but supports plain JavaScript as well). At its core, it:</p>
<ul>
<li><p><strong>Wraps</strong> a mature HTTP server library (Express or Fastify)</p>
</li>
<li><p><strong>Standardizes</strong> application architecture around modules, controllers, and providers</p>
</li>
<li><p><strong>Leverages</strong> TypeScript’s type system for compile-time safety and clear APIs</p>
</li>
<li><p><strong>Offers</strong> built-in support for things like validation, configuration, and testing</p>
</li>
</ul>
<p>Rather than stitching together middleware by hand, NestJS encourages a declarative, layered approach. You define <strong>modules</strong> to group related functionality, <strong>controllers</strong> to handle incoming requests, and <strong>providers</strong> (often called “services”) for your business logic. Behind the scenes, NestJS resolves dependencies via an IoC container, so you can focus on writing clean, reusable classes.</p>
<p>To start up a project, run the following commands:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Install the Nest CLI globally</span>
npm install -g @nestjs/cli

<span class="hljs-comment"># Create a new project called 'my-app'</span>
nest new my-app

<span class="hljs-built_in">cd</span> my-app
npm run start:dev
</code></pre>
<p>Once it’s running, you have a ready-to-go HTTP server with hot reloading, strict typing, and a sensible folder layout.</p>
<h3 id="heading-11-history-and-philosophy">1.1 History and Philosophy</h3>
<p>NestJS first appeared in 2017, created by Kamil Myśliwiec. Its goal was to bring the architectural patterns of Angular to the backend world, providing:</p>
<ol>
<li><p><strong>Consistency:</strong> A single, opinionated way to structure applications.</p>
</li>
<li><p><strong>Scalability:</strong> Clear boundaries (modules) make it easier to grow teams and codebases.</p>
</li>
<li><p><strong>Testability:</strong> Built-in support for Jest and clear separation of concerns.</p>
</li>
<li><p><strong>Extensibility:</strong> A pluggable module system makes it easy to integrate ORMs, WebSockets, GraphQL, microservices, and more.</p>
</li>
</ol>
<p>Under the hood, NestJS embraces these principles:</p>
<ul>
<li><p><strong>Modularity:</strong> Everything lives in a module (<code>AppModule</code>, <code>UsersModule</code>, and so on), which can import other modules or export providers.</p>
</li>
<li><p><strong>Dependency Injection:</strong> Services can be injected into controllers (and even into other services), which fosters loose coupling.</p>
</li>
<li><p><strong>Decorators and Metadata:</strong> With TypeScript decorators (<code>@Module()</code>, <code>@Controller()</code>, <code>@Injectable()</code>), NestJS reads metadata at runtime to wire everything together.</p>
</li>
</ul>
<p>Here’s a tiny example showing the interplay of these pieces:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// users.service.ts</span>
<span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersService {
  <span class="hljs-keyword">private</span> users = [{ id: <span class="hljs-number">1</span>, name: <span class="hljs-string">'Alice'</span> }];
  findAll() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.users;
  }
}

<span class="hljs-comment">// users.controller.ts</span>
<span class="hljs-keyword">import</span> { Controller, Get } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { UsersService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users.service'</span>;

<span class="hljs-meta">@Controller</span>(<span class="hljs-string">'users'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersController {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> usersService: UsersService</span>) {}

  <span class="hljs-meta">@Get</span>()
  getUsers() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.findAll();
  }
}

<span class="hljs-comment">// users.module.ts</span>
<span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { UsersController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users.controller'</span>;
<span class="hljs-keyword">import</span> { UsersService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users.service'</span>;

<span class="hljs-meta">@Module</span>({
  controllers: [UsersController],
  providers: [UsersService],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersModule {}
</code></pre>
<ul>
<li><p>The <code>@Module</code> decorator groups controller + service</p>
</li>
<li><p>The controller injects the service via its constructor</p>
</li>
<li><p>A simple <code>GET /users</code> route returns an array of user objects</p>
</li>
</ul>
<p>With that foundation laid, in the next section we’ll explore <strong>why you’d choose NestJS</strong>, comparing it to other popular Node frameworks and outlining common real-world use cases.</p>
<h2 id="heading-2-why-choose-nestjs">2. Why Choose NestJS?</h2>
<p>NestJS isn’t just another Node.js framework – it brings a structured, enterprise-grade approach to building backend services. In this section we’ll cover benefits and real-world use cases, then compare NestJS to other popular Node frameworks so you can see where it fits best.</p>
<h3 id="heading-21-benefits-and-use-cases">2.1 Benefits and Use Cases</h3>
<ol>
<li><p><strong>Strong architectural patterns</strong></p>
<ul>
<li><p><strong>Modularity:</strong> You break your app into focused modules (<code>AuthModule</code>, <code>ProductsModule</code>, and so on), each responsible for a slice of functionality.</p>
</li>
<li><p><strong>Separation of concerns:</strong> Controllers handle HTTP, services encapsulate business logic, modules wire everything up.</p>
</li>
<li><p><strong>Scalability:</strong> Growing teams map naturally onto modules—new features rarely touch existing code.</p>
</li>
</ul>
</li>
<li><p><strong>Built-in dependency injection (DI)</strong></p>
<ul>
<li><p>DI makes testing and swapping implementations trivial.</p>
</li>
<li><p>You can easily mock a service in a unit test:</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-typescript">    <span class="hljs-comment">// products.controller.spec.ts</span>
    <span class="hljs-keyword">import</span> { Test, TestingModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/testing'</span>;
    <span class="hljs-keyword">import</span> { ProductsController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./products.controller'</span>;
    <span class="hljs-keyword">import</span> { ProductsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./products.service'</span>;

    describe(<span class="hljs-string">'ProductsController'</span>, <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">let</span> controller: ProductsController;
      <span class="hljs-keyword">const</span> mockService = { findAll: <span class="hljs-function">() =&gt;</span> [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>] };

      beforeEach(<span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> <span class="hljs-keyword">module</span>: TestingModule = await Test.createTestingModule({
          controllers: [ProductsController],
          providers: [
            { provide: ProductsService, useValue: mockService },
          ],
        }).compile();

        controller = <span class="hljs-built_in">module</span>.get&lt;ProductsController&gt;(ProductsController);
      });

      it(<span class="hljs-string">'returns a list of products'</span>, <span class="hljs-function">() =&gt;</span> {
        expect(controller.getAll()).toEqual([<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>]);
      });
    });
</code></pre>
<ol start="3">
<li><p><strong>TypeScript-first</strong></p>
<ul>
<li><p>Full type safety at compile time.</p>
</li>
<li><p>Leverage interfaces and decorators (<code>@Body()</code>, <code>@Param()</code>) to validate and transform data.</p>
</li>
</ul>
</li>
<li><p><strong>Rich ecosystem and extensibility</strong></p>
<ul>
<li><p>Official integrations for WebSockets, GraphQL, microservices (RabbitMQ, Kafka), and more.</p>
</li>
<li><p>Hundreds of community modules (for example <code>@nestjs/swagger</code> for OpenAPI docs).</p>
</li>
</ul>
</li>
<li><p><strong>Production-grade tooling</strong></p>
<ul>
<li><p>CLI generates boilerplate (<code>nest g module</code>, <code>nest g service</code>).</p>
</li>
<li><p>Support for hot-reload in development (<code>npm run start:dev</code>).</p>
</li>
<li><p>Built-in testing setup with Jest.</p>
</li>
</ul>
</li>
</ol>
<p><strong>Real-World Use Cases:</strong></p>
<ul>
<li><p><strong>Enterprise APIs</strong> with strict module boundaries and RBAC.</p>
</li>
<li><p><strong>Microservices architectures</strong>, where each service is a self-contained NestJS app.</p>
</li>
<li><p><strong>Real-time applications</strong> (chat, live dashboards) using Nest’s WebSocket gateways.</p>
</li>
<li><p><strong>GraphQL backends</strong> with code-first schemas.</p>
</li>
<li><p><strong>Event-driven systems</strong> connecting to message brokers.</p>
</li>
</ul>
<h3 id="heading-22-comparison-with-other-frameworks">2.2 Comparison with Other Frameworks</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Express</td><td>Koa</td><td>NestJS</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Architecture</strong></td><td>Minimal, unopinionated</td><td>Minimal, middleware-based</td><td>Opinionated modules/controllers/services</td></tr>
<tr>
<td><strong>Dependency Injection</strong></td><td>Manual wiring</td><td>Manual wiring</td><td>Built-in, reflect-metadata</td></tr>
<tr>
<td><strong>TypeScript Support</strong></td><td>Via DefinitelyTyped</td><td>Via DefinitelyTyped</td><td>First-class, decorators</td></tr>
<tr>
<td><strong>CLI Tooling</strong></td><td>None (3rd-party)</td><td>None</td><td><code>@nestjs/cli</code> generates code</td></tr>
<tr>
<td><strong>Testing</strong></td><td>User-configured</td><td>User-configured</td><td>Jest + DI makes mocking easy</td></tr>
<tr>
<td><strong>Ecosystem</strong></td><td>Middleware library</td><td>Middleware library</td><td>Official microservices, GraphQL, Swagger modules</td></tr>
<tr>
<td><strong>Learning Curve</strong></td><td>Low</td><td>Low</td><td>Medium (learning Nest idioms)</td></tr>
</tbody>
</table>
</div><ul>
<li><p><strong>Express</strong> is great if you want minimal layers and full control, but you’ll end up hand-rolling a lot (DI, validation, folder structure).</p>
</li>
<li><p><strong>Koa</strong> offers a more modern middleware approach, but still leaves architecture decisions to you.</p>
</li>
<li><p><strong>NestJS</strong> provides the full stack: structure, DI, validation, testing, and official integrations, which is ideal if you value <strong>consistency</strong>, <strong>type safety</strong>, and <strong>out-of-the-box best practices</strong>.</p>
</li>
</ul>
<p><strong>When to choose NestJS:</strong></p>
<p>NextJS is great for various use cases. It’s particularly effective if you’re building a large-scale API or microservice suite, if you want a solid architecture from day one, and if you prefer TypeScript and DI to keep code testable and maintainable.</p>
<p>With these advantages in mind, you’ll find that NestJS can dramatically speed up development, especially on projects that need robust structure and clear boundaries.</p>
<p>In the next section, we’ll dive into getting started: installing the CLI, creating a project, and exploring the generated folder layout.</p>
<h2 id="heading-3-getting-started">3. Getting Started</h2>
<p>Let’s jump into the basics: installing the CLI, scaffolding a new project, and exploring the default folder layout.</p>
<h3 id="heading-31-installing-the-cli">3.1 Installing the CLI</h3>
<p>Nest ships with an official command-line tool that helps you generate modules, controllers, services, and more. Under the hood it uses Yeoman templates to keep everything consistent.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Install the CLI globally (requires npm ≥ 6)</span>
npm install -g @nestjs/cli
</code></pre>
<p>Once installed, you can run <code>nest --help</code> to see available commands:</p>
<pre><code class="lang-bash">nest --<span class="hljs-built_in">help</span>
Usage: nest &lt;<span class="hljs-built_in">command</span>&gt; [options]

Commands:
  new &lt;name&gt;       Scaffold a new project
  generate|g &lt;schematic&gt; [options]  Generate artifacts (modules, controllers, ...)
  build            Build project with webpack
  ...

Options:
  -v, --version    Show version number
  -h, --<span class="hljs-built_in">help</span>       Show <span class="hljs-built_in">help</span>
</code></pre>
<h3 id="heading-32-creating-your-first-project">3.2 Creating Your First Project</h3>
<p>Scaffolding a new app is a single command. The CLI will ask whether to use npm or yarn, and whether to enable strict TypeScript settings.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create a new Nest app in the "my-nest-app" folder</span>
nest new my-nest-app
</code></pre>
<p>After answering the prompts, you’ll have:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> my-nest-app
npm run start:dev
</code></pre>
<p>This launches a development server on <a target="_blank" href="http://localhost:3000"><code>http://localhost:3000</code></a> with automatic reload on file changes.</p>
<h3 id="heading-33-project-structure-overview">3.3 Project Structure Overview</h3>
<p>By default, you’ll see something like:</p>
<pre><code class="lang-bash">my-nest-app/
├── src/
│   ├── app.controller.ts      <span class="hljs-comment"># example controller</span>
│   ├── app.controller.spec.ts <span class="hljs-comment"># unit test for controller</span>
│   ├── app.module.ts          <span class="hljs-comment"># root application module</span>
│   ├── app.service.ts         <span class="hljs-comment"># example provider</span>
│   └── main.ts                <span class="hljs-comment"># entry point (bootstraps Nest)</span>
├── <span class="hljs-built_in">test</span>/                      <span class="hljs-comment"># end-to-end tests</span>
├── node_modules/
├── package.json
├── tsconfig.json
└── nest-cli.json             <span class="hljs-comment"># CLI configuration</span>
</code></pre>
<ul>
<li><p><strong>src/main.ts</strong><br>  The “bootstrap” script. It creates a Nest application instance and starts listening on a port:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">import</span> { NestFactory } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>;
  <span class="hljs-keyword">import</span> { AppModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.module'</span>;

  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create(AppModule);
    <span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`🚀 Application is running on: <span class="hljs-subst">${<span class="hljs-keyword">await</span> app.getUrl()}</span>`</span>);
  }
  bootstrap();
</code></pre>
</li>
<li><p><strong>src/app.module.ts</strong><br>  The root module. It ties together controllers and providers:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
  <span class="hljs-keyword">import</span> { AppController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.controller'</span>;
  <span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;

  <span class="hljs-meta">@Module</span>({
    imports: [],                 <span class="hljs-comment">// other modules to import</span>
    controllers: [AppController],
    providers: [AppService],
  })
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
</li>
<li><p><strong>src/app.controller.ts / app.service.ts</strong><br>  A simple example that shows dependency injection in action:</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// app.controller.ts</span>
  <span class="hljs-keyword">import</span> { Controller, Get } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
  <span class="hljs-keyword">import</span> { AppService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.service'</span>;

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

    <span class="hljs-meta">@Get</span>()
    getHello(): <span class="hljs-built_in">string</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.appService.getHello();
    }
  }

  <span class="hljs-comment">// app.service.ts</span>
  <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

  <span class="hljs-meta">@Injectable</span>()
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppService {
    getHello(): <span class="hljs-built_in">string</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, NestJS!'</span>;
    }
  }
</code></pre>
</li>
</ul>
<p>With this scaffold in place, you have a minimal – but fully functional – NestJS application. From here, you can generate new modules, controllers, and services:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Generate a new module, controller, and service for "tasks"</span>
nest g module tasks
nest g controller tasks
nest g service tasks
</code></pre>
<p>Each command will drop a new <code>.ts</code> file in the appropriate folder and update your module’s metadata. In the next section, we’ll dive into core Nest building blocks like modules, controllers, and providers in more detail.</p>
<h2 id="heading-4-core-nestjs-building-blocks">4. Core NestJS Building Blocks</h2>
<p>At the heart of every NestJS application are three pillars: <strong>Modules</strong>, <strong>Controllers</strong>, and <strong>Providers</strong> (often called Services). Let’s see what each one does, and how they fit together in theory and in practice.</p>
<h3 id="heading-41-modules">4.1 Modules</h3>
<p>A <strong>Module</strong> is a logical boundary – a container that groups related components (controllers, providers, and even other modules). Every NestJS app has at least one root module (usually <code>AppModule</code>), and you create feature modules (<code>UsersModule</code>, <code>AuthModule</code>, and so on) to organize code by domain.</p>
<h4 id="heading-module-decorator">@Module() Decorator</h4>
<ul>
<li><p><code>imports</code>: other modules to use</p>
</li>
<li><p><code>controllers</code>: controllers that handle incoming requests</p>
</li>
<li><p><code>providers</code>: services or values available via DI</p>
</li>
<li><p><code>exports</code>: providers that should be visible to importing modules</p>
</li>
</ul>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// cats.module.ts</span>
<span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.controller'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;

<span class="hljs-meta">@Module</span>({
  imports: [],            <span class="hljs-comment">// e.g. TypeOrmModule.forFeature([Cat])</span>
  controllers: [CatsController],
  providers: [CatsService],
  <span class="hljs-built_in">exports</span>: [CatsService], <span class="hljs-comment">// makes CatsService available to other modules</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CatsModule {}
</code></pre>
<p>Then in your root module:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// app.module.ts</span>
<span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats/cats.module'</span>;

<span class="hljs-meta">@Module</span>({
  imports: [CatsModule],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<p>Now anything that injects <code>CatsService</code> will resolve to the one defined inside <code>CatsModule</code>.</p>
<h3 id="heading-42-controllers">4.2 Controllers</h3>
<p>A <strong>Controller</strong> maps incoming HTTP requests to handler methods. It’s responsible for extracting request data (query parameters, body, headers) and returning a response. Controllers should remain thin – delegating business logic to providers.</p>
<ul>
<li><p><strong>@Controller(path?)</strong>: Defines a route prefix</p>
</li>
<li><p><strong>@Get, @Post, @Put, @Delete, and so on</strong>: Define method-level routes</p>
</li>
<li><p><strong>@Param(), @Query(), @Body(), @Headers(), @Req(), @Res()</strong>: Decorators to extract request details</p>
</li>
</ul>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// cats.controller.ts</span>
<span class="hljs-keyword">import</span> { Controller, Get, Post, Body, Param } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;
<span class="hljs-keyword">import</span> { CreateCatDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-cat.dto'</span>;

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

  <span class="hljs-meta">@Get</span>()
  findAll() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.findAll();  <span class="hljs-comment">// GET /cats</span>
  }

  <span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)
  findOne(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>) id: <span class="hljs-built_in">string</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.findOne(+id);  <span class="hljs-comment">// GET /cats/1</span>
  }

  <span class="hljs-meta">@Post</span>()
  create(<span class="hljs-meta">@Body</span>() createCatDto: CreateCatDto) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.create(createCatDto);  <span class="hljs-comment">// POST /cats</span>
  }
}
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// dto/create-cat.dto.ts</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CreateCatDto {
  <span class="hljs-keyword">readonly</span> name: <span class="hljs-built_in">string</span>;
  <span class="hljs-keyword">readonly</span> age: <span class="hljs-built_in">number</span>;
  <span class="hljs-keyword">readonly</span> breed?: <span class="hljs-built_in">string</span>;
}
</code></pre>
<h3 id="heading-43-providers-services">4.3 Providers (Services)</h3>
<p><strong>Providers</strong> are classes annotated with <code>@Injectable()</code> that contain your business logic or data access. Anything you want to inject elsewhere must be a provider. You can provide plain values, factory functions, or classes.</p>
<ul>
<li><p><strong>@Injectable()</strong>: Marks a class as available for DI</p>
</li>
<li><p><strong>Scope</strong>: Default is singleton, but you can change to request or transient</p>
</li>
<li><p><strong>Custom Providers</strong>: Use <code>useClass</code>, <code>useValue</code>, <code>useFactory</code>, or <code>useExisting</code> for more control</p>
</li>
</ul>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// cats.service.ts</span>
<span class="hljs-keyword">import</span> { Injectable, NotFoundException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { CreateCatDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-cat.dto'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CatsService {
  <span class="hljs-keyword">private</span> cats = [];

  create(dto: CreateCatDto) {
    <span class="hljs-keyword">const</span> newCat = { id: <span class="hljs-built_in">Date</span>.now(), ...dto };
    <span class="hljs-built_in">this</span>.cats.push(newCat);
    <span class="hljs-keyword">return</span> newCat;
  }

  findAll() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.cats;
  }

  findOne(id: <span class="hljs-built_in">number</span>) {
    <span class="hljs-keyword">const</span> cat = <span class="hljs-built_in">this</span>.cats.find(<span class="hljs-function"><span class="hljs-params">c</span> =&gt;</span> c.id === id);
    <span class="hljs-keyword">if</span> (!cat) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundException(<span class="hljs-string">`Cat #<span class="hljs-subst">${id}</span> not found`</span>);
    }
    <span class="hljs-keyword">return</span> cat;
  }
}
</code></pre>
<p><strong>Injecting a Custom Value:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// logger.provider.ts</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> LOGGER = {
  provide: <span class="hljs-string">'LOGGER'</span>,
  useValue: <span class="hljs-built_in">console</span>,
};

<span class="hljs-comment">// app.module.ts</span>
<span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { LOGGER } <span class="hljs-keyword">from</span> <span class="hljs-string">'./logger.provider'</span>;

<span class="hljs-meta">@Module</span>({
  providers: [LOGGER],
  <span class="hljs-built_in">exports</span>: [LOGGER],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// some.service.ts</span>
<span class="hljs-keyword">import</span> { Inject, Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> SomeService {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-meta">@Inject</span>(<span class="hljs-string">'LOGGER'</span>) <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> logger: Console</span>) {}

  logMessage(msg: <span class="hljs-built_in">string</span>) {
    <span class="hljs-built_in">this</span>.logger.log(<span class="hljs-string">`Custom log: <span class="hljs-subst">${msg}</span>`</span>);
  }
}
</code></pre>
<p>With modules wiring up controllers and providers, NestJS gives you a scalable, testable foundation. In the next section, we’ll explore <strong>Dependency Injection</strong> in depth – how it works under the hood and how to create custom providers and factory-based injections.</p>
<h2 id="heading-5-dependency-injection">5. Dependency Injection</h2>
<p>Nest’s built-in Dependency Injection (DI) system is the heart of how components (controllers, services, and so on) talk to each other in a loosely-coupled, testable way.</p>
<h3 id="heading-51-how-di-works-in-nestjs">5.1 How DI Works in NestJS</h3>
<p>When your application boots, Nest builds a <strong>module-based IoC container</strong>. Each <code>@Injectable()</code> provider is registered in the container under a token (by default, its class). When a class declares a dependency in its constructor, Nest looks up that token and injects the matching instance.</p>
<ul>
<li><p><strong>Singleton scope</strong>: One instance per application (default)</p>
</li>
<li><p><strong>Request scope</strong>: New instance per incoming request</p>
</li>
<li><p><strong>Transient scope</strong>: New instance every time it’s injected</p>
</li>
</ul>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// cats.service.ts</span>
<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CatsService {
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-comment">// cats.controller.ts</span>
<span class="hljs-meta">@Controller</span>(<span class="hljs-string">'cats'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CatsController {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> catsService: CatsService</span>) {}
  <span class="hljs-comment">// Nest sees CatsService in the constructor,</span>
  <span class="hljs-comment">// finds its singleton instance, and injects it.</span>
}
</code></pre>
<p><em>Behind the scenes</em>, Nest collects metadata from decorators (<code>@Injectable()</code>, <code>@Controller()</code>) and builds a graph of providers. When you call <code>NestFactory.create(AppModule)</code>, it resolves that graph and wires everything together.</p>
<h3 id="heading-52-custom-providers-and-factory-providers">5.2 Custom Providers and Factory Providers</h3>
<p>Sometimes you need to inject non-class values (APIs, constants) or run logic at registration time. Nest lets you define <strong>custom providers</strong> using the <code>provide</code> syntax.</p>
<h4 id="heading-usevalue"><code>useValue</code></h4>
<p>Inject a plain value or object:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// config.constant.ts</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> APP_NAME = {
  provide: <span class="hljs-string">'APP_NAME'</span>,
  useValue: <span class="hljs-string">'MyAwesomeApp'</span>,
};

<span class="hljs-comment">// app.module.ts</span>
<span class="hljs-meta">@Module</span>({
  providers: [APP_NAME],
  <span class="hljs-built_in">exports</span>: [<span class="hljs-string">'APP_NAME'</span>],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}

<span class="hljs-comment">// some.service.ts</span>
<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> SomeService {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-meta">@Inject</span>(<span class="hljs-string">'APP_NAME'</span>) <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> name: <span class="hljs-built_in">string</span></span>) {}

  whoAmI() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Running in <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>;
  }
}
</code></pre>
<h4 id="heading-useclass"><code>useClass</code></h4>
<p>Swap implementations easily (useful for testing or feature flags):</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// logger.interface.ts</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> Logger {
  log(msg: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">void</span>;
}

<span class="hljs-comment">// console-logger.ts</span>
<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ConsoleLogger <span class="hljs-keyword">implements</span> Logger {
  log(msg: <span class="hljs-built_in">string</span>) { <span class="hljs-built_in">console</span>.log(msg); }
}

<span class="hljs-comment">// file-logger.ts</span>
<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> FileLogger <span class="hljs-keyword">implements</span> Logger {
  log(msg: <span class="hljs-built_in">string</span>) { <span class="hljs-comment">/* write to file */</span> }
}

<span class="hljs-comment">// app.module.ts</span>
<span class="hljs-meta">@Module</span>({
  providers: [
    { provide: <span class="hljs-string">'Logger'</span>, useClass: FileLogger }, 
  ],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}

<span class="hljs-comment">// any.service.ts</span>
<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AnyService {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-meta">@Inject</span>(<span class="hljs-string">'Logger'</span>) <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> logger: Logger</span>) {}
}
</code></pre>
<h4 id="heading-usefactory"><code>useFactory</code></h4>
<p>Run arbitrary factory logic (for example, async initialization, dynamic config):</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// database.provider.ts</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> DATABASE = {
  provide: <span class="hljs-string">'DATABASE'</span>,
  useFactory: <span class="hljs-keyword">async</span> (configService: ConfigService) =&gt; {
    <span class="hljs-keyword">const</span> opts = configService.getDbOptions();
    <span class="hljs-keyword">const</span> connection = <span class="hljs-keyword">await</span> createConnection(opts);
    <span class="hljs-keyword">return</span> connection;
  },
  inject: [ConfigService],
};

<span class="hljs-comment">// app.module.ts</span>
<span class="hljs-meta">@Module</span>({
  imports: [ConfigModule],
  providers: [DATABASE],
  <span class="hljs-built_in">exports</span>: [<span class="hljs-string">'DATABASE'</span>],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}

<span class="hljs-comment">// users.service.ts</span>
<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersService {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-meta">@Inject</span>(<span class="hljs-string">'DATABASE'</span>) <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> db: Connection</span>) {}
}
</code></pre>
<p>With custom providers and the factory pattern, you can integrate external libraries, toggle implementations, or perform async setup – all while retaining the clear, testable structure NestJS provides.</p>
<p>In the next section we’ll look at <strong>Routing and Middleware</strong>, showing how to define route handlers, apply global or per-route middleware, and extend your HTTP pipeline.</p>
<h2 id="heading-6-routing-amp-middleware">6. Routing &amp; Middleware</h2>
<p>Routing in NestJS is built on top of your controllers and decorators, while middleware lets you hook into the request/response pipeline for cross-cutting concerns like logging, authentication checks, or CORS.</p>
<h3 id="heading-61-defining-routes">6.1 Defining Routes</h3>
<p>First, a bit of theory:</p>
<ul>
<li><p><strong>@Controller(path?)</strong> sets a URL prefix for all routes in that class.</p>
</li>
<li><p><strong>@Get, @Post, @Put, @Delete, etc.</strong> define HTTP-method handlers.</p>
</li>
<li><p><strong>@Param(), @Query(), @Body(), @Headers(), @Req(), @Res()</strong> extract parts of the incoming request.</p>
</li>
</ul>
<p>You can combine route decorators and parameter decorators to build expressive, type-safe endpoints.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// products.controller.ts</span>
<span class="hljs-keyword">import</span> { Controller, Get, Post, Param, Query, Body } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { ProductsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./products.service'</span>;
<span class="hljs-keyword">import</span> { CreateProductDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-product.dto'</span>;

<span class="hljs-meta">@Controller</span>(<span class="hljs-string">'products'</span>)                <span class="hljs-comment">// all routes here start with /products</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ProductsController {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> productsService: ProductsService</span>) {}

  <span class="hljs-meta">@Get</span>()                              <span class="hljs-comment">// GET /products</span>
  findAll(
    <span class="hljs-meta">@Query</span>(<span class="hljs-string">'limit'</span>) limit = <span class="hljs-string">'10'</span>,     <span class="hljs-comment">// optional query ?limit=20</span>
  ) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.productsService.findAll(+limit);
  }

  <span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)                         <span class="hljs-comment">// GET /products/123</span>
  findOne(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>) id: <span class="hljs-built_in">string</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.productsService.findOne(+id);
  }

  <span class="hljs-meta">@Post</span>()                             <span class="hljs-comment">// POST /products</span>
  create(<span class="hljs-meta">@Body</span>() dto: CreateProductDto) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.productsService.create(dto);
  }
}
</code></pre>
<p>You can also nest controllers by importing a feature module, and use <strong>@Patch</strong>, <strong>@Put</strong>, <strong>@Delete</strong>, <strong>@Head</strong>, and so on for full RESTful coverage.</p>
<h3 id="heading-62-applying-middleware">6.2 Applying Middleware</h3>
<p><strong>Middleware</strong> are functions that run <em>before</em> your routes handle a request. They’re useful for logging, body-parsing (though Nest provides built-ins), authentication guards at a lower level, rate limiting, and so on.</p>
<p>You can implement them either as a functional middleware or a class implementing <code>NestMiddleware</code>.</p>
<p><strong>Here’s an example (Functional Middleware):</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// logger.middleware.ts</span>
<span class="hljs-keyword">import</span> { Request, Response, NextFunction } <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logger</span>(<span class="hljs-params">req: Request, res: Response, next: NextFunction</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`[<span class="hljs-subst">${<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toISOString()}</span>] <span class="hljs-subst">${req.method}</span> <span class="hljs-subst">${req.url}</span>`</span>);
  next();
}

<span class="hljs-comment">// app.module.ts</span>
<span class="hljs-keyword">import</span> { Module, NestModule, MiddlewareConsumer } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { logger } <span class="hljs-keyword">from</span> <span class="hljs-string">'./logger.middleware'</span>;
<span class="hljs-keyword">import</span> { ProductsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./products/products.module'</span>;

<span class="hljs-meta">@Module</span>({
  imports: [ProductsModule],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule <span class="hljs-keyword">implements</span> NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(logger)                 <span class="hljs-comment">// apply logger</span>
      .forRoutes(<span class="hljs-string">'products'</span>);        <span class="hljs-comment">// only for /products routes</span>
  }
}
</code></pre>
<p><strong>And here’s another example (Class-based Middleware):</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// auth.middleware.ts</span>
<span class="hljs-keyword">import</span> { Injectable, NestMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { Request, Response, NextFunction } <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AuthMiddleware <span class="hljs-keyword">implements</span> NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    <span class="hljs-keyword">if</span> (!req.headers.authorization) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).send(<span class="hljs-string">'Unauthorized'</span>);
    }
    <span class="hljs-comment">// validate token...</span>
    next();
  }
}

<span class="hljs-comment">// security.module.ts</span>
<span class="hljs-keyword">import</span> { Module, NestModule, MiddlewareConsumer } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { AuthMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth.middleware'</span>;
<span class="hljs-keyword">import</span> { UsersController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users.controller'</span>;

<span class="hljs-meta">@Module</span>({
  controllers: [UsersController],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> SecurityModule <span class="hljs-keyword">implements</span> NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes(UsersController);    <span class="hljs-comment">// apply to all routes in UsersController</span>
  }
}
</code></pre>
<p><strong>Tip:</strong> Global middleware can be applied in your <code>main.ts</code> before the <code>app.listen()</code> call via <code>app.use(logger)</code> if you want it on <em>every</em> request.</p>
<p>With routing and middleware set up, you have full control over how requests flow through your application. Next up, we’ll dive into <strong>Request Lifecycle and Pipes</strong>, exploring how data transforms and validations happen as part of each request.</p>
<h2 id="heading-7-request-lifecycle-amp-pipes">7. Request Lifecycle &amp; Pipes</h2>
<p>NestJS processes each incoming request through a defined “lifecycle” of steps – routing to the correct handler, applying <strong>pipes</strong>, <strong>guards</strong>, <strong>interceptors</strong>, and finally invoking your controller method. <strong>Pipes</strong> sit between the incoming request and your handler, transforming or validating data before it reaches your business logic.</p>
<h3 id="heading-71-what-are-pipes">7.1 What Are Pipes?</h3>
<p>A <strong>Pipe</strong> is a class annotated with <code>@Injectable()</code> that implements the <code>PipeTransform</code> interface. It has a single method:</p>
<pre><code class="lang-typescript">transform(value: <span class="hljs-built_in">any</span>, metadata: ArgumentMetadata): <span class="hljs-built_in">any</span>
</code></pre>
<ul>
<li><p><strong>Transformation</strong>: Convert input data (for example, a string <code>"123"</code>) into the desired type (<code>number</code> <code>123</code>).</p>
</li>
<li><p><strong>Validation</strong>: Check that incoming data meets certain rules and throw an exception (usually a <code>BadRequestException</code>) if it doesn’t.</p>
</li>
</ul>
<p>By default, pipes run <strong>after</strong> middleware and <strong>before</strong> guards/interceptors, for each decorated parameter (<code>@Body()</code>, <code>@Param()</code>, and so on).</p>
<p><strong>Here’s how it works:</strong><br>Nest ships with a handy global validation pipe that integrates with class-validator:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// main.ts</span>
<span class="hljs-keyword">import</span> { ValidationPipe } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { NestFactory }    <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>;
<span class="hljs-keyword">import</span> { AppModule }      <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.module'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create(AppModule);
  <span class="hljs-comment">// Automatically validate and strip unknown properties</span>
  app.useGlobalPipes(<span class="hljs-keyword">new</span> ValidationPipe({ whitelist: <span class="hljs-literal">true</span>, forbidNonWhitelisted: <span class="hljs-literal">true</span> }));
  <span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
}
bootstrap();
</code></pre>
<p>With this in place, any DTO annotated with validation decorators will be checked before your handler runs:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// dto/create-user.dto.ts</span>
<span class="hljs-keyword">import</span> { IsEmail, IsString, MinLength } <span class="hljs-keyword">from</span> <span class="hljs-string">'class-validator'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CreateUserDto {
  <span class="hljs-meta">@IsEmail</span>()           <span class="hljs-comment">// must be a valid email</span>
  email: <span class="hljs-built_in">string</span>;

  <span class="hljs-meta">@IsString</span>()          <span class="hljs-comment">// must be a string</span>
  <span class="hljs-meta">@MinLength</span>(<span class="hljs-number">8</span>)        <span class="hljs-comment">// at least 8 characters</span>
  password: <span class="hljs-built_in">string</span>;
}

<span class="hljs-comment">// users.controller.ts</span>
<span class="hljs-meta">@Post</span>()
createUser(<span class="hljs-meta">@Body</span>() dto: CreateUserDto) {
  <span class="hljs-comment">// If body.email isn't an email, or password is shorter,</span>
  <span class="hljs-comment">// Nest throws a 400 Bad Request with details.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.create(dto);
}
</code></pre>
<h3 id="heading-72-built-in-vs-custom-pipes">7.2 Built-In vs. Custom Pipes</h3>
<h4 id="heading-built-in-pipes">Built-In Pipes</h4>
<p>Nest provides several out-of-the-box pipes:</p>
<ul>
<li><p><strong>ValidationPipe</strong>: Integrates with <code>class-validator</code> for DTO validation (shown above).</p>
</li>
<li><p><strong>ParseIntPipe</strong>: Converts a route parameter to <code>number</code> or throws <code>BadRequestException</code>.</p>
</li>
<li><p><strong>ParseBoolPipe</strong>, <strong>ParseUUIDPipe</strong>, <strong>ParseFloatPipe</strong>, and so on.</p>
</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)
getById(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>, ParseIntPipe) id: <span class="hljs-built_in">number</span>) {
  <span class="hljs-comment">// id is guaranteed to be a number here</span>
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.itemsService.findOne(id);
}
</code></pre>
<h4 id="heading-custom-pipes">Custom Pipes</h4>
<p>You can write your own to handle any transformation or validation logic:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PipeTransform, Injectable, BadRequestException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ParsePositiveIntPipe <span class="hljs-keyword">implements</span> PipeTransform&lt;<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>&gt; {
  transform(value: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">number</span> {
    <span class="hljs-keyword">const</span> val = <span class="hljs-built_in">parseInt</span>(value, <span class="hljs-number">10</span>);
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(val) || val &lt;= <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> BadRequestException(<span class="hljs-string">`"<span class="hljs-subst">${value}</span>" is not a positive integer`</span>);
    }
    <span class="hljs-keyword">return</span> val;
  }
}
</code></pre>
<p>Use it just like a built-in pipe:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@Get</span>(<span class="hljs-string">'order/:orderId'</span>)
getOrder(
  <span class="hljs-meta">@Param</span>(<span class="hljs-string">'orderId'</span>, ParsePositiveIntPipe) orderId: <span class="hljs-built_in">number</span>
) {
  <span class="hljs-comment">// orderId is a validated, positive integer</span>
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.ordersService.findById(orderId);
}
</code></pre>
<p>With pipes you ensure that every piece of data entering your handlers is correctly typed and valid, keeping your business logic clean and focused. In the next section, we’ll explore <strong>Guards and Authorization</strong> to control access to your endpoints.</p>
<h2 id="heading-8-guards-amp-authorization">8. Guards &amp; Authorization</h2>
<p>Guards sit in the request lifecycle <strong>after</strong> pipes and <strong>before</strong> interceptors/controllers. They determine whether a given request should be allowed to proceed based on custom logic. This is ideal for authentication, role checks, or feature flags.</p>
<h3 id="heading-81-implementing-guards">8.1 Implementing Guards</h3>
<p>A <strong>Guard</strong> is a class that implements the <code>CanActivate</code> interface, with a single method:</p>
<pre><code class="lang-typescript">canActivate(context: ExecutionContext): <span class="hljs-built_in">boolean</span> | <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">boolean</span>&gt; | Observable&lt;<span class="hljs-built_in">boolean</span>&gt;;
</code></pre>
<ul>
<li><p><strong>ExecutionContext</strong> gives you access to the underlying request/response and route metadata.</p>
</li>
<li><p>If <code>canActivate</code> returns <code>true</code>, the request continues. Returning <code>false</code> or throwing an exception (for example, <code>UnauthorizedException</code>) blocks it.</p>
</li>
</ul>
<p>You register guards either <strong>globally</strong>, at the <strong>controller</strong> level, or on <strong>individual routes</strong> with the <code>@UseGuards()</code> decorator.</p>
<p><strong>Here’s how guards work:</strong></p>
<ol>
<li><strong>Creating a simple auth guard:</strong></li>
</ol>
<pre><code class="lang-typescript"><span class="hljs-comment">// auth.guard.ts</span>
<span class="hljs-keyword">import</span> { Injectable, CanActivate, ExecutionContext, UnauthorizedException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AuthGuard <span class="hljs-keyword">implements</span> CanActivate {
  canActivate(context: ExecutionContext): <span class="hljs-built_in">boolean</span> {
    <span class="hljs-keyword">const</span> req = context.switchToHttp().getRequest();
    <span class="hljs-keyword">const</span> authHeader = req.headers.authorization;
    <span class="hljs-keyword">if</span> (!authHeader || !authHeader.startsWith(<span class="hljs-string">'Bearer '</span>)) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UnauthorizedException(<span class="hljs-string">'Missing or invalid authorization header'</span>);
    }
    <span class="hljs-comment">// Basic token check (replace with real validation)</span>
    <span class="hljs-keyword">const</span> token = authHeader.split(<span class="hljs-string">' '</span>)[<span class="hljs-number">1</span>];
    <span class="hljs-keyword">if</span> (token !== <span class="hljs-string">'valid-token'</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UnauthorizedException(<span class="hljs-string">'Invalid token'</span>);
    }
    <span class="hljs-comment">// Attach user info if needed:</span>
    req.user = { id: <span class="hljs-number">1</span>, name: <span class="hljs-string">'Alice'</span> };
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
}
</code></pre>
<ol start="2">
<li><strong>Applying the guard</strong></li>
</ol>
<ul>
<li><p><strong>Globally</strong> (in <code>main.ts</code>):</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">import</span> { NestFactory } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>;
  <span class="hljs-keyword">import</span> { AppModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.module'</span>;
  <span class="hljs-keyword">import</span> { AuthGuard } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth.guard'</span>;

  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create(AppModule);
    <span class="hljs-comment">// every incoming request passes through AuthGuard</span>
    app.useGlobalGuards(<span class="hljs-keyword">new</span> AuthGuard());
    <span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
  }
  bootstrap();
</code></pre>
</li>
<li><p><strong>Controller-Level</strong>:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">import</span> { Controller, Get, UseGuards } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
  <span class="hljs-keyword">import</span> { AuthGuard } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth.guard'</span>;

  <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'profile'</span>)
  <span class="hljs-meta">@UseGuards</span>(AuthGuard)       <span class="hljs-comment">// applies to all routes in this controller</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ProfileController {
    <span class="hljs-meta">@Get</span>()
    getProfile(<span class="hljs-meta">@Req</span>() req) {
      <span class="hljs-keyword">return</span> req.user;
    }
  }
</code></pre>
</li>
<li><p><strong>Route-Level</strong>:</p>
<pre><code class="lang-typescript">  <span class="hljs-meta">@Get</span>(<span class="hljs-string">'admin'</span>)
  <span class="hljs-meta">@UseGuards</span>(AdminGuard, AuthGuard)  <span class="hljs-comment">// chain multiple guards</span>
  getAdminData() { <span class="hljs-comment">/* ... */</span> }
</code></pre>
</li>
</ul>
<h3 id="heading-82-role-based-access-control">8.2 Role-Based Access Control</h3>
<p>Beyond plain authentication, you often need <strong>authorization</strong> – ensuring a user has the correct role or permission. You can build a guard that reads metadata (for example, required roles) and verifies user claims.</p>
<p><strong>Here’s how it works:</strong></p>
<ol>
<li><strong>Define a roles decorator:</strong></li>
</ol>
<pre><code class="lang-typescript"><span class="hljs-comment">// roles.decorator.ts</span>
<span class="hljs-keyword">import</span> { SetMetadata } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Roles = <span class="hljs-function">(<span class="hljs-params">...roles: <span class="hljs-built_in">string</span>[]</span>) =&gt;</span> SetMetadata(<span class="hljs-string">'roles'</span>, roles);
</code></pre>
<ol start="2">
<li><strong>Create a roles guard:</strong></li>
</ol>
<pre><code class="lang-typescript"><span class="hljs-comment">// roles.guard.ts</span>
<span class="hljs-keyword">import</span> { Injectable, CanActivate, ExecutionContext, ForbiddenException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { Reflector } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> RolesGuard <span class="hljs-keyword">implements</span> CanActivate {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> reflector: Reflector</span>) {}

  canActivate(context: ExecutionContext): <span class="hljs-built_in">boolean</span> {
    <span class="hljs-keyword">const</span> requiredRoles = <span class="hljs-built_in">this</span>.reflector.get&lt;<span class="hljs-built_in">string</span>[]&gt;(<span class="hljs-string">'roles'</span>, context.getHandler());
    <span class="hljs-keyword">if</span> (!requiredRoles) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; <span class="hljs-comment">// no roles metadata =&gt; open route</span>
    }
    <span class="hljs-keyword">const</span> { user } = context.switchToHttp().getRequest();
    <span class="hljs-keyword">const</span> hasRole = requiredRoles.some(<span class="hljs-function"><span class="hljs-params">role</span> =&gt;</span> user.roles?.includes(role));
    <span class="hljs-keyword">if</span> (!hasRole) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ForbiddenException(<span class="hljs-string">'You do not have permission (roles)'</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
}
</code></pre>
<ol start="3">
<li><strong>Apply roles metadata and guard:</strong></li>
</ol>
<pre><code class="lang-typescript"><span class="hljs-meta">@Controller</span>(<span class="hljs-string">'projects'</span>)
<span class="hljs-meta">@UseGuards</span>(AuthGuard, RolesGuard)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ProjectsController {
  <span class="hljs-meta">@Get</span>()
  <span class="hljs-meta">@Roles</span>(<span class="hljs-string">'user'</span>, <span class="hljs-string">'admin'</span>)         <span class="hljs-comment">// route requires either 'user' or 'admin'</span>
  findAll() { <span class="hljs-comment">/* ... */</span> }

  <span class="hljs-meta">@Post</span>()
  <span class="hljs-meta">@Roles</span>(<span class="hljs-string">'admin'</span>)                 <span class="hljs-comment">// only 'admin' can create</span>
  create() { <span class="hljs-comment">/* ... */</span> }
}
</code></pre>
<p>With this setup:</p>
<ul>
<li><p><code>AuthGuard</code> ensures the request is authenticated and populates <code>req.user</code>.</p>
</li>
<li><p><code>RolesGuard</code> reads the <code>@Roles()</code> metadata to enforce role-based access.</p>
</li>
</ul>
<p>Guards give you a powerful, declarative way to enforce security and authorization policies. In the next section, we’ll cover <strong>Exception Filters</strong> – how to catch and format errors centrally, keeping your controllers clean.</p>
<h2 id="heading-9-exception-filters">9. Exception Filters</h2>
<p>Exception filters let you centralize error handling, transforming thrown exceptions into consistent HTTP responses or other formats. You can rely on Nest’s built-in behavior for many cases, but custom filters give you control over logging, response shape, or handling non-HTTP errors.</p>
<h3 id="heading-91-handling-errors-gracefully">9.1 Handling Errors Gracefully</h3>
<p>By default, if a controller or service throws an <code>HttpException</code> (or one of Nest’s built-in exceptions like <code>NotFoundException</code>, <code>BadRequestException</code>, and so on), Nest catches it and sends an appropriate HTTP response with status code and JSON body containing <code>statusCode</code>, <code>message</code>, and <code>error</code>.</p>
<p>If an unexpected error (for example, a runtime error) bubbles up, Nest uses its default exception filter to return a 500 Internal Server Error with a generic message.</p>
<p>Controllers/services should throw exceptions rather than return error codes manually, so the framework can format consistently.</p>
<p><strong>Here’s how it works:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// users.service.ts</span>
<span class="hljs-keyword">import</span> { Injectable, NotFoundException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersService {
  <span class="hljs-keyword">private</span> users = [{ id: <span class="hljs-number">1</span>, name: <span class="hljs-string">'Alice'</span> }];

  findOne(id: <span class="hljs-built_in">number</span>) {
    <span class="hljs-keyword">const</span> user = <span class="hljs-built_in">this</span>.users.find(<span class="hljs-function"><span class="hljs-params">u</span> =&gt;</span> u.id === id);
    <span class="hljs-keyword">if</span> (!user) {
      <span class="hljs-comment">// results in 404 with JSON { statusCode: 404, message: 'User #2 not found', error: 'Not Found' }</span>
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundException(<span class="hljs-string">`User #<span class="hljs-subst">${id}</span> not found`</span>);
    }
    <span class="hljs-keyword">return</span> user;
  }
}
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// users.controller.ts</span>
<span class="hljs-keyword">import</span> { Controller, Get, Param, ParseIntPipe } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

<span class="hljs-meta">@Controller</span>(<span class="hljs-string">'users'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersController {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> usersService: UsersService</span>) {}

  <span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)
  getUser(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>, ParseIntPipe) id: <span class="hljs-built_in">number</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.findOne(id);
  }
}
</code></pre>
<p>If <code>findOne</code> throws, Nest’s default filter sends a structured JSON error. For unexpected errors (like a thrown <code>Error</code>), Nest wraps it into a 500 response.</p>
<h3 id="heading-92-creating-custom-filters">9.2 Creating Custom Filters</h3>
<p>You can implement the <code>ExceptionFilter</code> interface or extend <code>BaseExceptionFilter</code>. Just use the <code>@Catch()</code> decorator to target specific exception types (or leave empty to catch all).</p>
<p>In <code>catch(exception, host)</code>, you can extract context (HTTP request/response) and shape your response (for example, add metadata, custom fields, or a uniform envelope). You can also log exceptions or report to external systems here.</p>
<p>You can apply filters <strong>globally</strong>, to a controller, or to an individual route.</p>
<p><strong>Here’s how it works:</strong></p>
<ol>
<li><p><strong>Simple logging filter</strong><br> Catch all exceptions, log details, then delegate to default behavior:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// logging-exception.filter.ts</span>
 <span class="hljs-keyword">import</span> {
   ExceptionFilter,
   Catch,
   ArgumentsHost,
   HttpException,
   HttpStatus,
   Logger,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { BaseExceptionFilter } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>;

 <span class="hljs-meta">@Catch</span>() <span class="hljs-comment">// no args = catch every exception</span>
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> LoggingExceptionFilter <span class="hljs-keyword">extends</span> BaseExceptionFilter {
   <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> logger = <span class="hljs-keyword">new</span> Logger(LoggingExceptionFilter.name);

   <span class="hljs-keyword">catch</span>(exception: unknown, host: ArgumentsHost) {
     <span class="hljs-keyword">const</span> ctx = host.switchToHttp();
     <span class="hljs-keyword">const</span> req = ctx.getRequest&lt;Request&gt;();
     <span class="hljs-keyword">const</span> res = ctx.getResponse();

     <span class="hljs-comment">// Log stack or message</span>
     <span class="hljs-keyword">if</span> (exception <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Error</span>) {
       <span class="hljs-built_in">this</span>.logger.error(<span class="hljs-string">`Error on <span class="hljs-subst">${req.method}</span> <span class="hljs-subst">${req.url}</span>`</span>, exception.stack);
     } <span class="hljs-keyword">else</span> {
       <span class="hljs-built_in">this</span>.logger.error(<span class="hljs-string">`Unknown exception on <span class="hljs-subst">${req.method}</span> <span class="hljs-subst">${req.url}</span>`</span>);
     }

     <span class="hljs-comment">// Delegate to default filter for HTTP exceptions or generic 500</span>
     <span class="hljs-built_in">super</span>.catch(exception, host);
   }
 }
</code></pre>
<p> <strong>Apply globally</strong> in <code>main.ts</code>:</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create(AppModule);
   app.useGlobalFilters(<span class="hljs-keyword">new</span> LoggingExceptionFilter(app.get(HttpAdapterHost)));
   <span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
 }
</code></pre>
<p> (If extending <code>BaseExceptionFilter</code>, pass the adapter host to the constructor or super as needed.)</p>
</li>
<li><p><strong>Custom response shape</strong><br> Suppose you want all errors to return <code>{ success: false, error: { code, message } }</code>:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// custom-response.filter.ts</span>
 <span class="hljs-keyword">import</span> {
   ExceptionFilter,
   Catch,
   ArgumentsHost,
   HttpException,
   HttpStatus,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

 <span class="hljs-meta">@Catch</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CustomResponseFilter <span class="hljs-keyword">implements</span> ExceptionFilter {
   <span class="hljs-keyword">catch</span>(exception: unknown, host: ArgumentsHost) {
     <span class="hljs-keyword">const</span> ctx = host.switchToHttp();
     <span class="hljs-keyword">const</span> response = ctx.getResponse();
     <span class="hljs-keyword">const</span> request = ctx.getRequest&lt;Request&gt;();

     <span class="hljs-keyword">let</span> status: <span class="hljs-built_in">number</span>;
     <span class="hljs-keyword">let</span> message: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">object</span>;

     <span class="hljs-keyword">if</span> (exception <span class="hljs-keyword">instanceof</span> HttpException) {
       status = exception.getStatus();
       <span class="hljs-keyword">const</span> res = exception.getResponse();
       <span class="hljs-comment">// res might be a string or object</span>
       message = <span class="hljs-keyword">typeof</span> res === <span class="hljs-string">'string'</span> ? { message: res } : res;
     } <span class="hljs-keyword">else</span> {
       status = HttpStatus.INTERNAL_SERVER_ERROR;
       message = { message: <span class="hljs-string">'Internal server error'</span> };
     }

     response.status(status).json({
       success: <span class="hljs-literal">false</span>,
       error: {
         statusCode: status,
         ...(
           <span class="hljs-keyword">typeof</span> message === <span class="hljs-string">'object'</span>
             ? message
             : { message }
         ),
       },
       timestamp: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toISOString(),
       path: request.url,
     });
   }
 }
</code></pre>
<p> <strong>Apply at controller or route level</strong>:</p>
<pre><code class="lang-typescript"> <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'orders'</span>)
 <span class="hljs-meta">@UseFilters</span>(CustomResponseFilter)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> OrdersController {
   <span class="hljs-comment">// ...</span>
 }
</code></pre>
</li>
<li><p><strong>Catching specific exceptions</strong><br> If you have a custom exception class:</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> PaymentFailedException <span class="hljs-keyword">extends</span> HttpException {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params">details: <span class="hljs-built_in">string</span></span>) {
     <span class="hljs-built_in">super</span>({ message: <span class="hljs-string">'Payment failed'</span>, details }, HttpStatus.PAYMENT_REQUIRED);
   }
 }
</code></pre>
<p> You can write a filter that only catches that:</p>
<pre><code class="lang-typescript"> <span class="hljs-meta">@Catch</span>(PaymentFailedException)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> PaymentFailedFilter <span class="hljs-keyword">implements</span> ExceptionFilter {
   <span class="hljs-keyword">catch</span>(exception: PaymentFailedException, host: ArgumentsHost) {
     <span class="hljs-keyword">const</span> ctx = host.switchToHttp();
     <span class="hljs-keyword">const</span> res = ctx.getResponse();
     <span class="hljs-keyword">const</span> status = exception.getStatus();
     <span class="hljs-keyword">const</span> { message, details } = exception.getResponse() <span class="hljs-keyword">as</span> <span class="hljs-built_in">any</span>;
     res.status(status).json({
       error: {
         message,
         details,
       },
       help: <span class="hljs-string">'Please verify your payment method and retry.'</span>,
     });
   }
 }
</code></pre>
<p> Then apply only where payments occur:</p>
<pre><code class="lang-typescript"> <span class="hljs-meta">@Post</span>(<span class="hljs-string">'charge'</span>)
 <span class="hljs-meta">@UseFilters</span>(PaymentFailedFilter)
 charge() {
   <span class="hljs-comment">// ...</span>
 }
</code></pre>
</li>
</ol>
<p>With exception filters in place, you ensure a consistent error contract, centralized logging or reporting, and tailored handling of different error types. Next up: <strong>Interceptors and Logging</strong>, where we’ll see how to transform responses, measure performance, and hook around method execution.</p>
<h2 id="heading-10-interceptors-amp-logging">10. Interceptors &amp; Logging</h2>
<p>Interceptors wrap around method execution, letting you transform responses, bind extra logic before/after method calls, or measure performance. They’re ideal for cross-cutting concerns like logging, response shaping, caching, or timing metrics.</p>
<h3 id="heading-101-transforming-responses">10.1 Transforming Responses</h3>
<p>An <strong>Interceptor</strong> implements the <code>NestInterceptor</code> interface with an <code>intercept(context, next)</code> method.</p>
<p>Inside <code>intercept</code>, you typically call <code>next.handle()</code> which returns an <code>Observable</code> of the handler’s result. You can then apply RxJS operators (like <code>map</code>) to modify the data before it’s sent to the client.</p>
<p>Common uses are wrapping all responses in a uniform envelope, filtering out certain fields, or adding metadata.</p>
<p><strong>Here’s how it works:</strong></p>
<ol>
<li><p><strong>Basic response wrapper</strong><br> Suppose you want every successful response to be <code>{ success: true, data: &lt;original&gt; }</code>.</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// response.interceptor.ts</span>
 <span class="hljs-keyword">import</span> {
   Injectable,
   NestInterceptor,
   ExecutionContext,
   CallHandler,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
 <span class="hljs-keyword">import</span> { map } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/operators'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ResponseInterceptor <span class="hljs-keyword">implements</span> NestInterceptor {
   intercept(context: ExecutionContext, next: CallHandler): Observable&lt;<span class="hljs-built_in">any</span>&gt; {
     <span class="hljs-keyword">return</span> next.handle().pipe(
       map(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> ({
         success: <span class="hljs-literal">true</span>,
         data,
       })),
     );
   }
 }
</code></pre>
<p> <strong>Apply globally</strong> in <code>main.ts</code>:</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">import</span> { NestFactory } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>;
 <span class="hljs-keyword">import</span> { AppModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.module'</span>;
 <span class="hljs-keyword">import</span> { ResponseInterceptor } <span class="hljs-keyword">from</span> <span class="hljs-string">'./common/response.interceptor'</span>;

 <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create(AppModule);
   app.useGlobalInterceptors(<span class="hljs-keyword">new</span> ResponseInterceptor());
   <span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
 }
 bootstrap();
</code></pre>
<p> Now, if a controller method returns <code>{ id: 1, name: 'Alice' }</code>, the client sees:</p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"success"</span>: <span class="hljs-literal">true</span>,
   <span class="hljs-attr">"data"</span>: { <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Alice"</span> }
 }
</code></pre>
</li>
<li><p><strong>Filtering sensitive fields</strong><br> You might want to strip out fields like <code>password</code> before sending a user object:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// sanitize.interceptor.ts</span>
 <span class="hljs-keyword">import</span> {
   Injectable,
   NestInterceptor,
   ExecutionContext,
   CallHandler,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
 <span class="hljs-keyword">import</span> { map } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/operators'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> SanitizeInterceptor <span class="hljs-keyword">implements</span> NestInterceptor {
   intercept(context: ExecutionContext, next: CallHandler): Observable&lt;<span class="hljs-built_in">any</span>&gt; {
     <span class="hljs-keyword">return</span> next.handle().pipe(
       map(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
         <span class="hljs-keyword">if</span> (data &amp;&amp; <span class="hljs-keyword">typeof</span> data === <span class="hljs-string">'object'</span>) {
           <span class="hljs-keyword">const</span> { password, ...rest } = data;
           <span class="hljs-keyword">return</span> rest;
         }
         <span class="hljs-keyword">return</span> data;
       }),
     );
   }
 }
</code></pre>
<p> <strong>Apply at controller or route</strong>:</p>
<pre><code class="lang-typescript"> <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'users'</span>)
 <span class="hljs-meta">@UseInterceptors</span>(SanitizeInterceptor)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersController {
   <span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)
   getUser(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>) id: <span class="hljs-built_in">string</span>) {
     <span class="hljs-comment">// returns a user object with a password field internally,</span>
     <span class="hljs-comment">// but interceptor strips it before sending to client</span>
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.findOne(+id);
   }
 }
</code></pre>
</li>
<li><p><strong>Serializing with</strong> <code>class-transformer</code><br> If you use classes with decorators, you can integrate with <code>class-transformer</code>:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// user.entity.ts</span>
 <span class="hljs-keyword">import</span> { Exclude, Expose } <span class="hljs-keyword">from</span> <span class="hljs-string">'class-transformer'</span>;

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> User {
   id: <span class="hljs-built_in">number</span>;
   name: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@Exclude</span>()
   password: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@Expose</span>()
   get displayName(): <span class="hljs-built_in">string</span> {
     <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> (#<span class="hljs-subst">${<span class="hljs-built_in">this</span>.id}</span>)`</span>;
   }
 }
</code></pre>
<pre><code class="lang-typescript"> <span class="hljs-comment">// class-transform.interceptor.ts</span>
 <span class="hljs-keyword">import</span> {
   Injectable,
   NestInterceptor,
   ExecutionContext,
   CallHandler,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { plainToInstance } <span class="hljs-keyword">from</span> <span class="hljs-string">'class-transformer'</span>;
 <span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
 <span class="hljs-keyword">import</span> { map } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/operators'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ClassTransformInterceptor&lt;T&gt; <span class="hljs-keyword">implements</span> NestInterceptor {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> dto: <span class="hljs-keyword">new</span> (...args: <span class="hljs-built_in">any</span>[]) =&gt; T</span>) {}

   intercept(context: ExecutionContext, next: CallHandler): Observable&lt;<span class="hljs-built_in">any</span>&gt; {
     <span class="hljs-keyword">return</span> next.handle().pipe(
       map(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
         <span class="hljs-keyword">return</span> plainToInstance(<span class="hljs-built_in">this</span>.dto, data, {
           excludeExtraneousValues: <span class="hljs-literal">true</span>,
         });
       }),
     );
   }
 }
</code></pre>
<p> <strong>Apply with a DTO</strong>:</p>
<pre><code class="lang-typescript"> <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'users'</span>)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersController {
   <span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)
   <span class="hljs-meta">@UseInterceptors</span>(<span class="hljs-keyword">new</span> ClassTransformInterceptor(User))
   getUser(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>) id: <span class="hljs-built_in">string</span>) {
     <span class="hljs-comment">// service returns a plain object; interceptor transforms to User instance</span>
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.findOne(+id);
   }
 }
</code></pre>
</li>
</ol>
<h3 id="heading-102-logging-and-performance-metrics">10.2 Logging and Performance Metrics</h3>
<p>Interceptors can also measure execution time or log request/response details. You capture timestamps before and after <code>next.handle()</code>, logging the difference. This helps monitor slow endpoints. Combined with a logging framework or Nest’s <code>Logger</code>, you can standardize logs.</p>
<p><strong>Here’s how it works:</strong></p>
<ol>
<li><p><strong>Timing interceptor</strong><br> Logs how long each request-handler takes:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// logging.interceptor.ts</span>
 <span class="hljs-keyword">import</span> {
   Injectable,
   NestInterceptor,
   ExecutionContext,
   CallHandler,
   Logger,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
 <span class="hljs-keyword">import</span> { tap } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/operators'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> LoggingInterceptor <span class="hljs-keyword">implements</span> NestInterceptor {
   <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> logger = <span class="hljs-keyword">new</span> Logger(LoggingInterceptor.name);

   intercept(context: ExecutionContext, next: CallHandler): Observable&lt;<span class="hljs-built_in">any</span>&gt; {
     <span class="hljs-keyword">const</span> req = context.switchToHttp().getRequest();
     <span class="hljs-keyword">const</span> method = req.method;
     <span class="hljs-keyword">const</span> url = req.url;
     <span class="hljs-keyword">const</span> now = <span class="hljs-built_in">Date</span>.now();
     <span class="hljs-keyword">return</span> next.handle().pipe(
       tap(<span class="hljs-function">() =&gt;</span> {
         <span class="hljs-keyword">const</span> elapsed = <span class="hljs-built_in">Date</span>.now() - now;
         <span class="hljs-built_in">this</span>.logger.log(<span class="hljs-string">`<span class="hljs-subst">${method}</span> <span class="hljs-subst">${url}</span> - <span class="hljs-subst">${elapsed}</span>ms`</span>);
       }),
     );
   }
 }
</code></pre>
<p> <strong>Apply globally</strong>:</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create(AppModule);
   app.useGlobalInterceptors(<span class="hljs-keyword">new</span> LoggingInterceptor());
   <span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
 }
</code></pre>
<p> Now each request logs something like:</p>
<pre><code class="lang-bash"> [LoggingInterceptor] GET /users/1 - 35ms
</code></pre>
</li>
<li><p><strong>Detailed request/response logging</strong><br> For more detail, log request body or response size (careful with sensitive data):</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// detailed-logging.interceptor.ts</span>
 <span class="hljs-keyword">import</span> {
   Injectable,
   NestInterceptor,
   ExecutionContext,
   CallHandler,
   Logger,
 } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
 <span class="hljs-keyword">import</span> { tap, map } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/operators'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> DetailedLoggingInterceptor <span class="hljs-keyword">implements</span> NestInterceptor {
   <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> logger = <span class="hljs-keyword">new</span> Logger(<span class="hljs-string">'HTTP'</span>);

   intercept(context: ExecutionContext, next: CallHandler): Observable&lt;<span class="hljs-built_in">any</span>&gt; {
     <span class="hljs-keyword">const</span> ctx = context.switchToHttp();
     <span class="hljs-keyword">const</span> req = ctx.getRequest&lt;Request&gt;();
     <span class="hljs-keyword">const</span> { method, url, body } = req;
     <span class="hljs-keyword">const</span> now = <span class="hljs-built_in">Date</span>.now();

     <span class="hljs-built_in">this</span>.logger.log(<span class="hljs-string">`Incoming <span class="hljs-subst">${method}</span> <span class="hljs-subst">${url}</span> - body: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(body)}</span>`</span>);

     <span class="hljs-keyword">return</span> next.handle().pipe(
       map(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
         <span class="hljs-keyword">const</span> elapsed = <span class="hljs-built_in">Date</span>.now() - now;
         <span class="hljs-built_in">this</span>.logger.log(<span class="hljs-string">`Response <span class="hljs-subst">${method}</span> <span class="hljs-subst">${url}</span> - <span class="hljs-subst">${elapsed}</span>ms - data: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(data)}</span>`</span>);
         <span class="hljs-keyword">return</span> data;
       }),
     );
   }
 }
</code></pre>
<p> <strong>Apply conditionally</strong>: perhaps only in development:</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">if</span> (process.env.NODE_ENV !== <span class="hljs-string">'production'</span>) {
   app.useGlobalInterceptors(<span class="hljs-keyword">new</span> DetailedLoggingInterceptor());
 }
</code></pre>
</li>
<li><p><strong>Combining with guards/pipes</strong><br> Since interceptors run after guards and before the response is sent, logging time captures the full handler including service calls, but after validation/authorization. That ensures you measure only authorized requests and valid data flows.</p>
</li>
</ol>
<p>Interceptors offer a flexible way to wrap your handlers with extra behavior: transforming outputs, sanitizing data, timing execution, or adding headers. In the next section, we’ll explore <strong>Database integration</strong> to see how you can integrate your data layer in Nest.</p>
<h2 id="heading-11-database-integration">11. Database Integration</h2>
<p>In many real-world applications, persisting data is essential. NestJS offers first-class support and integrations for several database technologies. In this section we cover three common approaches:</p>
<ul>
<li><p><strong>TypeORM with NestJS</strong> (relational databases, Active Record/Data Mapper style)</p>
</li>
<li><p><strong>Mongoose (MongoDB)</strong> (NoSQL document store)</p>
</li>
<li><p><strong>Prisma</strong> (Type-safe query builder/ORM alternative)</p>
</li>
</ul>
<p>For each, we’ll explain the theory – when and why to choose it – and show concise practical examples of setup and usage in a NestJS context.</p>
<h3 id="heading-111-typeorm-with-nestjs">11.1 TypeORM with NestJS</h3>
<p>TypeORM is a popular ORM for Node.js that supports multiple relational databases (PostgreSQL, MySQL, SQLite, SQL Server, and so on), offering both Active Record and Data Mapper patterns.</p>
<p>In NestJS, the <code>@nestjs/typeorm</code> package wraps TypeORM to provide:</p>
<ul>
<li><p><strong>Automatic connection management</strong> via <code>TypeOrmModule.forRoot()</code></p>
</li>
<li><p><strong>Module-scoped repositories/entities</strong> via <code>TypeOrmModule.forFeature()</code></p>
</li>
<li><p><strong>Dependency injection</strong> for repositories and the <code>DataSource</code>/<code>Connection</code></p>
</li>
<li><p><strong>Entity decorators</strong> (<code>@Entity()</code>, <code>@Column()</code>, and so on) for schema definition</p>
</li>
<li><p><strong>Migrations</strong> and advanced features via TypeORM CLI or programmatic usage</p>
</li>
</ul>
<h4 id="heading-when-to-choose-typeorm">When to choose TypeORM</h4>
<p>Type ORM is useful in several scenarios. Use it when your data is relational and you want a full-featured ORM with decorators and built-in migrations. It’s also great if you prefer to work with classes/entities and automatically map them to tables. And it’s a great choice if you value built-in features like eager/lazy relations, cascading, query builders, and repository patterns.</p>
<h4 id="heading-heres-how-to-use-it">Here’s how to use it:</h4>
<ol>
<li><p><strong>Install dependencies:</strong></p>
<pre><code class="lang-bash"> npm install --save @nestjs/typeorm typeorm reflect-metadata
 <span class="hljs-comment"># Also install the database driver; e.g., for Postgres:</span>
 npm install --save pg
</code></pre>
</li>
<li><p><strong>Configure the root module:</strong></p>
<p> In <code>app.module.ts</code>, import <code>TypeOrmModule.forRoot()</code> with connection options. These can come from environment variables (discussed later in Configuration Management).</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/app.module.ts</span>
 <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { TypeOrmModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/typeorm'</span>;
 <span class="hljs-keyword">import</span> { UsersModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users/users.module'</span>;

 <span class="hljs-meta">@Module</span>({
   imports: [
     TypeOrmModule.forRoot({
       <span class="hljs-keyword">type</span>: <span class="hljs-string">'postgres'</span>,
       host: process.env.DB_HOST || <span class="hljs-string">'localhost'</span>,
       port: +process.env.DB_PORT || <span class="hljs-number">5432</span>,
       username: process.env.DB_USER || <span class="hljs-string">'postgres'</span>,
       password: process.env.DB_PASS || <span class="hljs-string">'password'</span>,
       database: process.env.DB_NAME || <span class="hljs-string">'mydb'</span>,
       entities: [__dirname + <span class="hljs-string">'/**/*.entity{.ts,.js}'</span>],
       synchronize: <span class="hljs-literal">false</span>, <span class="hljs-comment">// recommended false in production; use migrations</span>
       <span class="hljs-comment">// logging: true,</span>
     }),
     UsersModule,
     <span class="hljs-comment">// ...other modules</span>
   ],
 })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<ul>
<li><p><code>synchronize: true</code> can auto-sync schema in development, but in production prefer migrations.</p>
</li>
<li><p>Entities are auto-loaded via glob. Ensure path matches compiled output.</p>
</li>
</ul>
</li>
<li><p><strong>Define an entity:</strong></p>
<p> Create an entity class with decorators:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/users/user.entity.ts</span>
 <span class="hljs-keyword">import</span> { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } <span class="hljs-keyword">from</span> <span class="hljs-string">'typeorm'</span>;

 <span class="hljs-meta">@Entity</span>({ name: <span class="hljs-string">'users'</span> })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> User {
   <span class="hljs-meta">@PrimaryGeneratedColumn</span>()
   id: <span class="hljs-built_in">number</span>;

   <span class="hljs-meta">@Column</span>({ unique: <span class="hljs-literal">true</span> })
   email: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@Column</span>()
   password: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@Column</span>({ nullable: <span class="hljs-literal">true</span> })
   name?: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@CreateDateColumn</span>()
   createdAt: <span class="hljs-built_in">Date</span>;

   <span class="hljs-meta">@UpdateDateColumn</span>()
   updatedAt: <span class="hljs-built_in">Date</span>;
 }
</code></pre>
</li>
<li><p><strong>Set up the feature module:</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/users/users.module.ts</span>
 <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { TypeOrmModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/typeorm'</span>;
 <span class="hljs-keyword">import</span> { UsersService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users.service'</span>;
 <span class="hljs-keyword">import</span> { UsersController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users.controller'</span>;
 <span class="hljs-keyword">import</span> { User } <span class="hljs-keyword">from</span> <span class="hljs-string">'./user.entity'</span>;

 <span class="hljs-meta">@Module</span>({
   imports: [TypeOrmModule.forFeature([User])],
   providers: [UsersService],
   controllers: [UsersController],
   <span class="hljs-built_in">exports</span>: [UsersService], <span class="hljs-comment">// if other modules need UsersService</span>
 })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersModule {}
</code></pre>
</li>
<li><p><strong>Inject the repository:</strong></p>
<p> In the service, inject the <code>Repository&lt;User&gt;</code>:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/users/users.service.ts</span>
 <span class="hljs-keyword">import</span> { Injectable, NotFoundException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { InjectRepository } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/typeorm'</span>;
 <span class="hljs-keyword">import</span> { Repository } <span class="hljs-keyword">from</span> <span class="hljs-string">'typeorm'</span>;
 <span class="hljs-keyword">import</span> { User } <span class="hljs-keyword">from</span> <span class="hljs-string">'./user.entity'</span>;
 <span class="hljs-keyword">import</span> { CreateUserDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-user.dto'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersService {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params">
     <span class="hljs-meta">@InjectRepository</span>(User)
     <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> userRepository: Repository&lt;User&gt;,
   </span>) {}

   <span class="hljs-keyword">async</span> create(dto: CreateUserDto): <span class="hljs-built_in">Promise</span>&lt;User&gt; {
     <span class="hljs-keyword">const</span> user = <span class="hljs-built_in">this</span>.userRepository.create(dto); <span class="hljs-comment">// maps DTO fields to entity</span>
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.userRepository.save(user);
   }

   <span class="hljs-keyword">async</span> findAll(): <span class="hljs-built_in">Promise</span>&lt;User[]&gt; {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.userRepository.find();
   }

   <span class="hljs-keyword">async</span> findOne(id: <span class="hljs-built_in">number</span>): <span class="hljs-built_in">Promise</span>&lt;User&gt; {
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.userRepository.findOne({ where: { id } });
     <span class="hljs-keyword">if</span> (!user) {
       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundException(<span class="hljs-string">`User #<span class="hljs-subst">${id}</span> not found`</span>);
     }
     <span class="hljs-keyword">return</span> user;
   }

   <span class="hljs-keyword">async</span> update(id: <span class="hljs-built_in">number</span>, dto: Partial&lt;CreateUserDto&gt;): <span class="hljs-built_in">Promise</span>&lt;User&gt; {
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.findOne(id);
     <span class="hljs-built_in">Object</span>.assign(user, dto);
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.userRepository.save(user);
   }

   <span class="hljs-keyword">async</span> remove(id: <span class="hljs-built_in">number</span>): <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">void</span>&gt; {
     <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.userRepository.delete(id);
   }
 }
</code></pre>
</li>
<li><p><strong>Use in controller:</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/users/users.controller.ts</span>
 <span class="hljs-keyword">import</span> { Controller, Get, Post, Body, Param, ParseIntPipe, Put, Delete } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { UsersService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users.service'</span>;
 <span class="hljs-keyword">import</span> { CreateUserDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-user.dto'</span>;

 <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'users'</span>)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersController {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> usersService: UsersService</span>) {}

   <span class="hljs-meta">@Post</span>()
   create(<span class="hljs-meta">@Body</span>() dto: CreateUserDto) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.create(dto);
   }

   <span class="hljs-meta">@Get</span>()
   findAll() {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.findAll();
   }

   <span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)
   findOne(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>, ParseIntPipe) id: <span class="hljs-built_in">number</span>) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.findOne(id);
   }

   <span class="hljs-meta">@Put</span>(<span class="hljs-string">':id'</span>)
   update(
     <span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>, ParseIntPipe) id: <span class="hljs-built_in">number</span>,
     <span class="hljs-meta">@Body</span>() dto: Partial&lt;CreateUserDto&gt;,
   ) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.update(id, dto);
   }

   <span class="hljs-meta">@Delete</span>(<span class="hljs-string">':id'</span>)
   remove(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>, ParseIntPipe) id: <span class="hljs-built_in">number</span>) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.remove(id);
   }
 }
</code></pre>
</li>
<li><p><strong>Migrations (optional but recommended)</strong></p>
<ul>
<li><p>Use TypeORM CLI or programmatic migrations.</p>
</li>
<li><p>Configure a separate <code>ormconfig</code> or supply options in code.</p>
</li>
<li><p>Generate and run migrations to evolve schema without data loss.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-112-mongoose-mongodb">11.2 Mongoose (MongoDB)</h3>
<p>Mongoose is a widely used ODM (Object Document Mapper) for MongoDB. In NestJS, <code>@nestjs/mongoose</code> integrates Mongoose to:</p>
<ul>
<li><p>Define <strong>schemas</strong> via classes and decorators (<code>@Schema()</code>, <code>@Prop()</code>)</p>
</li>
<li><p>Register models in modules with <code>MongooseModule.forFeature()</code></p>
</li>
<li><p>Manage the MongoDB connection with <code>MongooseModule.forRoot()</code></p>
</li>
<li><p>Inject Mongoose <strong>Model</strong> instances into services</p>
</li>
<li><p>Work with documents in a type-safe way (with interfaces/types)</p>
</li>
<li><p>Leverage features like hooks, virtuals, and validation at schema level</p>
</li>
</ul>
<h4 id="heading-when-to-choose-mongoose">When to choose Mongoose</h4>
<p>Mongoose is a good choice if you need a document-oriented, schema-less/ schematized NoSQL store. It’s also great if your data shapes may vary, or you prefer MongoDB’s flexible schema. And it’s helpful if you want features like middleware hooks in schema (pre/post save), virtuals, and so on.</p>
<h4 id="heading-heres-how-to-use-it-1">Here’s how to use it:</h4>
<ol>
<li><p><strong>Install dependencies:</strong></p>
<pre><code class="lang-bash"> npm install --save @nestjs/mongoose mongoose
</code></pre>
</li>
<li><p><strong>Configure root module:</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/app.module.ts</span>
 <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { MongooseModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/mongoose'</span>;
 <span class="hljs-keyword">import</span> { CatsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats/cats.module'</span>;

 <span class="hljs-meta">@Module</span>({
   imports: [
     MongooseModule.forRoot(process.env.MONGO_URI || <span class="hljs-string">'mongodb://localhost/nest'</span>),
     CatsModule,
     <span class="hljs-comment">// ...other modules</span>
   ],
 })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
</li>
<li><p><strong>Define a schema and document:</strong></p>
<p> Use decorators and interfaces:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/cats/schemas/cat.schema.ts</span>
 <span class="hljs-keyword">import</span> { Prop, Schema, SchemaFactory } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/mongoose'</span>;
 <span class="hljs-keyword">import</span> { Document } <span class="hljs-keyword">from</span> <span class="hljs-string">'mongoose'</span>;

 <span class="hljs-meta">@Schema</span>({ timestamps: <span class="hljs-literal">true</span> })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> Cat <span class="hljs-keyword">extends</span> Document {
   <span class="hljs-meta">@Prop</span>({ required: <span class="hljs-literal">true</span> })
   name: <span class="hljs-built_in">string</span>;

   <span class="hljs-meta">@Prop</span>()
   age: <span class="hljs-built_in">number</span>;

   <span class="hljs-meta">@Prop</span>()
   breed: <span class="hljs-built_in">string</span>;
 }

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> CatSchema = SchemaFactory.createForClass(Cat);
</code></pre>
<ul>
<li><p>Extending <code>Document</code> gives the Mongoose document methods and properties.</p>
</li>
<li><p><code>timestamps: true</code> auto-adds <code>createdAt</code> and <code>updatedAt</code>.</p>
</li>
<li><p>You can add hooks:</p>
<pre><code class="lang-typescript">  CatSchema.pre&lt;Cat&gt;(<span class="hljs-string">'save'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">next</span>) </span>{
    <span class="hljs-comment">// e.g., modify data or log before saving</span>
    next();
  });
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Set up feature module:</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/cats/cats.module.ts</span>
 <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { MongooseModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/mongoose'</span>;
 <span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;
 <span class="hljs-keyword">import</span> { CatsController } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.controller'</span>;
 <span class="hljs-keyword">import</span> { Cat, CatSchema } <span class="hljs-keyword">from</span> <span class="hljs-string">'./schemas/cat.schema'</span>;

 <span class="hljs-meta">@Module</span>({
   imports: [
     MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }]),
   ],
   controllers: [CatsController],
   providers: [CatsService],
 })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CatsModule {}
</code></pre>
</li>
<li><p><strong>Inject the model:</strong></p>
<p> In the service, inject <code>Model&lt;Cat&gt;</code>:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/cats/cats.service.ts</span>
 <span class="hljs-keyword">import</span> { Injectable, NotFoundException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { InjectModel } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/mongoose'</span>;
 <span class="hljs-keyword">import</span> { Model } <span class="hljs-keyword">from</span> <span class="hljs-string">'mongoose'</span>;
 <span class="hljs-keyword">import</span> { Cat } <span class="hljs-keyword">from</span> <span class="hljs-string">'./schemas/cat.schema'</span>;
 <span class="hljs-keyword">import</span> { CreateCatDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-cat.dto'</span>;
 <span class="hljs-keyword">import</span> { UpdateCatDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/update-cat.dto'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> CatsService {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params">
     <span class="hljs-meta">@InjectModel</span>(Cat.name) <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> catModel: Model&lt;Cat&gt;,
   </span>) {}

   <span class="hljs-keyword">async</span> create(dto: CreateCatDto): <span class="hljs-built_in">Promise</span>&lt;Cat&gt; {
     <span class="hljs-keyword">const</span> created = <span class="hljs-keyword">new</span> <span class="hljs-built_in">this</span>.catModel(dto);
     <span class="hljs-keyword">return</span> created.save();
   }

   <span class="hljs-keyword">async</span> findAll(): <span class="hljs-built_in">Promise</span>&lt;Cat[]&gt; {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catModel.find().exec();
   }

   <span class="hljs-keyword">async</span> findOne(id: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">Promise</span>&lt;Cat&gt; {
     <span class="hljs-keyword">const</span> cat = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.catModel.findById(id).exec();
     <span class="hljs-keyword">if</span> (!cat) {
       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundException(<span class="hljs-string">`Cat <span class="hljs-subst">${id}</span> not found`</span>);
     }
     <span class="hljs-keyword">return</span> cat;
   }

   <span class="hljs-keyword">async</span> update(id: <span class="hljs-built_in">string</span>, dto: UpdateCatDto): <span class="hljs-built_in">Promise</span>&lt;Cat&gt; {
     <span class="hljs-keyword">const</span> updated = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.catModel
       .findByIdAndUpdate(id, dto, { <span class="hljs-keyword">new</span>: <span class="hljs-literal">true</span> })
       .exec();
     <span class="hljs-keyword">if</span> (!updated) {
       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundException(<span class="hljs-string">`Cat <span class="hljs-subst">${id}</span> not found`</span>);
     }
     <span class="hljs-keyword">return</span> updated;
   }

   <span class="hljs-keyword">async</span> remove(id: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">void</span>&gt; {
     <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.catModel.findByIdAndDelete(id).exec();
     <span class="hljs-keyword">if</span> (!res) {
       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundException(<span class="hljs-string">`Cat <span class="hljs-subst">${id}</span> not found`</span>);
     }
   }
 }
</code></pre>
</li>
<li><p><strong>Use in controller:</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/cats/cats.controller.ts</span>
 <span class="hljs-keyword">import</span> { Controller, Get, Post, Body, Param, Put, Delete } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { CatsService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cats.service'</span>;
 <span class="hljs-keyword">import</span> { CreateCatDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-cat.dto'</span>;
 <span class="hljs-keyword">import</span> { UpdateCatDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/update-cat.dto'</span>;

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

   <span class="hljs-meta">@Post</span>()
   create(<span class="hljs-meta">@Body</span>() dto: CreateCatDto) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.create(dto);
   }

   <span class="hljs-meta">@Get</span>()
   findAll() {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.findAll();
   }

   <span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)
   findOne(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>) id: <span class="hljs-built_in">string</span>) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.findOne(id);
   }

   <span class="hljs-meta">@Put</span>(<span class="hljs-string">':id'</span>)
   update(
     <span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>) id: <span class="hljs-built_in">string</span>,
     <span class="hljs-meta">@Body</span>() dto: UpdateCatDto,
   ) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.update(id, dto);
   }

   <span class="hljs-meta">@Delete</span>(<span class="hljs-string">':id'</span>)
   remove(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>) id: <span class="hljs-built_in">string</span>) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.catsService.remove(id);
   }
 }
</code></pre>
</li>
<li><p><strong>Advanced Mongoose features</strong></p>
<ul>
<li><p><strong>Virtuals</strong>: define computed properties not stored in DB.</p>
</li>
<li><p><strong>Indexes</strong>: via schema options or <code>@Prop({ index: true })</code>.</p>
</li>
<li><p><strong>Populate</strong>: reference other collections with <code>@Prop({ type: Types.ObjectId, ref: 'OtherModel' })</code>.</p>
</li>
<li><p><strong>Transactions</strong>: use MongoDB sessions for multi-document atomic operations.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-113-prisma">11.3 Prisma</h3>
<p>Prisma is a modern ORM/Query Builder that generates a type-safe client based on a schema definition. It supports relational databases (PostgreSQL, MySQL, SQLite, SQL Server, and more).</p>
<p>Here are some of its key features:</p>
<ul>
<li><p><strong>Type-safe queries</strong>: Autogenerated TypeScript definitions prevent many runtime errors.</p>
</li>
<li><p><strong>Prisma schema</strong>: A declarative <code>.prisma</code> file to define models, relations, and enums.</p>
</li>
<li><p><strong>Migrations</strong>: <code>prisma migrate</code> for evolving schema.</p>
</li>
<li><p><strong>Performance</strong>: Lean query builder without heavy runtime overhead.</p>
</li>
<li><p><strong>Flexibility</strong>: Supports raw queries when needed.</p>
</li>
</ul>
<h4 id="heading-when-to-choose-prisma">When to choose Prisma</h4>
<p>Prisma is a great choice if you prefer a schema-first approach with a clear DSL and auto-generated type-safe client. It’s also great if you want modern features like efficient migrations, rich type inference, and a straightforward developer experience. And it’s a solid choice if you don’t need Active Record pattern. Instead, you use the Prisma client in services.</p>
<h4 id="heading-heres-how-it-works">Here’s how it works:</h4>
<ol>
<li><p><strong>Install dependencies and initialize:</strong></p>
<pre><code class="lang-bash"> npm install @prisma/client
 npm install -D prisma
 npx prisma init
</code></pre>
<p> This creates a <code>prisma/schema.prisma</code> file and a <code>.env</code> with <code>DATABASE_URL</code>.</p>
</li>
<li><p><strong>Define the schema:</strong></p>
<p> In <code>prisma/schema.prisma</code>:</p>
<pre><code class="lang-bash"> datasource db {
   provider = <span class="hljs-string">"postgresql"</span>
   url      = env(<span class="hljs-string">"DATABASE_URL"</span>)
 }

 generator client {
   provider = <span class="hljs-string">"prisma-client-js"</span>
 }

 model User {
   id        Int      @id @default(autoincrement())
   email     String   @unique
   name      String?
   posts     Post[]
   createdAt DateTime @default(now())
   updatedAt DateTime @updatedAt
 }

 model Post {
   id        Int      @id @default(autoincrement())
   title     String
   content   String?
   author    User     @relation(fields: [authorId], references: [id])
   authorId  Int
   published Boolean  @default(<span class="hljs-literal">false</span>)
   createdAt DateTime @default(now())
   updatedAt DateTime @updatedAt
 }
</code></pre>
</li>
<li><p><strong>Run migrations and generate client:</strong></p>
<pre><code class="lang-bash"> npx prisma migrate dev --name init
 npx prisma generate
</code></pre>
<p> This updates the database schema and regenerates the TypeScript client.</p>
</li>
<li><p><strong>Create a PrismaService in NestJS:</strong></p>
<p> A common pattern is to wrap the <code>PrismaClient</code> in an injectable service, handling lifecycle hooks.</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/prisma/prisma.service.ts</span>
 <span class="hljs-keyword">import</span> { Injectable, OnModuleInit, OnModuleDestroy } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { PrismaClient } <span class="hljs-keyword">from</span> <span class="hljs-string">'@prisma/client'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> PrismaService <span class="hljs-keyword">extends</span> PrismaClient <span class="hljs-keyword">implements</span> OnModuleInit, OnModuleDestroy {
   <span class="hljs-keyword">async</span> onModuleInit() {
     <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.$connect();
   }

   <span class="hljs-keyword">async</span> onModuleDestroy() {
     <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.$disconnect();
   }
 }
</code></pre>
</li>
<li><p><strong>Register PrismaService in a module:</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/prisma/prisma.module.ts</span>
 <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { PrismaService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./prisma.service'</span>;

 <span class="hljs-meta">@Module</span>({
   providers: [PrismaService],
   <span class="hljs-built_in">exports</span>: [PrismaService],
 })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> PrismaModule {}
</code></pre>
<p> Then import <code>PrismaModule</code> in any feature module needing DB access.</p>
</li>
<li><p><strong>Use in a feature service:</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/users/users.service.ts</span>
 <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { PrismaService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../prisma/prisma.service'</span>;
 <span class="hljs-keyword">import</span> { CreateUserDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-user.dto'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersService {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> prisma: PrismaService</span>) {}

   <span class="hljs-keyword">async</span> create(dto: CreateUserDto) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.prisma.user.create({ data: dto });
   }

   <span class="hljs-keyword">async</span> findAll() {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.prisma.user.findMany();
   }

   <span class="hljs-keyword">async</span> findOne(id: <span class="hljs-built_in">number</span>) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.prisma.user.findUnique({ where: { id } });
   }

   <span class="hljs-keyword">async</span> update(id: <span class="hljs-built_in">number</span>, dto: Partial&lt;CreateUserDto&gt;) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.prisma.user.update({
       where: { id },
       data: dto,
     });
   }

   <span class="hljs-keyword">async</span> remove(id: <span class="hljs-built_in">number</span>) {
     <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.prisma.user.delete({ where: { id } });
     <span class="hljs-keyword">return</span> { deleted: <span class="hljs-literal">true</span> };
   }
 }
</code></pre>
<p> Note: DTO fields must align with Prisma schema types. Prisma client methods return typed results.</p>
</li>
<li><p><strong>Inject in controller:</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/users/users.controller.ts</span>
 <span class="hljs-keyword">import</span> { Controller, Get, Post, Body, Param, ParseIntPipe, Put, Delete } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { UsersService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users.service'</span>;
 <span class="hljs-keyword">import</span> { CreateUserDto } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dto/create-user.dto'</span>;

 <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'users'</span>)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersController {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> usersService: UsersService</span>) {}

   <span class="hljs-meta">@Post</span>()
   create(<span class="hljs-meta">@Body</span>() dto: CreateUserDto) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.create(dto);
   }

   <span class="hljs-meta">@Get</span>()
   findAll() {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.findAll();
   }

   <span class="hljs-meta">@Get</span>(<span class="hljs-string">':id'</span>)
   findOne(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>, ParseIntPipe) id: <span class="hljs-built_in">number</span>) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.findOne(id);
   }

   <span class="hljs-meta">@Put</span>(<span class="hljs-string">':id'</span>)
   update(
     <span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>, ParseIntPipe) id: <span class="hljs-built_in">number</span>,
     <span class="hljs-meta">@Body</span>() dto: Partial&lt;CreateUserDto&gt;,
   ) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.update(id, dto);
   }

   <span class="hljs-meta">@Delete</span>(<span class="hljs-string">':id'</span>)
   remove(<span class="hljs-meta">@Param</span>(<span class="hljs-string">'id'</span>, ParseIntPipe) id: <span class="hljs-built_in">number</span>) {
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.usersService.remove(id);
   }
 }
</code></pre>
</li>
<li><p><strong>Advanced Prisma usage</strong></p>
<ul>
<li><p><strong>Relations and nested writes</strong>: for example, create a post with nested author connect/create.</p>
</li>
<li><p><strong>Transactions</strong>: <code>this.prisma.$transaction([...])</code> for atomic operations.</p>
</li>
<li><p><strong>Raw queries</strong>: <code>this.prisma.$queryRaw</code> when needed.</p>
</li>
<li><p><strong>Middleware</strong>: Prisma supports middlewares on the client side.</p>
</li>
<li><p><strong>Performance tuning</strong>: select only needed fields, use pagination patterns.</p>
</li>
</ul>
</li>
</ol>
<p>With these three approaches, you can choose the database integration strategy that best fits your application’s needs:</p>
<ul>
<li><p><strong>TypeORM</strong> for a full-fledged ORM with decorators and migrations support in relational databases.</p>
</li>
<li><p><strong>Mongoose</strong> for flexible document schemas in MongoDB.</p>
</li>
<li><p><strong>Prisma</strong> for a modern, type-safe query builder/ORM alternative with excellent developer ergonomics.</p>
</li>
</ul>
<p>In the next section, we’ll cover <strong>Configuration Management</strong> – how to handle environment variables and config modules in NestJS.</p>
<h2 id="heading-12-configuration-management">12. Configuration Management</h2>
<p>Managing configuration cleanly is crucial for applications to behave correctly across environments (development, staging, production). NestJS provides the <code>@nestjs/config</code> module to centralize configuration loading, validation, and injection.</p>
<h3 id="heading-121-nestjsconfig-module">12.1 @nestjs/config Module</h3>
<p>The <code>@nestjs/config</code> module is a powerful utility for managing application configuration settings. Here are some of its key features:</p>
<ul>
<li><p><strong>Centralized config</strong>: Instead of sprinkling <code>process.env</code> throughout your code, it uses a dedicated service that loads and validates configuration once at startup.</p>
</li>
<li><p><strong>Environment agnostic</strong>: It loads variables from <code>.env</code> files, environment variables, or other sources, with support for different files per environment.</p>
</li>
<li><p><strong>Validation</strong>: It integrates a schema (for example, via Joi) to ensure required variables are present and correctly typed, failing fast if misconfigured.</p>
</li>
<li><p><strong>Config Namespacing</strong>: It organizes related settings into logical groups (for example, database, auth, third-party APIs) via configuration factories.</p>
</li>
<li><p><strong>Injection</strong>: It injects a <code>ConfigService</code> to read config values in services or modules, with type safety when using custom typed wrappers.</p>
</li>
</ul>
<h4 id="heading-heres-how-it-works-1">Here’s how it works:</h4>
<ol>
<li><p><strong>Install the package</strong></p>
<pre><code class="lang-bash"> npm install @nestjs/config
 npm install joi    <span class="hljs-comment"># if you plan to validate via Joi schemas</span>
</code></pre>
</li>
<li><p><strong>Import and initialize ConfigModule</strong></p>
<p> In your root module (<code>AppModule</code>), import <code>ConfigModule.forRoot()</code>. Typical options:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/app.module.ts</span>
 <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { ConfigModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;
 <span class="hljs-keyword">import</span> configuration <span class="hljs-keyword">from</span> <span class="hljs-string">'./config/configuration'</span>;
 <span class="hljs-keyword">import</span> { validationSchema } <span class="hljs-keyword">from</span> <span class="hljs-string">'./config/validation'</span>;

 <span class="hljs-meta">@Module</span>({
   imports: [
     ConfigModule.forRoot({
       <span class="hljs-comment">// Load .env automatically; specify envFilePath if custom:</span>
       isGlobal: <span class="hljs-literal">true</span>,           <span class="hljs-comment">// makes ConfigService available app-wide</span>
       envFilePath: [<span class="hljs-string">'.env.development.local'</span>, <span class="hljs-string">'.env.development'</span>, <span class="hljs-string">'.env'</span>], 
       load: [configuration],    <span class="hljs-comment">// optional: load custom config factory(s)</span>
       validationSchema,         <span class="hljs-comment">// optional: Joi schema to validate env vars</span>
       validationOptions: {
         allowUnknown: <span class="hljs-literal">true</span>,
         abortEarly: <span class="hljs-literal">true</span>,
       },
     }),
     <span class="hljs-comment">// ...other modules</span>
   ],
 })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<ul>
<li><p><code>isGlobal: true</code> avoids importing <code>ConfigModule</code> in every feature module.</p>
</li>
<li><p><code>envFilePath</code>: an array lets you try multiple files (for example, local overrides before default).</p>
</li>
<li><p><code>load</code>: array of functions returning partial config objects – see next step.</p>
</li>
<li><p><code>validationSchema</code>: a Joi schema ensuring required variables exist and are correct type/format.</p>
</li>
</ul>
</li>
<li><p><strong>Define a configuration factory</strong></p>
<p> Organize related settings into a typed object:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/config/configuration.ts</span>
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; ({
   port: <span class="hljs-built_in">parseInt</span>(process.env.PORT, <span class="hljs-number">10</span>) || <span class="hljs-number">3000</span>,
   database: {
     host: process.env.DB_HOST,
     port: <span class="hljs-built_in">parseInt</span>(process.env.DB_PORT, <span class="hljs-number">10</span>) || <span class="hljs-number">5432</span>,
     user: process.env.DB_USER,
     pass: process.env.DB_PASS,
     name: process.env.DB_NAME,
   },
   jwt: {
     secret: process.env.JWT_SECRET,
     expiresIn: process.env.JWT_EXPIRES_IN || <span class="hljs-string">'1h'</span>,
   },
   <span class="hljs-comment">// add other namespaces as needed</span>
 });
</code></pre>
</li>
<li><p><strong>Validate environment variables</strong></p>
<p> Using Joi for validation:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/config/validation.ts</span>
 <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> Joi <span class="hljs-keyword">from</span> <span class="hljs-string">'joi'</span>;

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> validationSchema = Joi.object({
   NODE_ENV: Joi.string()
     .valid(<span class="hljs-string">'development'</span>, <span class="hljs-string">'production'</span>, <span class="hljs-string">'test'</span>, <span class="hljs-string">'staging'</span>)
     .default(<span class="hljs-string">'development'</span>),
   PORT: Joi.number().default(<span class="hljs-number">3000</span>),
   DB_HOST: Joi.string().required(),
   DB_PORT: Joi.number().default(<span class="hljs-number">5432</span>),
   DB_USER: Joi.string().required(),
   DB_PASS: Joi.string().required(),
   DB_NAME: Joi.string().required(),
   JWT_SECRET: Joi.string().min(<span class="hljs-number">32</span>).required(),
   JWT_EXPIRES_IN: Joi.string().default(<span class="hljs-string">'1h'</span>),
   <span class="hljs-comment">// add other variables...</span>
 });
</code></pre>
<p> If validation fails at startup, the application will error out with details, preventing misconfigured deployments.</p>
</li>
<li><p><strong>Inject ConfigService</strong></p>
<p> Anywhere you need config, inject <code>ConfigService</code>:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/some/some.service.ts</span>
 <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { ConfigService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> SomeService {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> configService: ConfigService</span>) {}

   getDbConfig() {
     <span class="hljs-keyword">const</span> host = <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.host'</span>);
     <span class="hljs-keyword">const</span> port = <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-string">'database.port'</span>);
     <span class="hljs-comment">// Use these values to configure a database client, etc.</span>
     <span class="hljs-keyword">return</span> { host, port };
   }
 }
</code></pre>
<ul>
<li><p>Use dot notation for nested config: for example, <code>'jwt.secret'</code>.</p>
</li>
<li><p>You can also read raw env vars via <code>configService.get&lt;string&gt;('DB_HOST')</code> if needed, but preferring structured config is clearer.</p>
</li>
</ul>
</li>
<li><p><strong>Typed wrapper for ConfigService (optional)</strong></p>
<p> For stronger typing, create an interface matching your configuration and a wrapper:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/config/config.interface.ts</span>
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> AppConfig {
   port: <span class="hljs-built_in">number</span>;
   database: {
     host: <span class="hljs-built_in">string</span>;
     port: <span class="hljs-built_in">number</span>;
     user: <span class="hljs-built_in">string</span>;
     pass: <span class="hljs-built_in">string</span>;
     name: <span class="hljs-built_in">string</span>;
   };
   jwt: {
     secret: <span class="hljs-built_in">string</span>;
     expiresIn: <span class="hljs-built_in">string</span>;
   };
 }
</code></pre>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/config/typed-config.service.ts</span>
 <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { ConfigService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;
 <span class="hljs-keyword">import</span> { AppConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'./config.interface'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TypedConfigService {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> configService: ConfigService</span>) {}

   get appConfig(): AppConfig {
     <span class="hljs-keyword">return</span> {
       port: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-string">'port'</span>),
       database: {
         host: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.host'</span>),
         port: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-string">'database.port'</span>),
         user: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.user'</span>),
         pass: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.pass'</span>),
         name: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.name'</span>),
       },
       jwt: {
         secret: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'jwt.secret'</span>),
         expiresIn: <span class="hljs-built_in">this</span>.configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'jwt.expiresIn'</span>),
       },
     };
   }
 }
</code></pre>
<p> Register <code>TypedConfigService</code> in a module if you prefer injecting it instead of raw <code>ConfigService</code>.</p>
</li>
<li><p><strong>Dynamic module registration using config</strong></p>
<p> Many Nest modules accept dynamic options. For example, TypeORM:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/database/database.module.ts</span>
 <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { TypeOrmModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/typeorm'</span>;
 <span class="hljs-keyword">import</span> { ConfigService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;

 <span class="hljs-meta">@Module</span>({
   imports: [
     TypeOrmModule.forRootAsync({
       inject: [ConfigService],
       useFactory: <span class="hljs-function">(<span class="hljs-params">config: ConfigService</span>) =&gt;</span> ({
         <span class="hljs-keyword">type</span>: <span class="hljs-string">'postgres'</span>,
         host: config.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.host'</span>),
         port: config.get&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-string">'database.port'</span>),
         username: config.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.user'</span>),
         password: config.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.pass'</span>),
         database: config.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'database.name'</span>),
         entities: [__dirname + <span class="hljs-string">'/../**/*.entity{.ts,.js}'</span>],
         synchronize: config.get(<span class="hljs-string">'NODE_ENV'</span>) !== <span class="hljs-string">'production'</span>,
       }),
     }),
   ],
 })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> DatabaseModule {}
</code></pre>
<p> Using <code>forRootAsync</code> with <code>useFactory</code> ensures config is loaded before the module initializes.</p>
</li>
</ol>
<h3 id="heading-122-environment-variables">12.2 Environment Variables</h3>
<p>Environment variables serve as the bridge between code and its runtime environment, letting you decouple configuration (like database URLs, API keys, or feature flags) from your source.</p>
<p>By relying on environment variables, you ensure that the same application bundle can run safely across development, staging, and production – each providing its own sensitive or environment-specific settings without changing code. This is how it works:</p>
<ul>
<li><p><strong>12-Factor app principle</strong>: Stores config in the environment. Avoids hard-coding secrets or environment-specific settings in code.</p>
</li>
<li><p><strong>Separation of concerns</strong>: Code remains the same across environments. Behavior is driven by env vars or config files.</p>
</li>
<li><p><strong>Security</strong>: Keeps secrets (API keys, DB passwords) out of source control. Uses environment variables or secure vaults.</p>
</li>
<li><p><strong>Overrides and precedence</strong>: You may have multiple <code>.env</code> files (for example, <code>.env</code>, <code>.env.local</code>, <code>.env.production</code>) or CI/CD provided vars. It controls the order of loading.</p>
</li>
<li><p><strong>Defaults and fallbacks</strong>: Provides sensible defaults in code or config factories so the app can run in development without requiring every variable.</p>
</li>
</ul>
<h4 id="heading-heres-how-to-use-it-2">Here’s how to use it:</h4>
<ol>
<li><p><strong>.env files</strong></p>
<ul>
<li><p>Create a <code>.env</code> file at project root with key-value pairs:</p>
<pre><code class="lang-typescript">  PORT=<span class="hljs-number">3000</span>
  DB_HOST=localhost
  DB_PORT=<span class="hljs-number">5432</span>
  DB_USER=postgres
  DB_PASS=secret
  DB_NAME=mydb
  JWT_SECRET=supersecretjwtkey
  JWT_EXPIRES_IN=<span class="hljs-number">2</span>h
</code></pre>
</li>
<li><p>Optionally create <code>.env.development</code>, <code>.env.test</code>, <code>.env.production</code>, and load them based on <code>NODE_ENV</code>.</p>
</li>
<li><p>Ensure <code>.env</code> files are in <code>.gitignore</code> to avoid committing secrets.</p>
</li>
</ul>
</li>
<li><p><strong>Loading order</strong></p>
<ul>
<li><p>With <code>@nestjs/config</code>, specify <code>envFilePath</code> as an array, for example:</p>
<pre><code class="lang-typescript">  ConfigModule.forRoot({
    envFilePath: [
      <span class="hljs-string">`.env.<span class="hljs-subst">${process.env.NODE_ENV}</span>.local`</span>,
      <span class="hljs-string">`.env.<span class="hljs-subst">${process.env.NODE_ENV}</span>`</span>,
      <span class="hljs-string">`.env`</span>,
    ],
    isGlobal: <span class="hljs-literal">true</span>,
  });
</code></pre>
</li>
<li><p>This tries <code>.env.development.local</code>, then <code>.env.development</code>, then <code>.env</code>. CI/CD can set actual environment variables that override values in files.</p>
</li>
</ul>
</li>
<li><p><strong>Accessing raw environment variables</strong></p>
<ul>
<li><p>While structured config is preferred, sometimes you need direct access:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">const</span> raw = process.env.SOME_VAR;
</code></pre>
</li>
<li><p>Avoid scattering <code>process.env</code> in multiple places. Instead, prefer reading once in configuration factory and injecting via <code>ConfigService</code>.</p>
</li>
</ul>
</li>
<li><p><strong>Default values</strong></p>
<ul>
<li><p>In configuration factory or when reading via <code>ConfigService</code>, provide defaults:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">const</span> port = configService.get&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-string">'PORT'</span>, <span class="hljs-number">3000</span>);
</code></pre>
<p>  or in factory:</p>
<pre><code class="lang-typescript">  port: <span class="hljs-built_in">parseInt</span>(process.env.PORT, <span class="hljs-number">10</span>) || <span class="hljs-number">3000</span>
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Type coercion</strong></p>
<ul>
<li><p>Environment variables are strings by default. Convert to numbers or booleans as needed:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">const</span> isProd = configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'NODE_ENV'</span>) === <span class="hljs-string">'production'</span>;
  <span class="hljs-keyword">const</span> enableFeature = configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'FEATURE_FLAG'</span>) === <span class="hljs-string">'true'</span>;
  <span class="hljs-keyword">const</span> timeout = <span class="hljs-built_in">parseInt</span>(configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'TIMEOUT_MS'</span>), <span class="hljs-number">10</span>) || <span class="hljs-number">5000</span>;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Secret management</strong></p>
<ul>
<li><p>For sensitive data in production, consider using secret managers (AWS Secrets Manager, Vault) instead of plain <code>.env</code>. In that case, load secrets at startup (for example, via a custom provider or factory) and merge into the configuration.</p>
</li>
<li><p>Example: in <code>useFactory</code>, asynchronously fetch secrets and return a config object including them.</p>
</li>
</ul>
</li>
<li><p><strong>Runtime configuration changes</strong></p>
<ul>
<li>Generally configs are static at startup. If you need to reload config without restarting, implement a custom mechanism (for example, read from a database or remote config service periodically). Inject a service that fetches and caches values, but note this departs from 12-factor principles.</li>
</ul>
</li>
<li><p><strong>Validation in production</strong></p>
<ul>
<li><p>Always validate required env vars at startup so misconfigurations fail early. Use <code>validationSchema</code> with Joi or another validator.</p>
</li>
<li><p>Example error: if <code>JWT_SECRET</code> is missing or too short, the app should refuse to start, logging a clear error.</p>
</li>
</ul>
</li>
</ol>
<p>With configuration managed via <code>@nestjs/config</code> and environment variables, your NestJS app can adapt seamlessly across environments, keep secrets secure, and avoid environment-specific code changes. In the next section, we’ll cover <strong>Authentication</strong> strategies (JWT, OAuth2/social login).</p>
<h2 id="heading-13-authentication">13. Authentication</h2>
<p>Handling authentication securely is a common requirement. In NestJS, you typically use <strong>Passport</strong> strategies alongside the <strong>@nestjs/jwt</strong> module for JWT-based flows, or OAuth2 strategies for social login.</p>
<p>Here, we’ll cover two common approaches:</p>
<ul>
<li><p><strong>JWT Strategy</strong>: token-based authentication for APIs.</p>
</li>
<li><p><strong>OAuth2 / Social Login</strong>: integrating providers like Google or GitHub.</p>
</li>
</ul>
<h3 id="heading-131-jwt-strategy">13.1 JWT Strategy</h3>
<p>JSON Web Tokens (JWTs) are a compact, URL-safe means of representing claims between two parties. In an authentication context, the server issues a signed token containing user identity and possibly other claims, while the client stores and sends this token on subsequent requests (typically in the <code>Authorization: Bearer &lt;token&gt;</code> header).</p>
<p>Because the token is signed (and optionally encrypted), the server can verify its integrity and authenticity without needing to maintain session state in memory or a database. This stateless nature simplifies scaling and decouples services.</p>
<p>Tokens include an expiration (<code>exp</code>) so they automatically become invalid after a certain time. For longer-lived sessions, you can layer a refresh-token pattern on top.</p>
<p>In NestJS, we leverage <code>@nestjs/jwt</code> to sign and verify tokens and <code>@nestjs/passport</code> with <code>passport-jwt</code> to integrate a guard that checks incoming tokens. Below is how it works.</p>
<ul>
<li><p><strong>JWT (JSON Web Token)</strong>: a signed token containing claims (for example, user ID) that clients send in the <code>Authorization</code> header.</p>
</li>
<li><p><strong>Stateless</strong>: the server verifies the token signature without storing session state.</p>
</li>
<li><p><strong>Expiration</strong>: embed expiry (<code>exp</code>) so tokens auto-expire; possibly use refresh tokens for long-lived sessions.</p>
</li>
<li><p>In NestJS, you use <code>@nestjs/jwt</code> to sign/verify tokens and <code>@nestjs/passport</code> with <code>passport-jwt</code> to implement the guard.</p>
</li>
</ul>
<h4 id="heading-heres-how-to-use-it-3">Here’s how to use it:</h4>
<ol>
<li><p><strong>Install dependencies</strong></p>
<pre><code class="lang-bash"> npm install @nestjs/jwt passport-jwt @nestjs/passport passport
</code></pre>
</li>
<li><p><strong>Configuration</strong></p>
<p> Use <code>ConfigService</code> (from previous section) to load secrets and TTL:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/auth.config.ts</span>
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> () =&gt; ({
   jwt: {
     secret: process.env.JWT_SECRET || <span class="hljs-string">'default-secret'</span>,
     expiresIn: process.env.JWT_EXPIRES_IN || <span class="hljs-string">'1h'</span>,
   },
 });
</code></pre>
<p> Ensure <code>ConfigModule.forRoot({ load: [authConfig], isGlobal: true, validationSchema: ... })</code> is set in <code>AppModule</code>.</p>
</li>
<li><p><strong>AuthModule setup</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/auth.module.ts</span>
 <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { JwtModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/jwt'</span>;
 <span class="hljs-keyword">import</span> { PassportModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/passport'</span>;
 <span class="hljs-keyword">import</span> { ConfigService, ConfigModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;
 <span class="hljs-keyword">import</span> { JwtStrategy } <span class="hljs-keyword">from</span> <span class="hljs-string">'./jwt.strategy'</span>;
 <span class="hljs-keyword">import</span> { AuthService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth.service'</span>;
 <span class="hljs-keyword">import</span> { UsersModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'../users/users.module'</span>; <span class="hljs-comment">// assumes a UsersService</span>

 <span class="hljs-meta">@Module</span>({
   imports: [
     UsersModule,
     PassportModule.register({ defaultStrategy: <span class="hljs-string">'jwt'</span> }),
     JwtModule.registerAsync({
       imports: [ConfigModule],
       inject: [ConfigService],
       useFactory: <span class="hljs-function">(<span class="hljs-params">config: ConfigService</span>) =&gt;</span> ({
         secret: config.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'jwt.secret'</span>),
         signOptions: { expiresIn: config.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'jwt.expiresIn'</span>) },
       }),
     }),
   ],
   providers: [AuthService, JwtStrategy],
   <span class="hljs-built_in">exports</span>: [AuthService],
 })
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AuthModule {}
</code></pre>
</li>
<li><p><strong>AuthService</strong></p>
<p> Responsible for validating credentials and issuing tokens:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/auth.service.ts</span>
 <span class="hljs-keyword">import</span> { Injectable, UnauthorizedException } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { JwtService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/jwt'</span>;
 <span class="hljs-keyword">import</span> { UsersService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../users/users.service'</span>;
 <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> bcrypt <span class="hljs-keyword">from</span> <span class="hljs-string">'bcrypt'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AuthService {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params">
     <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> usersService: UsersService,
     <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> jwtService: JwtService,
   </span>) {}

   <span class="hljs-comment">// Validate user credentials (email/password)</span>
   <span class="hljs-keyword">async</span> validateUser(email: <span class="hljs-built_in">string</span>, pass: <span class="hljs-built_in">string</span>) {
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.usersService.findByEmail(email);
     <span class="hljs-keyword">if</span> (user &amp;&amp; (<span class="hljs-keyword">await</span> bcrypt.compare(pass, user.password))) {
       <span class="hljs-comment">// exclude password before returning</span>
       <span class="hljs-keyword">const</span> { password, ...result } = user;
       <span class="hljs-keyword">return</span> result;
     }
     <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
   }

   <span class="hljs-comment">// Called after validateUser succeeds</span>
   <span class="hljs-keyword">async</span> login(user: <span class="hljs-built_in">any</span>) {
     <span class="hljs-keyword">const</span> payload = { sub: user.id, email: user.email };
     <span class="hljs-keyword">return</span> {
       access_token: <span class="hljs-built_in">this</span>.jwtService.sign(payload),
     };
   }
 }
</code></pre>
</li>
<li><p><strong>JwtStrategy</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/jwt.strategy.ts</span>
 <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { PassportStrategy } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/passport'</span>;
 <span class="hljs-keyword">import</span> { ExtractJwt, Strategy } <span class="hljs-keyword">from</span> <span class="hljs-string">'passport-jwt'</span>;
 <span class="hljs-keyword">import</span> { ConfigService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> JwtStrategy <span class="hljs-keyword">extends</span> PassportStrategy(Strategy) {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> configService: ConfigService</span>) {
     <span class="hljs-built_in">super</span>({
       jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
       ignoreExpiration: <span class="hljs-literal">false</span>,
       secretOrKey: configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'jwt.secret'</span>),
     });
   }

   <span class="hljs-keyword">async</span> validate(payload: <span class="hljs-built_in">any</span>) {
     <span class="hljs-comment">// payload.sub is user ID</span>
     <span class="hljs-keyword">return</span> { userId: payload.sub, email: payload.email };
     <span class="hljs-comment">// returned value is assigned to req.user</span>
   }
 }
</code></pre>
</li>
<li><p><strong>Auth Controller</strong></p>
<p> Expose login endpoint:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/auth.controller.ts</span>
 <span class="hljs-keyword">import</span> { Controller, Post, Body, Request, UseGuards } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { AuthService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth.service'</span>;
 <span class="hljs-keyword">import</span> { LocalAuthGuard } <span class="hljs-keyword">from</span> <span class="hljs-string">'./local-auth.guard'</span>; <span class="hljs-comment">// optional if using local strategy</span>

 <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'auth'</span>)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AuthController {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> authService: AuthService</span>) {}

   <span class="hljs-comment">// Example: using a local strategy for email/password</span>
   <span class="hljs-meta">@UseGuards</span>(LocalAuthGuard)
   <span class="hljs-meta">@Post</span>(<span class="hljs-string">'login'</span>)
   <span class="hljs-keyword">async</span> login(<span class="hljs-meta">@Request</span>() req) {
     <span class="hljs-comment">// LocalAuthGuard attaches user to req.user</span>
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.authService.login(req.user);
   }

   <span class="hljs-comment">// Alternatively, implement login logic directly:</span>
   <span class="hljs-meta">@Post</span>(<span class="hljs-string">'login-basic'</span>)
   <span class="hljs-keyword">async</span> loginBasic(<span class="hljs-meta">@Body</span>() body: { email: <span class="hljs-built_in">string</span>; password: <span class="hljs-built_in">string</span> }) {
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.authService.validateUser(body.email, body.password);
     <span class="hljs-keyword">if</span> (!user) {
       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UnauthorizedException(<span class="hljs-string">'Invalid credentials'</span>);
     }
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.authService.login(user);
   }
 }
</code></pre>
<ul>
<li><strong>LocalAuthGuard</strong> would use a LocalStrategy to validate credentials via Passport.</li>
</ul>
</li>
<li><p><strong>Protecting routes</strong></p>
<p> Use the <strong>JwtAuthGuard</strong>:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/jwt-auth.guard.ts</span>
 <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { AuthGuard } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/passport'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> JwtAuthGuard <span class="hljs-keyword">extends</span> AuthGuard(<span class="hljs-string">'jwt'</span>) {}
</code></pre>
<p> Apply to controllers or routes:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/profile/profile.controller.ts</span>
 <span class="hljs-keyword">import</span> { Controller, Get, UseGuards, Request } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { JwtAuthGuard } <span class="hljs-keyword">from</span> <span class="hljs-string">'../auth/jwt-auth.guard'</span>;

 <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'profile'</span>)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ProfileController {
   <span class="hljs-meta">@UseGuards</span>(JwtAuthGuard)
   <span class="hljs-meta">@Get</span>()
   getProfile(<span class="hljs-meta">@Request</span>() req) {
     <span class="hljs-keyword">return</span> req.user; <span class="hljs-comment">// { userId, email }</span>
   }
 }
</code></pre>
</li>
<li><p><strong>Refresh Tokens (optional)</strong></p>
<ul>
<li><p>Issue a refresh token (longer expiry) and store it (for example, in DB or as HTTP-only cookie).</p>
</li>
<li><p>Create a separate endpoint to issue new access token when the access token expires.</p>
</li>
<li><p>Verify refresh token validity (for example, compare stored token or a hashed version).</p>
</li>
<li><p>Implementation details vary – consider security best practices (rotate tokens, revoke on logout).</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-132-oauth2-social-login">13.2 OAuth2 / Social Login</h3>
<p>Social login via OAuth2 lets users authenticate with third-party providers (Google, GitHub, Facebook, and so on) without creating a separate password for your service.</p>
<p>Under the Authorization Code Flow, the user is redirected to the provider’s consent screen. After granting permission, the provider redirects back with a temporary code. The backend exchanges this code for access (and optionally refresh) tokens, fetches the user’s profile, and then you can link or create a local user record. Finally, you typically issue your own JWT (or session) so the client can call your secured APIs.</p>
<p>Keeping OAuth client IDs/secrets in environment variables (via <code>ConfigService</code>) ensures security and flexibility. Here’s how it works:</p>
<ul>
<li><p><strong>OAuth2 Authorization Code Flow</strong>: Redirect the user to the provider’s consent screen. The provider redirects back with a code. The back-end exchanges code for tokens and retrieves user info.</p>
</li>
<li><p>In server-side (NestJS) you use Passport strategies (for example, <code>passport-google-oauth20</code>, <code>passport-github2</code>).</p>
</li>
<li><p>After getting user profile from provider, you look up or create a matching local user record, then issue your own JWT or session.</p>
</li>
<li><p>Keep secrets (client ID/secret) in environment variables and load via <code>ConfigService</code>.</p>
</li>
</ul>
<h4 id="heading-heres-how-to-use-it-4">Here’s how to use it:</h4>
<ol>
<li><p><strong>Install dependencies</strong></p>
<pre><code class="lang-bash"> npm install @nestjs/passport passport passport-google-oauth20
 <span class="hljs-comment"># or passport-facebook, passport-github2, etc.</span>
</code></pre>
</li>
<li><p><strong>Configuration</strong></p>
<p> Add OAuth credentials to env and <code>ConfigModule</code>:</p>
<pre><code class="lang-bash"> GOOGLE_CLIENT_ID=your-google-client-id
 GOOGLE_CLIENT_SECRET=your-google-client-secret
 GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback
</code></pre>
</li>
<li><p><strong>OAuth Strategy</strong></p>
<p> Example: Google</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/google.strategy.ts</span>
 <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { PassportStrategy } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/passport'</span>;
 <span class="hljs-keyword">import</span> { Strategy, VerifyCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">'passport-google-oauth20'</span>;
 <span class="hljs-keyword">import</span> { ConfigService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;
 <span class="hljs-keyword">import</span> { AuthService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth.service'</span>;

 <span class="hljs-meta">@Injectable</span>()
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> GoogleStrategy <span class="hljs-keyword">extends</span> PassportStrategy(Strategy, <span class="hljs-string">'google'</span>) {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params">configService: ConfigService, <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> authService: AuthService</span>) {
     <span class="hljs-built_in">super</span>({
       clientID: configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'GOOGLE_CLIENT_ID'</span>),
       clientSecret: configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'GOOGLE_CLIENT_SECRET'</span>),
       callbackURL: configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'GOOGLE_CALLBACK_URL'</span>),
       scope: [<span class="hljs-string">'email'</span>, <span class="hljs-string">'profile'</span>],
     });
   }

   <span class="hljs-keyword">async</span> validate(accessToken: <span class="hljs-built_in">string</span>, refreshToken: <span class="hljs-built_in">string</span>, profile: <span class="hljs-built_in">any</span>, done: VerifyCallback): <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">any</span>&gt; {
     <span class="hljs-keyword">const</span> { id, emails, displayName } = profile;
     <span class="hljs-keyword">const</span> email = emails &amp;&amp; emails[<span class="hljs-number">0</span>]?.value;
     <span class="hljs-comment">// Delegate to AuthService to find or create local user</span>
     <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.authService.validateOAuthLogin(<span class="hljs-string">'google'</span>, id, email, displayName);
     done(<span class="hljs-literal">null</span>, user);
   }
 }
</code></pre>
<p> In <code>AuthService</code>:</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/auth.service.ts (add method)</span>
 <span class="hljs-keyword">async</span> validateOAuthLogin(provider: <span class="hljs-built_in">string</span>, providerId: <span class="hljs-built_in">string</span>, email: <span class="hljs-built_in">string</span>, name?: <span class="hljs-built_in">string</span>) {
   <span class="hljs-comment">// Find existing user by provider+providerId or email</span>
   <span class="hljs-keyword">let</span> user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.usersService.findByProvider(provider, providerId);
   <span class="hljs-keyword">if</span> (!user) {
     <span class="hljs-comment">// Optionally check by email: if exists, link accounts; otherwise create new</span>
     user = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.usersService.createOAuthUser({ provider, providerId, email, name });
   }
   <span class="hljs-comment">// Issue JWT or return user object; here we return minimal payload for login</span>
   <span class="hljs-keyword">return</span> user;
 }
</code></pre>
</li>
<li><p><strong>AuthController endpoints</strong></p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// src/auth/auth.controller.ts</span>
 <span class="hljs-keyword">import</span> { Controller, Get, Req, UseGuards } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { AuthGuard } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/passport'</span>;
 <span class="hljs-keyword">import</span> { AuthService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./auth.service'</span>;

 <span class="hljs-meta">@Controller</span>(<span class="hljs-string">'auth'</span>)
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AuthController {
   <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> authService: AuthService</span>) {}

   <span class="hljs-meta">@Get</span>(<span class="hljs-string">'google'</span>)
   <span class="hljs-meta">@UseGuards</span>(AuthGuard(<span class="hljs-string">'google'</span>))
   <span class="hljs-keyword">async</span> googleAuth(<span class="hljs-meta">@Req</span>() req) {
     <span class="hljs-comment">// Initiates Google OAuth2 flow</span>
   }

   <span class="hljs-meta">@Get</span>(<span class="hljs-string">'google/callback'</span>)
   <span class="hljs-meta">@UseGuards</span>(AuthGuard(<span class="hljs-string">'google'</span>))
   <span class="hljs-keyword">async</span> googleAuthRedirect(<span class="hljs-meta">@Req</span>() req) {
     <span class="hljs-comment">// Google redirects here after consent; req.user set by GoogleStrategy.validate</span>
     <span class="hljs-keyword">const</span> user = req.user;
     <span class="hljs-comment">// Issue JWT or set a cookie, then redirect or return token</span>
     <span class="hljs-keyword">const</span> jwt = <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.authService.login(user);
     <span class="hljs-comment">// E.g., redirect with token as query, or set cookie:</span>
     <span class="hljs-comment">// res.redirect(`http://frontend-app.com?token=${jwt.access_token}`);</span>
     <span class="hljs-keyword">return</span> { access_token: jwt.access_token };
   }
 }
</code></pre>
<ul>
<li><p>The first endpoint (<code>/auth/google</code>) triggers redirect to Google.</p>
</li>
<li><p>The callback endpoint handles the response, then issues your JWT.</p>
</li>
</ul>
</li>
<li><p><strong>Session vs. Stateless</strong></p>
<ul>
<li><p>Many examples use sessions and <code>@nestjs/passport</code> session support, but for APIs you often skip sessions: Passport still invokes <code>validate</code>, returns user, and you issue JWT immediately.</p>
</li>
<li><p>Ensure you disable sessions in <code>PassportModule</code> registration: <code>PassportModule.register({ session: false })</code>.</p>
</li>
</ul>
</li>
<li><p><strong>Multiple Providers</strong></p>
<ul>
<li><p>Repeat strategy setup for each provider (for example, GitHubStrategy).</p>
</li>
<li><p>In <code>validateOAuthLogin</code>, handle <code>provider</code> parameter to distinguish logic.</p>
</li>
<li><p>You can store in your user entity fields like <code>googleId</code>, <code>githubId</code>, and so on, or a separate table for OAuth accounts.</p>
</li>
</ul>
</li>
<li><p><strong>Protecting routes post-login</strong></p>
<ul>
<li><p>Clients use the issued JWT in <code>Authorization: Bearer &lt;token&gt;</code> to access protected endpoints via <code>JwtAuthGuard</code>.</p>
</li>
<li><p>If you prefer sessions/cookies, configure Nest to use sessions and Passport's session features, but for SPAs or mobile clients JWT is common.</p>
</li>
</ul>
</li>
<li><p><strong>Frontend considerations</strong></p>
<ul>
<li><p>Redirect URIs must match those configured in the OAuth provider console.</p>
</li>
<li><p>After receiving JWT, store it securely (for example, HTTP-only cookie or secure storage on client).</p>
</li>
<li><p>Handle token expiry: possibly combine OAuth refresh tokens or your own refresh token flow.</p>
</li>
</ul>
</li>
</ol>
<p>With JWT and OAuth2 strategies set up, your NestJS backend can support secured endpoints, user registration/login flows, and social logins.</p>
<h2 id="heading-conclusion-amp-further-resources">Conclusion &amp; Further Resources</h2>
<h3 id="heading-summary">Summary</h3>
<p>We’ve walked through key aspects of building a NestJS application: its architectural patterns, core building blocks (modules, controllers, providers), dependency injection, routing and middleware, request lifecycle with pipes, guards, exception filters, interceptors, database integration options (TypeORM, Mongoose, Prisma), configuration management, authentication strategies (JWT, OAuth2), and strategies for migrating existing apps.</p>
<p>NestJS provides a structured, TypeScript-first framework that accelerates development of scalable, maintainable backends. By leveraging its module system and built-in integrations, you get consistency, testability, and clear separation of concerns out of the box.</p>
<p>Whether you choose a relational database via TypeORM, a document store with Mongoose, or Prisma’s type-safe client, you can plug these into Nest’s DI container and configuration module. Authentication flows – both JWT-based and social login – fit naturally into Nest’s Passport integration.</p>
<p>Overall, NestJS is well-suited for APIs, microservices, real-time apps, and enterprise backends where maintainability and developer experience matter.</p>
<h3 id="heading-official-docs-and-community-links">Official Docs and Community Links</h3>
<ul>
<li><p><strong>NestJS Official Documentation</strong>: Comprehensive guide and API reference for all core features.</p>
<ul>
<li>https://docs.nestjs.com</li>
</ul>
</li>
<li><p><strong>GitHub Repository</strong>: Source code, issue tracker, and community contributions.</p>
<ul>
<li><a target="_blank" href="https://github.com/nestjs/nest">https://github.com/nestjs/nest</a></li>
</ul>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create an npm Library ]]>
                </title>
                <description>
                    <![CDATA[ In the world of JavaScript development, npm (Node Package Manager) has become an essential tool for managing dependencies and sharing reusable code. Whether you're building a simple website or a complex web application, npm libraries help streamline ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-an-npm-library/</link>
                <guid isPermaLink="false">67a627bfaf028c3f4ba71a05</guid>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Yarn ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Fri, 07 Feb 2025 15:33:19 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738941301640/7189d889-387d-4bd2-bf5c-2cbcbd17faad.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the world of JavaScript development, <strong>npm</strong> (Node Package Manager) has become an essential tool for managing dependencies and sharing reusable code. Whether you're building a simple website or a complex web application, npm libraries help streamline development by providing pre-built solutions to common problems.</p>
<p>Another popular package manager is <strong>Yarn</strong>, which offers faster and more reliable dependency management while maintaining compatibility with the npm ecosystem.</p>
<p>In this article, we'll explore what npm libraries are, their benefits, and how they enhance the JavaScript and React ecosystem. We'll also go through a practical step-by-step guide on creating, publishing, and using your own npm library in a React project. We’ll also compare npm and Yarn, showing how you can use either of them effectively in your workflow.</p>
<p>By the end of this tutorial, you'll have a clear understanding of how to package and distribute your own code, making it reusable across multiple projects and even available to the wider developer community.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-npm">What is npm?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-npm-works">How npm works</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-role-of-packagejson">The role of the <code>package.json</code> file</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-npm-commands">Key npm Commands</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-why-use-npm-libraries">Why Use npm Libraries?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-code-reuse-and-modularization">Code reuse and modularization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-simplified-dependency-management">Simplified dependency management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-community-driven-ecosystem">Community-driven ecosystem</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-introducing-yarn-an-alternative-to-npm">Introducing Yarn: An Alternative to npm</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-yarn">What is Yarn?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-differences-between-npm-and-yarn">Differences between npm and Yarn</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-yarn-instead-of-npm">When to use Yarn instead of npm</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-your-own-npm-library">How to Create Your Own npm Library</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-setting-up-a-new-package">Setting up a new package</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-writing-modular-and-reusable-code">Writing modular and reusable code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-adding-dependencies-and-peer-dependencies">Adding dependencies and peer dependencies</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-publish-your-library-to-npm">How to Publish Your Library to npm</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-creating-an-npm-account">Creating an npm account</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-configuring-packagejson-for-publishing">Configuring package.json for Publishing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-publishing-the-package">Publishing the package</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-your-npm-library-in-a-react-project">How to Use Your npm Library in a React Project</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-installing-your-package">Installing your package</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-importing-and-using-the-library-in-a-react-component">Importing and using the package in a React component</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-handling-package-updates-and-versioning">Handling package updates and versioning</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-for-npm-and-yarn-libraries">Best Practices for npm and Yarn Libraries</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-write-meaningful-documentation">Write Meaningful Documentation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-follow-semantic-versioning-semver">Follow Semantic Versioning (SemVer)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-keep-dependencies-up-to-date">Keep Dependencies Up to Date</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-write-unit-tests-for-your-library">Write Unit Tests for Your Library</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ensure-cross-platform-compatibility">Ensure Cross-Platform Compatibility</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion &amp; Next Steps</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-recap-of-key-points">Recap of key points</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-resources">Additional resources for npm and Yarn library development</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-encouragement-to-contribute-to-open-source">Encouragement to contribute to open-source</a></p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-what-is-npm"><strong>What is npm?</strong></h2>
<p>npm (Node Package Manager) is the default package manager for JavaScript and Node.js. It allows developers to install, share, and manage libraries or dependencies that make building applications easier and more efficient.</p>
<p>npm provides access to a vast ecosystem of open-source packages hosted on the <strong>npm registry</strong>, making it one of the largest software repositories in the world.</p>
<p>npm comes bundled with <strong>Node.js</strong>, meaning that once you install Node.js, you automatically have access to npm. You can check if npm is installed by running the following command in your terminal:</p>
<pre><code class="lang-python">npm -v
</code></pre>
<p>This command should return the version of npm installed on your system.</p>
<h3 id="heading-how-npm-works"><strong>How npm Works</strong></h3>
<p>npm operates through three key components:</p>
<ol>
<li><p><strong>The npm Registry</strong> – A public repository that hosts open-source JavaScript packages.</p>
</li>
<li><p><strong>The npm CLI (Command Line Interface)</strong> – A tool that allows developers to install, update, and manage packages from the command line.</p>
</li>
<li><p><strong>The package.json File</strong> – A metadata file that keeps track of dependencies, scripts, and project configurations.</p>
</li>
</ol>
<p>When you install a package using npm, it pulls the package from the registry and saves it in the <code>node_modules</code> folder within your project.</p>
<p>For example, to install <strong>Lodash</strong>, a popular utility library, you would run:</p>
<pre><code class="lang-python">npm install lodash
</code></pre>
<p>This will:</p>
<ul>
<li><p>Download the latest version of <code>lodash</code> from the npm registry</p>
</li>
<li><p>Add it to your <code>node_modules</code> folder</p>
</li>
<li><p>Update the <code>package.json</code> and <code>package-lock.json</code> files to reflect the new dependency</p>
</li>
</ul>
<h3 id="heading-the-role-of-packagejson"><strong>The Role of</strong> <code>package.json</code></h3>
<p>The <code>package.json</code> file is the heart of any npm project. It serves as a blueprint, containing information about the project, including:</p>
<ul>
<li><p><strong>Project metadata</strong> (name, version, description)</p>
</li>
<li><p><strong>Dependencies</strong> (external packages required for the project)</p>
</li>
<li><p><strong>Scripts</strong> (commands to automate tasks like starting a server or running tests)</p>
</li>
<li><p><strong>Versioning information</strong> (ensuring compatibility between different versions of dependencies)</p>
</li>
</ul>
<p>A typical <code>package.json</code> file looks like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-awesome-project"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A sample project demonstrating npm usage"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"node index.js"</span>,
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"No tests specified\" &amp;&amp; exit 0"</span>
  },
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"lodash"</span>: <span class="hljs-string">"^4.17.21"</span>
  },
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"eslint"</span>: <span class="hljs-string">"^8.0.0"</span>
  },
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Your Name"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>
}
</code></pre>
<ul>
<li><p><code>dependencies</code> – Lists essential packages required for the application to function.</p>
</li>
<li><p><code>devDependencies</code> – Includes development-only dependencies (for example, testing and linting tools).</p>
</li>
<li><p><code>scripts</code> – Defines CLI commands for automating tasks.</p>
</li>
</ul>
<p>To install all dependencies listed in <code>package.json</code>, simply run:</p>
<pre><code class="lang-python">npm install
</code></pre>
<p>This ensures all required packages are downloaded and ready for use.</p>
<h3 id="heading-key-npm-commands"><strong>Key npm Commands</strong></h3>
<p>Here are some essential npm commands you’ll use frequently:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>npm init -y</code></td><td>Creates a default <code>package.json</code> file</td></tr>
<tr>
<td><code>npm install &lt;package-name&gt;</code></td><td>Installs a package and adds it to <code>dependencies</code></td></tr>
<tr>
<td><code>npm install &lt;package-name&gt; --save-dev</code></td><td>Installs a package and adds it to <code>devDependencies</code></td></tr>
<tr>
<td><code>npm uninstall &lt;package-name&gt;</code></td><td>Removes a package from the project</td></tr>
<tr>
<td><code>npm update</code></td><td>Updates all installed dependencies</td></tr>
<tr>
<td><code>npm outdated</code></td><td>Checks for outdated dependencies</td></tr>
<tr>
<td><code>npm run &lt;script-name&gt;</code></td><td>Runs a script defined in <code>package.json</code></td></tr>
</tbody>
</table>
</div><h2 id="heading-why-use-npm-libraries"><strong>Why Use npm Libraries?</strong></h2>
<p>As modern web development grows in complexity, using npm libraries has become essential for building scalable and maintainable applications. Instead of writing everything from scratch, you can leverage pre-built, tested, and optimized libraries to speed up development and ensure reliability.</p>
<p>In this section, we’ll explore the key advantages of using npm libraries and why they are crucial in JavaScript and React development.</p>
<h3 id="heading-code-reuse-and-modularization"><strong>Code Reuse and Modularization</strong></h3>
<p>One of the biggest benefits of npm libraries is <strong>code reuse</strong>. Instead of repeatedly writing the same functions or utilities in different projects, developers can:</p>
<ul>
<li><p>✅ Use existing open-source packages for common functionalities (for example, date formatting, HTTP requests, UI components).</p>
</li>
<li><p>✅ Create and publish their own reusable libraries to share across multiple projects.</p>
</li>
</ul>
<p>For example, instead of manually implementing a function to format dates, you can install a well-maintained package like date-fns:</p>
<pre><code class="lang-python">npm install date-fns
</code></pre>
<p>Then, you can use it in your project:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { format } <span class="hljs-keyword">from</span> <span class="hljs-string">"date-fns"</span>;

<span class="hljs-keyword">const</span> formattedDate = format(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(), <span class="hljs-string">"yyyy-MM-dd"</span>);
<span class="hljs-built_in">console</span>.log(formattedDate); <span class="hljs-comment">// Outputs: 2024-02-04 (or the current date)</span>
</code></pre>
<p>This modular approach saves time and ensures consistency across projects.</p>
<h3 id="heading-simplified-dependency-management"><strong>Simplified Dependency Management</strong></h3>
<p>npm makes it easy to manage dependencies in a project. Instead of manually downloading and maintaining different versions of external libraries, npm automates this process through the package.json and package-lock.json files.</p>
<p>Some key features include:</p>
<p>🔹 <strong>Automatic installation</strong> – Run <code>npm install</code>, and all dependencies are set up.<br>🔹 <strong>Version control</strong> – Specify package versions to avoid breaking changes.<br>🔹 <strong>Peer dependencies</strong> – Ensure compatibility between different libraries.</p>
<p>For example, here’s how npm helps manage dependency versions in <code>package.json</code>:</p>
<pre><code class="lang-json"><span class="hljs-string">"dependencies"</span>: {
  <span class="hljs-attr">"react"</span>: <span class="hljs-string">"^18.0.0"</span>,
  <span class="hljs-attr">"axios"</span>: <span class="hljs-string">"^1.5.0"</span>
}
</code></pre>
<ul>
<li><p><code>^18.0.0</code> – Allows minor updates but prevents major breaking changes.</p>
</li>
<li><p><code>axios</code> – Ensures HTTP requests are handled consistently across different projects.</p>
</li>
</ul>
<p>To update all dependencies safely, run:</p>
<pre><code class="lang-python">npm update
</code></pre>
<p>This ensures your project is always running on the latest stable versions.</p>
<h3 id="heading-community-driven-ecosystem"><strong>Community-Driven Ecosystem</strong></h3>
<p>npm has an active and growing community, meaning developers around the world contribute and maintain thousands of useful libraries. This results in:</p>
<p>🌎 <strong>Faster development</strong> – No need to reinvent the wheel.<br>🛠️ <strong>Well-tested solutions</strong> – Many libraries are battle-tested in production environments.<br>📚 <strong>Rich documentation</strong> – Most npm packages come with clear usage instructions and examples.</p>
<p>Popular npm libraries include:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Library</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td><strong>React</strong> (<code>react</code>)</td><td>UI library for building web applications</td></tr>
<tr>
<td><strong>Axios</strong> (<code>axios</code>)</td><td>HTTP client for making API requests</td></tr>
<tr>
<td><strong>Lodash</strong> (<code>lodash</code>)</td><td>Utility functions for working with arrays, objects, and strings</td></tr>
<tr>
<td><strong>Express</strong> (<code>express</code>)</td><td>Web framework for building backend services</td></tr>
<tr>
<td><strong>Jest</strong> (<code>jest</code>)</td><td>JavaScript testing framework</td></tr>
</tbody>
</table>
</div><p>For example, using <strong>Axios</strong> to make an API request:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;

axios.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>This replaces the need for writing complex <code>fetch</code> requests with error handling manually.</p>
<h2 id="heading-introducing-yarn-an-alternative-to-npm"><strong>Introducing Yarn: An Alternative to npm</strong></h2>
<p>While <strong>npm</strong> is the default package manager for Node.js, another powerful alternative exists: <strong>Yarn</strong>. Developed by Facebook in 2016, Yarn was created to improve speed, security, and reliability in dependency management.</p>
<p>In this section, we’ll explore what Yarn is, how it differs from npm, and when you might prefer using Yarn over npm.</p>
<h3 id="heading-what-is-yarn"><strong>What is Yarn?</strong></h3>
<p>Yarn (<strong>Yet Another Resource Negotiator</strong>) is a package manager that works similarly to npm but with a focus on performance, security, and consistency. It offers:</p>
<p>🚀 <strong>Faster dependency installation</strong> thanks to parallel downloads<br>🔐 <strong>More secure package management</strong> using checksum verification<br>📦 <strong>Reliable dependency resolution</strong> with an offline cache</p>
<p>To check if you have Yarn installed, run:</p>
<pre><code class="lang-python">yarn -v
</code></pre>
<p>If you don’t have it yet, you can install it globally using npm:</p>
<pre><code class="lang-python">npm install --<span class="hljs-keyword">global</span> yarn
</code></pre>
<p>Once installed, you can use it just like npm to manage dependencies.</p>
<h3 id="heading-differences-between-npm-and-yarn"><strong>Differences Between npm and Yarn</strong></h3>
<p>Although npm and Yarn serve the same purpose, they have some key differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>npm</td><td>Yarn</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Speed</strong></td><td>Installs packages one at a time</td><td>Installs multiple packages in parallel (faster)</td></tr>
<tr>
<td><strong>Lock File</strong></td><td><code>package-lock.json</code></td><td><code>yarn.lock</code></td></tr>
<tr>
<td><strong>Offline Cache</strong></td><td>Not available (by default)</td><td>Can install packages from local cache</td></tr>
<tr>
<td><strong>Security</strong></td><td>Verifies package integrity but lacks checksum enforcement</td><td>Uses checksum verification for security</td></tr>
<tr>
<td><strong>Monorepo Support</strong></td><td>Supports workspaces but not optimized</td><td>Built-in support for monorepos with <code>workspaces</code></td></tr>
</tbody>
</table>
</div><h4 id="heading-performance-comparison"><strong>Performance Comparison</strong></h4>
<p>When installing dependencies, Yarn is often faster because it downloads packages in parallel, while npm installs them sequentially.</p>
<p>For example, to install all dependencies in a project:</p>
<pre><code class="lang-python"><span class="hljs-comment"># With npm</span>
npm install

<span class="hljs-comment"># With Yarn</span>
yarn install
</code></pre>
<p>Yarn can also install packages from a local cache, meaning it doesn't always need to fetch dependencies from the internet.</p>
<h4 id="heading-common-yarn-commands-vs-npm"><strong>Common Yarn Commands vs. npm</strong></h4>
<p>Many npm commands have an equivalent in Yarn:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Action</td><td>npm Command</td><td>Yarn Command</td></tr>
</thead>
<tbody>
<tr>
<td>Initialize a new project</td><td><code>npm init</code></td><td><code>yarn init</code></td></tr>
<tr>
<td>Install all dependencies</td><td><code>npm install</code></td><td><code>yarn install</code></td></tr>
<tr>
<td>Install a package</td><td><code>npm install package-name</code></td><td><code>yarn add package-name</code></td></tr>
<tr>
<td>Install a dev dependency</td><td><code>npm install package-name --save-dev</code></td><td><code>yarn add package-name --dev</code></td></tr>
<tr>
<td>Remove a package</td><td><code>npm uninstall package-name</code></td><td><code>yarn remove package-name</code></td></tr>
<tr>
<td>Update all packages</td><td><code>npm update</code></td><td><code>yarn upgrade</code></td></tr>
<tr>
<td>Run a script</td><td><code>npm run script-name</code></td><td><code>yarn script-name</code></td></tr>
</tbody>
</table>
</div><p>For example, installing <code>axios</code> using Yarn:</p>
<pre><code class="lang-python">yarn add axios
</code></pre>
<h3 id="heading-when-to-use-yarn-instead-of-npm"><strong>When to Use Yarn Instead of npm</strong></h3>
<p>Yarn is a great choice when:</p>
<ul>
<li><p><strong>You want faster installations</strong> – Yarn installs multiple packages in parallel, making it faster than npm.</p>
</li>
<li><p><strong>You need better dependency consistency</strong> – The <code>yarn.lock</code> file ensures that all developers use the same dependency versions.</p>
</li>
<li><p><strong>You're working with monorepos</strong> – Yarn’s built-in <strong>workspaces</strong> make it easier to manage multiple projects within the same repository.</p>
</li>
<li><p><strong>You want improved security</strong> – Yarn’s checksum verification prevents corrupted packages from being installed.</p>
</li>
</ul>
<p>Still, npm has improved significantly in recent years, especially with npm v7+, making it a viable choice for most projects.</p>
<h4 id="heading-switching-between-npm-and-yarn"><strong>Switching Between npm and Yarn</strong></h4>
<p>If your project was originally set up using npm but you want to switch to Yarn, you can:</p>
<p>1️⃣ <strong>Delete</strong> <code>node_modules</code> and <code>package-lock.json</code></p>
<pre><code class="lang-python">rm -rf node_modules package-lock.json
</code></pre>
<p>2️⃣ <strong>Run Yarn to install dependencies</strong></p>
<pre><code class="lang-python">yarn install
</code></pre>
<p>This will generate a yarn.lock file, ensuring all dependencies are managed by Yarn moving forward.</p>
<p>Both npm and Yarn are powerful tools for package management. Choosing between them depends on your project’s needs:</p>
<p>✔️ Use <strong>npm</strong> if you want the default, widely used package manager that works well with most projects.<br>✔️ Use <strong>Yarn</strong> if you need faster installs, better security, and monorepo support.</p>
<p>Ultimately, both tools allow you to <strong>install, manage, and publish</strong> JavaScript packages efficiently.</p>
<h2 id="heading-how-to-create-your-own-npm-library"><strong>How to Create Your Own npm Library</strong></h2>
<p>Creating your own npm library is a great way to <strong>share reusable code</strong>, contribute to the open-source community, or even streamline development across multiple projects. In this section, we’ll walk through the step-by-step process of setting up, coding, and preparing a library for publishing on npm.</p>
<h3 id="heading-setting-up-a-new-package"><strong>Setting Up a New Package</strong></h3>
<p>Before writing code, you need to set up an npm package. Follow these steps:</p>
<h4 id="heading-step-1-create-a-new-project-folder"><strong>Step 1: Create a New Project Folder</strong></h4>
<pre><code class="lang-python">mkdir my-awesome-library
cd my-awesome-library
</code></pre>
<h4 id="heading-step-2-initialize-npm"><strong>Step 2: Initialize npm</strong></h4>
<p>Run the following command to create a <code>package.json</code> file:</p>
<pre><code class="lang-python">npm init
</code></pre>
<p>You will be prompted to enter details such as:</p>
<ul>
<li><p>Package name</p>
</li>
<li><p>Version</p>
</li>
<li><p>Description</p>
</li>
<li><p>Entry point (default: <code>index.js</code>)</p>
</li>
<li><p>Author</p>
</li>
<li><p>License</p>
</li>
</ul>
<p>💡 To skip the prompts and create a default <code>package.json</code>, use:</p>
<pre><code class="lang-python">npm init -y
</code></pre>
<h3 id="heading-writing-modular-and-reusable-code"><strong>Writing Modular and Reusable Code</strong></h3>
<p>Now, let’s create a simple utility library that provides a function to format dates.</p>
<h4 id="heading-step-3-create-an-indexjs-file"><strong>Step 3: Create an</strong> <code>index.js</code> File</h4>
<p>Inside the project folder, create a file named <code>index.js</code> and add the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatDate</span>(<span class="hljs-params">date</span>) </span>{
  <span class="hljs-keyword">if</span> (!(date <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Date</span>)) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Invalid date"</span>);
  }
  <span class="hljs-keyword">return</span> date.toISOString().split(<span class="hljs-string">"T"</span>)[<span class="hljs-number">0</span>];
}

<span class="hljs-built_in">module</span>.exports = { formatDate };
</code></pre>
<h3 id="heading-adding-dependencies-and-peer-dependencies"><strong>Adding Dependencies and Peer Dependencies</strong></h3>
<p>Your library might depend on external packages. For example, let’s use date-fns for better date formatting.</p>
<p>To install it as a dependency, run:</p>
<pre><code class="lang-python">npm install date-fns
</code></pre>
<p>Then, modify <code>index.js</code> to use <code>date-fns</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { format } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"date-fns"</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatDate</span>(<span class="hljs-params">date</span>) </span>{
  <span class="hljs-keyword">if</span> (!(date <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Date</span>)) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Invalid date"</span>);
  }
  <span class="hljs-keyword">return</span> format(date, <span class="hljs-string">"yyyy-MM-dd"</span>);
}

<span class="hljs-built_in">module</span>.exports = { formatDate };
</code></pre>
<p>If you're creating a React-specific library, you should add React as a peer dependency:</p>
<pre><code class="lang-python">npm install react --save-peer
</code></pre>
<p>This ensures users of your library install React separately, preventing version conflicts.</p>
<p>Before publishing, you should test how your package works when installed as a dependency.</p>
<h4 id="heading-step-4-link-the-package-locally"><strong>Step 4: Link the Package Locally</strong></h4>
<p>Run the following command in your package folder:</p>
<pre><code class="lang-python">npm link
</code></pre>
<p>Then, in another project where you want to use your package, navigate to that project and run:</p>
<pre><code class="lang-python">npm link my-awesome-library
</code></pre>
<p>Now, you can import and use your function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { formatDate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"my-awesome-library"</span>);

<span class="hljs-built_in">console</span>.log(formatDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>())); <span class="hljs-comment">// Output: 2025-02-04 (or the current date)</span>
</code></pre>
<p>Once you're happy with your package, it's time to <strong>publish it on npm</strong>.</p>
<h2 id="heading-how-to-publish-your-library-to-npm"><strong>How to Publish Your Library to npm</strong></h2>
<p>Now that we’ve created our npm package, the next step is <strong>publishing it to the npm registry</strong> so others can install and use it. In this section, we’ll cover how to publish the package step by step.</p>
<h3 id="heading-creating-an-npm-account"><strong>Creating an npm Account</strong></h3>
<p>Before publishing, you need an npm account.</p>
<h4 id="heading-step-1-sign-up-for-npm"><strong>Step 1: Sign Up for npm</strong></h4>
<ol>
<li><p>Go to <a target="_blank" href="https://www.npmjs.com/signup">https://www.npmjs.com/signup</a> and create an account.</p>
</li>
<li><p>Verify your email address.</p>
</li>
</ol>
<h4 id="heading-step-2-log-in-to-npm-from-the-terminal"><strong>Step 2: Log in to npm from the Terminal</strong></h4>
<p>Run the following command in your terminal:</p>
<pre><code class="lang-python">npm login
</code></pre>
<p>You will be prompted to enter:</p>
<ul>
<li><p>Your npm username</p>
</li>
<li><p>Your password</p>
</li>
<li><p>Your email (associated with your npm account)</p>
</li>
</ul>
<p>If the login is successful, you’ll see a message:</p>
<pre><code class="lang-python">Logged <span class="hljs-keyword">in</span> <span class="hljs-keyword">as</span> your-username on https://registry.npmjs.org/
</code></pre>
<h3 id="heading-configuring-packagejson-for-publishing"><strong>Configuring package.json for Publishing</strong></h3>
<h4 id="heading-step-3-ensure-your-package-name-is-unique"><strong>Step 3: Ensure Your Package Name is Unique</strong></h4>
<p>Every npm package needs a unique name. Run the following command to check if your desired name is available:</p>
<pre><code class="lang-python">npm search my-awesome-library
</code></pre>
<p>If the name is already taken, you’ll need to modify <code>package.json</code> and change the <code>"name"</code> field.</p>
<h4 id="heading-step-4-add-metadata-and-keywords"><strong>Step 4: Add Metadata and Keywords</strong></h4>
<p>Open <code>package.json</code> and ensure it includes useful metadata:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-awesome-library"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A simple npm package for formatting dates"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"repository"</span>: {
    <span class="hljs-attr">"type"</span>: <span class="hljs-string">"git"</span>,
    <span class="hljs-attr">"url"</span>: <span class="hljs-string">"https://github.com/yourusername/my-awesome-library.git"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [<span class="hljs-string">"date"</span>, <span class="hljs-string">"formatter"</span>, <span class="hljs-string">"utility"</span>, <span class="hljs-string">"npm package"</span>],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Your Name &lt;your-email@example.com&gt;"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>
}
</code></pre>
<p>🔹 <strong>repository</strong> – Useful if you plan to host the project on GitHub.<br>🔹 <strong>keywords</strong> – Helps people discover your package on npm.<br>🔹 <strong>license</strong> – Specifies how others can use your package (for example, MIT, GPL, and so on).</p>
<h3 id="heading-publishing-the-package"><strong>Publishing the Package</strong></h3>
<h4 id="heading-step-5-publish-your-package-to-npm"><strong>Step 5: Publish Your Package to npm</strong></h4>
<p>Run the following command inside your project folder:</p>
<pre><code class="lang-python">npm publish
</code></pre>
<p>If successful, you’ll see output similar to:</p>
<pre><code class="lang-python">+ my-awesome-library@<span class="hljs-number">1.0</span><span class="hljs-number">.0</span>
</code></pre>
<p>Your package is now available at:</p>
<p>📌 <a target="_blank" href="https://www.npmjs.com/package/my-awesome-library"><strong>https://www.npmjs.com/package/my-awesome-library</strong></a></p>
<h4 id="heading-step-6-making-changes-and-updating-the-package"><strong>Step 6: Making Changes and Updating the Package</strong></h4>
<p>If you want to release a new version, update the <code>version</code> field in <code>package.json</code>. npm follows Semantic Versioning (SemVer):</p>
<ul>
<li><p><strong>Patch:</strong> Bug fixes (1.0.0 → 1.0.1)</p>
</li>
<li><p><strong>Minor:</strong> New features, backward-compatible (1.0.0 → 1.1.0)</p>
</li>
<li><p><strong>Major:</strong> Breaking changes (1.0.0 → 2.0.0)</p>
</li>
</ul>
<p>Instead of manually updating <code>package.json</code>, use:</p>
<pre><code class="lang-python">npm version patch   <span class="hljs-comment"># 1.0.0 → 1.0.1</span>
npm version minor   <span class="hljs-comment"># 1.0.0 → 1.1.0</span>
npm version major   <span class="hljs-comment"># 1.0.0 → 2.0.0</span>
</code></pre>
<p>Then, publish the new version:</p>
<pre><code class="lang-python">npm publish
</code></pre>
<p>If you accidentally publish a package and need to remove it:</p>
<pre><code class="lang-python">npm unpublish my-awesome-library --force
</code></pre>
<p>⚠️ <strong>Note:</strong> You can only unpublish packages <strong>within 72 hours</strong> of publishing.</p>
<p>🎯 <strong>You’ve successfully published your own npm library!</strong> Now, other developers can install it using:</p>
<pre><code class="lang-python">npm install my-awesome-library
</code></pre>
<p>By following Semantic Versioning, writing clear documentation, and maintaining your package, you contribute to the open-source ecosystem and make your code reusable.</p>
<h2 id="heading-how-to-use-your-npm-library-in-a-react-project"><strong>How to Use Your npm Library in a React Project</strong></h2>
<p>Now that we’ve published our npm package, let’s see how to install, import, and use it inside a React project created with <strong>Vite</strong>. This section will guide you through the process using both npm and Yarn.</p>
<h3 id="heading-installing-your-package"><strong>Installing Your Package</strong></h3>
<h4 id="heading-step-1-create-a-new-react-project-with-vite-if-needed"><strong>Step 1: Create a New React Project with Vite (if needed)</strong></h4>
<p>If you don’t have an existing React project, create one using Vite:</p>
<h4 id="heading-using-npm"><strong>Using npm</strong></h4>
<pre><code class="lang-python">npm create vite@latest my-react-app --template react
cd my-react-app
npm install
</code></pre>
<h4 id="heading-using-yarn"><strong>Using Yarn</strong></h4>
<pre><code class="lang-python">yarn create vite@latest my-react-app --template react
cd my-react-app
yarn install
</code></pre>
<p>Once the installation is complete, you can start the development server:</p>
<pre><code class="lang-python">npm run dev
</code></pre>
<p>or</p>
<pre><code class="lang-python">yarn dev
</code></pre>
<h4 id="heading-step-2-install-your-npm-package"><strong>Step 2: Install Your npm Package</strong></h4>
<p>Now, install the npm library we created earlier (<code>my-awesome-library</code>).</p>
<h4 id="heading-using-npm-1"><strong>Using npm</strong></h4>
<pre><code class="lang-python">npm install my-awesome-library
</code></pre>
<h4 id="heading-using-yarn-1"><strong>Using Yarn</strong></h4>
<pre><code class="lang-python">yarn add my-awesome-library
</code></pre>
<h3 id="heading-importing-and-using-the-library-in-a-react-component"><strong>Importing and Using the Library in a React Component</strong></h3>
<p>Once installed, you can use the library inside a React component.</p>
<p>Open <code>src/App.jsx</code> and modify it as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { formatDate } <span class="hljs-keyword">from</span> <span class="hljs-string">"my-awesome-library"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> today = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Formatted Date<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{formatDate(today)}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Now, run your Vite React app:</p>
<pre><code class="lang-python">npm run dev
</code></pre>
<p>Or with Yarn:</p>
<pre><code class="lang-python">yarn dev
</code></pre>
<p>This will display a formatted date on the webpage, confirming that our library is working!</p>
<h3 id="heading-handling-package-updates-and-versioning"><strong>Handling Package Updates and Versioning</strong></h3>
<p>To update your npm package in your project:</p>
<h4 id="heading-using-npm-2"><strong>Using npm</strong></h4>
<pre><code class="lang-python">npm update my-awesome-library
</code></pre>
<h4 id="heading-using-yarn-2"><strong>Using Yarn</strong></h4>
<pre><code class="lang-python">yarn upgrade my-awesome-library
</code></pre>
<p>If you want to check outdated dependencies:</p>
<pre><code class="lang-python">npm outdated
</code></pre>
<p>or</p>
<pre><code class="lang-python">yarn outdated
</code></pre>
<h3 id="heading-using-a-local-version-of-your-package-in-development"><strong>Using a Local Version of Your Package in Development</strong></h3>
<p>If you’re still making changes to your npm package and want to test it in your React project <strong>before publishing</strong>, you can use <code>npm link</code> or <code>yarn link</code>.</p>
<h4 id="heading-step-1-link-your-package-locally"><strong>Step 1: Link Your Package Locally</strong></h4>
<p>Go to your package’s project folder:</p>
<pre><code class="lang-python">cd ~/path-to-my-awesome-library
npm link
</code></pre>
<p>or</p>
<pre><code class="lang-python">yarn link
</code></pre>
<h4 id="heading-step-2-use-it-in-your-react-project"><strong>Step 2: Use It in Your React Project</strong></h4>
<p>Navigate to your React app and link the package:</p>
<pre><code class="lang-python">cd ~/path-to-my-react-app
npm link my-awesome-library
</code></pre>
<p>or</p>
<pre><code class="lang-python">yarn link my-awesome-library
</code></pre>
<p>Now, when you import and use <code>my-awesome-library</code>, it will use the local version instead of the published one.</p>
<h3 id="heading-publishing-an-update-to-your-package"><strong>Publishing an Update to Your Package</strong></h3>
<p>If you’ve made changes to your package and want to publish a new version:</p>
<p>1️⃣ <strong>Update the version number</strong> in <code>package.json</code> (use <code>npm version patch</code> for small updates).<br>2️⃣ <strong>Run</strong> <code>npm publish</code> to upload the new version.<br>3️⃣ <strong>Run</strong> <code>npm update my-awesome-library</code> in your React project to get the latest version.</p>
<h3 id="heading-final-thoughts-on-using-npm-libraries-in-react-vite-edition"><strong>Final Thoughts on Using npm Libraries in React (Vite Edition)</strong></h3>
<p>By now, you should have a fully functional npm package and know how to install, use, and update it in a React project using Vite.</p>
<p>✔️ Vite is faster than Create React App and provides better performance for development.<br>✔️ npm and Yarn make dependency management easy.<br>✔️ <code>npm link</code> allows local testing before publishing.<br>✔️ Keeping dependencies updated ensures stability.</p>
<p>This workflow is essential for developers looking to create, maintain, and distribute reusable React components or JavaScript utilities.</p>
<h2 id="heading-best-practices-for-npm-and-yarn-libraries"><strong>Best Practices for npm and Yarn Libraries</strong></h2>
<p>Now that you've created, published, and used your own npm package, it's essential to follow best practices to ensure your package is reliable, maintainable, and easy to use. This section will cover key principles and techniques to make your npm library as professional as possible.</p>
<h3 id="heading-write-meaningful-documentation"><strong>Write Meaningful Documentation</strong></h3>
<p>A well-documented library helps other developers understand how to use it effectively.</p>
<h4 id="heading-what-to-include-in-your-documentation"><strong>What to Include in Your Documentation</strong></h4>
<p>📌 Installation instructions<br>📌 Usage examples<br>📌 API reference (functions, parameters, return values)<br>📌 Versioning and update history<br>📌 Contributions guide (if open-source)</p>
<p>For example, a simple <a target="_blank" href="http://README.md"><code>README.md</code></a> file for my-awesome-library:</p>
<pre><code class="lang-python"><span class="hljs-comment"># my-awesome-library</span>

A simple npm package <span class="hljs-keyword">for</span> formatting dates.

<span class="hljs-comment">## Installation</span>

<span class="hljs-comment">### Using npm</span>
```sh
npm install my-awesome-library
</code></pre>
<h4 id="heading-using-yarn-3">Using Yarn</h4>
<pre><code class="lang-python">yarn add my-awesome-library
</code></pre>
<h4 id="heading-usage">Usage</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { formatDate } <span class="hljs-keyword">from</span> <span class="hljs-string">"my-awesome-library"</span>;

<span class="hljs-built_in">console</span>.log(formatDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>())); <span class="hljs-comment">// Outputs: 2025-02-04</span>
</code></pre>
<h3 id="heading-follow-semantic-versioning-semver"><strong>Follow Semantic Versioning (SemVer)</strong></h3>
<p>Versioning helps maintain compatibility and informs users of changes. npm follows Semantic Versioning (SemVer):</p>
<p>MAJOR.MINOR.PATCH</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Change Type</td><td>Example</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Patch</strong></td><td><code>1.0.0 → 1.0.1</code></td><td>Bug fixes, no breaking changes</td></tr>
<tr>
<td><strong>Minor</strong></td><td><code>1.0.0 → 1.1.0</code></td><td>New features, no breaking changes</td></tr>
<tr>
<td><strong>Major</strong></td><td><code>1.0.0 → 2.0.0</code></td><td>Breaking changes</td></tr>
</tbody>
</table>
</div><p>💡 To bump versions automatically, use:</p>
<pre><code class="lang-javascript"><span class="hljs-string">``</span><span class="hljs-string">`sh
npm version patch   # Small bug fix
npm version minor   # New feature added
npm version major   # Breaking changes</span>
</code></pre>
<p>Then, publish the new version:</p>
<pre><code class="lang-javascript">npm publish
</code></pre>
<p>👉 Use proper versioning to prevent breaking projects that depend on your library.</p>
<h3 id="heading-keep-dependencies-up-to-date"><strong>Keep Dependencies Up to Date</strong></h3>
<p>Regularly updating dependencies improves security, performance, and compatibility.</p>
<h4 id="heading-check-for-outdated-dependencies"><strong>Check for outdated dependencies:</strong></h4>
<pre><code class="lang-javascript">npm outdated
</code></pre>
<p>or</p>
<pre><code class="lang-javascript">yarn outdated
</code></pre>
<h4 id="heading-update-dependencies"><strong>Update dependencies:</strong></h4>
<pre><code class="lang-javascript">npm update
</code></pre>
<p>or</p>
<pre><code class="lang-javascript">yarn upgrade
</code></pre>
<h3 id="heading-write-unit-tests-for-your-library"><strong>Write Unit Tests for Your Library</strong></h3>
<p>Testing ensures your package works correctly before publishing updates.</p>
<h4 id="heading-install-a-testing-framework-jest"><strong>Install a Testing Framework (Jest)</strong></h4>
<pre><code class="lang-javascript">npm install --save-dev jest
</code></pre>
<h4 id="heading-create-a-test-file-indextestjs"><strong>Create a Test File (</strong><code>index.test.js</code>)</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { formatDate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./index"</span>);

test(<span class="hljs-string">"formats a date correctly"</span>, <span class="hljs-function">() =&gt;</span> {
  expect(formatDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">"2025-02-04"</span>))).toBe(<span class="hljs-string">"2025-02-04"</span>);
});

test(<span class="hljs-string">"throws an error if input is not a date"</span>, <span class="hljs-function">() =&gt;</span> {
  expect(<span class="hljs-function">() =&gt;</span> formatDate(<span class="hljs-string">"not a date"</span>)).toThrow(<span class="hljs-string">"Invalid date"</span>);
});
</code></pre>
<h4 id="heading-run-tests"><strong>Run Tests</strong></h4>
<pre><code class="lang-javascript">shCopyEditnpm test
</code></pre>
<p>👉 You can use CI/CD (for example, GitHub Actions) to run tests automatically on every push.</p>
<h3 id="heading-using-cicd-for-automated-publishing"><strong>Using CI/CD for Automated Publishing</strong></h3>
<h4 id="heading-automate-publishing-with-github-actions"><strong>Automate Publishing with GitHub Actions</strong></h4>
<p>Create a <code>.github/workflows/publish.yml</code> file:</p>
<pre><code class="lang-javascript">ymlCopyEditname: Publish to npm
<span class="hljs-attr">on</span>:
  push:
    branches:
      - main

<span class="hljs-attr">jobs</span>:
  publish:
    runs-on: ubuntu-latest
    <span class="hljs-attr">steps</span>:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        <span class="hljs-attr">with</span>:
          node-version: <span class="hljs-number">18</span>
          registry-url: <span class="hljs-string">"https://registry.npmjs.org/"</span>
      - run: npm install
      - run: npm test
      - run: npm publish
        <span class="hljs-attr">env</span>:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
</code></pre>
<p>1️⃣ <strong>Create an npm token</strong>:<br>Run:</p>
<pre><code class="lang-javascript">shCopyEditnpm token create
</code></pre>
<p>Copy the token and add it to GitHub Secrets (<code>NPM_TOKEN</code>).</p>
<p>2️⃣ <strong>Push code to GitHub</strong> → Auto-publish on npm!</p>
<p>👉 Automating publishing prevents human errors and ensures quality control.</p>
<h3 id="heading-ensure-cross-platform-compatibility"><strong>Ensure Cross-Platform Compatibility</strong></h3>
<ul>
<li><p>Use <strong>ES modules (</strong><code>import/export</code>) for modern compatibility.</p>
</li>
<li><p>Include <strong>CommonJS (</strong><code>require/module.exports</code>) support for older environments.</p>
</li>
<li><p>Test with different <strong>Node.js versions</strong> using CI/CD.</p>
</li>
</ul>
<p>Example <code>package.json</code> for dual compatibility:</p>
<pre><code class="lang-javascript">jsonCopyEdit<span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span>,
<span class="hljs-string">"main"</span>: <span class="hljs-string">"index.cjs"</span>,
<span class="hljs-string">"exports"</span>: {
  <span class="hljs-string">"import"</span>: <span class="hljs-string">"./index.mjs"</span>,
  <span class="hljs-string">"require"</span>: <span class="hljs-string">"./index.cjs"</span>
}
</code></pre>
<p>👉 This ensures your package works everywhere (Node.js, React, Next.js, and so on).</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Congratulations! 🎉 You’ve successfully learned how to create, publish, and use your own npm package, while also understanding the benefits of both <strong>npm</strong> and <strong>Yarn</strong> for package management.</p>
<p>Throughout this guide, we covered:</p>
<p>✔️ What npm is and why it’s important<br>✔️ How to use npm and Yarn to manage dependencies<br>✔️ How to create a reusable npm package<br>✔️ How to publish and update your package on npm<br>✔️ How to integrate your package into a React project with Vite<br>✔️ Best practices for writing, testing, and maintaining your library</p>
<p>By following these steps, you've taken an important step toward open-source development and modular programming, making your code reusable for both yourself and the developer community.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Learn Python for JavaScript Developers [Full Handbook] ]]>
                </title>
                <description>
                    <![CDATA[ As a developer with experience in JavaScript, you likely know how versatile the language is, especially when it comes to web development. JavaScript powers both frontend and backend development (thanks to Node.js) and has grown to become one of the m... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-python-for-javascript-developers-handbook/</link>
                <guid isPermaLink="false">67409b36d94f5ae0c0e97650</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Fri, 22 Nov 2024 14:54:46 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732278833514/c23ea6ad-25b9-45c9-a7a7-c32499ca1d8b.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As a developer with experience in JavaScript, you likely know how versatile the language is, especially when it comes to web development. JavaScript powers both frontend and backend development (thanks to Node.js) and has grown to become one of the most widely used programming languages.</p>
<p>But while JavaScript is powerful, there are other languages that shine in specific areas where JavaScript may not be the most efficient choice. One of those languages is Python.</p>
<p>This handbook aims to introduce Python to experienced JavaScript developers, not merely as an alternative but as a complementary tool that can broaden your development capabilities.</p>
<p>Python is renowned for its simplicity, readability, and extensive libraries, which make it particularly useful in domains like data science, machine learning, automation, and backend development. By understanding Python’s core features and how they compare to JavaScript, you can leverage the strengths of both languages, choosing the right tool for each task.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-1-brief-overview-of-javascript-and-python">Brief Overview of JavaScript and Python</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-language-paradigms-and-use-cases">Language Paradigms and Use Cases</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-syntax-and-language-features">Syntax and Language Features</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-data-structures-and-collections">Data Structures and Collections</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-functions-and-scope">Functions and Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-object-oriented-programming-oop">Object-Oriented Programming (OOP)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-asynchronous-programming">Asynchronous Programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-modules-packages-and-dependency-management">Modules, Packages, and Dependency Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-error-handling-and-debugging">Error Handling and Debugging</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-testing-and-frameworks">Testing and Frameworks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-11-practical-applications-and-examples">Practical Applications and Examples</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-12-community-libraries-and-ecosystem">Community, Libraries, and Ecosystem</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-13-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-1-brief-overview-of-javascript-and-python">1. Brief Overview of JavaScript and Python</h2>
<p>Before diving into the details, let’s take a high-level look at the origins and purposes of both languages.</p>
<p><strong>JavaScript</strong> was initially created as a scripting language for web browsers, designed to make web pages interactive. Over the years, JavaScript has evolved significantly and is now used on the server side (thanks to Node.js) and in a variety of application environments beyond the browser.</p>
<p>JavaScript is event-driven, and it’s often praised for its versatility and asynchronous capabilities, which are essential for building modern, responsive web applications.</p>
<p><strong>Python</strong>, on the other hand, was developed with a focus on simplicity and readability. Created in the late 1980s and gaining popularity in the early 2000s, Python is known for its clear and concise syntax that emphasizes readability. It is widely used in scientific research, data analysis, machine learning, and web development.</p>
<p>Python’s extensive standard library and vibrant ecosystem of third-party libraries make it highly productive for developers working in various fields, from scripting to full-scale application development.</p>
<p>While both languages are high-level and dynamically typed, they cater to different paradigms and have distinct strengths. For example, Python is often seen as more beginner-friendly due to its readable syntax, while JavaScript is more commonly encountered in the web development ecosystem.</p>
<h3 id="heading-why-javascript-developers-should-learn-python">Why JavaScript Developers Should Learn Python</h3>
<p>As a JavaScript developer, learning Python can significantly enhance your versatility and open up new opportunities. Here are some reasons why learning Python might be a worthwhile addition to your skill set:</p>
<ol>
<li><p><strong>Expanded Career Opportunities</strong><br> While JavaScript jobs are abundant, Python’s rise in popularity has created many roles in fields like data science, artificial intelligence, machine learning, and DevOps. By adding Python to your skillset, you can tap into these growing job markets.</p>
</li>
<li><p><strong>Enhanced Development Speed and Readability</strong><br> Python’s syntax is famously concise and readable. Python code often resembles pseudocode, which makes it not only faster to write but also easier to understand and maintain. This can be a significant advantage when building prototypes or handling complex algorithms, as you’ll see more of your time spent on problem-solving rather than syntax management.</p>
</li>
<li><p><strong>Versatile Applications</strong><br> While JavaScript dominates web development, Python is widely used in fields like automation, web scraping, and scientific computing. For example, if you’re looking to automate repetitive tasks, Python provides a straightforward approach with powerful libraries like <code>os</code>, <code>shutil</code>, and <code>sys</code> for system operations. In web scraping, libraries like <code>BeautifulSoup</code> and <code>Scrapy</code> make data extraction a breeze.</p>
</li>
<li><p><strong>Rich Ecosystem for Data Science and Machine Learning</strong><br> If you’re interested in working with data, machine learning, or AI, Python is the language to know. Python’s ecosystem for data science includes libraries such as <code>Pandas</code>, <code>NumPy</code>, and <code>Matplotlib</code>, which enable sophisticated data manipulation and visualization with relatively little code. Machine learning frameworks like <code>TensorFlow</code>, <code>Keras</code>, and <code>PyTorch</code> also have deep Python integration, making Python a top choice for data-intensive applications.</p>
</li>
<li><p><strong>Better Interoperability in Multilingual Projects</strong><br> Many large projects utilize multiple languages, selecting the best language for each part of the system. JavaScript and Python can work well together, with Python handling backend processes, data analysis, or automation, while JavaScript powers the user interface. Understanding both languages allows you to contribute across the stack and enhances your ability to collaborate on diverse codebases.</p>
</li>
<li><p><strong>Increasing Role in Web Development</strong><br> Though JavaScript is still the primary language for frontend development, Python is becoming more prominent in backend web development through frameworks like <code>Django</code> and <code>Flask</code>. These frameworks make it easy to build scalable and secure web applications, and Python’s ease of use can lead to faster development cycles.</p>
</li>
</ol>
<p>By learning Python, JavaScript developers can enjoy a more complete toolkit that covers everything from frontend to backend development, data science, and beyond. As you progress through this article, we’ll explore how Python’s features and syntax compare to JavaScript, providing you with a strong foundation to get started with Python.</p>
<h2 id="heading-2-language-paradigms-and-use-cases">2. <strong>Language Paradigms and Use Cases</strong></h2>
<h3 id="heading-javascript-vs-python-scripting-backend-and-full-stack">JavaScript vs. Python: Scripting, Backend, and Full-Stack</h3>
<p>Both JavaScript and Python are high-level, interpreted languages, but they were initially created with distinct purposes in mind. Over the years, they have evolved to expand their applications, making them popular choices for both general-purpose and specialized development tasks.</p>
<p>Understanding these differences in paradigms and common use cases helps clarify when to use each language and the kind of projects they are best suited for.</p>
<h4 id="heading-javascript"><strong>JavaScript</strong></h4>
<p>Known primarily as the language of the web, JavaScript was originally designed to add interactivity to HTML documents within browsers. Today, with the advent of frameworks like React, Angular, and Vue, JavaScript is at the core of modern, interactive frontend web development.</p>
<p>The language’s reach expanded even further with Node.js, which brought JavaScript to the server side. Now, JavaScript is a full-stack language that powers single-page applications (SPAs), RESTful APIs, and server-side rendering.</p>
<p>JavaScript is event-driven and asynchronous by design, making it ideal for real-time applications such as chat apps, collaborative tools, and streaming services.</p>
<h4 id="heading-python"><strong>Python</strong></h4>
<p>Initially created with a focus on readability and simplicity, Python has become one of the most versatile languages in the world. While JavaScript is often tied to web applications, Python is more commonly used in fields like scientific computing, data analysis, machine learning, and artificial intelligence. Its readability and simplicity make it a great choice for scripting, automation, and rapid prototyping.</p>
<p>Also, Python’s rich ecosystem of libraries and frameworks, such as Django and Flask, allow it to be used for backend web development.</p>
<p>Unlike JavaScript, Python is synchronous by default, which makes it better suited for tasks that don’t require real-time interaction but benefit from efficiency, such as data processing and batch operations.</p>
<h3 id="heading-core-differences-in-approach-dynamic-typing-functional-programming-and-oop">Core Differences in Approach: Dynamic Typing, Functional Programming, and OOP</h3>
<p>Both JavaScript and Python are dynamically typed, meaning that variables do not need to be declared with a specific type and can hold different types of data at runtime. But the two languages implement this dynamic typing in slightly different ways, and they each approach functional programming and object-oriented programming (OOP) differently.</p>
<p><strong>Dynamic Typing</strong>: Both languages allow flexibility in declaring variables without specifying types, making them highly flexible. But Python’s strict indentation requirements and clear error messages provide a more structured approach to dynamic typing.</p>
<p>JavaScript, on the other hand, has a looser syntax, which sometimes leads to quirks, such as type coercion, that can result in unexpected behavior (for example, <code>0 == ''</code> evaluates to <code>true</code>).</p>
<p><strong>Functional Programming</strong>: Both languages support functional programming techniques, but JavaScript leans heavily on it. Functions are first-class citizens in JavaScript, allowing developers to pass functions as arguments, return them from other functions, and store them in variables. Higher-order functions, such as <code>map</code>, <code>reduce</code>, and <code>filter</code>, are commonly used in JavaScript to process arrays and data collections.</p>
<p>Python also supports functional programming, and it includes a <code>lambda</code> feature for anonymous functions as well as <code>map</code>, <code>filter</code>, and <code>reduce</code> functions. But functional programming is less central in Python, which encourages readability and simplicity over deeply functional constructs.</p>
<p><strong>Object-Oriented Programming (OOP)</strong>: JavaScript’s OOP model is prototype-based, meaning that objects can inherit directly from other objects without the need for classes. Since ES6, JavaScript has also included support for <code>class</code> syntax, making it easier for developers coming from class-based languages to work with objects.</p>
<p>Python, on the other hand, uses a class-based model that is more in line with traditional OOP languages like Java and C++. Classes, inheritance, and polymorphism in Python are straightforward, making it an excellent choice for developers who prefer a clear and well-structured approach to OOP.</p>
<h3 id="heading-typical-use-cases-for-javascript-and-python">Typical Use Cases for JavaScript and Python</h3>
<p>To understand the strengths of each language, it’s helpful to consider the types of projects that developers commonly use JavaScript and Python for:</p>
<h4 id="heading-common-use-cases-for-javascript"><strong>Common Use Cases for JavaScript</strong>:</h4>
<ul>
<li><p><strong>Frontend Web Development</strong>: JavaScript is essential for building interactive user interfaces in web browsers. With libraries and frameworks like React, Vue, and Angular, developers can build rich, responsive applications that run entirely in the browser.</p>
</li>
<li><p><strong>Full-Stack Web Development</strong>: Node.js allows JavaScript to be used on the backend, enabling full-stack development with JavaScript across the entire application. Express, NestJS, and other frameworks provide the tools for creating RESTful APIs, real-time applications, and server-side rendering.</p>
</li>
<li><p><strong>Real-Time Applications</strong>: JavaScript’s asynchronous and non-blocking nature makes it ideal for applications that require real-time updates, such as chat applications, live streaming, and collaborative tools.</p>
</li>
<li><p><strong>Mobile App Development</strong>: With frameworks like React Native, JavaScript can also be used to build cross-platform mobile applications. This allows JavaScript developers to leverage their web development skills to create mobile apps that work on both iOS and Android devices.</p>
</li>
</ul>
<h4 id="heading-common-use-cases-for-python"><strong>Common Use Cases for Python</strong>:</h4>
<ul>
<li><p><strong>Data Science and Analysis</strong>: Python’s popularity in data science is unparalleled, with libraries like Pandas, NumPy, and Matplotlib providing robust tools for data manipulation, analysis, and visualization. Python is the go-to language for data scientists and analysts.</p>
</li>
<li><p><strong>Machine Learning and Artificial Intelligence</strong>: Python’s machine learning libraries, such as TensorFlow, Keras, and PyTorch, make it an ideal language for building machine learning models and neural networks. Python’s readability is especially useful when experimenting with complex algorithms.</p>
</li>
<li><p><strong>Automation and Scripting</strong>: Python’s simplicity and versatility make it a popular choice for automation. Tasks like file manipulation, batch processing, and web scraping can be accomplished with Python scripts, using libraries like BeautifulSoup, Selenium, and Requests.</p>
</li>
<li><p><strong>Backend Web Development</strong>: Python’s web frameworks, such as Django and Flask, provide powerful tools for creating scalable and secure web applications. Python is widely used for backend development, particularly in projects that require quick prototyping, as its concise syntax speeds up development.</p>
</li>
<li><p><strong>Scientific Computing and Research</strong>: Python is commonly used in scientific research due to its extensive scientific libraries, such as SciPy and SymPy, and its compatibility with environments like Jupyter notebooks.</p>
</li>
</ul>
<p>By understanding the typical use cases and paradigms that each language supports, JavaScript developers can better appreciate Python’s unique strengths.</p>
<p>JavaScript is inherently event-driven, making it ideal for interactive applications, while Python’s strengths lie in readability and a well-defined structure, making it an excellent choice for projects that demand clarity and precision, like data science, scripting, and backend development.</p>
<h2 id="heading-3-syntax-and-language-features">3. <strong>Syntax and Language Features</strong></h2>
<p>While both JavaScript and Python are dynamically typed, high-level languages, they have distinct syntax rules and language features that can affect code readability, structure, and maintenance.</p>
<p>This section highlights some of the core syntactical differences and introduces language features that will be especially relevant for a JavaScript developer learning Python.</p>
<h3 id="heading-comparison-of-syntax-simplicity-and-readability">Comparison of Syntax Simplicity and Readability</h3>
<p>One of Python’s main selling points is its clear, readable syntax. Often described as “executable pseudocode,” Python emphasizes simplicity, aiming for code that’s easy to write and, perhaps more importantly, easy to read.</p>
<p>Unlike JavaScript, which uses braces (<code>{}</code>) to define code blocks, Python uses indentation to enforce structure, which naturally encourages clean, organized code.</p>
<h4 id="heading-example-hello-world-and-simple-loops"><strong>Example: Hello World and Simple Loops</strong></h4>
<p>In both languages, the "Hello, World!" example highlights the difference in syntax:</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python">print(<span class="hljs-string">"Hello, World!"</span>)
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello, World!"</span>);
</code></pre>
<p>Python’s built-in <code>print</code> function makes printing straightforward without additional syntax. In JavaScript, <code>console.log</code> performs the same task but requires a more explicit object-method format.</p>
<p>Now, consider a simple loop that prints numbers from 0 to 4:</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):
    print(i)
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
    <span class="hljs-built_in">console</span>.log(i);
}
</code></pre>
<p>The difference here is striking. Python’s <code>for</code> loop with <code>range()</code> is compact and highly readable, while JavaScript’s loop uses a more complex syntax with initialization, condition, and increment clauses. This is a minor but illustrative example of Python’s design philosophy: code should be intuitive and easy to follow.</p>
<h3 id="heading-data-types-and-variable-declaration">Data Types and Variable Declaration</h3>
<p>Both JavaScript and Python are dynamically typed, meaning that you don’t need to specify variable types explicitly. But there are differences in variable declaration and type handling that are worth noting.</p>
<h4 id="heading-variable-declaration"><strong>Variable Declaration</strong></h4>
<p>JavaScript requires <code>let</code>, <code>const</code>, or <code>var</code> to declare variables. The use of <code>let</code> and <code>const</code> in modern JavaScript helps manage scope and constancy of variables, with <code>const</code> enforcing immutability.</p>
<p>In Python, there is no need to specify <code>let</code>, <code>const</code>, or <code>var</code> – you simply assign a value to a variable, and Python infers the type based on the value.</p>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-number">25</span>;  <span class="hljs-comment">// Using 'let' for a block-scoped variable</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">"Alice"</span>;  <span class="hljs-comment">// Using 'const' for an immutable variable</span>
</code></pre>
<p><strong>Python:</strong></p>
<pre><code class="lang-python">age = <span class="hljs-number">25</span>  <span class="hljs-comment"># Python infers type automatically</span>
name = <span class="hljs-string">"Alice"</span>  <span class="hljs-comment"># No need to declare as const or let</span>
</code></pre>
<h4 id="heading-type-checking-and-conversion"><strong>Type Checking and Conversion</strong></h4>
<p>Python’s type-checking system is more consistent, while JavaScript sometimes has quirky behavior due to type coercion, where values of different types are implicitly converted for comparison. For example:</p>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">0</span> == <span class="hljs-string">""</span>);  <span class="hljs-comment">// true due to type coercion</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">0</span> === <span class="hljs-string">""</span>); <span class="hljs-comment">// false due to strict equality</span>
</code></pre>
<p><strong>Python</strong>:</p>
<pre><code class="lang-python">print(<span class="hljs-number">0</span> == <span class="hljs-string">""</span>)  <span class="hljs-comment"># Raises a TypeError: 'int' and 'str' cannot be compared</span>
</code></pre>
<p>Python does not allow implicit type coercion, reducing potential bugs related to unexpected type behavior. If type conversion is needed, Python requires explicit casting.</p>
<h3 id="heading-working-with-primitive-data-types">Working with Primitive Data Types</h3>
<p>JavaScript and Python share some primitive types but also have unique types and handling:</p>
<ul>
<li><p><strong>Numbers</strong>: Both JavaScript and Python have number types, but Python distinguishes between <code>int</code> and <code>float</code> for integers and decimal numbers. JavaScript has only a single <code>Number</code> type for all numeric values (including <code>NaN</code> for “not-a-number”).</p>
</li>
<li><p><strong>Strings</strong>: Both languages treat strings as sequences of characters, allowing methods like concatenation, splitting, and indexing. In Python, strings are immutable, meaning once created, they cannot be modified directly.</p>
</li>
<li><p><strong>Booleans</strong>: Both languages have <code>true</code> and <code>false</code> values. But JavaScript’s type coercion can lead to unexpected results in conditions, which Python avoids with explicit boolean handling.</p>
</li>
<li><p><strong>Null and Undefined</strong>: JavaScript distinguishes between <code>null</code> (an intentional absence of value) and <code>undefined</code> (an uninitialized variable). Python uses <code>None</code> as a single, consistent representation of “no value.”</p>
</li>
</ul>
<h3 id="heading-data-collections-lists-tuples-sets-and-dictionaries">Data Collections: Lists, Tuples, Sets, and Dictionaries</h3>
<p>Both JavaScript and Python offer various data structures to handle collections, but Python has built-in types that allow for more specific data handling.</p>
<h4 id="heading-lists-and-arrays"><strong>Lists and Arrays</strong></h4>
<p>Python’s <code>list</code> type is analogous to JavaScript’s array, but it’s more versatile, as Python lists can store elements of different types and support built-in functions for manipulation. In contrast, JavaScript arrays are specialized objects with numerical indices.</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python">my_list = [<span class="hljs-number">1</span>, <span class="hljs-string">"apple"</span>, <span class="hljs-number">3.14</span>]
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-string">"apple"</span>, <span class="hljs-number">3.14</span>];
</code></pre>
<h4 id="heading-tuples"><strong>Tuples</strong></h4>
<p>Python offers <code>tuple</code> as an immutable version of a list, useful when data should not be modified. JavaScript has no direct equivalent, though <code>const</code> can create a similar effect by enforcing immutability.</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python">my_tuple = (<span class="hljs-number">1</span>, <span class="hljs-string">"apple"</span>, <span class="hljs-number">3.14</span>)
</code></pre>
<h4 id="heading-sets"><strong>Sets</strong></h4>
<p>Both languages offer a set data type for collections of unique elements. Python has <code>set</code>, while JavaScript uses <code>Set</code>.</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python">my_set = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> mySet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);
</code></pre>
<h4 id="heading-dictionaries-and-objects"><strong>Dictionaries and Objects</strong></h4>
<p>Python’s <code>dict</code> and JavaScript’s objects are both key-value structures, but they differ in design and functionality.</p>
<p>In Python, dictionaries are optimized for hashable keys, whereas JavaScript objects are more flexible but can lead to type-related issues when keys are non-string values.</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python">my_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">25</span>}
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myObject = { <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> };
</code></pre>
<h3 id="heading-control-structures-conditionals-and-loops">Control Structures: Conditionals and Loops</h3>
<p>Both Python and JavaScript have similar control structures, such as <code>if</code>, <code>for</code>, and <code>while</code> loops. But Python's syntax is simplified due to its reliance on indentation.</p>
<h4 id="heading-conditionals"><strong>Conditionals</strong></h4>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> age &gt; <span class="hljs-number">18</span>:
    print(<span class="hljs-string">"Adult"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Minor"</span>)
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (age &gt; <span class="hljs-number">18</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Adult"</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Minor"</span>);
}
</code></pre>
<p>Python’s syntax avoids the braces used in JavaScript, relying on indentation to signify code blocks. This makes code look cleaner but enforces strict formatting, which can be a learning curve for JavaScript developers.</p>
<h4 id="heading-loops"><strong>Loops</strong></h4>
<ul>
<li><strong>For Loops</strong>: Python’s <code>for</code> loop is often simpler, especially with the <code>range()</code> function. JavaScript’s traditional <code>for</code> loop has more structure but allows for flexibility.</li>
</ul>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):
    print(i)
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
    <span class="hljs-built_in">console</span>.log(i);
}
</code></pre>
<ul>
<li><strong>While Loops</strong>: Both languages support <code>while</code> loops, and they’re functionally similar. But Python uses plain English for keywords and syntax, which some find more readable.</li>
</ul>
<p><strong>Python:</strong></p>
<pre><code class="lang-python">count = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> count &lt; <span class="hljs-number">5</span>:
    print(count)
    count += <span class="hljs-number">1</span>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
<span class="hljs-keyword">while</span> (count &lt; <span class="hljs-number">5</span>) {
    <span class="hljs-built_in">console</span>.log(count);
    count++;
}
</code></pre>
<h4 id="heading-key-takeaways">Key Takeaways:</h4>
<ul>
<li><p>Python’s syntax is minimalist and requires indentation, which encourages clean, readable code.</p>
</li>
<li><p>Variable declaration in Python is simpler due to inferred types, while JavaScript uses <code>let</code>, <code>const</code>, and <code>var</code> for scope management.</p>
</li>
<li><p>Python has built-in data structures like lists, tuples, sets, and dictionaries, each with specific use cases, while JavaScript relies on arrays and objects.</p>
</li>
<li><p>Control structures in Python focus on readability with fewer symbols, whereas JavaScript uses braces and parentheses to define blocks.</p>
</li>
</ul>
<h2 id="heading-4-data-structures-and-collections">4. <strong>Data Structures and Collections</strong></h2>
<p>Data structures are foundational to any programming language, as they define how data is stored, accessed, and manipulated. Both JavaScript and Python offer a variety of built-in data structures, but each language provides different tools and features for handling collections.</p>
<p>In this section, we’ll explore Python’s main data structures and compare them with JavaScript’s corresponding structures.</p>
<h3 id="heading-lists-and-arrays-1">Lists and Arrays</h3>
<p>In Python, lists are versatile, mutable sequences that allow you to store elements of different types. They are comparable to JavaScript’s arrays but come with built-in methods and utilities that make them easier to manipulate for many use cases.</p>
<p><strong>Python Lists</strong>:</p>
<ul>
<li><p>Lists in Python are denoted by square brackets (<code>[]</code>) and support various built-in functions, such as appending, inserting, and removing elements.</p>
</li>
<li><p>They can store any type of data, including other lists, making them useful for nested data structures.</p>
</li>
</ul>
<p><strong>JavaScript Arrays</strong>:</p>
<ul>
<li><p>Arrays in JavaScript are also denoted by square brackets (<code>[]</code>) and can hold elements of different types.</p>
</li>
<li><p>JavaScript arrays are technically objects, so they come with a range of methods for manipulation (<code>push</code>, <code>pop</code>, <code>splice</code>, <code>map</code>, etc.).</p>
</li>
</ul>
<p><strong>Example</strong>: Adding and removing elements in lists and arrays:</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating and manipulating a list</span>
my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
my_list.append(<span class="hljs-number">4</span>)       <span class="hljs-comment"># Adds 4 to the end</span>
my_list.insert(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>)   <span class="hljs-comment"># Inserts 10 at index 1</span>
my_list.remove(<span class="hljs-number">2</span>)       <span class="hljs-comment"># Removes the first occurrence of 2</span>
print(my_list)          <span class="hljs-comment"># Output: [1, 10, 3, 4]</span>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating and manipulating an array</span>
<span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
myArray.push(<span class="hljs-number">4</span>);        <span class="hljs-comment">// Adds 4 to the end</span>
myArray.splice(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">10</span>); <span class="hljs-comment">// Inserts 10 at index 1</span>
myArray.splice(myArray.indexOf(<span class="hljs-number">2</span>), <span class="hljs-number">1</span>); <span class="hljs-comment">// Removes the first occurrence of 2</span>
<span class="hljs-built_in">console</span>.log(myArray);   <span class="hljs-comment">// Output: [1, 10, 3, 4]</span>
</code></pre>
<p>Python’s list functions are often simpler and more intuitive, which is particularly beneficial for quick data manipulation.</p>
<h3 id="heading-tuples-1">Tuples</h3>
<p>Python offers tuples as an immutable sequence type, meaning their elements cannot be changed once created. Tuples are useful when you need a sequence of items that should remain constant throughout the program’s execution.</p>
<p>JavaScript does not have an equivalent immutable sequence structure, though arrays declared with <code>const</code> can serve a similar purpose in restricting reassignment.</p>
<p><strong>Python Tuple:</strong></p>
<pre><code class="lang-python">my_tuple = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
<span class="hljs-comment"># Attempting to modify will raise an error:</span>
<span class="hljs-comment"># my_tuple[0] = 10  # Raises TypeError</span>
</code></pre>
<p>Tuples are ideal for fixed collections, such as coordinates or configuration values, where data should not change.</p>
<h3 id="heading-sets-1">Sets</h3>
<p>Both JavaScript and Python offer sets as a way to store unique values. Sets are unordered and do not allow duplicates, making them ideal for collections where each item should be unique.</p>
<p><strong>Python Sets:</strong></p>
<ul>
<li><p>In Python, sets are defined using curly braces (<code>{}</code>) or the <code>set()</code> function.</p>
</li>
<li><p>Python sets support set operations like union, intersection, and difference, which can be useful for tasks like finding common elements or removing duplicates.</p>
</li>
</ul>
<p><strong>JavaScript Sets:</strong></p>
<ul>
<li><p>JavaScript introduced the <code>Set</code> object in ES6.</p>
</li>
<li><p>Similar to Python, JavaScript sets can perform union and intersection operations with some extra syntax.</p>
</li>
</ul>
<p><strong>Example</strong>: Working with sets in Python and JavaScript:</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating and using a set</span>
fruits = {<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>}
fruits.add(<span class="hljs-string">"orange"</span>)           <span class="hljs-comment"># Adds "orange" to the set</span>
fruits.discard(<span class="hljs-string">"banana"</span>)       <span class="hljs-comment"># Removes "banana" from the set</span>
print(fruits)                  <span class="hljs-comment"># Output: {"apple", "cherry", "orange"}</span>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating and using a set</span>
<span class="hljs-keyword">let</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>]);
fruits.add(<span class="hljs-string">"orange"</span>);           <span class="hljs-comment">// Adds "orange" to the set</span>
fruits.delete(<span class="hljs-string">"banana"</span>);        <span class="hljs-comment">// Removes "banana" from the set</span>
<span class="hljs-built_in">console</span>.log(fruits);            <span class="hljs-comment">// Output: Set { "apple", "cherry", "orange" }</span>
</code></pre>
<p>Python’s set functions (<code>union</code>, <code>intersection</code>, <code>difference</code>) make it easy to perform mathematical set operations directly, which is especially useful for data processing tasks.</p>
<h3 id="heading-dictionaries-and-objects-1">Dictionaries and Objects</h3>
<p>Python’s <code>dict</code> and JavaScript’s objects are both key-value pair data structures, but they have slightly different features and limitations.</p>
<ul>
<li><p><strong>Python Dictionaries</strong>: Python’s dictionaries are optimized for fast lookup and can use immutable types (for example, strings, numbers, tuples) as keys. Dictionaries are widely used in Python for data management, configuration, and lookups.</p>
</li>
<li><p><strong>JavaScript Objects</strong>: JavaScript objects serve a similar purpose but are less restrictive in terms of key types. Objects can use strings and symbols as keys but lack some of the dictionary-specific functions found in Python.</p>
</li>
</ul>
<p><strong>Example</strong>: Creating and accessing elements in dictionaries and objects:</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating and manipulating a dictionary</span>
person = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">30</span>}
person[<span class="hljs-string">"city"</span>] = <span class="hljs-string">"New York"</span>     <span class="hljs-comment"># Adding a new key-value pair</span>
print(person[<span class="hljs-string">"name"</span>])           <span class="hljs-comment"># Output: Alice</span>
<span class="hljs-keyword">del</span> person[<span class="hljs-string">"age"</span>]               <span class="hljs-comment"># Removing a key-value pair</span>
print(person)                   <span class="hljs-comment"># Output: {"name": "Alice", "city": "New York"}</span>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating and manipulating an object</span>
<span class="hljs-keyword">let</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
person.city = <span class="hljs-string">"New York"</span>;       <span class="hljs-comment">// Adding a new key-value pair</span>
<span class="hljs-built_in">console</span>.log(person.name);       <span class="hljs-comment">// Output: Alice</span>
<span class="hljs-keyword">delete</span> person.age;              <span class="hljs-comment">// Removing a key-value pair</span>
<span class="hljs-built_in">console</span>.log(person);            <span class="hljs-comment">// Output: { name: "Alice", city: "New York" }</span>
</code></pre>
<p>Python dictionaries also support powerful methods like <code>get</code>, <code>keys</code>, <code>values</code>, and <code>items</code>, which provide more direct ways to access and manipulate dictionary contents compared to JavaScript’s object handling.</p>
<h3 id="heading-working-with-json-data">Working with JSON Data</h3>
<p>Both Python and JavaScript work well with JSON, a format frequently used for data interchange in web applications. JavaScript’s native compatibility with JSON is a natural fit for web APIs, while Python’s <code>json</code> module allows for easy parsing and generation of JSON data.</p>
<p><strong>Example</strong>: Converting a dictionary/object to JSON and parsing JSON data:</p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Convert dictionary to JSON string</span>
person_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">30</span>}
person_json = json.dumps(person_dict)
print(person_json)  <span class="hljs-comment"># Output: {"name": "Alice", "age": 30}</span>

<span class="hljs-comment"># Parse JSON string to dictionary</span>
parsed_dict = json.loads(person_json)
print(parsed_dict)  <span class="hljs-comment"># Output: {'name': 'Alice', 'age': 30}</span>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Convert object to JSON string</span>
<span class="hljs-keyword">let</span> personObject = { <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
<span class="hljs-keyword">let</span> personJson = <span class="hljs-built_in">JSON</span>.stringify(personObject);
<span class="hljs-built_in">console</span>.log(personJson); <span class="hljs-comment">// Output: {"name":"Alice","age":30}</span>

<span class="hljs-comment">// Parse JSON string to object</span>
<span class="hljs-keyword">let</span> parsedObject = <span class="hljs-built_in">JSON</span>.parse(personJson);
<span class="hljs-built_in">console</span>.log(parsedObject); <span class="hljs-comment">// Output: { name: 'Alice', age: 30 }</span>
</code></pre>
<h4 id="heading-key-takeaways-1">Key Takeaways:</h4>
<ul>
<li><p><strong>Lists and Arrays</strong>: Python’s lists are versatile and come with built-in manipulation methods. JavaScript arrays are flexible but less concise in syntax.</p>
</li>
<li><p><strong>Tuples</strong>: Python’s tuples are immutable sequences ideal for fixed data collections, which JavaScript lacks an equivalent for.</p>
</li>
<li><p><strong>Sets</strong>: Both Python and JavaScript offer sets for unique collections, but Python’s sets support more direct mathematical operations.</p>
</li>
<li><p><strong>Dictionaries and Objects</strong>: Python’s dictionaries and JavaScript’s objects serve similar purposes, though Python offers additional methods specifically for dictionary manipulation.</p>
</li>
<li><p><strong>JSON</strong>: Both languages handle JSON data, with JavaScript having native JSON support and Python using the <code>json</code> module.</p>
</li>
</ul>
<h2 id="heading-5-functions-and-scope">5. <strong>Functions and Scope</strong></h2>
<p>Functions are the building blocks of any programming language. They allow you to encapsulate code for reuse, organization, and clarity.</p>
<p>Both Python and JavaScript support first-class functions, meaning functions can be assigned to variables, passed as arguments, and returned from other functions. But there are differences in how functions are defined, scoped, and used in each language.</p>
<h3 id="heading-defining-functions-in-python-vs-javascript">Defining Functions in Python vs. JavaScript</h3>
<p><strong>Python Functions</strong>:<br>In Python, functions are defined using the <code>def</code> keyword, followed by the function name, parameters in parentheses, and a colon. Python uses indentation to define the function body, which makes the syntax clean and readable.</p>
<p><strong>JavaScript Functions</strong>:<br>In JavaScript, functions can be defined in several ways: using the <code>function</code> keyword, as an arrow function (<code>=&gt;</code>), or as a method within an object. Modern JavaScript commonly uses arrow functions for their brevity and lexical <code>this</code> behavior.</p>
<p><strong>Example: Basic Function Definition</strong></p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">f"Hello, <span class="hljs-subst">{name}</span>!"</span>

print(greet(<span class="hljs-string">"Alice"</span>))  <span class="hljs-comment"># Output: Hello, Alice!</span>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
}

<span class="hljs-built_in">console</span>.log(greet(<span class="hljs-string">"Alice"</span>)); <span class="hljs-comment">// Output: Hello, Alice!</span>
</code></pre>
<p><strong>Arrow Functions in JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> greet = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
<span class="hljs-built_in">console</span>.log(greet(<span class="hljs-string">"Alice"</span>)); <span class="hljs-comment">// Output: Hello, Alice!</span>
</code></pre>
<p><strong>Key Differences:</strong></p>
<ol>
<li><p>Python uses explicit keywords like <code>def</code> and <code>return</code>, while JavaScript has multiple ways to define functions, which can sometimes be overwhelming for beginners.</p>
</li>
<li><p>Arrow functions in JavaScript provide concise syntax but are not equivalent to Python’s lambda (more on that below).</p>
</li>
</ol>
<h3 id="heading-scope-rules-closures-in-javascript-vs-legb-rule-in-python">Scope Rules: Closures in JavaScript vs. LEGB Rule in Python</h3>
<p><strong>Scope</strong> refers to where a variable is accessible in your code. Both Python and JavaScript have rules for variable scoping, but they are implemented differently.</p>
<p><strong>Python’s LEGB Rule</strong>:<br>Python uses the LEGB rule to determine variable scope:</p>
<ul>
<li><p><strong>L</strong>ocal: Variables defined inside a function.</p>
</li>
<li><p><strong>E</strong>nclosing: Variables in the nearest enclosing scope (for example, nested functions).</p>
</li>
<li><p><strong>G</strong>lobal: Variables defined at the top level of the module.</p>
</li>
<li><p><strong>B</strong>uilt-in: Predefined names in Python (for example, <code>len</code>, <code>print</code>).</p>
</li>
</ul>
<p>Example of Python scope:</p>
<pre><code class="lang-python">x = <span class="hljs-string">"global"</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outer_function</span>():</span>
    x = <span class="hljs-string">"enclosing"</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_function</span>():</span>
        x = <span class="hljs-string">"local"</span>
        print(x)

    inner_function()

outer_function()  <span class="hljs-comment"># Output: local</span>
print(x)          <span class="hljs-comment"># Output: global</span>
</code></pre>
<p><strong>JavaScript Closures</strong>:<br>JavaScript handles scope using function-level and block-level scoping. Variables declared with <code>let</code> and <code>const</code> have block scope, while <code>var</code> has function scope.</p>
<p>Closures are an essential concept in JavaScript, allowing inner functions to access variables from their outer (enclosing) functions even after the outer function has executed.</p>
<p>Example of JavaScript closure:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> x = <span class="hljs-string">"enclosing"</span>;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">let</span> x = <span class="hljs-string">"local"</span>;
        <span class="hljs-built_in">console</span>.log(x);
    }

    innerFunction();
}

outerFunction(); <span class="hljs-comment">// Output: local</span>
</code></pre>
<p><strong>Key Differences:</strong></p>
<ul>
<li><p>Python’s scope is determined by its LEGB rule, whereas JavaScript relies on closures and block scoping (with <code>let</code> and <code>const</code>).</p>
</li>
<li><p>Python has explicit mechanisms like the <code>global</code> and <code>nonlocal</code> keywords to modify variable scope, while JavaScript uses closures implicitly.</p>
</li>
</ul>
<h3 id="heading-anonymous-functions-lambda-expressions-vs-arrow-functions">Anonymous Functions: Lambda Expressions vs. Arrow Functions</h3>
<p><strong>Python’s Lambda Expressions</strong>:<br>Python’s <code>lambda</code> allows you to define small, unnamed functions in a single line. They are typically used for short-lived operations, like filtering or mapping, where defining a full function would be unnecessary.</p>
<p>Example of a Python lambda:</p>
<pre><code class="lang-python">square = <span class="hljs-keyword">lambda</span> x: x ** <span class="hljs-number">2</span>
print(square(<span class="hljs-number">5</span>))  <span class="hljs-comment"># Output: 25</span>

<span class="hljs-comment"># Using lambda in a map function</span>
numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
squared = map(<span class="hljs-keyword">lambda</span> x: x ** <span class="hljs-number">2</span>, numbers)
print(list(squared))  <span class="hljs-comment"># Output: [1, 4, 9, 16]</span>
</code></pre>
<p><strong>JavaScript’s Arrow Functions</strong>:<br>Arrow functions in JavaScript serve a similar purpose but are more versatile. They provide a concise way to define functions and automatically bind <code>this</code> to the enclosing context, which is particularly useful in object-oriented or asynchronous programming.</p>
<p>Example of a JavaScript arrow function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> square = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x ** <span class="hljs-number">2</span>;
<span class="hljs-built_in">console</span>.log(square(<span class="hljs-number">5</span>)); <span class="hljs-comment">// Output: 25</span>

<span class="hljs-comment">// Using an arrow function in map</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-keyword">const</span> squared = numbers.map(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x ** <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(squared); <span class="hljs-comment">// Output: [1, 4, 9, 16]</span>
</code></pre>
<p><strong>Key Differences:</strong></p>
<ol>
<li><p><strong>Purpose</strong>: Python’s <code>lambda</code> is limited to single expressions and is primarily used for quick operations. Arrow functions in JavaScript are more flexible and can have multiple statements and explicit return values.</p>
</li>
<li><p><strong>Scope Binding</strong>: Arrow functions inherit the <code>this</code> context of their enclosing block, while Python’s lambdas are independent functions with no context-related behavior.</p>
</li>
</ol>
<h3 id="heading-function-parameters-and-default-values">Function Parameters and Default Values</h3>
<p>Both Python and JavaScript support default parameter values, but Python offers additional features like keyword arguments and variable-length arguments (<code>*args</code> and <code>**kwargs</code>).</p>
<p><strong>Python Default and Variable-Length Arguments</strong>:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name=<span class="hljs-string">"World"</span>, *args, **kwargs</span>):</span>
    print(<span class="hljs-string">f"Hello, <span class="hljs-subst">{name}</span>!"</span>)
    print(<span class="hljs-string">"Arguments:"</span>, args)
    print(<span class="hljs-string">"Keyword Arguments:"</span>, kwargs)

greet(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, color=<span class="hljs-string">"blue"</span>, age=<span class="hljs-number">30</span>)
<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># Hello, Alice!</span>
<span class="hljs-comment"># Arguments: (1, 2)</span>
<span class="hljs-comment"># Keyword Arguments: {'color': 'blue', 'age': 30}</span>
</code></pre>
<p><strong>JavaScript Default Parameters</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name = <span class="hljs-string">"World"</span>, ...args</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Arguments:"</span>, args);
}

greet(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, { <span class="hljs-attr">color</span>: <span class="hljs-string">"blue"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> });
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Hello, Alice!</span>
<span class="hljs-comment">// Arguments: [1, 2, { color: 'blue', age: 30 }]</span>
</code></pre>
<p>Python’s keyword arguments (<code>**kwargs</code>) provide a more structured way to handle optional parameters compared to JavaScript’s <code>arguments</code> or rest parameters.</p>
<h4 id="heading-key-takeaways-2">Key Takeaways:</h4>
<ul>
<li><p>Python’s function syntax (<code>def</code>) is straightforward and emphasizes readability, while JavaScript offers flexibility with <code>function</code>, arrow functions, and method definitions.</p>
</li>
<li><p>Python’s LEGB scope rule makes variable visibility predictable and explicit, while JavaScript’s closures offer powerful but implicit scoping.</p>
</li>
<li><p>Python’s <code>lambda</code> expressions are limited to simple operations, whereas JavaScript’s arrow functions provide greater flexibility and contextual <code>this</code> binding.</p>
</li>
<li><p>Python’s support for keyword and variable-length arguments adds flexibility and clarity when passing data to functions.</p>
</li>
</ul>
<p>This section demonstrates that while both languages handle functions and scope effectively, Python’s approach prioritizes simplicity and readability, while JavaScript offers more flexibility and dynamic behavior. Both approaches have their advantages, depending on the task at hand.</p>
<h2 id="heading-6-object-oriented-programming-oop">6. <strong>Object-Oriented Programming (OOP)</strong></h2>
<p>Object-Oriented Programming (OOP) allows developers to create reusable and modular code by encapsulating data and behavior into objects. Both Python and JavaScript support OOP, but they implement it differently.</p>
<p>Python uses a class-based model, with clearly defined syntax for attributes and methods. JavaScript traditionally relied on prototype-based inheritance but has introduced class syntax (since ES6) that closely resembles traditional OOP languages, providing familiarity for developers transitioning from Python or Java.</p>
<h3 id="heading-classes-inheritance-and-polymorphism">Classes, Inheritance, and Polymorphism</h3>
<p>At its core, OOP involves defining <strong>classes</strong> (blueprints for objects), creating <strong>instances</strong> of those classes, and implementing <strong>inheritance</strong> to extend or modify behavior. Both Python and JavaScript support these concepts, albeit with different syntax.</p>
<p><strong>Example: Basic Class Definition</strong></p>
<p><strong>Python:</strong></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name</span>):</span>
        self.name = name

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">speak</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{self.name}</span> makes a sound."</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">speak</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{self.name}</span> barks."</span>

<span class="hljs-comment"># Using the classes</span>
generic_animal = Animal(<span class="hljs-string">"Generic Animal"</span>)
dog = Dog(<span class="hljs-string">"Buddy"</span>)

print(generic_animal.speak())  <span class="hljs-comment"># Output: Generic Animal makes a sound.</span>
print(dog.speak())             <span class="hljs-comment"># Output: Buddy barks.</span>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>.name = name;
    }

    speak() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> makes a sound.`</span>;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    speak() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> barks.`</span>;
    }
}

<span class="hljs-comment">// Using the classes</span>
<span class="hljs-keyword">const</span> genericAnimal = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">"Generic Animal"</span>);
<span class="hljs-keyword">const</span> dog = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">"Buddy"</span>);

<span class="hljs-built_in">console</span>.log(genericAnimal.speak()); <span class="hljs-comment">// Output: Generic Animal makes a sound.</span>
<span class="hljs-built_in">console</span>.log(dog.speak());           <span class="hljs-comment">// Output: Buddy barks.</span>
</code></pre>
<p>In both examples, you see:</p>
<ul>
<li><p><strong>Class Definition</strong>: <code>class</code> is used in both Python and JavaScript.</p>
</li>
<li><p><strong>Inheritance</strong>: The <code>Dog</code> class extends the <code>Animal</code> class, overriding the <code>speak</code> method in both languages.</p>
</li>
</ul>
<h3 id="heading-differences-in-constructors-and-the-this-vs-self-keyword">Differences in Constructors and the <code>this</code> vs. <code>self</code> Keyword</h3>
<p>One key difference in OOP syntax between Python and JavaScript lies in how constructors are defined and how the instance is referenced within a class.</p>
<p><strong>Python Constructor and</strong> <code>self</code>:</p>
<p>Python uses <code>__init__</code> as a special method to initialize an object. It explicitly requires <code>self</code> as the first parameter in all instance methods to refer to the object itself.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"My name is <span class="hljs-subst">{self.name}</span> and I am <span class="hljs-subst">{self.age}</span> years old."</span>

person = Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">30</span>)
print(person.greet())  <span class="hljs-comment"># Output: My name is Alice and I am 30 years old.</span>
</code></pre>
<p><strong>JavaScript Constructor and</strong> <code>this</code>:</p>
<p>JavaScript uses a <code>constructor</code> method to initialize an object. Inside methods, <code>this</code> is used to reference the current instance, but <code>this</code> can behave differently depending on the context.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-keyword">constructor</span>(name, age) {
        <span class="hljs-built_in">this</span>.name = name;
        <span class="hljs-built_in">this</span>.age = age;
    }

    greet() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>;
    }
}

<span class="hljs-keyword">const</span> person = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">30</span>);
<span class="hljs-built_in">console</span>.log(person.greet()); <span class="hljs-comment">// Output: My name is Alice and I am 30 years old.</span>
</code></pre>
<p><strong>Key Differences</strong>:</p>
<ol>
<li><p><strong>Explicit vs. Implicit Instance Reference</strong>: Python always requires <code>self</code> explicitly, while JavaScript implicitly uses <code>this</code>.</p>
</li>
<li><p><strong>Context Sensitivity</strong>: In JavaScript, <code>this</code> can lose its binding in certain contexts (for example, when passing methods as callbacks). Arrow functions provide a way to avoid this issue by binding <code>this</code> to the lexical scope.</p>
</li>
</ol>
<h3 id="heading-polymorphism-in-python-and-javascript">Polymorphism in Python and JavaScript</h3>
<p>Polymorphism allows methods to behave differently depending on the object that calls them. This is a fundamental OOP concept and is supported in both Python and JavaScript.</p>
<p><strong>Python Example:</strong></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fly</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Birds can fly."</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Penguin</span>(<span class="hljs-params">Bird</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fly</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Penguins cannot fly."</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_flight_ability</span>(<span class="hljs-params">bird</span>):</span>
    print(bird.fly())

sparrow = Bird()
penguin = Penguin()

get_flight_ability(sparrow)  <span class="hljs-comment"># Output: Birds can fly.</span>
get_flight_ability(penguin)  <span class="hljs-comment"># Output: Penguins cannot fly.</span>
</code></pre>
<p><strong>JavaScript Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span> </span>{
    fly() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Birds can fly."</span>;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Penguin</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Bird</span> </span>{
    fly() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Penguins cannot fly."</span>;
    }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFlightAbility</span>(<span class="hljs-params">bird</span>) </span>{
    <span class="hljs-built_in">console</span>.log(bird.fly());
}

<span class="hljs-keyword">const</span> sparrow = <span class="hljs-keyword">new</span> Bird();
<span class="hljs-keyword">const</span> penguin = <span class="hljs-keyword">new</span> Penguin();

getFlightAbility(sparrow);  <span class="hljs-comment">// Output: Birds can fly.</span>
getFlightAbility(penguin);  <span class="hljs-comment">// Output: Penguins cannot fly.</span>
</code></pre>
<h3 id="heading-prototypes-in-javascript-vs-classes-in-python">Prototypes in JavaScript vs. Classes in Python</h3>
<p>JavaScript's OOP was initially based on prototypes, where objects could inherit properties and methods directly from other objects. Although ES6 introduced <code>class</code>, it is syntactic sugar over JavaScript's prototypal inheritance.</p>
<p><strong>JavaScript Prototype Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Calculator</span>(<span class="hljs-params"></span>) </span>{}

Calculator.prototype.add = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a + b;
};

Calculator.prototype.multiply = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a * b;
};

<span class="hljs-keyword">const</span> calc = <span class="hljs-keyword">new</span> Calculator();
<span class="hljs-built_in">console</span>.log(calc.add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>));       <span class="hljs-comment">// Output: 8</span>
<span class="hljs-built_in">console</span>.log(calc.multiply(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>));  <span class="hljs-comment">// Output: 15</span>
</code></pre>
<p><strong>Modern JavaScript Class Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> </span>{
    add(a, b) {
        <span class="hljs-keyword">return</span> a + b;
    }

    multiply(a, b) {
        <span class="hljs-keyword">return</span> a * b;
    }
}

<span class="hljs-keyword">const</span> calc = <span class="hljs-keyword">new</span> Calculator();
<span class="hljs-built_in">console</span>.log(calc.add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>));       <span class="hljs-comment">// Output: 8</span>
<span class="hljs-built_in">console</span>.log(calc.multiply(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>));  <span class="hljs-comment">// Output: 15</span>
</code></pre>
<p>Python, in contrast, always uses a class-based system for OOP, avoiding the confusion of prototypes.</p>
<p><strong>Python Example:</strong></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">self, a, b</span>):</span>
        <span class="hljs-keyword">return</span> a + b

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">self, a, b</span>):</span>
        <span class="hljs-keyword">return</span> a * b

calc = Calculator()
print(calc.add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>))       <span class="hljs-comment"># Output: 8</span>
print(calc.multiply(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>))  <span class="hljs-comment"># Output: 15</span>
</code></pre>
<h4 id="heading-key-takeaways-3">Key Takeaways:</h4>
<ul>
<li><p>Python’s OOP model is straightforward, using <code>class</code>, <code>__init__</code> for constructors, and <code>self</code> to refer to instance attributes.</p>
</li>
<li><p>JavaScript has both prototypal and class-based OOP. The modern <code>class</code> syntax simplifies prototypal inheritance but can lead to confusion with <code>this</code>.</p>
</li>
<li><p>Both languages support core OOP principles like encapsulation, inheritance, and polymorphism, but Python’s implementation is more explicit and traditional, while JavaScript’s flexibility stems from its prototypal roots.</p>
</li>
</ul>
<h2 id="heading-7-asynchronous-programming">7. <strong>Asynchronous Programming</strong></h2>
<p>Asynchronous programming is essential for handling tasks like network requests, file I/O, or any operation that takes time to complete.</p>
<p>Both Python and JavaScript support asynchronous programming, but their implementations differ significantly. JavaScript is inherently asynchronous and event-driven, while Python introduced asynchronous programming more recently with the <code>asyncio</code> library and <code>async/await</code> syntax.</p>
<h3 id="heading-event-loop-and-promises-in-javascript">Event Loop and Promises in JavaScript</h3>
<p>JavaScript’s asynchronous model is based on the <strong>event loop</strong>, which processes tasks in a non-blocking manner. This makes it ideal for web applications where responsiveness is key. JavaScript uses <strong>callbacks</strong>, <strong>Promises</strong>, and <strong>async/await</strong> to handle asynchronous tasks.</p>
<p><strong>Example: Fetching Data with Promises</strong></p>
<p>A common asynchronous operation is fetching data from an API.</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(data);
    })
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
    });
</code></pre>
<p><strong>How it works:</strong></p>
<ol>
<li><p>The <code>fetch</code> function returns a Promise.</p>
</li>
<li><p>The <code>.then</code> method is used to handle the resolved Promise, where <code>response.json()</code> parses the JSON data.</p>
</li>
<li><p>The <code>.catch</code> method handles errors, such as network issues.</p>
</li>
</ol>
<p><strong>Example: Using Async/Await</strong></p>
<p>Async/await simplifies the syntax for working with Promises.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
        <span class="hljs-built_in">console</span>.log(data);
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
    }
}

fetchData();
</code></pre>
<p>In this example, <code>await</code> pauses the execution of the <code>fetchData</code> function until the Promise is resolved or rejected, providing a more synchronous-like flow.</p>
<h3 id="heading-asyncio-and-await-syntax-in-python">Asyncio and Await Syntax in Python</h3>
<p>Python’s asynchronous programming revolves around the <code>asyncio</code> library, which introduced the <code>async</code> and <code>await</code> keywords to handle asynchronous operations. Unlike JavaScript, Python does not have a built-in event loop – it relies on <code>asyncio</code> to create and manage one.</p>
<p><strong>Example: Fetching Data with Asyncio</strong></p>
<p>Using Python’s <code>aiohttp</code> library for asynchronous HTTP requests:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> aiohttp

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_data</span>():</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> aiohttp.ClientSession() <span class="hljs-keyword">as</span> session:
        <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> session.get(<span class="hljs-string">'https://api.example.com/data'</span>) <span class="hljs-keyword">as</span> response:
            data = <span class="hljs-keyword">await</span> response.json()
            print(data)

asyncio.run(fetch_data())
</code></pre>
<p><strong>How it works:</strong></p>
<ol>
<li><p>The <code>async def</code> syntax defines an asynchronous function.</p>
</li>
<li><p><code>await</code> is used to pause execution until the <code>get</code> request completes.</p>
</li>
<li><p><a target="_blank" href="http://asyncio.run"><code>asyncio.run</code></a><code>()</code> starts the event loop and runs the asynchronous function.</p>
</li>
</ol>
<p><strong>Key Differences from JavaScript:</strong></p>
<ul>
<li><p>Python explicitly defines asynchronous functions with <code>async def</code>.</p>
</li>
<li><p>The <code>asyncio</code> library is required to run the event loop.</p>
</li>
<li><p>Python’s <code>async/await</code> syntax is more structured but requires more setup compared to JavaScript.</p>
</li>
</ul>
<h3 id="heading-use-cases-and-performance-considerations">Use Cases and Performance Considerations</h3>
<p>Asynchronous programming is suitable for tasks that involve waiting, such as network requests, file I/O, or database queries. Here’s how Python and JavaScript handle common use cases:</p>
<p><strong>Real-Time Applications (JavaScript)</strong>: JavaScript’s event-driven model makes it ideal for real-time applications like chat systems, live streaming, or collaborative tools.</p>
<p><strong>Example: WebSocket in JavaScript</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> socket = <span class="hljs-keyword">new</span> WebSocket(<span class="hljs-string">'ws://example.com/socket'</span>);

socket.onmessage = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Message from server:'</span>, event.data);
};
</code></pre>
<p><strong>I/O-Bound Tasks (Python)</strong>: Python’s asynchronous model excels at handling I/O-bound tasks such as file processing, web scraping, or database queries.</p>
<p><strong>Example: Asynchronous File Reading in Python</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> aiofiles
<span class="hljs-keyword">import</span> asyncio

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_file</span>():</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> aiofiles.open(<span class="hljs-string">'example.txt'</span>, mode=<span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> file:
        content = <span class="hljs-keyword">await</span> file.read()
        print(content)

asyncio.run(read_file())
</code></pre>
<p><strong>Performance Considerations</strong>:</p>
<ol>
<li><p><strong>Concurrency</strong>: Both languages handle concurrency well, but JavaScript’s event loop and non-blocking I/O model are better suited for high-throughput, real-time applications.</p>
</li>
<li><p><strong>Threading</strong>: Python’s <code>asyncio</code> works best for I/O-bound tasks. For CPU-bound tasks, Python relies on multi-threading or multi-processing.</p>
</li>
<li><p><strong>Ease of Use</strong>: JavaScript’s async/await is simpler to implement for beginners, while Python requires familiarity with <code>asyncio</code> for similar functionality.</p>
</li>
</ol>
<h4 id="heading-key-takeaways-4">Key Takeaways:</h4>
<ul>
<li><p><strong>JavaScript</strong>: Asynchronous programming is central to JavaScript’s design. Its event loop and Promises make it highly efficient for real-time, event-driven applications.</p>
</li>
<li><p><strong>Python</strong>: Asynchronous programming is a newer addition to Python, focused on handling I/O-bound tasks efficiently with <code>asyncio</code>.</p>
</li>
<li><p><strong>Syntax</strong>: Both languages use <code>async/await</code>, but Python requires explicit setup with <code>asyncio</code>, while JavaScript integrates it natively.</p>
</li>
</ul>
<h2 id="heading-8-modules-packages-and-dependency-management">8. <strong>Modules, Packages, and Dependency Management</strong></h2>
<p>Both Python and JavaScript encourage modular programming, allowing developers to divide code into reusable and maintainable components.</p>
<p>Managing modules, packages, and dependencies is essential for any non-trivial project, and both languages provide robust systems to handle these needs. But the tools and ecosystems differ significantly.</p>
<h3 id="heading-nodejs-modules-vs-python-packages">Node.js Modules vs. Python Packages</h3>
<p><strong>JavaScript</strong>: JavaScript uses the <strong>Node.js module system</strong>, which allows developers to organize code into modules. Modules can be imported using <code>require</code> (CommonJS) or <code>import</code> (ES6 modules).</p>
<p><strong>Example: Exporting and Importing Modules in JavaScript</strong></p>
<p><strong>Exporting from a module (utils.js):</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a * b;
}
</code></pre>
<p><strong>Importing in another file (main.js):</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { add, multiply } <span class="hljs-keyword">from</span> <span class="hljs-string">'./utils.js'</span>;

<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));       <span class="hljs-comment">// Output: 5</span>
<span class="hljs-built_in">console</span>.log(multiply(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));  <span class="hljs-comment">// Output: 6</span>
</code></pre>
<p><strong>CommonJS</strong> uses <code>module.exports</code> and <code>require()</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// utils.js</span>
<span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-attr">add</span>: <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b,
    <span class="hljs-attr">multiply</span>: <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a * b,
};

<span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">const</span> { add, multiply } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./utils'</span>);
<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));       <span class="hljs-comment">// Output: 5</span>
<span class="hljs-built_in">console</span>.log(multiply(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));  <span class="hljs-comment">// Output: 6</span>
</code></pre>
<p><strong>Python</strong>: Python organizes reusable code into <strong>modules</strong> and <strong>packages</strong>. A module is simply a <code>.py</code> file, and a package is a directory containing a special <code>__init__.py</code> file, which can include one or more modules.</p>
<p><strong>Example: Exporting and Importing Modules in Python</strong></p>
<p><strong>Exporting from a module (</strong><a target="_blank" href="http://utils.py"><strong>utils.py</strong></a><strong>):</strong></p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a + b

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a * b
</code></pre>
<p><strong>Importing in another file (</strong><a target="_blank" href="http://main.py"><strong>main.py</strong></a><strong>):</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> utils <span class="hljs-keyword">import</span> add, multiply

print(add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>))       <span class="hljs-comment"># Output: 5</span>
print(multiply(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>))  <span class="hljs-comment"># Output: 6</span>
</code></pre>
<p>Python uses <code>import</code> for loading modules and supports relative imports for packages.</p>
<h3 id="heading-package-managers-npm-vs-pip">Package Managers: NPM vs. pip</h3>
<p>Both languages provide package managers for installing and managing third-party libraries and dependencies.</p>
<p><strong>NPM (JavaScript)</strong>:</p>
<ul>
<li><p><strong>Node Package Manager (NPM)</strong> is JavaScript’s default package manager, and it comes bundled with Node.js.</p>
</li>
<li><p>It uses a <code>package.json</code> file to define dependencies, scripts, and metadata for a project.</p>
</li>
</ul>
<p><strong>Example: Installing a Library with NPM</strong></p>
<pre><code class="lang-javascript">npm install express
</code></pre>
<p><strong>Example: Defining Dependencies in package.json</strong></p>
<pre><code class="lang-javascript">{
    <span class="hljs-string">"dependencies"</span>: {
        <span class="hljs-string">"express"</span>: <span class="hljs-string">"^4.18.2"</span>
    }
}
</code></pre>
<p><strong>pip (Python)</strong>:</p>
<ul>
<li><p>Python uses <strong>pip</strong> (Python Installer Package) to manage libraries and frameworks.</p>
</li>
<li><p>Python projects commonly use a <code>requirements.txt</code> file to list dependencies.</p>
</li>
</ul>
<p><strong>Example: Installing a Library with pip</strong></p>
<pre><code class="lang-python">pip install flask
</code></pre>
<p><strong>Example: Defining Dependencies in requirements.txt</strong></p>
<pre><code class="lang-python">flask==<span class="hljs-number">2.3</span><span class="hljs-number">.0</span>
requests==<span class="hljs-number">2.31</span><span class="hljs-number">.0</span>
</code></pre>
<p>To install all dependencies in <code>requirements.txt</code>:</p>
<pre><code class="lang-python">bashCopy codepip install -r requirements.txt
</code></pre>
<p><strong>Comparison</strong>:</p>
<ul>
<li><p>NPM allows version ranges and automatically creates <code>node_modules</code> to manage dependencies. It also supports both development (<code>--save-dev</code>) and production dependencies.</p>
</li>
<li><p>pip installs libraries globally or in a virtual environment but lacks the automatic distinction between dev and production dependencies, which must be handled manually.</p>
</li>
</ul>
<h3 id="heading-managing-dependencies-in-python-with-virtual-environments">Managing Dependencies in Python with Virtual Environments</h3>
<p>Python has a unique feature for isolating dependencies: <strong>virtual environments</strong>. Virtual environments ensure that dependencies for one project don’t interfere with another, avoiding conflicts.</p>
<p><strong>Creating a Virtual Environment</strong>:</p>
<pre><code class="lang-bash">python -m venv myenv
</code></pre>
<p><strong>Activating the Virtual Environment</strong>:</p>
<ul>
<li><strong>Windows</strong>:</li>
</ul>
<pre><code class="lang-bash">myenv\Scripts\activate
</code></pre>
<ul>
<li><strong>macOS/Linux</strong>:</li>
</ul>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> myenv/bin/activate
</code></pre>
<p><strong>Installing Libraries in the Virtual Environment</strong>:</p>
<pre><code class="lang-bash">pip install flask
</code></pre>
<p><strong>Deactivating the Virtual Environment</strong>:</p>
<pre><code class="lang-bash">deactivate
</code></pre>
<p><strong>JavaScript Alternative</strong>: While JavaScript does not require virtual environments, tools like <code>nvm</code> (Node Version Manager) can be used to manage different Node.js versions for projects.</p>
<h3 id="heading-project-structures-and-best-practices">Project Structures and Best Practices</h3>
<p><strong>JavaScript Project Structure</strong>: A typical Node.js project includes:</p>
<pre><code class="lang-javascript">my-node-project/
├── node_modules/  # Installed dependencies
├── src/           # Source code
│   ├── app.js     # Entry point
│   ├── utils.js   # Utility <span class="hljs-built_in">module</span>
├── package.json   # Dependency and project metadata
├── package-lock.json  # Dependency tree <span class="hljs-keyword">for</span> consistency
</code></pre>
<p><strong>Python Project Structure</strong>: A typical Python project includes:</p>
<pre><code class="lang-python">my-python-project/
├── venv/            <span class="hljs-comment"># Virtual environment</span>
├── src/             <span class="hljs-comment"># Source code</span>
│   ├── __init__.py  <span class="hljs-comment"># Package initializer</span>
│   ├── app.py       <span class="hljs-comment"># Entry point</span>
│   ├── utils.py     <span class="hljs-comment"># Utility module</span>
├── requirements.txt <span class="hljs-comment"># Dependency list</span>
</code></pre>
<h4 id="heading-key-takeaways-5">Key Takeaways:</h4>
<ol>
<li><p><strong>Modules</strong>: Both languages support modular programming. Python modules are simple <code>.py</code> files, while JavaScript has both CommonJS and ES6 modules.</p>
</li>
<li><p><strong>Package Managers</strong>: NPM and pip serve similar purposes but have different approaches. NPM is more feature-rich, supporting scripts and version management, while pip is simpler but relies on virtual environments for isolation.</p>
</li>
<li><p><strong>Dependency Isolation</strong>: Python’s virtual environments ensure clean project separation, a feature not natively required in JavaScript due to its global Node.js architecture.</p>
</li>
</ol>
<h2 id="heading-9-error-handling-and-debugging">9. <strong>Error Handling and Debugging</strong></h2>
<p>Error handling and debugging are critical for writing robust and maintainable code. Both Python and JavaScript provide mechanisms for catching and managing errors, but they handle these tasks differently. Understanding these mechanisms is essential for developers transitioning between the two languages.</p>
<h3 id="heading-exception-handling-in-python-vs-error-handling-in-javascript">Exception Handling in Python vs. Error Handling in JavaScript</h3>
<p>Both Python and JavaScript use <code>try</code>-<code>except</code> (or <code>try</code>-<code>catch</code> in JavaScript) blocks to handle errors. These constructs allow developers to catch exceptions, manage them gracefully, and prevent program crashes.</p>
<p><strong>Python Exception Handling</strong>: Python uses <code>try</code>, <code>except</code>, and <code>finally</code> to handle exceptions. The <code>else</code> clause can also be used to execute code only if no exceptions occur.</p>
<p><strong>Example: Python Exception Handling</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    result = <span class="hljs-number">10</span> / <span class="hljs-number">0</span>
<span class="hljs-keyword">except</span> ZeroDivisionError <span class="hljs-keyword">as</span> e:
    print(<span class="hljs-string">f"Error: <span class="hljs-subst">{e}</span>"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"No errors occurred!"</span>)
<span class="hljs-keyword">finally</span>:
    print(<span class="hljs-string">"Execution complete."</span>)
<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># Error: division by zero</span>
<span class="hljs-comment"># Execution complete.</span>
</code></pre>
<p><strong>Key Features of Python Exception Handling</strong>:</p>
<ol>
<li><p><strong>Specific Exceptions</strong>: Python allows catching specific exceptions like <code>ZeroDivisionError</code>, making error handling more precise.</p>
</li>
<li><p><strong>Optional Else Block</strong>: The <code>else</code> block runs if no exceptions are raised, which can simplify code logic.</p>
</li>
</ol>
<p><strong>JavaScript Error Handling</strong>: JavaScript uses <code>try</code>, <code>catch</code>, and <code>finally</code> for error handling. Errors can be thrown manually using the <code>throw</code> keyword.</p>
<p><strong>Example: JavaScript Error Handling</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-number">10</span> / <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">isFinite</span>(result)) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Division by zero is not allowed."</span>);
    }
} <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error: <span class="hljs-subst">${error.message}</span>`</span>);
} <span class="hljs-keyword">finally</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Execution complete."</span>);
}
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Error: Division by zero is not allowed.</span>
<span class="hljs-comment">// Execution complete.</span>
</code></pre>
<p><strong>Key Features of JavaScript Error Handling</strong>:</p>
<ol>
<li><p><strong>Generic Catch Block</strong>: JavaScript's <code>catch</code> block catches all errors by default. To handle specific error types, manual checks are needed.</p>
</li>
<li><p><strong>Error Object</strong>: JavaScript provides an <code>Error</code> object with properties like <code>message</code>, <code>name</code>, and <code>stack</code> for debugging.</p>
</li>
</ol>
<h3 id="heading-common-errors-and-how-to-debug-them">Common Errors and How to Debug Them</h3>
<p>Both Python and JavaScript have common runtime errors, but their debugging tools and techniques differ.</p>
<p><strong>Python Common Errors</strong>:</p>
<ol>
<li><p><strong>SyntaxError</strong>: Occurs when code violates Python's syntax rules.</p>
<pre><code class="lang-python"> print(<span class="hljs-string">"Hello World"</span>  <span class="hljs-comment"># Missing closing parenthesis</span>
</code></pre>
</li>
<li><p><strong>TypeError</strong>: Raised when an operation is applied to an object of inappropriate type.</p>
<pre><code class="lang-python"> print(<span class="hljs-string">"Hello"</span> + <span class="hljs-number">5</span>)  <span class="hljs-comment"># Cannot concatenate str and int</span>
</code></pre>
</li>
<li><p><strong>ValueError</strong>: Raised when a function receives an argument of the correct type but invalid value.</p>
<pre><code class="lang-python"> int(<span class="hljs-string">"abc"</span>)  <span class="hljs-comment"># Cannot convert string to int</span>
</code></pre>
</li>
</ol>
<p><strong>Debugging in Python</strong>:</p>
<ul>
<li><p><strong>Stack Trace</strong>: Python provides a detailed stack trace when an exception occurs, showing the file, line number, and call stack.</p>
</li>
<li><p><strong>Logging</strong>: Python’s <code>logging</code> module helps record errors and program state.</p>
<pre><code class="lang-python">  <span class="hljs-keyword">import</span> logging
  logging.basicConfig(level=logging.ERROR)
  logging.error(<span class="hljs-string">"An error occurred."</span>)
</code></pre>
</li>
<li><p><strong>Debuggers</strong>: Tools like <code>pdb</code> (Python Debugger) allow stepping through code to inspect variables.</p>
<pre><code class="lang-python">  <span class="hljs-keyword">import</span> pdb; pdb.set_trace()
</code></pre>
</li>
</ul>
<p><strong>JavaScript Common Errors</strong>:</p>
<ol>
<li><p><strong>SyntaxError</strong>: Thrown when code violates JavaScript's syntax rules.</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World"</span> <span class="hljs-comment">// Missing closing parenthesis</span>
</code></pre>
</li>
<li><p><strong>TypeError</strong>: Occurs when an operation is performed on an undefined or incompatible type.</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span> + <span class="hljs-number">5</span>); <span class="hljs-comment">// Allowed, but accessing a method on null is a TypeError</span>
</code></pre>
</li>
<li><p><strong>ReferenceError</strong>: Thrown when accessing a variable that hasn’t been declared.</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// x is not defined</span>
</code></pre>
</li>
</ol>
<p><strong>Debugging in JavaScript</strong>:</p>
<ul>
<li><p><strong>Stack Trace</strong>: JavaScript errors include a stack trace, showing the error type and line number.</p>
</li>
<li><p><strong>Console Logging</strong>: The <code>console.log</code> and <code>console.error</code> methods are often used for debugging.</p>
<pre><code class="lang-javascript">  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Variable value:"</span>, myVar);
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"An error occurred."</span>);
</code></pre>
</li>
<li><p><strong>Browser DevTools</strong>: Modern browsers include developer tools with JavaScript debuggers, allowing you to set breakpoints, step through code, and inspect variables.</p>
</li>
<li><p><strong>Debugging with Node.js</strong>: Use the <code>--inspect</code> flag to debug Node.js applications with Chrome DevTools.</p>
<pre><code class="lang-bash">  node --inspect app.js
</code></pre>
</li>
</ul>
<h3 id="heading-tools-for-debugging">Tools for Debugging</h3>
<p>Both Python and JavaScript have robust tools for debugging, ranging from built-in modules to integrated development environments (IDEs).</p>
<p><strong>Python Debugging Tools</strong>:</p>
<ol>
<li><p><strong>Built-In Debugger (</strong><code>pdb</code>): A command-line tool for inspecting and controlling execution.</p>
</li>
<li><p><strong>IDE Debugging</strong>: IDEs like PyCharm and VS Code provide graphical debugging with breakpoints and variable inspection.</p>
</li>
<li><p><strong>Logging</strong>: The <code>logging</code> module can be configured to capture detailed runtime information.</p>
</li>
</ol>
<p><strong>JavaScript Debugging Tools</strong>:</p>
<ol>
<li><p><strong>Browser Developer Tools</strong>: Chrome DevTools, Firefox Developer Tools, and Edge DevTools are indispensable for frontend debugging.</p>
</li>
<li><p><strong>Node.js Debugger</strong>: Debug Node.js applications using <code>node inspect</code> or <code>--inspect</code> with a compatible debugger like Chrome DevTools.</p>
</li>
<li><p><strong>Third-Party Tools</strong>: Tools like ESLint help catch errors before runtime by enforcing coding standards and highlighting potential issues.</p>
</li>
</ol>
<h4 id="heading-key-takeaways-6">Key Takeaways:</h4>
<ul>
<li><p><strong>Error Handling Syntax</strong>: Both Python and JavaScript use <code>try</code>-<code>catch</code> constructs, but Python’s <code>except</code> supports catching specific exception types.</p>
</li>
<li><p><strong>Debugging Approaches</strong>: Python relies heavily on logging and the <code>pdb</code> debugger, while JavaScript benefits from browser DevTools and real-time inspection.</p>
</li>
<li><p><strong>Common Errors</strong>: Syntax and type-related errors are common in both languages, but Python’s explicit type system provides clearer error messages compared to JavaScript’s looser type handling.</p>
</li>
<li><p><strong>Tools</strong>: Each language has a rich ecosystem of debugging tools tailored to its common use cases.</p>
</li>
</ul>
<h2 id="heading-10-testing-and-frameworks">10. <strong>Testing and Frameworks</strong></h2>
<p>Testing is an integral part of software development, ensuring that applications behave as expected and reducing the likelihood of bugs. Both Python and JavaScript have robust ecosystems for testing, offering various frameworks and tools to streamline the process.</p>
<h3 id="heading-popular-testing-frameworks-mochachai-vs-pytestunittest">Popular Testing Frameworks: Mocha/Chai vs. Pytest/Unittest</h3>
<p>Both Python and JavaScript have multiple testing frameworks, each tailored to specific needs. For JavaScript, <strong>Mocha</strong> and <strong>Chai</strong> are popular choices, while Python developers often use <strong>Pytest</strong> or the built-in <strong>Unittest</strong> module.</p>
<p><strong>JavaScript: Mocha and Chai</strong><br>Mocha is a flexible testing framework for JavaScript, and Chai is often paired with it to provide assertion libraries for more readable test cases.</p>
<p><strong>Example: Mocha and Chai</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { expect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'chai'</span>);

<span class="hljs-comment">// Function to test</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-comment">// Mocha test</span>
describe(<span class="hljs-string">'Add Function'</span>, <span class="hljs-function">() =&gt;</span> {
    it(<span class="hljs-string">'should return the sum of two numbers'</span>, <span class="hljs-function">() =&gt;</span> {
        expect(add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)).to.equal(<span class="hljs-number">5</span>);
    });

    it(<span class="hljs-string">'should handle negative numbers'</span>, <span class="hljs-function">() =&gt;</span> {
        expect(add(<span class="hljs-number">-2</span>, <span class="hljs-number">-3</span>)).to.equal(<span class="hljs-number">-5</span>);
    });
});
</code></pre>
<p><strong>Python: Pytest</strong><br>Pytest is a widely used framework in Python that emphasizes simplicity and flexibility. Tests can be written as plain functions, and Pytest’s built-in fixtures streamline setup and teardown.</p>
<p><strong>Example: Pytest</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pytest

<span class="hljs-comment"># Function to test</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a + b

<span class="hljs-comment"># Pytest functions</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_add_positive_numbers</span>():</span>
    <span class="hljs-keyword">assert</span> add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) == <span class="hljs-number">5</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_add_negative_numbers</span>():</span>
    <span class="hljs-keyword">assert</span> add(<span class="hljs-number">-2</span>, <span class="hljs-number">-3</span>) == <span class="hljs-number">-5</span>
</code></pre>
<p><strong>Key Differences</strong>:</p>
<ol>
<li><p><strong>Syntax</strong>: Mocha/Chai uses JavaScript syntax with chaining assertions (<code>expect</code>), while Pytest relies on Python’s <code>assert</code> keyword.</p>
</li>
<li><p><strong>Fixtures</strong>: Pytest fixtures simplify test setup, whereas Mocha relies on manual setup functions (<code>before</code>, <code>beforeEach</code>).</p>
</li>
</ol>
<h3 id="heading-writing-unit-tests-and-test-coverage">Writing Unit Tests and Test Coverage</h3>
<p>Unit testing focuses on verifying individual components or functions in isolation. Both Python and JavaScript frameworks support unit tests, but the tools for measuring test coverage differ.</p>
<p><strong>JavaScript: nyc (Istanbul)</strong><br>The <code>nyc</code> tool, built on Istanbul, is commonly used to measure test coverage in JavaScript projects.</p>
<p><strong>Example: Generating Coverage Reports with Mocha and nyc</strong></p>
<pre><code class="lang-bash">npm install --save-dev mocha nyc
</code></pre>
<p>Add a test script to <code>package.json</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"mocha"</span>,
    <span class="hljs-string">"coverage"</span>: <span class="hljs-string">"nyc mocha"</span>
}
</code></pre>
<p>Run the coverage command:</p>
<pre><code class="lang-bash">npm run coverage
</code></pre>
<p>This generates a report showing which parts of the code were covered during tests.</p>
<p><strong>Python:</strong> <a target="_blank" href="http://Coverage.py"><strong>Coverage.py</strong></a><br>In Python, <a target="_blank" href="http://coverage.py"><code>coverage.py</code></a> is the standard tool for measuring test coverage.</p>
<p><strong>Example: Generating Coverage Reports with Pytest and</strong> <a target="_blank" href="http://Coverage.py"><strong>Coverage.py</strong></a></p>
<pre><code class="lang-bash">pip install pytest coverage
</code></pre>
<p>Run tests with coverage:</p>
<pre><code class="lang-bash">coverage run -m pytest
coverage report
</code></pre>
<p>This displays coverage percentages for each file and highlights untested lines.</p>
<p><strong>Key Differences</strong>:</p>
<ul>
<li>JavaScript tools like nyc integrate easily with CI/CD pipelines, while <a target="_blank" href="http://coverage.py"><code>coverage.py</code></a> provides detailed line-by-line reports.</li>
</ul>
<h3 id="heading-automation-and-cicd-compatibility">Automation and CI/CD Compatibility</h3>
<p>Modern development workflows often include automated testing integrated into CI/CD pipelines. Both Python and JavaScript testing frameworks are compatible with CI/CD tools like Jenkins, GitHub Actions, and GitLab CI.</p>
<p><strong>Example: Automating Tests in a CI/CD Pipeline</strong></p>
<p><strong>JavaScript (GitHub Actions)</strong>:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">name:</span> <span class="hljs-string">Node.js</span> <span class="hljs-string">CI</span>

<span class="hljs-attr">on:</span> [<span class="hljs-string">push</span>]

<span class="hljs-attr">jobs:</span>
  <span class="hljs-attr">test:</span>
    <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>
    <span class="hljs-attr">steps:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v2</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/setup-node@v2</span>
      <span class="hljs-attr">with:</span>
        <span class="hljs-attr">node-version:</span> <span class="hljs-string">'14'</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">npm</span> <span class="hljs-string">install</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">npm</span> <span class="hljs-string">test</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">npm</span> <span class="hljs-string">run</span> <span class="hljs-string">coverage</span>
</code></pre>
<p><strong>Python (GitHub Actions)</strong>:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">name:</span> <span class="hljs-string">Python</span> <span class="hljs-string">CI</span>

<span class="hljs-attr">on:</span> [<span class="hljs-string">push</span>]

<span class="hljs-attr">jobs:</span>
  <span class="hljs-attr">test:</span>
    <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>
    <span class="hljs-attr">steps:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v2</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/setup-python@v2</span>
      <span class="hljs-attr">with:</span>
        <span class="hljs-attr">python-version:</span> <span class="hljs-string">'3.9'</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">pip</span> <span class="hljs-string">install</span> <span class="hljs-string">-r</span> <span class="hljs-string">requirements.txt</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">run:</span> <span class="hljs-string">pytest</span> <span class="hljs-string">--cov=.</span>
</code></pre>
<h3 id="heading-integration-and-end-to-end-testing">Integration and End-to-End Testing</h3>
<p>In addition to unit testing, both languages support integration and end-to-end (E2E) testing.</p>
<p><strong>JavaScript: Cypress for E2E Testing</strong><br>Cypress is a popular tool for E2E testing of web applications, providing a developer-friendly interface and real-time browser interaction.</p>
<p><strong>Example: Cypress Test</strong></p>
<pre><code class="lang-javascript">describe(<span class="hljs-string">'Login Page'</span>, <span class="hljs-function">() =&gt;</span> {
    it(<span class="hljs-string">'should log in with valid credentials'</span>, <span class="hljs-function">() =&gt;</span> {
        cy.visit(<span class="hljs-string">'/login'</span>);
        cy.get(<span class="hljs-string">'#username'</span>).type(<span class="hljs-string">'user'</span>);
        cy.get(<span class="hljs-string">'#password'</span>).type(<span class="hljs-string">'password'</span>);
        cy.get(<span class="hljs-string">'button[type="submit"]'</span>).click();
        cy.url().should(<span class="hljs-string">'include'</span>, <span class="hljs-string">'/dashboard'</span>);
    });
});
</code></pre>
<p><strong>Python: Selenium for Browser Automation</strong><br>Selenium is commonly used in Python for E2E testing of web applications, automating browser interactions.</p>
<p><strong>Example: Selenium Test</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_login</span>():</span>
    driver = webdriver.Chrome()
    driver.get(<span class="hljs-string">"http://example.com/login"</span>)
    driver.find_element_by_id(<span class="hljs-string">"username"</span>).send_keys(<span class="hljs-string">"user"</span>)
    driver.find_element_by_id(<span class="hljs-string">"password"</span>).send_keys(<span class="hljs-string">"password"</span>)
    driver.find_element_by_css_selector(<span class="hljs-string">"button[type='submit']"</span>).click()
    <span class="hljs-keyword">assert</span> <span class="hljs-string">"dashboard"</span> <span class="hljs-keyword">in</span> driver.current_url
    driver.quit()
</code></pre>
<h4 id="heading-key-takeaways-7">Key Takeaways:</h4>
<ol>
<li><p><strong>Unit Testing</strong>: JavaScript (Mocha/Chai) and Python (Pytest) frameworks are highly flexible, but Pytest’s concise syntax makes it particularly beginner-friendly.</p>
</li>
<li><p><strong>Test Coverage</strong>: Both <code>nyc</code> (JavaScript) and <a target="_blank" href="http://coverage.py"><code>coverage.py</code></a> (Python) are effective for measuring test coverage and identifying gaps.</p>
</li>
<li><p><strong>E2E Testing</strong>: JavaScript developers can leverage Cypress for browser testing, while Python offers Selenium for automation.</p>
</li>
<li><p><strong>CI/CD Compatibility</strong>: Both languages integrate seamlessly with modern CI/CD pipelines, enabling automated testing at every stage of development.</p>
</li>
</ol>
<h2 id="heading-11-practical-applications-and-examples">11. <strong>Practical Applications and Examples</strong></h2>
<p>Both Python and JavaScript excel in various practical applications, but their strengths shine in different domains. This section explores common use cases for each language, providing hands-on examples to showcase their capabilities and differences.</p>
<h3 id="heading-writing-a-simple-web-scraper">Writing a Simple Web Scraper</h3>
<p><strong>Python: Using BeautifulSoup</strong><br>Python’s libraries, such as BeautifulSoup and Requests, make web scraping straightforward and efficient.</p>
<p><strong>Example: Web Scraper in Python</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup

<span class="hljs-comment"># Fetch the webpage</span>
url = <span class="hljs-string">"https://example.com"</span>
response = requests.get(url)

<span class="hljs-comment"># Parse the HTML content</span>
soup = BeautifulSoup(response.content, <span class="hljs-string">"html.parser"</span>)

<span class="hljs-comment"># Extract specific data</span>
titles = soup.find_all(<span class="hljs-string">"h2"</span>)
<span class="hljs-keyword">for</span> title <span class="hljs-keyword">in</span> titles:
    print(title.text)
</code></pre>
<p><strong>JavaScript: Using Puppeteer</strong><br>JavaScript can also scrape web content using libraries like Puppeteer, which allows headless browsing.</p>
<p><strong>Example: Web Scraper in JavaScript</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> puppeteer = <span class="hljs-built_in">require</span>(<span class="hljs-string">'puppeteer'</span>);

(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> browser = <span class="hljs-keyword">await</span> puppeteer.launch();
    <span class="hljs-keyword">const</span> page = <span class="hljs-keyword">await</span> browser.newPage();
    <span class="hljs-keyword">await</span> page.goto(<span class="hljs-string">'https://example.com'</span>);

    <span class="hljs-comment">// Extract specific data</span>
    <span class="hljs-keyword">const</span> titles = <span class="hljs-keyword">await</span> page.$$eval(<span class="hljs-string">'h2'</span>, <span class="hljs-function"><span class="hljs-params">elements</span> =&gt;</span> elements.map(<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el.textContent));
    <span class="hljs-built_in">console</span>.log(titles);

    <span class="hljs-keyword">await</span> browser.close();
})();
</code></pre>
<p><strong>Key Differences</strong>:</p>
<ul>
<li>Python’s BeautifulSoup is simpler for static pages, while Puppeteer provides more flexibility for dynamic content rendered by JavaScript.</li>
</ul>
<h3 id="heading-creating-a-rest-api">Creating a REST API</h3>
<p><strong>Python: Flask</strong><br>Python’s Flask framework is lightweight and ideal for quickly building APIs.</p>
<p><strong>Example: REST API in Python</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, jsonify

app = Flask(__name__)

<span class="hljs-meta">@app.route('/api/data', methods=['GET'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_data</span>():</span>
    <span class="hljs-keyword">return</span> jsonify({<span class="hljs-string">"message"</span>: <span class="hljs-string">"Hello, World!"</span>})

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    app.run(debug=<span class="hljs-literal">True</span>)
</code></pre>
<p><strong>JavaScript: Express</strong><br>Express is a popular framework for creating REST APIs in JavaScript.</p>
<p><strong>Example: REST API in JavaScript</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();

app.get(<span class="hljs-string">'/api/data'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Hello, World!'</span> });
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on port 3000'</span>);
});
</code></pre>
<p><strong>Key Differences</strong>:</p>
<ul>
<li><p>Flask offers built-in simplicity with decorators for routing.</p>
</li>
<li><p>Express requires more explicit configuration but is better suited for large-scale Node.js projects.</p>
</li>
</ul>
<h3 id="heading-automation-scripts-file-handling-network-requests-and-scripting">Automation Scripts: File Handling, Network Requests, and Scripting</h3>
<p><strong>Python: Automation with os and shutil</strong><br>Python excels at automation tasks, making file and system operations straightforward.</p>
<p><strong>Example: File Automation in Python</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> shutil

<span class="hljs-comment"># Create a directory</span>
os.makedirs(<span class="hljs-string">"example_dir"</span>, exist_ok=<span class="hljs-literal">True</span>)

<span class="hljs-comment"># Move a file</span>
shutil.move(<span class="hljs-string">"source.txt"</span>, <span class="hljs-string">"example_dir/destination.txt"</span>)

<span class="hljs-comment"># List files in a directory</span>
<span class="hljs-keyword">for</span> file <span class="hljs-keyword">in</span> os.listdir(<span class="hljs-string">"example_dir"</span>):
    print(file)
</code></pre>
<p><strong>JavaScript: File System Module (fs)</strong><br>JavaScript’s <code>fs</code> module allows file handling, but it requires more boilerplate.</p>
<p><strong>Example: File Automation in JavaScript</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);

<span class="hljs-comment">// Create a directory</span>
fs.mkdirSync(<span class="hljs-string">'example_dir'</span>, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> });

<span class="hljs-comment">// Move a file</span>
fs.renameSync(<span class="hljs-string">'source.txt'</span>, path.join(<span class="hljs-string">'example_dir'</span>, <span class="hljs-string">'destination.txt'</span>));

<span class="hljs-comment">// List files in a directory</span>
fs.readdirSync(<span class="hljs-string">'example_dir'</span>).forEach(<span class="hljs-function"><span class="hljs-params">file</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(file);
});
</code></pre>
<p><strong>Key Differences</strong>:</p>
<ul>
<li><p>Python’s <code>os</code> and <code>shutil</code> modules provide concise methods for file and system operations.</p>
</li>
<li><p>JavaScript requires more explicit handling for similar tasks using Node.js modules.</p>
</li>
</ul>
<h3 id="heading-data-processing-and-visualization">Data Processing and Visualization</h3>
<p><strong>Python: Data Science with Pandas and Matplotlib</strong><br>Python dominates data processing and visualization with libraries like Pandas and Matplotlib.</p>
<p><strong>Example: Data Analysis in Python</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt

<span class="hljs-comment"># Create a DataFrame</span>
data = {<span class="hljs-string">'Name'</span>: [<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Charlie'</span>], <span class="hljs-string">'Age'</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">35</span>]}
df = pd.DataFrame(data)

<span class="hljs-comment"># Plot the data</span>
df.plot(x=<span class="hljs-string">'Name'</span>, y=<span class="hljs-string">'Age'</span>, kind=<span class="hljs-string">'bar'</span>)
plt.show()
</code></pre>
<p><strong>JavaScript: Data Visualization with D3.js</strong><br>JavaScript excels at interactive web-based visualizations with D3.js.</p>
<p><strong>Example: Data Visualization in JavaScript</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> d3 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'d3'</span>);
<span class="hljs-keyword">const</span> data = [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Bob'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Charlie'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">35</span> }
];

<span class="hljs-keyword">const</span> svg = d3.create(<span class="hljs-string">"svg"</span>)
    .attr(<span class="hljs-string">"width"</span>, <span class="hljs-number">500</span>)
    .attr(<span class="hljs-string">"height"</span>, <span class="hljs-number">300</span>);

svg.selectAll(<span class="hljs-string">"rect"</span>)
    .data(data)
    .enter()
    .append(<span class="hljs-string">"rect"</span>)
    .attr(<span class="hljs-string">"x"</span>, <span class="hljs-function">(<span class="hljs-params">d, i</span>) =&gt;</span> i * <span class="hljs-number">100</span>)
    .attr(<span class="hljs-string">"y"</span>, <span class="hljs-function"><span class="hljs-params">d</span> =&gt;</span> <span class="hljs-number">300</span> - d.age * <span class="hljs-number">5</span>)
    .attr(<span class="hljs-string">"width"</span>, <span class="hljs-number">50</span>)
    .attr(<span class="hljs-string">"height"</span>, <span class="hljs-function"><span class="hljs-params">d</span> =&gt;</span> d.age * <span class="hljs-number">5</span>);

<span class="hljs-built_in">console</span>.log(svg.node().outerHTML);
</code></pre>
<p><strong>Key Differences</strong>:</p>
<ul>
<li><p>Python’s data libraries are geared toward analysis and are simpler for static visualizations.</p>
</li>
<li><p>JavaScript’s D3.js creates highly interactive visualizations for web applications.</p>
</li>
</ul>
<h3 id="heading-machine-learning-and-ai">Machine Learning and AI</h3>
<p><strong>Python: TensorFlow</strong><br>Python’s TensorFlow library simplifies building machine learning models.</p>
<p><strong>Example: Machine Learning in Python</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf

<span class="hljs-comment"># Define a simple model</span>
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=<span class="hljs-number">1</span>, input_shape=[<span class="hljs-number">1</span>])
])

model.compile(optimizer=<span class="hljs-string">'sgd'</span>, loss=<span class="hljs-string">'mean_squared_error'</span>)

<span class="hljs-comment"># Train the model</span>
xs = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
ys = [<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>]
model.fit(xs, ys, epochs=<span class="hljs-number">500</span>, verbose=<span class="hljs-number">0</span>)

<span class="hljs-comment"># Predict</span>
print(model.predict([<span class="hljs-number">5</span>]))  <span class="hljs-comment"># Output: [[10]]</span>
</code></pre>
<p><strong>JavaScript: TensorFlow.js</strong><br>TensorFlow.js brings machine learning capabilities to JavaScript.</p>
<p><strong>Example: Machine Learning in JavaScript</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> tf = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@tensorflow/tfjs-node'</span>);

<span class="hljs-comment">// Define a simple model</span>
<span class="hljs-keyword">const</span> model = tf.sequential();
model.add(tf.layers.dense({ <span class="hljs-attr">units</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">inputShape</span>: [<span class="hljs-number">1</span>] }));
model.compile({ <span class="hljs-attr">optimizer</span>: <span class="hljs-string">'sgd'</span>, <span class="hljs-attr">loss</span>: <span class="hljs-string">'meanSquaredError'</span> });

<span class="hljs-comment">// Train the model</span>
<span class="hljs-keyword">const</span> xs = tf.tensor([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
<span class="hljs-keyword">const</span> ys = tf.tensor([<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>]);
model.fit(xs, ys, { <span class="hljs-attr">epochs</span>: <span class="hljs-number">500</span> }).then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Predict</span>
    model.predict(tf.tensor([<span class="hljs-number">5</span>])).print();  <span class="hljs-comment">// Output: [[10]]</span>
});
</code></pre>
<p><strong>Key Differences</strong>:</p>
<ul>
<li><p>Python dominates in machine learning due to its mature ecosystem and extensive documentation.</p>
</li>
<li><p>TensorFlow.js allows machine learning in JavaScript, but it is less mature compared to Python’s TensorFlow.</p>
</li>
</ul>
<h4 id="heading-key-takeaways-8">Key Takeaways:</h4>
<ul>
<li><p><strong>Web Scraping</strong>: Python excels with BeautifulSoup for static content, while Puppeteer is better for dynamic content.</p>
</li>
<li><p><strong>REST APIs</strong>: Python’s Flask is lightweight and easy to use, while JavaScript’s Express offers flexibility and scalability.</p>
</li>
<li><p><strong>Automation</strong>: Python simplifies file and system operations with <code>os</code> and <code>shutil</code>, while JavaScript achieves similar results with Node.js modules.</p>
</li>
<li><p><strong>Data Visualization</strong>: Python’s libraries focus on analysis, while JavaScript’s D3.js creates interactive, web-based visualizations.</p>
</li>
<li><p><strong>Machine Learning</strong>: Python leads with TensorFlow and other ML frameworks, while TensorFlow.js brings ML capabilities to JavaScript.</p>
</li>
</ul>
<h2 id="heading-12-community-libraries-and-ecosystem">12. <strong>Community, Libraries, and Ecosystem</strong></h2>
<p>The strength of a programming language often lies in its community, ecosystem, and the libraries available for solving common problems. Both Python and JavaScript have vast ecosystems supported by active communities, but they cater to different domains and developer needs.</p>
<h3 id="heading-open-source-libraries-npm-vs-pypi">Open Source Libraries: NPM vs. PyPI</h3>
<p>Both Python and JavaScript have centralized repositories for distributing and installing open-source libraries: <strong>PyPI (Python Package Index)</strong> for Python and <strong>NPM (Node Package Manager)</strong> for JavaScript.</p>
<p><strong>Python: PyPI</strong></p>
<ul>
<li><p>PyPI hosts over 400,000 packages, supporting fields like data science, web development, machine learning, and automation.</p>
</li>
<li><p>Popular libraries include:</p>
<ul>
<li><p><strong>Pandas</strong> for data manipulation.</p>
</li>
<li><p><strong>NumPy</strong> for numerical computing.</p>
</li>
<li><p><strong>Django</strong> and <strong>Flask</strong> for web development.</p>
</li>
<li><p><strong>BeautifulSoup</strong> and <strong>Scrapy</strong> for web scraping.</p>
</li>
</ul>
</li>
</ul>
<p><strong>Example: Installing and Using a PyPI Library</strong></p>
<pre><code class="lang-bash">pip install requests
</code></pre>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests

response = requests.get(<span class="hljs-string">"https://api.example.com/data"</span>)
print(response.json())
</code></pre>
<p><strong>JavaScript: NPM</strong></p>
<ul>
<li><p>NPM is the world’s largest software registry, with over 2 million packages for frontend, backend, and full-stack development.</p>
</li>
<li><p>Popular libraries include:</p>
<ul>
<li><p><strong>React</strong> and <strong>Vue</strong> for frontend development.</p>
</li>
<li><p><strong>Express</strong> for backend services.</p>
</li>
<li><p><strong>Lodash</strong> for utility functions.</p>
</li>
<li><p><strong>Axios</strong> for HTTP requests.</p>
</li>
</ul>
</li>
</ul>
<p><strong>Example: Installing and Using an NPM Library</strong></p>
<pre><code class="lang-bash">npm install axios
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> axios = <span class="hljs-built_in">require</span>(<span class="hljs-string">'axios'</span>);

axios.get(<span class="hljs-string">'https://api.example.com/data'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data));
</code></pre>
<p><strong>Comparison</strong>:</p>
<ul>
<li><p><strong>Breadth</strong>: NPM focuses on web development, while PyPI covers a wider range of domains, including data science and scientific research.</p>
</li>
<li><p><strong>Tools</strong>: NPM’s CLI offers additional functionality like scripts and versioning, while pip focuses purely on library installation.</p>
</li>
</ul>
<h3 id="heading-key-libraries-for-data-science-web-development-and-automation">Key Libraries for Data Science, Web Development, and Automation</h3>
<p>Both ecosystems excel in their respective strengths:</p>
<p><strong>Data Science</strong>:</p>
<ul>
<li><p>Python dominates with libraries like Pandas, Matplotlib, and TensorFlow, making it the top choice for data manipulation, visualization, and machine learning.</p>
</li>
<li><p>JavaScript has D3.js for interactive visualizations and TensorFlow.js for machine learning, though its ecosystem for data science is less mature.</p>
</li>
</ul>
<p><strong>Web Development</strong>:</p>
<ul>
<li><p>JavaScript is unrivaled in frontend development with React, Vue, and Angular. For backend services, Node.js with Express is a common choice.</p>
</li>
<li><p>Python excels in backend web development with frameworks like Django and Flask, offering rapid development and scalability.</p>
</li>
</ul>
<p><strong>Automation</strong>:</p>
<ul>
<li><p>Python is widely used for scripting and automation, with libraries like <code>os</code>, <code>shutil</code>, and <code>schedule</code>.</p>
</li>
<li><p>JavaScript, while less focused on automation, can handle automation tasks effectively with Node.js and tools like Puppeteer for browser automation.</p>
</li>
</ul>
<h3 id="heading-pythons-strengths-in-data-science-and-machine-learning">Python's Strengths in Data Science and Machine Learning</h3>
<p>Python has established itself as the go-to language for data science and machine learning due to its extensive ecosystem and user-friendly syntax.</p>
<p><strong>Popular Python Libraries for Data Science</strong>:</p>
<ol>
<li><p><strong>Pandas</strong>: Data manipulation and analysis.</p>
</li>
<li><p><strong>NumPy</strong>: Numerical computing and arrays.</p>
</li>
<li><p><strong>Matplotlib/Seaborn</strong>: Data visualization.</p>
</li>
<li><p><strong>Scikit-learn</strong>: Machine learning algorithms.</p>
</li>
<li><p><strong>TensorFlow/Keras</strong>: Deep learning frameworks.</p>
</li>
</ol>
<p><strong>Example: Data Analysis with Pandas</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {<span class="hljs-string">'Name'</span>: [<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Charlie'</span>], <span class="hljs-string">'Age'</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">35</span>]}
df = pd.DataFrame(data)

print(df.describe())
</code></pre>
<p><strong>Machine Learning with TensorFlow</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf

model = tf.keras.Sequential([tf.keras.layers.Dense(units=<span class="hljs-number">1</span>, input_shape=[<span class="hljs-number">1</span>])])
model.compile(optimizer=<span class="hljs-string">'sgd'</span>, loss=<span class="hljs-string">'mean_squared_error'</span>)
model.fit([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], [<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>], epochs=<span class="hljs-number">500</span>)
print(model.predict([<span class="hljs-number">5</span>]))
</code></pre>
<p>Python’s simplicity makes it easy for non-programmers, such as data analysts and researchers, to leverage these powerful tools.</p>
<h3 id="heading-javascripts-strengths-in-web-development">JavaScript's Strengths in Web Development</h3>
<p>JavaScript’s dominance in web development stems from its ability to run natively in the browser and its wide array of frontend frameworks.</p>
<p><strong>Popular JavaScript Libraries for Web Development</strong>:</p>
<ol>
<li><p><strong>React</strong>: Component-based UI development.</p>
</li>
<li><p><strong>Vue</strong>: Simple and progressive framework for building UIs.</p>
</li>
<li><p><strong>Angular</strong>: Comprehensive framework for large-scale applications.</p>
</li>
<li><p><strong>Express</strong>: Lightweight framework for creating REST APIs.</p>
</li>
<li><p><strong>Next.js</strong>: Full-stack framework for React applications with server-side rendering.</p>
</li>
</ol>
<p><strong>Example: Creating a Frontend with React</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));
</code></pre>
<p><strong>Example: Creating a Backend with Express</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.send(<span class="hljs-string">'Hello, World!'</span>);
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on port 3000'</span>);
});
</code></pre>
<p>JavaScript’s ecosystem allows developers to build full-stack applications using a single language, streamlining development workflows.</p>
<h3 id="heading-community-support-and-contribution">Community Support and Contribution</h3>
<p>Both Python and JavaScript have vibrant communities that contribute to their continuous growth and evolution:</p>
<ol>
<li><p><strong>Python</strong>:</p>
<ul>
<li><p>Python Software Foundation (PSF) drives the language's development.</p>
</li>
<li><p>Annual events like PyCon foster collaboration and learning.</p>
</li>
<li><p>Strong academic adoption ensures its popularity in education and research.</p>
</li>
</ul>
</li>
<li><p><strong>JavaScript</strong>:</p>
<ul>
<li><p>Backed by major organizations like Node.js Foundation and open-source communities.</p>
</li>
<li><p>Events like JSConf and React Conf promote innovation.</p>
</li>
<li><p>A highly active GitHub community ensures frequent updates and new libraries.</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-13-conclusion">13. <strong>Conclusion</strong></h2>
<p>Python and JavaScript are two of the most popular and versatile programming languages in the world. Each language has its own strengths, use cases, and ecosystems, making them ideal for different types of projects.</p>
<p>For experienced JavaScript developers, learning Python can open up new opportunities in fields like data science, machine learning, and automation, complementing their existing skills in web development and real-time applications.</p>
<h3 id="heading-summary-of-key-comparisons">Summary of Key Comparisons</h3>
<ol>
<li><p><strong>Syntax</strong>:</p>
<ul>
<li><p>Python emphasizes simplicity and readability with its indentation-based syntax, making it easier to learn and maintain.</p>
</li>
<li><p>JavaScript’s flexibility allows multiple paradigms, but its quirks, like type coercion, require careful handling.</p>
</li>
</ul>
</li>
<li><p><strong>Asynchronous Programming</strong>:</p>
<ul>
<li><p>JavaScript is inherently asynchronous, with its event-driven model excelling in real-time applications.</p>
</li>
<li><p>Python’s <code>asyncio</code> library is newer but powerful for handling I/O-bound tasks.</p>
</li>
</ul>
</li>
<li><p><strong>OOP</strong>:</p>
<ul>
<li><p>Python’s class-based system is more traditional and explicit.</p>
</li>
<li><p>JavaScript offers both prototypal inheritance and class-based syntax, providing flexibility.</p>
</li>
</ul>
</li>
<li><p><strong>Modules and Dependency Management</strong>:</p>
<ul>
<li><p>Python’s <code>pip</code> and virtual environments excel at dependency isolation.</p>
</li>
<li><p>JavaScript’s NPM is more versatile, with integrated features like script management.</p>
</li>
</ul>
</li>
<li><p><strong>Testing</strong>:</p>
<ul>
<li><p>Python’s Pytest emphasizes simplicity and readability.</p>
</li>
<li><p>JavaScript’s Mocha/Chai is highly flexible and integrates well with modern development pipelines.</p>
</li>
</ul>
</li>
<li><p><strong>Ecosystem and Community</strong>:</p>
<ul>
<li><p>Python dominates in data science, machine learning, and scripting.</p>
</li>
<li><p>JavaScript is unmatched in web development, particularly for full-stack and frontend applications.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-how-python-complements-javascript-skills">How Python Complements JavaScript Skills</h3>
<p>For JavaScript developers, Python can expand your horizons in several ways:</p>
<ul>
<li><p><strong>Data Science and Machine Learning</strong>: Python’s libraries like Pandas, TensorFlow, and Scikit-learn allow you to explore fields beyond traditional programming.</p>
</li>
<li><p><strong>Backend Development</strong>: Frameworks like Flask and Django provide a new perspective on backend services compared to Node.js.</p>
</li>
<li><p><strong>Automation and Scripting</strong>: Python’s simplicity makes it ideal for automating repetitive tasks, from file handling to web scraping.</p>
</li>
</ul>
<p>By adding Python to your skill set, you can become a more versatile developer, capable of tackling projects that require both web development expertise and computational power.</p>
<h3 id="heading-resources-and-next-steps-for-learning-python">Resources and Next Steps for Learning Python</h3>
<p>Here are some recommended resources to start learning Python:</p>
<ol>
<li><p><strong>Official Python Documentation</strong>: Comprehensive guides and tutorials for all skill levels: <a target="_blank" href="https://docs.python.org/">https://docs.python.org/</a></p>
</li>
<li><p><strong>Books</strong>:</p>
<ul>
<li><p><em>Automate the Boring Stuff with Python</em> by Al Sweigart (great for automation and scripting).</p>
</li>
<li><p><em>Python Crash Course</em> by Eric Matthes (a beginner-friendly introduction).</p>
</li>
</ul>
</li>
<li><p><strong>Online Courses</strong>:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/python-for-everybody/">Python for Everybody</a> from Dr. Chuck on freeCodeCamp’s YouTube channel</p>
</li>
<li><p>Check out <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/">freeCodeCamp’s Python certs</a></p>
</li>
</ul>
</li>
<li><p><strong>Practice Platforms</strong>:</p>
<ul>
<li>Solve Python problems on platforms like LeetCode, HackerRank, and Codewars.</li>
</ul>
</li>
<li><p><strong>Communities</strong>:</p>
<ul>
<li>Join Python forums and communities such as r/Python on Reddit or the Python Discord server.</li>
</ul>
</li>
</ol>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>As a JavaScript developer, you already have a strong foundation in programming. Python’s clean syntax, extensive libraries, and focus on readability make it an excellent language to learn next.</p>
<p>By understanding how Python complements JavaScript, you can choose the best tool for each task and position yourself as a well-rounded developer in today’s competitive landscape.</p>
<p>The journey to mastering Python will not only broaden your technical skills but also open doors to exciting domains like data science, machine learning, and automation, allowing you to tackle diverse challenges with confidence.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Style a React Application – Different Options Compared ]]>
                </title>
                <description>
                    <![CDATA[ Styling plays a vital role in creating visually appealing and user-friendly web applications. When it comes to React applications, there are numerous ways to style components and UI elements. In this article, we will explore several popular options, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-style-a-react-app/</link>
                <guid isPermaLink="false">66d45f049208fb118cc6cf9d</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 05 Jun 2023 21:52:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/pawel-czerwinski-3k9PGKWt7ik-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Styling plays a vital role in creating visually appealing and user-friendly web applications. When it comes to React applications, there are numerous ways to style components and UI elements.</p>
<p>In this article, we will explore several popular options, including pure CSS, CSS modules, CSS preprocessors, Tailwind CSS, CSS-in-JS libraries like Styled Components, and pre-built component libraries like Chakra UI, Material-UI, and Bootstrap.</p>
<p>We'll delve into each option's main characteristics, advantages, and disadvantages to help you choose the right styling approach for your React projects.</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<p>You'll learn how to style your React apps using:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-style-your-react-apps-using-pure-css">Pure CSS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-style-your-react-apps-using-css-modules">CSS modules</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-style-your-react-apps-using-css-preprocessors">CSS preprocessors</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-style-your-react-apps-using-tailwind-css">Tailwind CSS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-style-your-react-apps-using-css-in-js">CSS-in-JS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-style-your-react-apps-using-component-libraries">Component libraries</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h1 id="heading-how-to-style-your-react-apps-using-pure-css">How to Style Your React Apps Using Pure CSS</h1>
<p>Pure CSS involves writing stylesheets using standard CSS syntax and linking them to your React components.</p>
<p>This approach is simple and widely supported, making it an excellent choice for small-scale projects. But it can become challenging to manage and scale as the application grows.</p>
<h3 id="heading-pros">Pros:</h3>
<ul>
<li><p><strong>Familiarity:</strong> Developers with CSS expertise can quickly adapt to this approach.</p>
</li>
<li><p><strong>Browser Support:</strong> Pure CSS is supported by all modern browsers.</p>
</li>
<li><p><strong>Lightweight:</strong> CSS files can be cached by the browser, resulting in faster page loading times.</p>
</li>
</ul>
<h3 id="heading-cons">Cons:</h3>
<ul>
<li><p><strong>Global Scope:</strong> Styles defined in CSS are global by default, which can lead to naming conflicts and style leakages.</p>
</li>
<li><p><strong>Limited Reusability:</strong> Reusing styles across components requires manually maintaining class names and selectors.</p>
</li>
</ul>
<h3 id="heading-example">Example:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./MyComponent.css'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"my-component"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"title"</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"description"</span>&gt;</span>This is a styled React component.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we have a component called <code>MyComponent</code>. To apply styles using pure CSS, we import an external CSS file called <code>MyComponent.css</code>. Here's how the CSS file might look:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.my-component</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f2f2f2</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-class">.title</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-class">.description</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#777</span>;
}

<span class="hljs-selector-class">.btn</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#007bff</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">4px</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">transition</span>: background-color <span class="hljs-number">0.3s</span> ease;
}

<span class="hljs-selector-class">.btn</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#0056b3</span>;
}
</code></pre>
<p>In this CSS file, we define styles for the different classes used in the component. The <code>my-component</code> class styles the container div, the <code>title</code> class styles the heading, the <code>description</code> class styles the paragraph, and the <code>btn</code> class styles the button.</p>
<p>When the <code>MyComponent</code> is rendered, it will have the defined styles applied. The container div will have a light gray background with padding and border-radius. The heading will have a larger font size and a dark gray color, while the paragraph will have a smaller font size and a light gray color. The button will have a blue background with white text, and it will transition to a darker blue on hover.</p>
<p>Remember to import the CSS file correctly, ensuring that the path is accurate based on your project structure.</p>
<h1 id="heading-how-to-style-your-react-apps-using-css-modules">How to Style Your React Apps Using CSS Modules</h1>
<p>CSS Modules aim to solve the global scope and reusability issues of pure CSS. They allow you to write modular stylesheets, where class names are scoped to specific components.</p>
<h3 id="heading-pros-1">Pros:</h3>
<ul>
<li><p><strong>Scoped Styles:</strong> CSS Modules generate unique class names for each component, avoiding style clashes.</p>
</li>
<li><p><strong>Reusability:</strong> Styles defined in CSS Modules can be easily reused across components.</p>
</li>
<li><p><strong>Clear Dependencies:</strong> Stylesheets are imported and linked directly to the components that use them.</p>
</li>
</ul>
<h3 id="heading-cons-1">Cons:</h3>
<ul>
<li><p><strong>Learning Curve:</strong> Developers must learn and understand the CSS Modules syntax and import mechanism.</p>
</li>
<li><p><strong>Additional Configuration:</strong> Integrating CSS Modules into a React project often requires extra configuration setup.</p>
</li>
</ul>
<h3 id="heading-example-1">Example</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">'./MyComponent.module.css'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.myComponent}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.title}</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.description}</span>&gt;</span>This is a styled React component.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.btn}</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we import an external CSS module file called <code>MyComponent.module.css</code> and assign it to the <code>styles</code> object. The <code>styles</code> object contains mappings of CSS class names to unique generated class names specific to the component.</p>
<p>Here's how the CSS module file might look:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.myComponent</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f2f2f2</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-class">.title</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-class">.description</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#777</span>;
}

<span class="hljs-selector-class">.btn</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#007bff</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">4px</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">transition</span>: background-color <span class="hljs-number">0.3s</span> ease;
}

<span class="hljs-selector-class">.btn</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#0056b3</span>;
}
</code></pre>
<p>In the CSS module file, you define styles as you would in regular CSS, but instead of using global class names, you use local class names. These local class names are scoped to the component and have unique names generated during the build process.</p>
<p>When the <code>MyComponent</code> is rendered, the CSS module styles are applied using the corresponding class names from the <code>styles</code> object. The component's container div, heading, paragraph, and button will have the respective styles applied.</p>
<p>Make sure to use the <code>className</code> attribute and reference the CSS module class names from the <code>styles</code> object in your component's JSX. The CSS module system will automatically map these class names to the unique generated class names, ensuring style encapsulation and preventing class name collisions.</p>
<p>Note that the CSS module file should have the <code>.module.css</code> file extension for the module to work correctly.</p>
<h1 id="heading-how-to-style-your-react-apps-using-css-preprocessors">How to Style Your React Apps Using CSS preprocessors</h1>
<p>CSS preprocessors like <a target="_blank" href="https://sass-lang.com/">SASS</a>, <a target="_blank" href="https://lesscss.org/">LESS</a> or <a target="_blank" href="https://stylus-lang.com/">Stylus</a> provide additional features like variables, nesting, mixins, and more. It enhances the productivity and maintainability of CSS code.</p>
<h3 id="heading-pros-2">Pros:</h3>
<ul>
<li><p><strong>Advanced Features:</strong> SCSS introduces powerful features that simplify CSS writing and management.</p>
</li>
<li><p><strong>Code Reusability:</strong> SCSS allows creating reusable code snippets using mixins and variables.</p>
</li>
<li><p><strong>Easy Migration:</strong> Existing CSS files can be gradually converted to SCSS without significant refactoring.</p>
</li>
</ul>
<h3 id="heading-cons-2">Cons:</h3>
<ul>
<li><p><strong>Compilation Step:</strong> SCSS files need to be compiled into regular CSS before they can be used.</p>
</li>
<li><p><strong>Learning Curve:</strong> Developers must learn SCSS syntax and its specific features.</p>
</li>
</ul>
<h3 id="heading-example-2">Example</h3>
<p>Here's an example of how you can use Sass to style a React component. First, make sure you have Sass installed in your project by running <code>npm install node-sass</code> or <code>yarn add node-sass</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./MyComponent.scss'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"my-component"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"title"</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"description"</span>&gt;</span>This is a styled React component.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we import an external SCSS file called <code>MyComponent.scss</code>. Make sure the file extension is <code>.scss</code> for Sass files. Here's how the SCSS file might look:</p>
<pre><code class="lang-scss"><span class="hljs-selector-class">.my-component</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f2f2f2</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">text-align</span>: center;

  <span class="hljs-selector-class">.title</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">10px</span>;
  }

  <span class="hljs-selector-class">.description</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#777</span>;
  }

  <span class="hljs-selector-class">.btn</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#007bff</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">border</span>: none;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">4px</span>;
    <span class="hljs-attribute">cursor</span>: pointer;
    <span class="hljs-attribute">transition</span>: background-color <span class="hljs-number">0.3s</span> ease;

    &amp;<span class="hljs-selector-pseudo">:hover</span> {
      <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#0056b3</span>;
    }
  }
}
</code></pre>
<h1 id="heading-how-to-style-your-react-apps-using-tailwind-css">How to Style Your React Apps Using Tailwind CSS</h1>
<p><a target="_blank" href="https://tailwindcss.com/">Tailwind CSS</a> is a utility-first CSS framework that offers a vast set of pre-defined utility classes. It promotes rapid development and consistent styling across an application.</p>
<h3 id="heading-pros-3">Pros:</h3>
<ul>
<li><p><strong>Rapid Prototyping:</strong> Tailwind CSS provides an extensive collection of utility classes, enabling quick UI development.</p>
</li>
<li><p><strong>Highly Customizable:</strong> The framework allows customization through a configuration file, enabling tailored styling.</p>
</li>
<li><p><strong>Consistent Styling:</strong> By using predefined utility classes, styling consistency can be easily maintained.</p>
</li>
</ul>
<h3 id="heading-cons-3">Cons:</h3>
<ul>
<li><p><strong>File Size:</strong> Including the entire Tailwind CSS framework can result in a larger bundle size.</p>
</li>
<li><p><strong>Class Overload:</strong> Over-reliance on utility classes may lead to bloated HTML markup.</p>
</li>
</ul>
<h3 id="heading-example-3">Example:</h3>
<p>First, make sure you have Tailwind CSS installed in your project by following the <a target="_blank" href="https://tailwindcss.com/docs/installation">installation guide in the official Tailwind CSS documentation</a>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"bg-gray-200 p-4 rounded-lg text-center"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-2xl text-gray-800 mb-2"</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-base text-gray-600"</span>&gt;</span>This is a styled React component.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"</span>&gt;</span>
        Click Me
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we don't import any external CSS or SCSS files. Instead, we directly use Tailwind CSS utility classes within the component's JSX. The utility classes provide ready-to-use styles for various aspects of the component.</p>
<p>The utility classes used in the example (<code>bg-gray-200</code>, <code>p-4</code>, <code>rounded-lg</code>, <code>text-center</code>, <code>text-2xl</code>, <code>text-gray-800</code>, <code>mb-2</code>, <code>text-base</code>, <code>text-gray-600</code>, <code>bg-blue-500</code>, <code>hover:bg-blue-700</code>, <code>text-white</code>, <code>font-bold</code>, <code>py-2</code>, <code>px-4</code>, <code>rounded</code>) define the background color, padding, border radius, text alignment, text size, text color, margins, button styling, and more.</p>
<p>When the <code>MyComponent</code> is rendered, the respective utility classes from Tailwind CSS will be applied to the corresponding elements, resulting in the desired styles.</p>
<p>Ensure that your project is properly configured to use Tailwind CSS, including importing the necessary Tailwind CSS stylesheets and applying the required build process (such as running <code>npm run build</code> or <code>yarn build</code> to generate the production-ready CSS file).</p>
<p>Tailwind CSS provides a wide range of utility classes, and you can mix and match them to create the desired styling for your React components. Refer to the official Tailwind CSS documentation for more information on available utility classes and customization options.</p>
<h1 id="heading-how-to-style-your-react-apps-using-css-in-js">How to Style Your React Apps Using CSS-in-JS</h1>
<p>CSS-in-JS libraries like <a target="_blank" href="https://styled-components.com/">Styled Components</a> offer a unique approach to styling by allowing developers to write CSS directly in their JavaScript code. Styled Components offer a way to create reusable and scoped styles within React components.</p>
<h3 id="heading-pros-4">Pros:</h3>
<ul>
<li><p><strong>Component-Based Styling:</strong> Styles are written within the component, enhancing code organization and reusability.</p>
</li>
<li><p><strong>Dynamic Styling:</strong> Styled Components enable dynamic styling based on component props or state.</p>
</li>
<li><p><strong>Easy Theme Integration:</strong> Themes can be easily incorporated, providing consistent styling throughout the application.</p>
</li>
</ul>
<h3 id="heading-cons-4">Cons:</h3>
<ul>
<li><p><strong>Build Complexity:</strong> CSS-in-JS solutions often require additional build tools and dependencies.</p>
</li>
<li><p><strong>Performance Impact:</strong> Generating dynamic styles at runtime can impact the application's performance.</p>
</li>
</ul>
<h3 id="heading-example-4">Example</h3>
<p>First, make sure you have the Styled Components library installed in your project by running <code>npm install styled-components</code> or <code>yarn add styled-components</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">const</span> StyledDiv = styled.div<span class="hljs-string">`
  background-color: #f2f2f2;
  padding: 20px;
  border-radius: 5px;
  text-align: center;
`</span>;

<span class="hljs-keyword">const</span> StyledTitle = styled.h1<span class="hljs-string">`
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
`</span>;

<span class="hljs-keyword">const</span> StyledDescription = styled.p<span class="hljs-string">`
  font-size: 16px;
  color: #777;
`</span>;

<span class="hljs-keyword">const</span> StyledButton = styled.button<span class="hljs-string">`
  background-color: #007bff;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;

  &amp;:hover {
    background-color: #0056b3;
  }
`</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">StyledDiv</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledTitle</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">StyledTitle</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledDescription</span>&gt;</span>This is a styled React component.<span class="hljs-tag">&lt;/<span class="hljs-name">StyledDescription</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledButton</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">StyledButton</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">StyledDiv</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we import the <code>styled</code> function from the <code>styled-components</code> library. We then create styled components by assigning the result of calling <code>styled</code> with the desired HTML element to variables (<code>StyledDiv</code>, <code>StyledTitle</code>, <code>StyledDescription</code>, <code>StyledButton</code>).</p>
<p>Within the backticks (`) of each styled component, we define the CSS rules specific to that component.</p>
<p>When the <code>MyComponent</code> is rendered, the styled components are used in place of the regular HTML elements. The styles defined within the respective styled components will be applied to the corresponding elements.</p>
<p>Styled Components allow you to write CSS directly within your JavaScript code, making it easy to encapsulate styles and create reusable components. You can also pass props to styled components and use them in your CSS rules to create dynamic styles.</p>
<p>Make sure to import the <code>styled</code> function from <code>styled-components</code> and define your styled components before using them in your component.</p>
<p>Remember to install and configure Styled Components in your project before using them.</p>
<h1 id="heading-how-to-style-your-react-apps-using-component-libraries">How to Style Your React Apps Using Component Libraries</h1>
<p>Component libraries like <a target="_blank" href="https://chakra-ui.com/">Chakra UI</a>, <a target="_blank" href="https://mui.com/">Material-UI</a>, and <a target="_blank" href="https://getbootstrap.com/">Bootstrap</a> offer pre-built and styled React components along with accompanying styles. These libraries provide a consistent and cohesive UI design language.</p>
<h3 id="heading-pros-5">Pros:</h3>
<ul>
<li><p><strong>Rapid Development:</strong> Ready-to-use components speed up the development process.</p>
</li>
<li><p><strong>Consistent Styling:</strong> Components within a library adhere to a unified design system, ensuring visual consistency.</p>
</li>
<li><p><strong>Extensive Documentation:</strong> Popular component libraries have well-documented APIs and guidelines.</p>
</li>
</ul>
<h3 id="heading-cons-5">Cons:</h3>
<ul>
<li><p><strong>Customization Limitations:</strong> While these libraries offer customization options, they may not fulfill every design requirement.</p>
</li>
<li><p><strong>Bundle Size:</strong> Including an entire component library can increase the application's bundle size.</p>
</li>
</ul>
<h3 id="heading-example-5">Example</h3>
<p>First, make sure you have Material-UI installed in your project by running <code>npm install @mui/material</code> or <code>yarn add @mui/material</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { styled } <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/system'</span>;
<span class="hljs-keyword">import</span> { Button, Paper, Typography } <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material'</span>;

<span class="hljs-keyword">const</span> StyledPaper = styled(Paper)(<span class="hljs-function">(<span class="hljs-params">{ theme }</span>) =&gt;</span> ({
  <span class="hljs-attr">backgroundColor</span>: <span class="hljs-string">'#f2f2f2'</span>,
  <span class="hljs-attr">padding</span>: theme.spacing(<span class="hljs-number">2</span>),
  <span class="hljs-attr">borderRadius</span>: theme.spacing(<span class="hljs-number">1</span>),
  <span class="hljs-attr">textAlign</span>: <span class="hljs-string">'center'</span>,
}));

<span class="hljs-keyword">const</span> StyledTitle = styled(Typography)(<span class="hljs-function">(<span class="hljs-params">{ theme }</span>) =&gt;</span> ({
  <span class="hljs-attr">fontSize</span>: <span class="hljs-number">24</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'#333'</span>,
  <span class="hljs-attr">marginBottom</span>: theme.spacing(<span class="hljs-number">1</span>),
}));

<span class="hljs-keyword">const</span> StyledDescription = styled(Typography)(<span class="hljs-function">(<span class="hljs-params">{ theme }</span>) =&gt;</span> ({
  <span class="hljs-attr">fontSize</span>: <span class="hljs-number">16</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'#777'</span>,
}));

<span class="hljs-keyword">const</span> StyledButton = styled(Button)(<span class="hljs-function">(<span class="hljs-params">{ theme }</span>) =&gt;</span> ({
  <span class="hljs-attr">backgroundColor</span>: <span class="hljs-string">'#007bff'</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'#fff'</span>,
  <span class="hljs-attr">borderRadius</span>: theme.spacing(<span class="hljs-number">1</span>),
  <span class="hljs-attr">padding</span>: theme.spacing(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>),
  <span class="hljs-attr">transition</span>: <span class="hljs-string">'background-color 0.3s ease'</span>,

  <span class="hljs-string">'&amp;:hover'</span>: {
    <span class="hljs-attr">backgroundColor</span>: <span class="hljs-string">'#0056b3'</span>,
  },
}));

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">StyledPaper</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledTitle</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"h1"</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">StyledTitle</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledDescription</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"body1"</span>&gt;</span>This is a styled React component.<span class="hljs-tag">&lt;/<span class="hljs-name">StyledDescription</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledButton</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"contained"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">StyledButton</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">StyledPaper</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we import the necessary components from Material-UI (<code>Button</code>, <code>Paper</code>, <code>Typography</code>) and the <code>styled</code> function from <code>@mui/system</code>. We then create styled components using the <code>styled</code> function, assigning the result to variables (<code>StyledPaper</code>, <code>StyledTitle</code>, <code>StyledDescription</code>, <code>StyledButton</code>).</p>
<p>Within the function passed to <code>styled</code>, we define the CSS rules specific to each styled component using the Material-UI theme object (<code>theme</code>) for consistent theming.</p>
<p>When the <code>MyComponent</code> is rendered, the styled components are used in place of the regular Material-UI components. The styles defined within the respective styled components will be applied to the corresponding elements.</p>
<p>Styled components in Material-UI follow a similar approach to Styled Components, allowing you to encapsulate styles within your components using the <code>styled</code> function and the Material-UI theme object.</p>
<p>Make sure to import the necessary components and functions from Material-UI and define your styled components before using them in your component.</p>
<p>Remember to install and configure Material-UI in your project before using it.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Based on what we've seen, here's a quick comparison table between different options for styling a React app:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Option</strong></td><td><strong>Main Characteristics</strong></td><td><strong>Pros</strong></td><td><strong>Cons</strong></td><td><strong>When to Use</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Pure CSS</td><td>Traditional approach with global CSS files</td><td>Simple and familiar</td><td>Lack of encapsulation and potential for class name collisions</td><td>Small projects or when CSS customization is the main focus</td></tr>
<tr>
<td>CSS Modules</td><td>CSS files with locally scoped class names</td><td>Scoped styles and prevents class name clashes</td><td>Requires importing and referencing unique class names</td><td>Medium-sized projects requiring style encapsulation</td></tr>
<tr>
<td>CSS Preprocessors (e.g., Sass, Less)</td><td>Enhanced CSS syntax with variables, mixins, etc.</td><td>Reusable code, modular and maintainable styles</td><td>Build process needed for compilation</td><td>Projects that benefit from enhanced CSS syntax</td></tr>
<tr>
<td>Tailwind CSS</td><td>Utility-based CSS framework</td><td>Rapid development, consistent styling, extensive utility classes</td><td>Large file size due to utility classes</td><td>Prototyping or projects where rapid development is crucial</td></tr>
<tr>
<td>CSS-in-JS</td><td>Writing CSS directly in JavaScript using libraries like Styled Components or Emotion</td><td>Component-based styles, dynamic styling, props-based styles</td><td>Increased bundle size, additional learning curve</td><td>Projects with complex or dynamic styling requirements</td></tr>
<tr>
<td>Component Libraries (e.g., MUI, Chakra)</td><td>Pre-styled and customizable UI components</td><td>Consistent design, extensive component library, theming support</td><td>Limited customization options, larger bundle size</td><td>Projects requiring ready-to-use UI components with theming support</td></tr>
</tbody>
</table>
</div><p>Each option has its own strengths and weaknesses, and the choice depends on the specific project requirements and preferences. Here's a breakdown of when each option may be more convenient:</p>
<ul>
<li><p><strong>Pure CSS:</strong> Suitable for small projects or when CSS customization is the main focus. It is simple and familiar but lacks encapsulation and can lead to class name collisions in larger projects.</p>
</li>
<li><p><strong>CSS Modules:</strong> Ideal for medium-sized projects that require style encapsulation. It offers scoped styles, prevents class name clashes, and requires importing and referencing unique class names.</p>
</li>
<li><p><strong>CSS Preprocessors:</strong> Recommended for projects that benefit from enhanced CSS syntax with variables, mixins, and other features. They promote reusable and maintainable styles but require a build process for compilation.</p>
</li>
<li><p><strong>Tailwind CSS:</strong> Perfect for rapid development and prototyping. It provides an extensive set of utility classes for consistent styling but can result in a large file size due to the number of utility classes.</p>
</li>
<li><p><strong>CSS-in-JS:</strong> Well-suited for projects with complex or dynamic styling requirements. Writing CSS directly in JavaScript offers component-based styles and dynamic styling capabilities, but it may increase the bundle size and has an additional learning curve.</p>
</li>
<li><p><strong>Component Libraries:</strong> Useful when you need ready-to-use UI components with consistent design and theming support. They offer extensive component libraries but may have limited customization options and result in a larger bundle size.</p>
</li>
</ul>
<p>Consider the project's size, styling needs, development speed, and customization requirements when choosing the appropriate styling option. It's also worth considering the team's familiarity with the chosen option and its ecosystem.</p>
<p>Well everyone, as always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/c70acd30c5bc4847faea61747c11bece.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Clean Code – Tips and Best Practices (Full Handbook) ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this handbook we're going to talk about writing "clean" code. It's a topic that used to confuse me a bit when I was starting out as a programmer, and I find that it has many nuances and possible interpretations. So in this article we'... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-clean-code/</link>
                <guid isPermaLink="false">66d45f073dce891ac3a967f6</guid>
                
                    <category>
                        <![CDATA[ best practices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 15 May 2023 14:43:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/pexels-ken-tomita-389819.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this handbook we're going to talk about writing "clean" code. It's a topic that used to confuse me a bit when I was starting out as a programmer, and I find that it has many nuances and possible interpretations.</p>
<p>So in this article we'll talk about what the term "clean code" means, why it's important, how can we assess whether a codebase is clean or not. You'll also learn some best practices and conventions you can follow to make your code cleaner.</p>
<p>Let's go!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-does-it-mean-to-write-clean-code-and-why-should-i-care">What does it mean to write "clean code" and why should I care?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-can-i-assess-whether-a-codebase-is-clean-or-not">How can I assess whether a codebase is clean or not?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tips-and-conventions-to-write-cleaner-code">Tips and conventions to write cleaner code</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-effectiveness-efficiency-and-simplicity">Effectiveness, efficiency and simplicity</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-format-and-syntax">Format and syntax</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-naming">Naming</a></p>
</li>
<li><p><a class="post-section-overview" href="#conciseness-versus-clarity">Conciseness versus clarity</a></p>
</li>
<li><p><a class="post-section-overview" href="#re-usability">Re-usability</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-clear-flow-of-execution">Clear flow of execution</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-single-responsibility-principle">Single responsibility principle</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-having-a-single-source-of-truth">Having a "single source of truth"</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-only-expose-and-consume-data-you-need">Only expose and consume information you need</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-modularization">Modularization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-folder-structures">Folder structures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-documentation">Documentation</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></p>
</li>
</ul>
<h1 id="heading-what-does-it-mean-to-write-clean-code-and-why-should-i-care">What Does it Mean to Write "Clean Code" and Why Should I Care?</h1>
<p>Clean code is a term used to describe computer code that is easy to read, understand, and maintain. Clean code is written in a way that makes it simple, concise, and expressive. It follows a set of conventions, standards, and practices that make it easy to read and follow.</p>
<p>Clean code is free from complexity, redundancy, and other code smells and anti-patterns that can make it difficult to maintain, debug, and modify.</p>
<p>I can't overstate the importance of clean code. When code is easy to read and understand, it makes it easier for developers to work on the codebase. This can lead to increased productivity and reduced errors.</p>
<p>Also, when code is easy to maintain, it ensures that the codebase can be improved and updated over time. This is especially important for long-term projects where code must be maintained and updated for years to come.</p>
<h1 id="heading-how-can-i-assess-whether-a-codebase-is-clean-or-not">How Can I Assess Whether a Codebase is Clean or Not?</h1>
<p>You can assess clean code in a variety of ways. Good documentation, consistent formatting, and a well-organized codebase are all indicators of clean code.</p>
<p>Code reviews can also help to identify potential issues and ensure that code follows best practices and conventions.</p>
<p>Testing is also an important aspect of clean code. It helps to ensure that code is functioning as expected and can catch errors early.</p>
<p>There are several tools, practices, and conventions you can implement to ensure a clean codebase. By implementing these tools and practices, developers can create a codebase that is easy to read, understand, and maintain.</p>
<p>It's also important to remember that there's an inevitable amount of subjectivity related to this topic, and there are a number of different opinions and tips out there. What might look clean and awesome for one person or one project might not be so for another person or another project.</p>
<p>But still there are a few general conventions we can follow to achieve cleaner code, so let's jump into that now.</p>
<h1 id="heading-tips-and-conventions-to-write-cleaner-code">Tips and Conventions to Write Cleaner Code</h1>
<h2 id="heading-effectiveness-efficiency-and-simplicity">Effectiveness, Efficiency and Simplicity</h2>
<p>Whenever I need to think about how to implement a new feature into an already existing codebase, or how to tackle the solution of a specific problem, I always prioritize this three simple things.</p>
<h3 id="heading-effectiveness">Effectiveness</h3>
<p>First, our code should be <strong>effective</strong>, meaning it should solve the problem it's supposed to solve. Of course this is the most basic expectation we could have for our code, but if our implementation doesn't actually work, it's worthless to think about any other thing.</p>
<h3 id="heading-efficiency">Efficiency</h3>
<p>Second, once we know our code solves the problem, we should check if it does so <strong>efficiently</strong>. Does the program run using a reasonable amount of resources in terms of time and space? Can it run faster and with less space?</p>
<p>Algorithmic complexity is something you should be aware of in order to evaluate this. If you're not familiar with it, you can check <a target="_blank" href="https://www.freecodecamp.org/news/introduction-to-algorithms-with-javascript-examples/#algorithmic-complexity">this article I wrote</a>.</p>
<p>To expand upon efficiency, here are two examples of a function that calculates the sum of all numbers in an array.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Inefficient Example</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumArrayInefficient</span>(<span class="hljs-params">array</span>) </span>{
  <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; array.length; i++) {
    sum += array[i];
  }
  <span class="hljs-keyword">return</span> sum;
}
</code></pre>
<p>This implementation of the <code>sumArrayInefficient</code> function iterates over the array using a <code>for</code> loop and adds each element to the <code>sum</code> variable. This is a valid solution, but it is not very efficient because it requires iterating over the entire array, regardless of its length.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Efficient example</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumArrayEfficient</span>(<span class="hljs-params">array</span>) </span>{
  <span class="hljs-keyword">return</span> array.reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b, <span class="hljs-number">0</span>);
}
</code></pre>
<p>This implementation of the <code>sumArrayEfficient</code> function uses the <code>reduce</code> method to sum the elements of the array. The <code>reduce</code> method applies a function to each element of the array and accumulates the result. In this case, the function simply adds each element to the accumulator, which starts at 0.</p>
<p>This is a more efficient solution because it only requires a single iteration over the array and performs the summing operation on each element as it goes.</p>
<h3 id="heading-simplicity">Simplicity</h3>
<p>And last comes <strong>simplicity</strong>. This is the toughest one to evaluate because its subjective, it depends on the person who reads the code. But some guidelines we can follow are:</p>
<ol>
<li><p>Can you easily understand what the program does at each line?</p>
</li>
<li><p>Do functions and variables have names that clearly represent their responsibilities?</p>
</li>
<li><p>Is the code indented correctly and spaced with the same format all along the codebase?</p>
</li>
<li><p>Is there any documentation available for the code? Are comments used to explain complex parts of the program?</p>
</li>
<li><p>How quick can you identify in which part of the codebase are certain features of the program? Can you delete/add new features without the need of modifying many other parts of the code?</p>
</li>
<li><p>Does the code follow a modular approach, with different features separated in components?</p>
</li>
<li><p>Is code reused when possible?</p>
</li>
<li><p>Are the same architecture, design, and implementation decisions followed equally all along the codebase?</p>
</li>
</ol>
<p>By following and prioritizing these three concepts of effectiveness, efficiency, and simplicity, we can always have a guideline to follow when thinking about how to implement a solution. Now let's expand upon some of the guidelines that can help us simplify our code.</p>
<h2 id="heading-format-and-syntax">Format and Syntax</h2>
<p>Using consistent formatting and syntax throughout a codebase is an important aspect of writing clean code. This is because consistent formatting and syntax make the code more readable and easier to understand.</p>
<p>When code is consistent, developers can easily identify patterns and understand how the code works, which makes it easier to debug, maintain, and update the codebase over time. Consistency also helps to reduce errors, as it ensures that all developers are following the same standards and conventions.</p>
<p>Some of the things we should think about regarding format and syntax are:</p>
<ul>
<li><strong>Indentation and spacing</strong></li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// bad indentation and spacing</span>
<span class="hljs-keyword">const</span> myFunc=<span class="hljs-function">(<span class="hljs-params">number1,number2</span>)=&gt;</span>{
<span class="hljs-keyword">const</span> result=number1+number2;
<span class="hljs-keyword">return</span> result;
}

<span class="hljs-comment">// good indentation and spacing</span>
<span class="hljs-keyword">const</span> myFunc = <span class="hljs-function">(<span class="hljs-params">number1, number2</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> result = number1 + number2
    <span class="hljs-keyword">return</span> result
}
</code></pre>
<p>Here we have an example of a same function, one done with no indentation and spacing, and the other properly spaced and indented. We can see that the second one is clearly easier to read.</p>
<ul>
<li><strong>Consistent syntax</strong></li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Arrow function, no colons, no return</span>
<span class="hljs-keyword">const</span> multiplyByTwo = <span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> number * <span class="hljs-number">2</span>

<span class="hljs-comment">// Function, colons, return</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyByThree</span>(<span class="hljs-params">number</span>) </span>{
    <span class="hljs-keyword">return</span> number * <span class="hljs-number">3</span>;
}
</code></pre>
<p>Again, here we have very similar functions implemented with different syntax. The first one is an arrow function, with no colons and no return, while the other is a common function that uses colons and a return.</p>
<p>Both work and are just fine, but we should aim to always use the same syntax for similar operations, as it becomes more even and readable along the codebase.</p>
<p>Linterns and code formatters are great tools we can use in our projects to automatize the syntax and formatting conventions in our codebase. If you're not familiar with this tools, <a target="_blank" href="https://www.freecodecamp.org/news/using-prettier-and-jslint/">check out this other article of mine</a>.</p>
<ul>
<li><strong>Consistent case conventions</strong></li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// camelCase</span>
<span class="hljs-keyword">const</span> myName = <span class="hljs-string">'John'</span>
<span class="hljs-comment">// PascalCase</span>
<span class="hljs-keyword">const</span> MyName = <span class="hljs-string">'John'</span>
<span class="hljs-comment">// snake_case</span>
<span class="hljs-keyword">const</span> my_name = <span class="hljs-string">'John'</span>
</code></pre>
<p>Same goes for the case convention we choose to follow. All of these work, but we should aim to consistently use the same one all through our project.</p>
<h2 id="heading-naming">Naming</h2>
<p>Naming variables and functions clearly and descriptively is an important aspect of writing clean code. It helps to improve the readability and maintainability of the codebase. When names are well-chosen, other developers can quickly understand what the variable or function is doing, and how it is related to the rest of the code.</p>
<p>Here are two examples in JavaScript that demonstrate the importance of clear and descriptive naming:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Poor Naming</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ab</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">let</span> y = a + b + x;
  <span class="hljs-built_in">console</span>.log(y);
}

ab(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>);
</code></pre>
<p>In this example, we have a function that takes two parameters, adds them to a hardcoded value of 10, and logs the result to the console. The function name and variable names are poorly chosen and don't give any indication of what the function does or what the variables represent.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Good Naming</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotalWithTax</span>(<span class="hljs-params">basePrice, taxRate</span>) </span>{
  <span class="hljs-keyword">const</span> BASE_TAX = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">const</span> totalWithTax = basePrice + (basePrice * (taxRate / <span class="hljs-number">100</span>)) + BASE_TAX;
  <span class="hljs-built_in">console</span>.log(totalWithTax);
}

calculateTotalWithTax(<span class="hljs-number">50</span>, <span class="hljs-number">20</span>);
</code></pre>
<p>In this example, we have a function that calculates the total price of a product including tax. The function name and variable names are well-chosen and give a clear indication of what the function does and what the variables represent.</p>
<p>This makes the code easier to read and understand, especially for other developers who may be working with the codebase in the future.</p>
<h2 id="heading-conciseness-vs-clarity">Conciseness vs Clarity</h2>
<p>When it comes to writing clean code, it's important to strike a balance between conciseness and clarity. While it's important to keep code concise to improve its readability and maintainability, it's equally important to ensure that the code is clear and easy to understand. Writing overly concise code can lead to confusion and errors, and can make the code difficult to work with for other developers.</p>
<p>Here are two examples that demonstrate the importance of conciseness and clarity:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Concise function</span>
<span class="hljs-keyword">const</span> countVowels = <span class="hljs-function"><span class="hljs-params">s</span> =&gt;</span> (s.match(<span class="hljs-regexp">/[aeiou]/gi</span>) || []).length;
<span class="hljs-built_in">console</span>.log(countVowels(<span class="hljs-string">"hello world"</span>));
</code></pre>
<p>This example uses a concise arrow function and regex to count the number of vowels in a given string. While the code is very short and easy to write, it may not be immediately clear to other developers how the regex pattern works, especially if they are not familiar with regex syntax.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 2: More verbose and clearer function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">countVowels</span>(<span class="hljs-params">s</span>) </span>{
  <span class="hljs-keyword">const</span> vowelRegex = <span class="hljs-regexp">/[aeiou]/gi</span>;
  <span class="hljs-keyword">const</span> matches = s.match(vowelRegex) || [];
  <span class="hljs-keyword">return</span> matches.length;
}

<span class="hljs-built_in">console</span>.log(countVowels(<span class="hljs-string">"hello world"</span>));
</code></pre>
<p>This example uses a traditional function and regex to count the number of vowels in a given string, but does so in a way that is clear and easy to understand. The function name and variable names are descriptive, and the regex pattern is stored in a variable with a clear name. This makes it easy to see what the function is doing and how it works.</p>
<p>It's important to strike a balance between conciseness and clarity when writing code. While concise code can improve readability and maintainability, it's important to ensure that the code is still clear and easy to understand for other developers who may be working with the codebase in the future.</p>
<p>By using descriptive function and variable names, and making use of clear and readable code formatting and comments, it's possible to write clean and concise code that is easy to understand and work with.</p>
<h2 id="heading-reusability">Reusability</h2>
<p>Code reusability is a fundamental concept in software engineering that refers to the ability of code to be used multiple times without modification.</p>
<p>The importance of code reusability lies in the fact that it can greatly improve the efficiency and productivity of software development by reducing the amount of code that needs to be written and tested.</p>
<p>By reusing existing code, developers can save time and effort, improve code quality and consistency, and minimize the risk of introducing bugs and errors. Reusable code also allows for more modular and scalable software architectures, making it easier to maintain and update codebases over time.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: No re-usability</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateCircleArea</span>(<span class="hljs-params">radius</span>) </span>{
  <span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14</span>;
  <span class="hljs-keyword">return</span> PI * radius * radius;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateRectangleArea</span>(<span class="hljs-params">length, width</span>) </span>{
  <span class="hljs-keyword">return</span> length * width;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTriangleArea</span>(<span class="hljs-params">base, height</span>) </span>{
  <span class="hljs-keyword">return</span> (base * height) / <span class="hljs-number">2</span>;
}

<span class="hljs-keyword">const</span> circleArea = calculateCircleArea(<span class="hljs-number">5</span>);
<span class="hljs-keyword">const</span> rectangleArea = calculateRectangleArea(<span class="hljs-number">4</span>, <span class="hljs-number">6</span>);
<span class="hljs-keyword">const</span> triangleArea = calculateTriangleArea(<span class="hljs-number">3</span>, <span class="hljs-number">7</span>);

<span class="hljs-built_in">console</span>.log(circleArea, rectangleArea, triangleArea);
</code></pre>
<p>This example defines three functions that calculate the area of a circle, rectangle, and triangle, respectively. Each function performs a specific task, but none of them are reusable for other similar tasks.</p>
<p>Additionally, the use of a hard-coded PI value can lead to errors if the value needs to be changed in the future. The code is inefficient since it repeats the same logic multiple times.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 2: Implementing re-usability</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateArea</span>(<span class="hljs-params">shape, ...args</span>) </span>{
  <span class="hljs-keyword">if</span> (shape === <span class="hljs-string">'circle'</span>) {
    <span class="hljs-keyword">const</span> [radius] = args;
    <span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14</span>;
    <span class="hljs-keyword">return</span> PI * radius * radius;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (shape === <span class="hljs-string">'rectangle'</span>) {
    <span class="hljs-keyword">const</span> [length, width] = args;
    <span class="hljs-keyword">return</span> length * width;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (shape === <span class="hljs-string">'triangle'</span>) {
    <span class="hljs-keyword">const</span> [base, height] = args;
    <span class="hljs-keyword">return</span> (base * height) / <span class="hljs-number">2</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Shape "<span class="hljs-subst">${shape}</span>" not supported.`</span>);
  }
}

<span class="hljs-keyword">const</span> circleArea = calculateArea(<span class="hljs-string">'circle'</span>, <span class="hljs-number">5</span>);
<span class="hljs-keyword">const</span> rectangleArea = calculateArea(<span class="hljs-string">'rectangle'</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>);
<span class="hljs-keyword">const</span> triangleArea = calculateArea(<span class="hljs-string">'triangle'</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>);

<span class="hljs-built_in">console</span>.log(circleArea, rectangleArea, triangleArea);
</code></pre>
<p>This example defines a single function <code>calculateArea</code> that takes a <code>shape</code> argument and a variable number of arguments. Based on the <code>shape</code> argument, the function performs the appropriate calculation and returns the result.</p>
<p>This approach is much more efficient since it eliminates the need to repeat code for similar tasks. It is also more flexible and extensible, as additional shapes can easily be added in the future.</p>
<h2 id="heading-clear-flow-of-execution">Clear Flow of Execution</h2>
<p>Having a clear flow of execution is essential for writing clean code because it makes the code easier to read, understand, and maintain. Code that follows a clear and logical structure is less prone to errors, easier to modify and extend, and more efficient in terms of time and resources.</p>
<p>On the other hand, spaghetti code is a term used to describe code that is convoluted and difficult to follow, often characterized by long, tangled, and unorganized code blocks. Spaghetti code can be a result of poor design decisions, excessive coupling, or lack of proper documentation and commenting.</p>
<p>Here are two examples of JavaScript code that perform the same task, one with a clear flow of execution, and the other with spaghetti code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Clear flow of execution</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateDiscount</span>(<span class="hljs-params">price, discountPercentage</span>) </span>{
  <span class="hljs-keyword">const</span> discountAmount = price * (discountPercentage / <span class="hljs-number">100</span>);
  <span class="hljs-keyword">const</span> discountedPrice = price - discountAmount;
  <span class="hljs-keyword">return</span> discountedPrice;
}

<span class="hljs-keyword">const</span> originalPrice = <span class="hljs-number">100</span>;
<span class="hljs-keyword">const</span> discountPercentage = <span class="hljs-number">20</span>;
<span class="hljs-keyword">const</span> finalPrice = calculateDiscount(originalPrice, discountPercentage);

<span class="hljs-built_in">console</span>.log(finalPrice);

<span class="hljs-comment">// Example 2: Spaghetti code</span>
<span class="hljs-keyword">const</span> originalPrice = <span class="hljs-number">100</span>;
<span class="hljs-keyword">const</span> discountPercentage = <span class="hljs-number">20</span>;

<span class="hljs-keyword">let</span> discountedPrice;
<span class="hljs-keyword">let</span> discountAmount;
<span class="hljs-keyword">if</span> (originalPrice &amp;&amp; discountPercentage) {
  discountAmount = originalPrice * (discountPercentage / <span class="hljs-number">100</span>);
  discountedPrice = originalPrice - discountAmount;
}

<span class="hljs-keyword">if</span> (discountedPrice) {
  <span class="hljs-built_in">console</span>.log(discountedPrice);
}
</code></pre>
<p>As we can see, example 1 follows a clear and logical structure, with a function that takes in the necessary parameters and returns the calculated result. On the other hand, example 2 is much more convoluted, with variables declared outside of any function and multiple if statements used to check if the code block has executed successfully.</p>
<h2 id="heading-single-responsibility-principle">Single Responsibility Principle</h2>
<p>The Single Responsibility Principle (SRP) is a principle in software development that states that each class or module should have only one reason to change, or in other words, each entity in our codebase should have a single responsibility.</p>
<p>This principle helps to create code that is easy to understand, maintain, and extend.</p>
<p>By applying SRP, we can create code that is easier to test, reuse, and refactor, since each module only handles a single responsibility. This makes it less likely to have side effects or dependencies that can make the code harder to work with.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Withouth SRP</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processOrder</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-comment">// validate order</span>
  <span class="hljs-keyword">if</span> (order.items.length === <span class="hljs-number">0</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error: Order has no items"</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-comment">// calculate total</span>
  <span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>;
  order.items.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
    total += item.price * item.quantity;
  });

  <span class="hljs-comment">// apply discounts</span>
  <span class="hljs-keyword">if</span> (order.customer === <span class="hljs-string">"vip"</span>) {
    total *= <span class="hljs-number">0.9</span>;
  }

  <span class="hljs-comment">// save order</span>
  <span class="hljs-keyword">const</span> db = <span class="hljs-keyword">new</span> Database();
  db.connect();
  db.saveOrder(order, total);
}
</code></pre>
<p>In this example, the <code>processOrder</code> function handles several responsibilities: it validates the order, calculates the total, applies discounts, and saves the order to a database. This makes the function long and hard to understand, and any changes to one responsibility may affect the others, making it harder to maintain.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 2: With SRP</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderProcessor</span> </span>{
  <span class="hljs-keyword">constructor</span>(order) {
    <span class="hljs-built_in">this</span>.order = order;
  }

  validate() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.order.items.length === <span class="hljs-number">0</span>) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error: Order has no items"</span>);
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }

  calculateTotal() {
    <span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>;
    <span class="hljs-built_in">this</span>.order.items.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
      total += item.price * item.quantity;
    });
    <span class="hljs-keyword">return</span> total;
  }

  applyDiscounts(total) {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.order.customer === <span class="hljs-string">"vip"</span>) {
      total *= <span class="hljs-number">0.9</span>;
    }
    <span class="hljs-keyword">return</span> total;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderSaver</span> </span>{
  <span class="hljs-keyword">constructor</span>(order, total) {
    <span class="hljs-built_in">this</span>.order = order;
    <span class="hljs-built_in">this</span>.total = total;
  }

  save() {
    <span class="hljs-keyword">const</span> db = <span class="hljs-keyword">new</span> Database();
    db.connect();
    db.saveOrder(<span class="hljs-built_in">this</span>.order, <span class="hljs-built_in">this</span>.total);
  }
}

<span class="hljs-keyword">const</span> order = <span class="hljs-keyword">new</span> Order();
<span class="hljs-keyword">const</span> processor = <span class="hljs-keyword">new</span> OrderProcessor(order);

<span class="hljs-keyword">if</span> (processor.validate()) {
  <span class="hljs-keyword">const</span> total = processor.calculateTotal();
  <span class="hljs-keyword">const</span> totalWithDiscounts = processor.applyDiscounts(total);
  <span class="hljs-keyword">const</span> saver = <span class="hljs-keyword">new</span> OrderSaver(order, totalWithDiscounts);
  saver.save();
}
</code></pre>
<p>In this example, the <code>processOrder</code> function has been split into two classes that follow the SRP: <code>OrderProcessor</code> and <code>OrderSaver</code>.</p>
<p>The <code>OrderProcessor</code> class handles the responsibilities of validating the order, calculating the total, and applying discounts, while the <code>OrderSaver</code> class handles the responsibility of saving the order to the database.</p>
<p>This makes the code easier to understand, test, and maintain, since each class has a clear responsibility and can be modified or replaced without affecting the others.</p>
<h2 id="heading-having-a-single-source-of-truth">Having a "Single Source of Truth"</h2>
<p>Having a "single source of truth" means that there is only one place where a particular piece of data or configuration is stored in the codebase, and any other references to it in the code refer back to that one source. This is important because it ensures that the data is consistent and avoids duplication and inconsistency.</p>
<p>Here's an example to illustrate the concept. Let's say we have an application that needs to display the current weather conditions in a city. We could implement this feature in two different ways:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Option 1: No "single source of truth"</span>

<span class="hljs-comment">// file 1: weatherAPI.js</span>
<span class="hljs-keyword">const</span> apiKey = <span class="hljs-string">'12345abcde'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCurrentWeather</span>(<span class="hljs-params">city</span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`https://api.weather.com/conditions/v1/<span class="hljs-subst">${city}</span>?apiKey=<span class="hljs-subst">${apiKey}</span>`</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json());
}

<span class="hljs-comment">// file 2: weatherComponent.js</span>
<span class="hljs-keyword">const</span> apiKey = <span class="hljs-string">'12345abcde'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayCurrentWeather</span>(<span class="hljs-params">city</span>) </span>{
  getCurrentWeather(city)
    .then(<span class="hljs-function"><span class="hljs-params">weatherData</span> =&gt;</span> {
      <span class="hljs-comment">// display weatherData on the UI</span>
    });
}
</code></pre>
<p>In this option, the API key is duplicated in two different files, making it harder to maintain and update. If we ever need to change the API key, we have to remember to update it in both places.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Option 2: "Single source of truth"</span>

<span class="hljs-comment">// file 1: weatherAPI.js</span>
<span class="hljs-keyword">const</span> apiKey = <span class="hljs-string">'12345abcde'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCurrentWeather</span>(<span class="hljs-params">city</span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`https://api.weather.com/conditions/v1/<span class="hljs-subst">${city}</span>?apiKey=<span class="hljs-subst">${apiKey}</span>`</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json());
}

<span class="hljs-keyword">export</span> { getCurrentWeather, apiKey };


<span class="hljs-comment">// file 2: weatherComponent.js</span>
<span class="hljs-keyword">import</span> { getCurrentWeather } <span class="hljs-keyword">from</span> <span class="hljs-string">'./weatherAPI'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayCurrentWeather</span>(<span class="hljs-params">city</span>) </span>{
  getCurrentWeather(city)
    .then(<span class="hljs-function"><span class="hljs-params">weatherData</span> =&gt;</span> {
      <span class="hljs-comment">// display weatherData on the UI</span>
    });
}
</code></pre>
<p>In this option, the API key is stored in one place (in the <code>weatherAPI.js</code> file) and exported for other modules to use. This ensures that there is only one source of truth for the API key and avoids duplication and inconsistency.</p>
<p>If we ever need to update the API key, we can do it in one place and all other modules that use it will automatically get the updated value.</p>
<h2 id="heading-only-expose-and-consume-data-you-need">Only Expose and Consume Data You Need</h2>
<p>One important principle of writing clean code is to only expose and consume the information that is necessary for a particular task. This helps to reduce complexity, increase efficiency, and avoid errors that can arise from using unnecessary data.</p>
<p>When data that is not needed is exposed or consumed, it can lead to performance issues and make the code more difficult to understand and maintain.</p>
<p>Suppose you have an object with multiple properties, but you only need to use a few of them. One way to do this would be to reference the object and the specific properties every time you need them. But this can become verbose and error-prone, especially if the object is deeply nested. A cleaner and more efficient solution would be to use object destructuring to only expose and consume the information you need.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Original object</span>
<span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>,
  <span class="hljs-attr">email</span>: <span class="hljs-string">'alice@example.com'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>,
  <span class="hljs-attr">address</span>: {
    <span class="hljs-attr">street</span>: <span class="hljs-string">'123 Main St'</span>,
    <span class="hljs-attr">city</span>: <span class="hljs-string">'Anytown'</span>,
    <span class="hljs-attr">state</span>: <span class="hljs-string">'CA'</span>,
    <span class="hljs-attr">zip</span>: <span class="hljs-string">'12345'</span>
  }
};

<span class="hljs-comment">// Only expose and consume the name and email properties</span>
<span class="hljs-keyword">const</span> { name, email } = user;

<span class="hljs-built_in">console</span>.log(name); <span class="hljs-comment">// 'Alice'</span>
<span class="hljs-built_in">console</span>.log(email); <span class="hljs-comment">// 'alice@example.com'</span>
</code></pre>
<h2 id="heading-modularization">Modularization</h2>
<p>Modularization is an essential concept in writing clean code. It refers to the practice of breaking down large, complex code into smaller, more manageable modules or functions. This makes the code easier to understand, test, and maintain.</p>
<p>Using modularization provides several benefits such as:</p>
<ol>
<li><p>Re-usability: Modules can be reused in different parts of the application or in other applications, saving time and effort in development.</p>
</li>
<li><p>Encapsulation: Modules allow you to hide the internal details of a function or object, exposing only the essential interface to the outside world. This helps to reduce coupling between different parts of the code and improve overall code quality.</p>
</li>
<li><p>Scalability: By breaking down large code into smaller, modular pieces, you can easily add or remove functionality without affecting the entire codebase.</p>
</li>
</ol>
<p>Here is an example in JavaScript of a piece of code that performs a simple task, one not using modularization and the other implementing modularization.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Without modularization</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculatePrice</span>(<span class="hljs-params">quantity, price, tax</span>) </span>{
  <span class="hljs-keyword">let</span> subtotal = quantity * price;
  <span class="hljs-keyword">let</span> total = subtotal + (subtotal * tax);
  <span class="hljs-keyword">return</span> total;
}

<span class="hljs-comment">// Without modularization</span>
<span class="hljs-keyword">let</span> quantity = <span class="hljs-built_in">parseInt</span>(prompt(<span class="hljs-string">"Enter quantity: "</span>));
<span class="hljs-keyword">let</span> price = <span class="hljs-built_in">parseFloat</span>(prompt(<span class="hljs-string">"Enter price: "</span>));
<span class="hljs-keyword">let</span> tax = <span class="hljs-built_in">parseFloat</span>(prompt(<span class="hljs-string">"Enter tax rate: "</span>));

<span class="hljs-keyword">let</span> total = calculatePrice(quantity, price, tax);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Total: $"</span> + total.toFixed(<span class="hljs-number">2</span>));
</code></pre>
<p>In the above example, the <code>calculatePrice</code> function is used to calculate the total price of an item given its quantity, price, and tax rate. However, this function is not modularized and is tightly coupled with the user input and output logic. This can make it difficult to test and maintain.</p>
<p>Now, let's see an example of the same code using modularization:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// With modularization</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateSubtotal</span>(<span class="hljs-params">quantity, price</span>) </span>{
  <span class="hljs-keyword">return</span> quantity * price;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotal</span>(<span class="hljs-params">subtotal, tax</span>) </span>{
  <span class="hljs-keyword">return</span> subtotal + (subtotal * tax);
}

<span class="hljs-comment">// With modularization</span>
<span class="hljs-keyword">let</span> quantity = <span class="hljs-built_in">parseInt</span>(prompt(<span class="hljs-string">"Enter quantity: "</span>));
<span class="hljs-keyword">let</span> price = <span class="hljs-built_in">parseFloat</span>(prompt(<span class="hljs-string">"Enter price: "</span>));
<span class="hljs-keyword">let</span> tax = <span class="hljs-built_in">parseFloat</span>(prompt(<span class="hljs-string">"Enter tax rate: "</span>));

<span class="hljs-keyword">let</span> subtotal = calculateSubtotal(quantity, price);
<span class="hljs-keyword">let</span> total = calculateTotal(subtotal, tax);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Total: $"</span> + total.toFixed(<span class="hljs-number">2</span>));
</code></pre>
<p>In the above example, the <code>calculatePrice</code> function has been broken down into two smaller functions: <code>calculateSubtotal</code> and <code>calculateTotal</code>. These functions are now modularized and are responsible for calculating the subtotal and total, respectively. This makes the code easier to understand, test, and maintain, and also makes it more reusable in other parts of the application.</p>
<p>Modularization can also refer to the practice of dividing single files of code into many smaller files that are later on compiled back on to a single (or fewer files). This practice has the same benefits we just talked about.</p>
<p>If you'd like to know how to implement this in JavaScript using modules, <a target="_blank" href="https://www.freecodecamp.org/news/modules-in-javascript/">check out this other article of mine</a>.</p>
<h2 id="heading-folder-structures">Folder Structures</h2>
<p>Choosing a good folder structure is an essential part of writing clean code. A well-organized project structure helps developers find and modify code easily, reduces code complexity, and improves project scalability and maintainability.</p>
<p>On the other hand, a poor folder structure can make it challenging to understand the project's architecture, navigate the codebase, and lead to confusion and errors.</p>
<p>Here are examples of a good and a bad folder structure using a React project as an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Bad folder structure</span>
my-app/
├── App.js
├── index.js
├── components/
│   ├── Button.js
│   ├── Card.js
│   └── Navbar.js
├── containers/
│   ├── Home.js
│   ├── Login.js
│   └── Profile.js
├── pages/
│   ├── Home.js
│   ├── Login.js
│   └── Profile.js
└── utilities/
    ├── api.js
    └── helpers.js
</code></pre>
<p>In this example, the project structure is organized around file types, such as components, containers, and pages.</p>
<p>But this approach can lead to confusion and duplication, as it's not clear which files belong where. For example, the <code>Home</code> component is present in both the <code>containers</code> and <code>pages</code> folders. It can also make it challenging to find and modify code, as developers may need to navigate multiple folders to find the code they need.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Good folder structure</span>
my-app/
├── src/
│   ├── components/
│   │   ├── Button/
│   │   │   ├── Button.js
│   │   │   ├── Button.module.css
│   │   │   └── index.js
│   │   ├── Card/
│   │   │   ├── Card.js
│   │   │   ├── Card.module.css
│   │   │   └── index.js
│   │   └── Navbar/
│   │       ├── Navbar.js
│   │       ├── Navbar.module.css
│   │       └── index.js
│   ├── pages/
│   │   ├── Home/
│   │   │   ├── Home.js
│   │   │   ├── Home.module.css
│   │   │   └── index.js
│   │   ├── Login/
│   │   │   ├── Login.js
│   │   │   ├── Login.module.css
│   │   │   └── index.js
│   │   └── Profile/
│   │       ├── Profile.js
│   │       ├── Profile.module.css
│   │       └── index.js
│   ├── utils/
│   │   ├── api.js
│   │   └── helpers.js
│   ├── App.js
│   └── index.js
└── public/
    ├── index.html
    └── favicon.ico
</code></pre>
<p>In this example, the project structure is organized around features, such as components, pages, and utils. Each feature has its own folder, which contains all the files related to that feature.</p>
<p>This approach makes it easy to find and modify code, as all the files related to a feature are located in the same folder. It also reduces code duplication and complexity, as features are separated, and their related files are organized together.</p>
<p>Overall, a good folder structure should be organized around features, not file types, and should make it easy to find and modify code. A clear and logical structure can make a project easier to maintain, understand and scale, while a confusing and inconsistent structure can lead to errors and confusion.</p>
<p>If you're interested in learning more about this, <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-software-architecture-patterns/#different-folder-structures-to-know">in this article I wrote about software architecture</a> I expanded upon the topic of folder structures and well-known patterns you can follow.</p>
<h2 id="heading-documentation">Documentation</h2>
<p>Documentation is an essential part of writing clean code. Proper documentation not only helps the developer who wrote the code understand it better in the future but also makes it easier for other developers to read and understand the codebase. When code is well-documented, it can save time and effort in debugging and maintaining the code.</p>
<p>Documenting is specially important in cases in which simple and easy to understand solutions can't be implemented, cases when the business logic is quite complex, and cases in which people who are not familiar with the codebase have to interact with it.</p>
<p>One way to document code is by using comments. Comments can provide context and explain what the code is doing. But it's important to use comments wisely, only commenting where necessary and avoiding redundant or unnecessary ones.</p>
<p>Another way to document code is by using inline documentation. Inline documentation is embedded in the code itself and can be used to explain what a specific function or piece of code does. Inline documentation is often used in combination with tools like <a target="_blank" href="https://jsdoc.app/">JSDoc</a>, which provides a standard for documenting code in JavaScript.</p>
<p>Tools like Typescript can also provide automatic documentation for our codebase, which is hugely helpful.</p>
<p>If you'd like to know more about Typescript, I wrote <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-typescript/#otherfunctionalitiesoftypescript">a beginner friendly guide a while ago</a>.</p>
<p>And Lastly, tools like Swagger and Postman can be used to document APIs, providing a way to easily understand how to interact with them</p>
<p>If you're interested in knowing how to fully implement, test, consume and document APIs, I recently wrote two guides for <a target="_blank" href="https://www.freecodecamp.org/news/build-consume-and-document-a-rest-api/">REST APIs</a> and <a target="_blank" href="https://www.freecodecamp.org/news/building-consuming-and-documenting-a-graphql-api/">GraphQL APIs</a>.</p>
<h1 id="heading-wrapping-up"><strong>Wrap</strong>ping <strong>Up</strong></h1>
<p>Well everyone, as always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/giphy.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The GraphQL API Handbook – How to Build, Test, Consume and Document GraphQL APIs ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this tutorial we're going to take a deep dive into GraphQL APIs. I recently wrote this article where I explained the main differences between common API types nowadays. And this tutorial aims to show you an example of how you can full... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/building-consuming-and-documenting-a-graphql-api/</link>
                <guid isPermaLink="false">66d45ef1230dff0166905805</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Tue, 02 May 2023 13:23:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/jj-ying-8bghKxNU1j0-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this tutorial we're going to take a deep dive into GraphQL APIs.</p>
<p>I recently wrote <a target="_blank" href="https://www.freecodecamp.org/news/rest-vs-graphql-apis/">this article</a> where I explained the main differences between common API types nowadays. And this tutorial aims to show you an example of how you can fully implement a GraphQL API.</p>
<p>We'll cover basic setup and architecture with Node and Apollo GraphQL, unit testing with Supertest, seeing how we can consume the API from a React front-end app using Apollo client and finally documenting the API using Apollo sandbox.</p>
<p>Keep in mind we won't go too deep into how each technology works. The goal here is to give you a general overview of how a GraphQL API works, how its pieces interact, and what a full implementation might consist of.</p>
<p>Let's go!</p>
<h1 id="heading-table-of-contents"><strong>Table of Contents</strong></h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-graphql">What is GraphQL?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-core-graphql-concepts">Core GraphQL concepts</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-object-types">Object Types</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-queries">Queries</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-mutations">Mutations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-resolvers">Resolvers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-schemas">Schemas</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tldr-and-comparison-with-equivalent-rest-concepts">TLDR and comparison with equivalent REST concepts</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-a-graphql-api-with-node-and-apollo-graphql">How to Build a GraphQL API with Node and Apollo GraphQL</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-test-a-graphql-api-with-supertest">How to Test a GraphQL API with Supertest</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-consume-a-graphql-api-on-a-front-end-react-app">How to Consume a GraphQL API on a Front-end React App</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-document-a-graphql-api-with-apollo-sandbox">How to Document a GraphQL API with Apollo sandbox</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></p>
</li>
</ul>
<h1 id="heading-what-is-graphql">What is GraphQL?</h1>
<p><a target="_blank" href="https://graphql.org/">GraphQL</a> is a query language and runtime for APIs that was developed by Facebook in 2012. It was released to the public in 2015 and has since gained popularity as an alternative to REST APIs.</p>
<p>GraphQL was originally developed by Facebook as a way to simplify data fetching for their mobile applications. They needed a way to make complex data requests from the server without causing performance issues or over-fetching data. GraphQL was born out of the need to solve these problems.</p>
<p>GraphQL was released as an open-source project in 2015 and has since gained popularity in the developer community. It is now supported by many development tools and frameworks, including Apollo, Prisma, and Hasura.</p>
<p><strong>Main Characteristics:</strong></p>
<ol>
<li><p><strong>Strongly Typed:</strong> GraphQL APIs are strongly typed, which means that each field has a specific data type. This makes it easier to validate and handle data on the client and server sides.</p>
</li>
<li><p><strong>Query Language:</strong> GraphQL has its own query language that allows clients to specify exactly what data they need. This reduces over-fetching of data and improves performance.</p>
</li>
<li><p><strong>Single Endpoint:</strong> GraphQL APIs have a single endpoint, which means that clients can fetch all the data they need from a single request.</p>
</li>
<li><p><strong>Declarative:</strong> GraphQL APIs are declarative, which means that clients specify what they want, not how to get it. This allows for more efficient and flexible data fetching.</p>
</li>
<li><p><strong>Schema-Driven:</strong> GraphQL APIs are schema-driven, which means that the schema defines the structure of the data and the available queries and mutations. This makes it easier for developers to understand and work with the API.</p>
</li>
</ol>
<p><strong>Pros:</strong></p>
<ul>
<li><p><strong>Efficient Data Fetching:</strong> GraphQL APIs allow clients to fetch only the data they need, reducing over-fetching and improving performance.</p>
</li>
<li><p><strong>Strongly Typed:</strong> GraphQL APIs are strongly typed, making it easier to validate and handle data.</p>
</li>
<li><p><strong>Single Endpoint:</strong> GraphQL APIs have a single endpoint, reducing the complexity of the API and making it easier to work with.</p>
</li>
<li><p><strong>Schema-Driven:</strong> GraphQL APIs are schema-driven, which makes it easier for developers to understand and work with the API.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p><strong>Complexity:</strong> GraphQL APIs can be more complex to set up and work with compared to REST APIs.</p>
</li>
<li><p><strong>Caching:</strong> Caching can be more challenging with GraphQL APIs due to the flexible nature of the API.</p>
</li>
<li><p><strong>Learning Curve:</strong> GraphQL requires a learning curve for both developers and clients, as it has its own query language and approach to data fetching.</p>
</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li><p><strong>Efficient and flexible needs:</strong> GraphQL is well-suited for building applications that require efficient and flexible data fetching, such as mobile and web applications.</p>
</li>
<li><p><strong>Complex data requirements:</strong> It is particularly useful in situations where there are complex data requirements and where over-fetching data can cause performance issues.</p>
</li>
</ul>
<p>So to recap, GraphQL is a query language and runtime for APIs that provides efficient and flexible data fetching capabilities.</p>
<p>While it can be more complex to set up and work with compared to REST APIs, it offers benefits such as strongly typed data, single endpoints, and schema-driven development. It is well-suited for building applications with complex data requirements and where efficient data fetching is important.</p>
<h1 id="heading-core-graphql-concepts">Core GraphQL Concepts</h1>
<p>Before we jump into building stuff, there are some core GraphQL concepts you need to understand in order to know what you're doing and how the code will work.</p>
<h2 id="heading-object-types">Object Types</h2>
<p>In GraphQL, an Object Type is a complex type that represents a collection of fields. <strong>Object Types are used to define the structure of data that can be queried and mutated</strong> through a GraphQL API.</p>
<p>Each Object Type has a unique name and a set of fields, where each field has a name and a type. The type of a field can be a scalar type (such as Int, String, or Boolean), another Object Type, or a list of another type.</p>
<p>If you're familiar with <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-typescript/#interfaces">Typescript and interfaces</a>, this might ring a bell or two for you.</p>
<p>Here's an example of an Object Type that represents a "User" in a social media application:</p>
<pre><code class="lang-yaml"><span class="hljs-string">type</span> <span class="hljs-string">User</span> {
  <span class="hljs-attr">id:</span> <span class="hljs-string">ID!</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">String!</span>
  <span class="hljs-attr">email:</span> <span class="hljs-string">String!</span>
  <span class="hljs-attr">friends:</span> [<span class="hljs-string">User!</span>]<span class="hljs-string">!</span>
}
</code></pre>
<p>The <code>!</code> sign means the field is mandatory.</p>
<p>In this example, the "User" Object Type has four fields: "id", "name", "email", and "friends". The "id" field has a type of ID, which is a built-in scalar type in GraphQL that represents a unique identifier. The "name" and "email" fields have a type of String, and the "friends" field has a type of a list of "User" Objects.</p>
<p>Here's another example of an Object Type that represents a "Book" in a library application:</p>
<pre><code class="lang-yaml"><span class="hljs-string">type</span> <span class="hljs-string">Book</span> {
  <span class="hljs-attr">id:</span> <span class="hljs-string">ID!</span>
  <span class="hljs-attr">title:</span> <span class="hljs-string">String!</span>
  <span class="hljs-attr">author:</span> <span class="hljs-string">Author!</span>
  <span class="hljs-attr">genre:</span> <span class="hljs-string">String!</span>
  <span class="hljs-attr">published:</span> <span class="hljs-string">Int!</span>
}
</code></pre>
<p>In this example, the "Book" Object Type has five fields: "id", "title", "author", "genre", and "published". The "id" field has a type of ID, the "title" and "genre" fields have a type of String, the "published" field has a type of Int, and the "author" field has a type of an "Author" Object.</p>
<p>Object Types can be used to define the structure of data that is returned from a query or mutation in a GraphQL API. For example, a query that returns a list of users might look like this:</p>
<pre><code class="lang-yaml"><span class="hljs-string">query</span> {
  <span class="hljs-string">users</span> {
    <span class="hljs-string">id</span>
    <span class="hljs-string">name</span>
    <span class="hljs-string">email</span>
    <span class="hljs-string">friends</span> {
      <span class="hljs-string">id</span>
      <span class="hljs-string">name</span>
    }
  }
}
</code></pre>
<p>In this query, the "users" field returns a list of "User" Objects, and the query specifies which fields to include in the response.</p>
<h2 id="heading-queries">Queries</h2>
<p>In GraphQL, <strong>a query is a request for specific data from the server</strong>. The query specifies the shape of the data that the client wants to receive, and the server responds with the requested data in the same shape.</p>
<p>A query in GraphQL follows a similar structure to the shape of the data it expects to receive. It consists of a set of fields that correspond to the properties of the data the client wants to retrieve. Each field can also have arguments that modify the data returned.</p>
<p>Here's an example of a simple query in GraphQL:</p>
<pre><code class="lang-yaml"><span class="hljs-string">query</span> {
  <span class="hljs-string">user(id:</span> <span class="hljs-string">"1"</span><span class="hljs-string">)</span> {
    <span class="hljs-string">name</span>
    <span class="hljs-string">email</span>
    <span class="hljs-string">age</span>
  }
}
</code></pre>
<p>In this example, the query is requesting information about a user with the ID of "1". The fields specified in the query are "name", "email", and "age", which correspond to the properties of the user object.</p>
<p>The response from the server would be in the same shape as the query, with the requested data returned in the corresponding fields:</p>
<pre><code class="lang-yaml">{
  <span class="hljs-attr">"data":</span> {
    <span class="hljs-attr">"user":</span> {
      <span class="hljs-attr">"name":</span> <span class="hljs-string">"John Doe"</span>,
      <span class="hljs-attr">"email":</span> <span class="hljs-string">"johndoe@example.com"</span>,
      <span class="hljs-attr">"age":</span> <span class="hljs-number">25</span>
    }
  }
}
</code></pre>
<p>Here, the server has returned the requested data about the user in the "name", "email", and "age" fields. The data is contained in a "data" object to differentiate it from any errors or other metadata that may be included in the response.</p>
<h2 id="heading-mutations">Mutations</h2>
<p>In GraphQL, mutations are used to modify or create data on the server. Like queries, mutations specify the shape of the data being sent to and received from the server. The main difference is that while <strong>queries only read data, mutations can both read and write data</strong>.</p>
<p>Here's an example of a simple mutation in GraphQL:</p>
<pre><code class="lang-yaml"><span class="hljs-string">mutation</span> {
  <span class="hljs-string">createUser(name:</span> <span class="hljs-string">"Jane Doe"</span>, <span class="hljs-attr">email:</span> <span class="hljs-string">"janedoe@example.com"</span>, <span class="hljs-attr">age:</span> <span class="hljs-number">30</span><span class="hljs-string">)</span> {
    <span class="hljs-string">id</span>
    <span class="hljs-string">name</span>
    <span class="hljs-string">email</span>
    <span class="hljs-string">age</span>
  }
}
</code></pre>
<p>In this example, the mutation is creating a new user on the server with the name "Jane Doe", email "janedoe@example.com", and age 30. The fields specified in the mutation are "id", "name", "email", and "age", which correspond to the properties of the user object.</p>
<p>The response from the server would be in the same shape as the mutation, with the newly created user data returned in the corresponding fields:</p>
<pre><code class="lang-yaml">{
  <span class="hljs-attr">"data":</span> {
    <span class="hljs-attr">"createUser":</span> {
      <span class="hljs-attr">"id":</span> <span class="hljs-string">"123"</span>,
      <span class="hljs-attr">"name":</span> <span class="hljs-string">"Jane Doe"</span>,
      <span class="hljs-attr">"email":</span> <span class="hljs-string">"janedoe@example.com"</span>,
      <span class="hljs-attr">"age":</span> <span class="hljs-number">30</span>
    }
  }
}
</code></pre>
<p>Here, the server has returned the data about the newly created user in the "id", "name", "email", and "age" fields.</p>
<p>Mutations can also be used to update or delete data on the server. Here's an example of a mutation that updates a user's name:</p>
<pre><code class="lang-yaml"><span class="hljs-string">mutation</span> {
  <span class="hljs-string">updateUser(id:</span> <span class="hljs-string">"123"</span>, <span class="hljs-attr">name:</span> <span class="hljs-string">"Jane Smith"</span><span class="hljs-string">)</span> {
    <span class="hljs-string">id</span>
    <span class="hljs-string">name</span>
    <span class="hljs-string">email</span>
    <span class="hljs-string">age</span>
  }
}
</code></pre>
<p>In this example, the mutation is updating the user with the ID of "123" to have the name "Jane Smith". The fields specified in the mutation are the same as in the previous example.</p>
<p>The response from the server would be the updated user data:</p>
<pre><code class="lang-yaml">{
  <span class="hljs-attr">"data":</span> {
    <span class="hljs-attr">"updateUser":</span> {
      <span class="hljs-attr">"id":</span> <span class="hljs-string">"123"</span>,
      <span class="hljs-attr">"name":</span> <span class="hljs-string">"Jane Smith"</span>,
      <span class="hljs-attr">"email":</span> <span class="hljs-string">"janedoe@example.com"</span>,
      <span class="hljs-attr">"age":</span> <span class="hljs-number">30</span>
    }
  }
}
</code></pre>
<p>Mutations in GraphQL are designed to be composable, meaning that multiple mutations can be combined into a single request. This allows clients to perform complex operations with a single network round-trip.</p>
<h2 id="heading-resolvers">Resolvers</h2>
<p>In GraphQL, a resolver is a function responsible for fetching the data for a specific field defined in a GraphQL schema. Resolvers are the bridge between the schema and the data source. The resolver function receives four parameters: parent, args, context, and info.</p>
<ul>
<li><p><code>parent</code>: The parent object for the current field. In nested queries, it refers to the parent field's value.</p>
</li>
<li><p><code>args</code>: The arguments passed to the current field. It is an object with key-value pairs of the argument names and their values.</p>
</li>
<li><p><code>context</code>: An object shared across all resolvers for a particular request. It contains information about the request such as the currently authenticated user, database connection, etc.</p>
</li>
<li><p><code>info</code>: Contains information about the query including the field name, alias, and the query document AST.</p>
</li>
</ul>
<p>Here's an example of a resolver function for a <code>User</code> type's <code>posts</code> field:</p>
<pre><code class="lang-yaml"><span class="hljs-string">const</span> <span class="hljs-string">resolvers</span> <span class="hljs-string">=</span> {
  <span class="hljs-attr">User:</span> {
    <span class="hljs-attr">posts:</span> <span class="hljs-string">(parent</span>, <span class="hljs-string">args</span>, <span class="hljs-string">context</span>, <span class="hljs-string">info)</span> <span class="hljs-string">=&gt;</span> {
      <span class="hljs-string">return</span> <span class="hljs-string">getPostsByUserId(parent.id);</span>
    },
  },
}<span class="hljs-string">;</span>
</code></pre>
<p>In this example, <code>User</code> is a GraphQL object type with a <code>posts</code> field. When the <code>posts</code> field is queried, the resolver function is called with the parent object <code>User</code>, any arguments passed, the context object, and query information. In this example, the resolver function calls a function <code>getPostsByUserId</code> to fetch the posts for the current user.</p>
<p>Resolvers can also be used for mutations to create, update or delete data. Here's an example of a resolver function for a <code>createUser</code> mutation:</p>
<pre><code class="lang-yaml"><span class="hljs-string">const</span> <span class="hljs-string">resolvers</span> <span class="hljs-string">=</span> {
  <span class="hljs-attr">Mutation:</span> {
    <span class="hljs-attr">createUser:</span> <span class="hljs-string">(parent</span>, <span class="hljs-string">args</span>, <span class="hljs-string">context</span>, <span class="hljs-string">info)</span> <span class="hljs-string">=&gt;</span> {
      <span class="hljs-string">const</span> <span class="hljs-string">user</span> <span class="hljs-string">=</span> { <span class="hljs-attr">name:</span> <span class="hljs-string">args.name</span>, <span class="hljs-attr">email:</span> <span class="hljs-string">args.email</span> }<span class="hljs-string">;</span>
      <span class="hljs-string">const</span> <span class="hljs-string">createdUser</span> <span class="hljs-string">=</span> <span class="hljs-string">createUser(user);</span>
      <span class="hljs-string">return</span> <span class="hljs-string">createdUser;</span>
    },
  },
}<span class="hljs-string">;</span>
</code></pre>
<p>In this example, <code>Mutation</code> is a GraphQL object type with a <code>createUser</code> mutation field. When the mutation is invoked, the resolver function is called with the parent object, arguments passed, context object, and query information. In this example, the resolver function calls a function <code>createUser</code> to create a new user with the given name and email, and returns the newly created user.</p>
<h2 id="heading-schemas">Schemas</h2>
<p>In GraphQL, a schema is a blueprint that defines the structure of the data that can be queried in the API. It defines the available types, fields, and operations that can be performed on those types.</p>
<p>GraphQL schemas are written in the GraphQL Schema Definition Language (SDL), which uses a simple syntax to define the types and fields available in the API. The schema is typically defined in the server-side code and then used to validate and execute incoming queries.</p>
<p>Here's an example of a simple GraphQL schema definition:</p>
<pre><code class="lang-yaml"><span class="hljs-string">type</span> <span class="hljs-string">Book</span> {
  <span class="hljs-attr">id:</span> <span class="hljs-string">ID!</span>
  <span class="hljs-attr">title:</span> <span class="hljs-string">String!</span>
  <span class="hljs-attr">author:</span> <span class="hljs-string">String!</span>
  <span class="hljs-attr">published:</span> <span class="hljs-string">Int!</span>
}

<span class="hljs-string">type</span> <span class="hljs-string">Query</span> {
  <span class="hljs-attr">books:</span> [<span class="hljs-string">Book!</span>]<span class="hljs-string">!</span>
  <span class="hljs-string">book(id:</span> <span class="hljs-string">ID!):</span> <span class="hljs-string">Book</span>
}

<span class="hljs-string">type</span> <span class="hljs-string">Mutation</span> {
  <span class="hljs-string">addBook(title:</span> <span class="hljs-string">String!</span>, <span class="hljs-attr">author:</span> <span class="hljs-string">String!</span>, <span class="hljs-attr">published:</span> <span class="hljs-string">Int!):</span> <span class="hljs-string">Book!</span>
  <span class="hljs-string">updateBook(id:</span> <span class="hljs-string">ID!</span>, <span class="hljs-attr">title:</span> <span class="hljs-string">String</span>, <span class="hljs-attr">author:</span> <span class="hljs-string">String</span>, <span class="hljs-attr">published:</span> <span class="hljs-string">Int):</span> <span class="hljs-string">Book</span>
  <span class="hljs-string">deleteBook(id:</span> <span class="hljs-string">ID!):</span> <span class="hljs-string">Book</span>
}
</code></pre>
<p>In this schema, we have three types: <code>Book</code>, <code>Query</code>, and <code>Mutation</code>. The <code>Book</code> type has four fields: <code>id</code>, <code>title</code>, <code>author</code>, and <code>published</code>. The <code>Query</code> type has two fields: <code>books</code> and <code>book</code>, which can be used to retrieve a list of books or a specific book by ID, respectively. The <code>Mutation</code> type has three fields: <code>addBook</code>, <code>updateBook</code>, and <code>deleteBook</code>, which can be used to create, update, or delete books.</p>
<p>Note that each field has a type, which can be a built-in scalar type like <code>String</code> or <code>Int</code>, or a custom type like <code>Book</code>. The <code>!</code> after a type indicates that the field is non-nullable, meaning it must always return a value (that is, it cannot be null).</p>
<h2 id="heading-tldr-and-comparison-with-equivalent-rest-concepts">TLDR and Comparison with Equivalent REST Concepts</h2>
<ul>
<li><p><strong>Object Types:</strong> In GraphQL, Object Types are used to define the data that can be queried from an API, similar to how the response data model is defined in REST APIs. However, unlike REST, where data models are often defined in different formats (for example, JSON or XML), GraphQL Object Types are defined using a single language-agnostic syntax.</p>
</li>
<li><p><strong>Queries:</strong> In GraphQL, queries are used to fetch data from an API, similar to HTTP GET requests in REST APIs. However, unlike REST APIs, where multiple requests may be required to fetch nested data, GraphQL queries can be used to fetch nested data in a single request.</p>
</li>
<li><p><strong>Mutations:</strong> In GraphQL, mutations are used to modify data in an API, similar to HTTP POST, PUT, and DELETE requests in REST APIs. However, unlike REST APIs, where different endpoints may be required to perform different modifications, GraphQL mutations are performed through a single endpoint.</p>
</li>
<li><p><strong>Resolvers:</strong> In GraphQL, resolvers are used to specify how to fetch data for a particular field in a query or mutation. Resolvers are similar to controller methods in REST APIs, which are used to fetch data from a database and return it as a response.</p>
</li>
<li><p><strong>Schemas:</strong> In GraphQL, a schema is used to define the data that can be queried or mutated from an API. It specifies the types of data that can be requested, how they can be queried, and what mutations are allowed. In REST APIs, schemas are often defined using OpenAPI or Swagger, which specify the endpoints, request and response types, and other metadata for an API.</p>
</li>
</ul>
<p>Overall, GraphQL and REST APIs differ in how they handle data fetching and modification.</p>
<p>REST APIs rely on multiple endpoints and HTTP methods to fetch and modify data, whereas GraphQL uses a single endpoint and queries/mutations to accomplish the same.</p>
<p>GraphQL's use of a single schema to define the data model of an API makes it easier to understand and maintain compared to REST APIs, which often require multiple documentation formats to describe the same data model.</p>
<h1 id="heading-how-to-build-a-graphql-api-with-node-and-apollo-graphql">How to Build a GraphQL API with Node and Apollo GraphQL</h1>
<h2 id="heading-our-tools">Our Tools</h2>
<p><a target="_blank" href="https://nodejs.org/"><strong>Node.js</strong></a> is an open-source, cross-platform, back-end JavaScript runtime environment that allows developers to execute JavaScript code outside of a web browser. It was created by Ryan Dahl in 2009 and has since become a popular choice for building web applications, APIs, and servers.</p>
<p>Node.js provides an event-driven, non-blocking I/O model that makes it lightweight and efficient, allowing it to handle large amounts of data with high performance. It also has a large and active community, with many libraries and modules available to help developers build their applications more quickly and easily.</p>
<p><a target="_blank" href="https://www.apollographql.com/"><strong>Apollo GraphQL</strong></a> is a full-stack platform for building GraphQL APIs. It provides tools and libraries that simplify the process of building, managing, and consuming GraphQL APIs.</p>
<p>The core of the Apollo GraphQL platform is the Apollo Server, a lightweight and flexible server that makes it easy to build scalable and performant GraphQL APIs. The Apollo Server supports a wide range of data sources, including databases, REST APIs, and other services, making it easy to integrate with existing systems.</p>
<p>Apollo also provides a number of client libraries, including the Apollo Client for web and mobile, which simplifies the process of consuming GraphQL APIs. The Apollo Client makes it easy to query and mutate data, and provides advanced features like caching, optimistic UI, and real-time updates.</p>
<p>In addition to the Apollo Server and Apollo Client, Apollo provides a number of other tools and services, including a schema management platform, a GraphQL analytics service, and a set of developer tools for building and debugging GraphQL APIs.</p>
<p>If you're new to GraphQL or to Apollo itself, I really recommend you <a target="_blank" href="https://www.apollographql.com/docs/">check out their docs</a>. They're some of the best out there in my opinion.</p>
<h2 id="heading-our-architecture">Our Architecture</h2>
<p>For this project we'll follow a layers architecture in our codebase. Layers architecture is about dividing concerns and responsibilities into different folders and files, and allowing direct communication only between certain folders and files.</p>
<p>The matter of how many layers should your project have, what names should each layer have, and what actions should it handle is all a matter of discussion. So let's see what I think is a good approach for our example.</p>
<p>Our application will have five different layers, which will be ordered in this way:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/Untitled-Diagram.drawio.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Application layers</em></p>
<ul>
<li><p>The application layer will have the basic setup of our server and the connection to our schema and resolvers (the next layer).</p>
</li>
<li><p>The schema and resolvers layer will have the type definitions for our data and the connection to our queries and mutations (the next layer).</p>
</li>
<li><p>The queries and mutations layer will have the actual logic we want to perform in each of our queries and mutations and the connection to the model layer (the next layer, you get the idea...)</p>
</li>
<li><p>The model layer will hold the logic for interacting with our mock database.</p>
</li>
<li><p>Finally, the persistence layer is where our database will be.</p>
</li>
</ul>
<p>An important thing to keep in mind is that in these kinds of architectures, <strong>there's a defined communication flow</strong> between the layers that has to be followed for it to make sense.</p>
<p>This means that a request first has to go through the first layer, then the second, then the third and so on. No request should skip layers because that would mess with the logic of the architecture and the benefits of organization and modularity it gives us.</p>
<p>If you'd like to know some other API architecture options, I recommend <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-software-architecture-patterns/">this software architecture article</a> I wrote a while ago.</p>
<h2 id="heading-the-code">The Code</h2>
<p>Before jumping to the code, let's mention what we'll actually build. We'll be building an API for a pet shelter business. This pet shelter needs to register the pets that are staying in the shelter, and for that we'll perform basic CRUD operations (create, read, update and delete).</p>
<p>We're using the exact same example we used in <a target="_blank" href="https://www.freecodecamp.org/news/build-consume-and-document-a-rest-api/">my article about fully implementing a REST API.</a> If you're interested in reading that too, this should help to compare concepts between REST and GraphQL, and understand its differences and similarities. ;)</p>
<p>Now let's get this thing going. Create a new directory, hop in to it and start a new Node project by running <code>npm init -y</code>. For our GraphQL server we'll need two more dependencies, so run <code>npm i @apollo/server</code> and <code>npm i graphql</code> too.</p>
<h3 id="heading-appjs">App.js</h3>
<p>In the root of your project, create an <code>app.js</code> file and drop this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { ApolloServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/server'</span>
<span class="hljs-keyword">import</span> { startStandaloneServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/server/standalone'</span>
<span class="hljs-keyword">import</span> { typeDefs, resolvers } <span class="hljs-keyword">from</span> <span class="hljs-string">'./pets/index.js'</span>

<span class="hljs-comment">// The ApolloServer constructor requires two parameters: your schema</span>
<span class="hljs-comment">// definition and your set of resolvers.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-keyword">new</span> ApolloServer({
    typeDefs,
    resolvers
})

<span class="hljs-comment">// Passing an ApolloServer instance to the `startStandaloneServer` function:</span>
<span class="hljs-comment">//  1. creates an Express app</span>
<span class="hljs-comment">//  2. installs your ApolloServer instance as middleware</span>
<span class="hljs-comment">//  3. prepares your app to handle incoming requests</span>
<span class="hljs-keyword">const</span> { url } = <span class="hljs-keyword">await</span> startStandaloneServer(server, {
    <span class="hljs-attr">listen</span>: { <span class="hljs-attr">port</span>: <span class="hljs-number">4000</span> }
})

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`🚀  Server ready at: <span class="hljs-subst">${url}</span>`</span>)
</code></pre>
<p>Here we're setting up our Apollo server, by passing it our typeDefs and resolvers (we'll explain those in a sec), and then starting the server in port 4000.</p>
<p>Next, go ahead and create this folder structure in your project:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Our folder structure</em></p>
<h3 id="heading-indexjs">index.js</h3>
<p>Within the <code>index.js</code> file put this code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { addPet, editPet, deletePet } <span class="hljs-keyword">from</span> <span class="hljs-string">'./mutations/pets.mutations.js'</span>
<span class="hljs-keyword">import</span> { listPets, getPet } <span class="hljs-keyword">from</span> <span class="hljs-string">'./queries/pets.queries.js'</span>

<span class="hljs-comment">// A schema is a collection of type definitions (hence "typeDefs")</span>
<span class="hljs-comment">// that together define the "shape" of queries that are executed against your data.</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> typeDefs = <span class="hljs-string">`#graphql
  # OBJECT TYPES
  # This "Pet" type defines the queryable fields for every pet in our data source.
  type Pet {
    id: ID!
    name: String!
    type: String!
    age: Int!
    breed: String!
  }

  # INPUT TYPES
  # Define the input objects for addPet and editPet mutations
  input PetToEdit {
    id: ID!
    name: String!
    type: String!
    age: Int!
    breed: String!
  }

  input PetToAdd {
    name: String!
    type: String!
    age: Int!
    breed: String!
  }

  # The "Query" type is special: it lists all of the available queries that
  # clients can execute, along with the return type for each. In this
  # case, the "pets" query returns an array of zero or more pets.
  # QUERY TYPES
  type Query {
    pets: [Pet],
    pet(id: ID!): Pet
  }

  # MUTATION TYPES
  type Mutation {
    addPet(petToAdd: PetToAdd!): Pet,
    editPet(petToEdit: PetToEdit!): Pet,
    deletePet(id: ID!): [Pet],
  }
`</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> resolvers = {
    <span class="hljs-comment">// Resolvers for Queries</span>
    <span class="hljs-attr">Query</span>: {
        <span class="hljs-attr">pets</span>: <span class="hljs-function">() =&gt;</span> listPets(),
        <span class="hljs-attr">pet</span>: <span class="hljs-function">(<span class="hljs-params">_, { id }</span>) =&gt;</span> getPet(id)
    },

    <span class="hljs-comment">// Resolvers for Mutations</span>
    <span class="hljs-attr">Mutation</span>: {
        <span class="hljs-attr">addPet</span>: <span class="hljs-function">(<span class="hljs-params">_, { petToAdd }</span>) =&gt;</span> addPet(petToAdd),
        <span class="hljs-attr">editPet</span>: <span class="hljs-function">(<span class="hljs-params">_, { petToEdit }</span>) =&gt;</span> editPet(petToEdit),
        <span class="hljs-attr">deletePet</span>: <span class="hljs-function">(<span class="hljs-params">_, { id }</span>) =&gt;</span> deletePet(id)
    }
}
</code></pre>
<p>Here we have two main things: typeDefs and resolvers.</p>
<p><strong>typeDefs</strong> defines the types for the data that can be queried in our API (in our case that's the <code>pet</code> object), as well as the input for queries/mutations (in our case that's <code>PetToEdit</code> and <code>PetToAdd</code>).</p>
<p>Lastly, it also defines the available queries and mutations for our API, declaring their names, as well as their input and return values. In our case we have two queries (<code>pets</code> and <code>pet</code>) and three mutations (<code>addPet</code>, <code>editPet</code> and <code>deletePet</code>).</p>
<p><strong>resolvers</strong> contain the actual implementation of our queries and mutations types. Here we're declaring each query and mutation, and indicating what each should do. In our case, we're linking them with the queries/mutations we're importing from our queries/mutations layer.</p>
<h3 id="heading-petsqueriesjs">pets.queries.js</h3>
<p>In your <code>pets.queries.js</code> file drop this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { getItem, listItems } <span class="hljs-keyword">from</span> <span class="hljs-string">'../models/pets.models.js'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getPet = <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = getItem(id)
        <span class="hljs-keyword">return</span> resp
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-keyword">return</span> err
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> listPets = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = listItems()
        <span class="hljs-keyword">return</span> resp
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-keyword">return</span> err
    }
}
</code></pre>
<p>As you can see, this file is very simple. It declares the functions that are imported in the <code>index.js</code> file and links them to the functions declared in the models layer.</p>
<h3 id="heading-petsmutationsjs">pets.mutations.js</h3>
<p>Same goes for our <code>pets.mutations.js</code> file, but with mutations now.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { editItem, addItem, deleteItem } <span class="hljs-keyword">from</span> <span class="hljs-string">'../models/pets.models.js'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> addPet = <span class="hljs-function"><span class="hljs-params">petToAdd</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = addItem(petToAdd)
        <span class="hljs-keyword">return</span> resp
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-keyword">return</span> err
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> editPet = <span class="hljs-function"><span class="hljs-params">petToEdit</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = editItem(petToEdit?.id, petToEdit)
        <span class="hljs-keyword">return</span> resp
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-keyword">return</span> err
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> deletePet = <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = deleteItem(id)
        <span class="hljs-keyword">return</span> resp
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-keyword">return</span> err
    }
}
</code></pre>
<h3 id="heading-petsmodelsjs">pets.models.js</h3>
<p>Now go to the models folder and create a <code>pets.models.js</code> file with this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> db <span class="hljs-keyword">from</span> <span class="hljs-string">'../../db/db.js'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getItem = <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> pet = db?.pets?.filter(<span class="hljs-function"><span class="hljs-params">pet</span> =&gt;</span> pet?.id === <span class="hljs-built_in">parseInt</span>(id))[<span class="hljs-number">0</span>]
        <span class="hljs-keyword">return</span> pet
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error'</span>, err)
        <span class="hljs-keyword">return</span> err
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> listItems = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">return</span> db?.pets
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error'</span>, err)
        <span class="hljs-keyword">return</span> err
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> editItem = <span class="hljs-function">(<span class="hljs-params">id, data</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> index = db.pets.findIndex(<span class="hljs-function"><span class="hljs-params">pet</span> =&gt;</span> pet.id === <span class="hljs-built_in">parseInt</span>(id))

        <span class="hljs-keyword">if</span> (index === <span class="hljs-number">-1</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Pet not found'</span>)
        <span class="hljs-keyword">else</span> {
            data.id = <span class="hljs-built_in">parseInt</span>(data.id)
            db.pets[index] = data
            <span class="hljs-keyword">return</span> db.pets[index]
        }
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error'</span>, err)
        <span class="hljs-keyword">return</span> err
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> addItem = <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> newPet = { <span class="hljs-attr">id</span>: db.pets.length + <span class="hljs-number">1</span>, ...data }
        db.pets.push(newPet)
        <span class="hljs-keyword">return</span> newPet
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error'</span>, err)
        <span class="hljs-keyword">return</span> err
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> deleteItem = <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// delete item from db</span>
        <span class="hljs-keyword">const</span> index = db.pets.findIndex(<span class="hljs-function"><span class="hljs-params">pet</span> =&gt;</span> pet.id === <span class="hljs-built_in">parseInt</span>(id))

        <span class="hljs-keyword">if</span> (index === <span class="hljs-number">-1</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Pet not found'</span>)
        <span class="hljs-keyword">else</span> {
            db.pets.splice(index, <span class="hljs-number">1</span>)
            <span class="hljs-keyword">return</span> db.pets
        }
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error'</span>, err)
        <span class="hljs-keyword">return</span> err
    }
}
</code></pre>
<p>These are the functions responsible for interacting with our data layer (database) and returning the corresponding information to our controllers.</p>
<h3 id="heading-database"><strong>Database</strong></h3>
<p>We wont use a real database for this example. Instead we'll just use a simple array that will work just fine for example purposes, though our data will of course reset every time our server does.</p>
<p>In the root of our project, create a <code>db</code> folder and a <code>db.js</code> file with this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> db = {
    <span class="hljs-attr">pets</span>: [
        {
            <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Rex'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">3</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'labrador'</span>,
        },
        {
            <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Fido'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'poodle'</span>,
        },
        {
            <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Mittens'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">2</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'tabby'</span>,
        },
    ]
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> db
</code></pre>
<p>As you can see, our <code>db</code> object contains a <code>pets</code> property whose value is an array of objects, each object being a pet. For each pet, we store an id, name, type, age and breed.</p>
<p>Now go to your terminal and run <code>nodemon app.js</code>. You should see this message confirming your server is alive: <code>🚀 Server ready at: [http://localhost:4000/](http://localhost:4000/)</code>.</p>
<h1 id="heading-how-to-test-a-graphql-api-with-supertest">How to Test a GraphQL API with Supertest</h1>
<p>Now that our server is up and running, let's implement a simple test suit to check if our queries and mutations behave as expected.</p>
<p>If you're not familiar with automated testing, I recommend you read <a target="_blank" href="https://www.freecodecamp.org/news/test-a-react-app-with-jest-testing-library-and-cypress/">this introductory article I wrote a while ago</a>.</p>
<h2 id="heading-our-tools-1"><strong>Our Tools</strong></h2>
<p><a target="_blank" href="https://www.npmjs.com/package/supertest"><strong>SuperTest</strong></a> is a JavaScript library that is used for testing HTTP servers or web applications that make HTTP requests. It provides a high-level abstraction for testing HTTP, allowing developers to send HTTP requests and make assertions about the responses received, making it easier to write automated tests for web applications.</p>
<p>SuperTest works with any JavaScript testing framework, such as <a target="_blank" href="https://mochajs.org/">Mocha</a> or <a target="_blank" href="https://jestjs.io/">Jest</a>, and can be used with any HTTP server or web application framework, such as Express.</p>
<p>SuperTest is built on top of the popular testing library Mocha, and uses the <a target="_blank" href="https://www.chaijs.com/">Chai</a> assertion library to make assertions about the responses received. It provides an easy-to-use API for making HTTP requests, including support for authentication, headers, and request bodies.</p>
<p>SuperTest also allows developers to test the entire request/response cycle, including middleware and error handling, making it a powerful tool for testing web applications.</p>
<p>Overall, SuperTest is a valuable tool for developers who want to write automated tests for their web applications. It helps ensure that their applications are functioning correctly and that any changes they make to the codebase do not introduce new bugs or issues.</p>
<h2 id="heading-the-code-1"><strong>The Code</strong></h2>
<p>First we'll need to install some dependencies. To save up terminal commands, go to your <code>package.json</code> file and replace your <code>devDependencies</code> section with the code below. Then run <code>npm install</code>.</p>
<pre><code class="lang-javascript">  <span class="hljs-string">"devDependencies"</span>: {
    <span class="hljs-string">"@babel/core"</span>: <span class="hljs-string">"^7.21.4"</span>,
    <span class="hljs-string">"@babel/preset-env"</span>: <span class="hljs-string">"^7.21.4"</span>,
    <span class="hljs-string">"babel-jest"</span>: <span class="hljs-string">"^29.5.0"</span>,
    <span class="hljs-string">"jest"</span>: <span class="hljs-string">"^29.5.0"</span>,
    <span class="hljs-string">"jest-babel"</span>: <span class="hljs-string">"^1.0.1"</span>,
    <span class="hljs-string">"nodemon"</span>: <span class="hljs-string">"^2.0.22"</span>,
    <span class="hljs-string">"supertest"</span>: <span class="hljs-string">"^6.3.3"</span>
  }
</code></pre>
<p>Here we're installing the <code>supertest</code> and <code>jest</code> libraries, which we need for our tests to run, plus some <code>babel</code> stuff we need for our project to correctly identify which files are test files.</p>
<p>Still in your <code>package.json</code>, add this script:</p>
<pre><code class="lang-javascript">  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"jest"</span>
  },
</code></pre>
<p>To end with the boilerplate, in the root of your project, create a <code>babel.config.cjs</code> file and drop this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//babel.config.cjs</span>
<span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-attr">presets</span>: [
      [
        <span class="hljs-string">'@babel/preset-env'</span>,
        {
          <span class="hljs-attr">targets</span>: {
            <span class="hljs-attr">node</span>: <span class="hljs-string">'current'</span>,
          },
        },
      ],
    ],
  };
</code></pre>
<p>Now let's write some actual tests! Within your pets folder, create a <code>pets.test.js</code> file with this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> request <span class="hljs-keyword">from</span> <span class="hljs-string">'supertest'</span>

<span class="hljs-keyword">const</span> graphQLEndpoint = <span class="hljs-string">'http://localhost:4000/'</span>

describe(<span class="hljs-string">'Get all pets'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> postData = {
        <span class="hljs-attr">query</span>: <span class="hljs-string">`query Pets {
            pets {
                id
                name
                type
                age
                breed
            }
        }`</span>
    }

    test(<span class="hljs-string">'returns all pets'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        request(graphQLEndpoint)
            .post(<span class="hljs-string">'?'</span>)
            .send(postData)
            .expect(<span class="hljs-number">200</span>)
            .end(<span class="hljs-function">(<span class="hljs-params">error, response</span>) =&gt;</span> {
                <span class="hljs-keyword">if</span> (error) <span class="hljs-built_in">console</span>.error(error)

                <span class="hljs-keyword">const</span> res = <span class="hljs-built_in">JSON</span>.parse(response.text)

                expect(res.data.pets).toEqual([
                    {
                        <span class="hljs-attr">id</span>: <span class="hljs-string">'1'</span>,
                        <span class="hljs-attr">name</span>: <span class="hljs-string">'Rex'</span>,
                        <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
                        <span class="hljs-attr">age</span>: <span class="hljs-number">3</span>,
                        <span class="hljs-attr">breed</span>: <span class="hljs-string">'labrador'</span>
                    },
                    {
                        <span class="hljs-attr">id</span>: <span class="hljs-string">'2'</span>,
                        <span class="hljs-attr">name</span>: <span class="hljs-string">'Fido'</span>,
                        <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
                        <span class="hljs-attr">age</span>: <span class="hljs-number">1</span>,
                        <span class="hljs-attr">breed</span>: <span class="hljs-string">'poodle'</span>
                    },
                    {
                        <span class="hljs-attr">id</span>: <span class="hljs-string">'3'</span>,
                        <span class="hljs-attr">name</span>: <span class="hljs-string">'Mittens'</span>,
                        <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
                        <span class="hljs-attr">age</span>: <span class="hljs-number">2</span>,
                        <span class="hljs-attr">breed</span>: <span class="hljs-string">'tabby'</span>
                    }
                ])
            })
    })
})

describe(<span class="hljs-string">'Get pet detail'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> postData = {
        <span class="hljs-attr">query</span>: <span class="hljs-string">`query Pet {
            pet(id: 1) {
                id
                name
                type
                age
                breed
            }
        }`</span>
    }

    test(<span class="hljs-string">'Return pet detail information'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        request(graphQLEndpoint)
            .post(<span class="hljs-string">'?'</span>)
            .send(postData)
            .expect(<span class="hljs-number">200</span>)
            .end(<span class="hljs-function">(<span class="hljs-params">error, response</span>) =&gt;</span> {
                <span class="hljs-keyword">if</span> (error) <span class="hljs-built_in">console</span>.error(error)

                <span class="hljs-keyword">const</span> res = <span class="hljs-built_in">JSON</span>.parse(response.text)

                expect(res.data.pet).toEqual({
                    <span class="hljs-attr">id</span>: <span class="hljs-string">'1'</span>,
                    <span class="hljs-attr">name</span>: <span class="hljs-string">'Rex'</span>,
                    <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
                    <span class="hljs-attr">age</span>: <span class="hljs-number">3</span>,
                    <span class="hljs-attr">breed</span>: <span class="hljs-string">'labrador'</span>
                })
            })
    })
})

describe(<span class="hljs-string">'Edit pet'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> postData = {
        <span class="hljs-attr">query</span>: <span class="hljs-string">`mutation EditPet($petToEdit: PetToEdit!) {
            editPet(petToEdit: $petToEdit) {
                id
                name
                type
                age
                breed
            }
        }`</span>,
        <span class="hljs-attr">variables</span>: {
            <span class="hljs-attr">petToEdit</span>: {
                <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Rexo'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'dogo'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'doberman'</span>
            }
        }
    }

    test(<span class="hljs-string">'Updates pet and returns it'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        request(graphQLEndpoint)
            .post(<span class="hljs-string">'?'</span>)
            .send(postData)
            .expect(<span class="hljs-number">200</span>)
            .end(<span class="hljs-function">(<span class="hljs-params">error, response</span>) =&gt;</span> {
                <span class="hljs-keyword">if</span> (error) <span class="hljs-built_in">console</span>.error(error)

                <span class="hljs-keyword">const</span> res = <span class="hljs-built_in">JSON</span>.parse(response.text)

                expect(res.data.editPet).toEqual({
                    <span class="hljs-attr">id</span>: <span class="hljs-string">'1'</span>,
                    <span class="hljs-attr">name</span>: <span class="hljs-string">'Rexo'</span>,
                    <span class="hljs-attr">type</span>: <span class="hljs-string">'dogo'</span>,
                    <span class="hljs-attr">age</span>: <span class="hljs-number">4</span>,
                    <span class="hljs-attr">breed</span>: <span class="hljs-string">'doberman'</span>
                })
            })
    })
})

describe(<span class="hljs-string">'Add pet'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> postData = {
        <span class="hljs-attr">query</span>: <span class="hljs-string">`mutation AddPet($petToAdd: PetToAdd!) {
            addPet(petToAdd: $petToAdd) {
                id
                name
                type
                age
                breed
            }
        }`</span>,
        <span class="hljs-attr">variables</span>: {
            <span class="hljs-attr">petToAdd</span>: {
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Salame'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">6</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'pinky'</span>
            }
        }
    }

    test(<span class="hljs-string">'Adds new pet and returns the added item'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        request(graphQLEndpoint)
            .post(<span class="hljs-string">'?'</span>)
            .send(postData)
            .expect(<span class="hljs-number">200</span>)
            .end(<span class="hljs-function">(<span class="hljs-params">error, response</span>) =&gt;</span> {
                <span class="hljs-keyword">if</span> (error) <span class="hljs-built_in">console</span>.error(error)

                <span class="hljs-keyword">const</span> res = <span class="hljs-built_in">JSON</span>.parse(response.text)

                expect(res.data.addPet).toEqual({
                    <span class="hljs-attr">id</span>: <span class="hljs-string">'4'</span>,
                    <span class="hljs-attr">name</span>: <span class="hljs-string">'Salame'</span>,
                    <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
                    <span class="hljs-attr">age</span>: <span class="hljs-number">6</span>,
                    <span class="hljs-attr">breed</span>: <span class="hljs-string">'pinky'</span>
                })
            })
    })
})

describe(<span class="hljs-string">'Delete pet'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> postData = {
        <span class="hljs-attr">query</span>: <span class="hljs-string">`mutation DeletePet {
            deletePet(id: 2) {
                id,
                name,
                type,
                age,
                breed
            }
        }`</span>
    }

    test(<span class="hljs-string">'Deletes given pet and returns updated list'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        request(graphQLEndpoint)
            .post(<span class="hljs-string">'?'</span>)
            .send(postData)
            .expect(<span class="hljs-number">200</span>)
            .end(<span class="hljs-function">(<span class="hljs-params">error, response</span>) =&gt;</span> {
                <span class="hljs-keyword">if</span> (error) <span class="hljs-built_in">console</span>.error(error)

                <span class="hljs-keyword">const</span> res = <span class="hljs-built_in">JSON</span>.parse(response.text)

                expect(res.data.deletePet).toEqual([
                    {
                        <span class="hljs-attr">id</span>: <span class="hljs-string">'1'</span>,
                        <span class="hljs-attr">name</span>: <span class="hljs-string">'Rexo'</span>,
                        <span class="hljs-attr">type</span>: <span class="hljs-string">'dogo'</span>,
                        <span class="hljs-attr">age</span>: <span class="hljs-number">4</span>,
                        <span class="hljs-attr">breed</span>: <span class="hljs-string">'doberman'</span>
                    },
                    {
                        <span class="hljs-attr">id</span>: <span class="hljs-string">'3'</span>,
                        <span class="hljs-attr">name</span>: <span class="hljs-string">'Mittens'</span>,
                        <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
                        <span class="hljs-attr">age</span>: <span class="hljs-number">2</span>,
                        <span class="hljs-attr">breed</span>: <span class="hljs-string">'tabby'</span>
                    },
                    {
                        <span class="hljs-attr">id</span>: <span class="hljs-string">'4'</span>,
                        <span class="hljs-attr">name</span>: <span class="hljs-string">'Salame'</span>,
                        <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
                        <span class="hljs-attr">age</span>: <span class="hljs-number">6</span>,
                        <span class="hljs-attr">breed</span>: <span class="hljs-string">'pinky'</span>
                    }
                ])
            })
    })
})
</code></pre>
<p>This a test suite for our GraphQL API. It uses the <code>supertest</code> library to make HTTP requests to the API endpoint (<code>http://localhost:4000/</code>) and verifies that the API responds correctly to various queries and mutations.</p>
<p>The code has five different test cases:</p>
<ol>
<li><p><code>Get all pets</code>: This test queries the API for all pets and verifies that the response matches an expected list of pets.</p>
</li>
<li><p><code>Get pet detail</code>: This test queries the API for the details of a specific pet and verifies that the response matches the expected details for that pet.</p>
</li>
<li><p><code>Edit pet</code>: This test performs a mutation to edit the details of a specific pet and verifies that the response matches the expected edited details for that pet.</p>
</li>
<li><p><code>Add pet</code>: This test performs a mutation to add a new pet and verifies that the response matches the expected details for the newly added pet.</p>
</li>
<li><p><code>Delete pet</code>: This test performs a mutation to delete a specific pet and verifies that the response matches the expected list of pets after the deletion.</p>
</li>
</ol>
<p>Each test case includes a <code>postData</code> object that contains the GraphQL query or mutation to be sent to the API endpoint as well as any necessary variables.</p>
<p>The actual HTTP request is made using the <code>request</code> function from the <code>supertest</code> library, which sends a POST request to the API endpoint with the <code>postData</code> object in the request body. The response is then parsed as JSON and the test case verifies that the response matches the expected result using the <code>expect</code> function from the Jest testing framework.</p>
<p>Now go to your terminal, run <code>npm test</code>, and you should see all your tests passing:</p>
<pre><code class="lang-javascript">&gt; jest

 PASS  pets/pets.test.js
  Get all pets
    ✓ returns all pets (<span class="hljs-number">15</span> ms)
  Get pet detail
    ✓ Return pet detail information (<span class="hljs-number">2</span> ms)
  Edit pet
    ✓ Updates pet and returns it (<span class="hljs-number">1</span> ms)
  Add pet
    ✓ Adds <span class="hljs-keyword">new</span> pet and returns the added item (<span class="hljs-number">1</span> ms)
  Delete pet
    ✓ Deletes given pet and returns updated list (<span class="hljs-number">1</span> ms)

Test Suites: <span class="hljs-number">1</span> passed, <span class="hljs-number">1</span> total
<span class="hljs-attr">Tests</span>:       <span class="hljs-number">5</span> passed, <span class="hljs-number">5</span> total
<span class="hljs-attr">Snapshots</span>:   <span class="hljs-number">0</span> total
<span class="hljs-attr">Time</span>:        <span class="hljs-number">0.607</span> s, estimated <span class="hljs-number">1</span> s
Ran all test suites.
</code></pre>
<h1 id="heading-how-to-consume-a-graphql-api-on-a-front-end-react-app">How to Consume a GraphQL API on a Front-end React App</h1>
<p>Now we know our server is running and behaving as expected. Let's see some more realistic example of how our API might be consumed by a front end app.</p>
<p>For this example, we'll use a React application, and <a target="_blank" href="https://www.apollographql.com/docs/react/">Apollo client</a> to send and process our requests.</p>
<h2 id="heading-our-tools-2">Our Tools</h2>
<p><a target="_blank" href="https://react.dev/"><strong>React</strong></a> is a popular JavaScript library for building user interfaces. It allows developers to create reusable UI components and efficiently update and render them in response to changes in application state.</p>
<p>Regarding <strong>Apollo client</strong>, we've introduced it already.</p>
<p>Side comment – we're using Apollo client here since it's a very popular tool and it makes sense to use the same set of libraries both in front and back-end. If you're interested in other possible ways a GraphQL API can be consumed from a front-end React App, <a target="_blank" href="https://www.freecodecamp.org/news/5-ways-to-fetch-data-react-graphql/">Reed Barger has a pretty cool article on this topic</a>.</p>
<h2 id="heading-the-code-2">The Code</h2>
<p>Let's create our React app by running <code>yarn create vite</code> and following the terminal prompts. Once that's done, run <code>yarn add react-router-dom</code> (which we'll use to setup basic routing in our app).</p>
<h3 id="heading-appjsx"><strong>App.jsx</strong></h3>
<p>Put this code within your <code>App.jsx</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Suspense, lazy, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> { BrowserRouter <span class="hljs-keyword">as</span> Router, Routes, Route } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-keyword">const</span> PetList = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./pages/PetList'</span>))
<span class="hljs-keyword">const</span> PetDetail = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./pages/PetDetail'</span>))
<span class="hljs-keyword">const</span> EditPet = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./pages/EditPet'</span>))
<span class="hljs-keyword">const</span> AddPet = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./pages/AddPet'</span>))

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [petToEdit, setPetToEdit] = useState(<span class="hljs-literal">null</span>)

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'App'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Router</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Pet shelter<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

                <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">Route</span>
                        <span class="hljs-attr">path</span>=<span class="hljs-string">'/'</span>
                        <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>
                            &lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;
                                <span class="hljs-tag">&lt;<span class="hljs-name">PetList</span> /&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
                        }
                    /&gt;

                    <span class="hljs-tag">&lt;<span class="hljs-name">Route</span>
                        <span class="hljs-attr">path</span>=<span class="hljs-string">'/:petId'</span>
                        <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>
                            &lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;
                                <span class="hljs-tag">&lt;<span class="hljs-name">PetDetail</span> <span class="hljs-attr">setPetToEdit</span>=<span class="hljs-string">{setPetToEdit}</span> /&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
                        }
                    /&gt;

                    <span class="hljs-tag">&lt;<span class="hljs-name">Route</span>
                        <span class="hljs-attr">path</span>=<span class="hljs-string">'/:petId/edit'</span>
                        <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>
                            &lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;
                                <span class="hljs-tag">&lt;<span class="hljs-name">EditPet</span> <span class="hljs-attr">petToEdit</span>=<span class="hljs-string">{petToEdit}</span> /&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
                        }
                    /&gt;</span>

                    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Route</span>
                        <span class="hljs-attr">path</span>=<span class="hljs-string">'/add'</span>
                        <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>
                            &lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;
                                <span class="hljs-tag">&lt;<span class="hljs-name">AddPet</span> /&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>
                        }
                    /&gt;
                &lt;/Routes&gt;
            &lt;/Router&gt;
        &lt;/div&gt;
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Here we're just defining our routes. We'll have 4 main routes in our app, each corresponding to a different view:</p>
<ul>
<li><p>One to see the whole list of pets.</p>
</li>
<li><p>One to see the detail of a single pet.</p>
</li>
<li><p>One to edit a single pet.</p>
</li>
<li><p>One to add a new pet to the list.</p>
</li>
</ul>
<p>Besides, we have a button to add a new pet and a state that will store the information of the pet we want to edit.</p>
<p>Next, create a <code>pages</code> directory with these files in it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-281.png" alt="image-281" width="600" height="400" loading="lazy"></p>
<p><em>Folder structure</em></p>
<h3 id="heading-mainjs">main.js</h3>
<p>Before jumping into our pages, we have to set up the Apollo client library. Run <code>yarn add @apollo/client</code> and <code>yarn add graphql</code> to install the necessary dependencies.</p>
<p>The go to the <code>main.js</code> file and drop this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.css'</span>
<span class="hljs-keyword">import</span> { ApolloClient, InMemoryCache, ApolloProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>

<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> ApolloClient({
  <span class="hljs-attr">uri</span>: <span class="hljs-string">'http://localhost:4000/'</span>,
  <span class="hljs-attr">cache</span>: <span class="hljs-keyword">new</span> InMemoryCache(),
})

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ApolloProvider</span> <span class="hljs-attr">client</span>=<span class="hljs-string">{client}</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">ApolloProvider</span>&gt;</span></span>
)
</code></pre>
<p>Here we're initializing the <code>ApolloClient</code>, passing its constructor a configuration object with the <code>uri</code> and <code>cache</code> fields:</p>
<ul>
<li><p><code>uri</code> specifies the URL of our GraphQL server.</p>
</li>
<li><p><code>cache</code> is an instance of <code>InMemoryCache</code>, which Apollo Client uses to cache query results after fetching them.</p>
</li>
</ul>
<p>Then we wrap our <code>App</code> component with our ApolloProvider. This allows any component in our component tree to use the hooks provided by Apollo client, much like React Context works. ;)</p>
<h3 id="heading-mutations-and-queries">Mutations and queries</h3>
<p>In the root of your project, create this folder structure:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Folder structure</em></p>
<p>In these two files we'll declare the request bodies we'll use for our queries and mutations. I like to separate this into different files because it gives use a clear view of the different kinds of request we have in our app, and it also keeps our component's code cleaner.</p>
<p>In the <code>queries.js</code> file drop this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { gql } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GET_PETS = gql<span class="hljs-string">`
    query Pets {
        pets {
            id
            name
            type
            breed
        }
    }
`</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GET_PET = gql<span class="hljs-string">`
    query Pet($petId: ID!) {
        pet(id: $petId) {
            id
            name
            type
            age
            breed
        }
    }
`</span>
</code></pre>
<p>And in the <code>mutations.js</code> file drop this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { gql } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> DELETE_PET = gql<span class="hljs-string">`
    mutation DeletePet($deletePetId: ID!) {
        deletePet(id: $deletePetId) {
            id
        }
    }
`</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ADD_PET = gql<span class="hljs-string">`
    mutation AddPet($petToAdd: PetToAdd!) {
        addPet(petToAdd: $petToAdd) {
            id
            name
            type
            age
            breed
        }
    }
`</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> EDIT_PET = gql<span class="hljs-string">`
    mutation EditPet($petToEdit: PetToEdit!) {
        editPet(petToEdit: $petToEdit) {
            id
            name
            type
            age
            breed
        }
    }
`</span>
</code></pre>
<p>As you can see, the syntax for queries and mutations is fairly similar. Request bodies are written in GraphQL query language, which is used to define the structure and data types of data that can be requested from a GraphQL API.</p>
<ul>
<li>GraphQL Query Syntax:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GET_PETS = gql<span class="hljs-string">`
    query Pets {
        pets {
            id
            name
            type
            breed
        }
    }
`</span>
</code></pre>
<p>This query is named <code>Pets</code> and it requests data from the <code>pets</code> field. The fields <code>id</code>, <code>name</code>, <code>type</code>, and <code>breed</code> are requested from each <code>Pet</code> object returned by the API.</p>
<p>In GraphQL, queries always start with the keyword <code>query</code> and are followed by the name of the query, if provided. The fields requested are enclosed in curly braces and can be nested to request data from related fields.</p>
<ul>
<li>GraphQL Mutation Syntax:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ADD_PET = gql<span class="hljs-string">`
    mutation AddPet($petToAdd: PetToAdd!) {
        addPet(petToAdd: $petToAdd) {
            id
            name
            type
            age
            breed
        }
    }
`</span>
</code></pre>
<p>This mutation is named <code>AddPet</code> and sends a new <code>Pet</code> object to be added to the API via the <code>addPet</code> mutation. The <code>$petToAdd</code> variable is defined as a required input of type <code>PetToAdd</code>. When the mutation is executed, the input variable will be passed in as an argument to the <code>addPet</code> mutation. The mutation then returns the <code>id</code>, <code>name</code>, <code>type</code>, <code>age</code>, and <code>breed</code> fields for the newly created <code>Pet</code> object.</p>
<p>In GraphQL, mutations always start with the keyword <code>mutation</code> and are followed by the name of the mutation, if provided. The fields requested in the mutation response are also enclosed in curly braces.</p>
<p>Note that both queries and mutations in GraphQL can accept variables as input, which are defined in the query or mutation body using a special syntax (<code>$variableName: variableType!</code>). These variables can be passed in when the query or mutation is executed, allowing for more dynamic and reusable queries and mutations.</p>
<h3 id="heading-petlistjsx"><strong>PetList.jsx</strong></h3>
<p>Let's start with the file responsible for rendering the whole list of pets:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> { useQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>
<span class="hljs-keyword">import</span> { GET_PETS } <span class="hljs-keyword">from</span> <span class="hljs-string">'../api/queries'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PetList</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> { loading, error, data } = useQuery(GET_PETS)

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Pet List<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">'/add'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Add new pet<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>

            {loading &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
            {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error: {error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}

            {data?.pets?.map(pet =&gt; {
                return (
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{pet?.id}</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
                            {pet?.name} - {pet?.type} - {pet?.breed}
                        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

                        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>`/${<span class="hljs-attr">pet</span>?<span class="hljs-attr">.id</span>}`}&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Pet detail<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                )
            })}
        <span class="hljs-tag">&lt;/&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PetList
</code></pre>
<p>This code defines a React functional component called <code>PetList</code> that fetches a list of pets from a GraphQL API using the <code>useQuery</code> hook provided by the <code>@apollo/client</code> library. The query used to fetch the pets is defined in a separate file called <code>queries.js</code>, which exports a GraphQL query called <code>GET_PETS</code>.</p>
<p>The <code>useQuery</code> hook returns an object with three properties: <code>loading</code>, <code>error</code>, and <code>data</code>. These properties are destructured from the object and used to conditionally render different UI elements depending on the status of the API request.</p>
<p>If <code>loading</code> is true, a loading message is displayed on the screen. If <code>error</code> is defined, an error message is displayed with the specific error message returned by the API. If <code>data</code> is defined and contains an array of <code>pets</code>, each <code>pet</code> is displayed in a div with their <code>name</code>, <code>type</code>, and <code>breed</code>. Each pet div also contains a link to view more details about the pet.</p>
<p>The <code>useQuery</code> hook works by executing the <code>GET_PETS</code> query and returning the result as an object with the <code>loading</code>, <code>error</code>, and <code>data</code> properties. When the component first renders, <code>loading</code> is true while the query is being executed. If the query is successful, <code>loading</code> is false and <code>data</code> is populated with the results. If the query encounters an error, <code>error</code> is populated with the specific error message.</p>
<p>As you can see, managing requests with Apollo client is really nice and simple. And the hooks it provides, save us quite a bit of code normally used to execute requests, store it's response and handle errors.</p>
<p>Remember that to make calls to our server, we must have it up and running by running <code>nodemon app.js</code> in our server project terminal.</p>
<p>Just to show there's no weird magic going on here, if we go to our browser, open the dev tools and go to the network tab, we could see our app is making a POST request to our server endpoint. And that the payload is our request body in the form of a string.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The POST request</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-8.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Request body</em></p>
<p>This means that if we wanted to, we could also consume our GraphQL API by using fetch, like following:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PetList</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-keyword">const</span> [pets, setPets] = useState([])

    <span class="hljs-keyword">const</span> getPets = <span class="hljs-function">() =&gt;</span> {
        fetch(<span class="hljs-string">'http://localhost:4000/'</span>, {
            <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
            <span class="hljs-attr">headers</span>: {
                <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
            },
            <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
                <span class="hljs-attr">query</span>: <span class="hljs-string">`
                query Pets {
                    pets {
                    id
                    name
                    type
                    breed
                    }
                }
                `</span>
            })
        })
            .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
            .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> setPets(data?.data?.pets))
            .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error))
    }

    useEffect(<span class="hljs-function">() =&gt;</span> {
        getPets()
    }, [])

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Pet List<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">'/add'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Add new pet<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>

            {pets?.map(pet =&gt; {
                return (
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{pet?.id}</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
                            {pet?.name} - {pet?.type} - {pet?.breed}
                        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

                        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>`/${<span class="hljs-attr">pet</span>?<span class="hljs-attr">.id</span>}`}&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Pet detail<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                )
            })}
        <span class="hljs-tag">&lt;/&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PetList
</code></pre>
<p>If you check your network tab again, you should see still the same POST request with the some request body.</p>
<p>Of course this approach is not very practical as it requires more lines of code to perform the same thing. But it's important to know that libraries like Apollo only give us a <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-programming-paradigms/#declarative-programming">declarative API</a> to work with and simplify our code. Beneath it all we're still working with regular HTTP requests.</p>
<h3 id="heading-petdetailjsx"><strong>PetDetail.jsx</strong></h3>
<p>Now let's go to the <code>PetDetail.jsx</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> { useParams, Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> { useQuery, useMutation } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>
<span class="hljs-keyword">import</span> { GET_PET } <span class="hljs-keyword">from</span> <span class="hljs-string">'../api/queries'</span>
<span class="hljs-keyword">import</span> { DELETE_PET } <span class="hljs-keyword">from</span> <span class="hljs-string">'../api/mutations'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PetDetail</span>(<span class="hljs-params">{ setPetToEdit }</span>) </span>{
    <span class="hljs-keyword">const</span> { petId } = useParams()

    <span class="hljs-keyword">const</span> { loading, error, data } = useQuery(GET_PET, {
        <span class="hljs-attr">variables</span>: { petId }
    })

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (data &amp;&amp; data?.pet) setPetToEdit(data?.pet)
    }, [data])

    <span class="hljs-keyword">const</span> [deletePet, { <span class="hljs-attr">loading</span>: deleteLoading, <span class="hljs-attr">error</span>: deleteError, <span class="hljs-attr">data</span>: deleteData }] = useMutation(DELETE_PET, {
        <span class="hljs-attr">variables</span>: { <span class="hljs-attr">deletePetId</span>: petId }
    })

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (deleteData &amp;&amp; deleteData?.deletePet) <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">'/'</span>
    }, [deleteData])

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">justifyContent:</span> '<span class="hljs-attr">center</span>', <span class="hljs-attr">aligniItems:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Pet Detail<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">'/'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Back to list<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>

            {(loading || deleteLoading) &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}

            {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error: {error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
            {deleteError &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>deleteError: {deleteError.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}

            {data?.pet &amp;&amp; (
                <span class="hljs-tag">&lt;&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pet name: {data?.pet?.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pet type: {data?.pet?.type}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pet age: {data?.pet?.age}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pet breed: {data?.pet?.breed}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">justifyContent:</span> '<span class="hljs-attr">center</span>', <span class="hljs-attr">aligniItems:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>`/${<span class="hljs-attr">data</span>?<span class="hljs-attr">.pet</span>?<span class="hljs-attr">.id</span>}/<span class="hljs-attr">edit</span>`}&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginRight:</span> <span class="hljs-attr">10</span> }}&gt;</span>Edit pet<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>

                        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginLeft:</span> <span class="hljs-attr">10</span> }} <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> deletePet()}&gt;
                            Delete pet
                        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/&gt;</span></span>
            )}
        &lt;/div&gt;
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PetDetail
</code></pre>
<p>This component loads the detail info of the pet by executing a query in a very similar way than the previous component.</p>
<p>Moreover, it executes the mutation needed to delete the pet register. You can see that for this we're using the <code>useMutation</code> hook. It's quite similar to <code>useQuery</code>, but besides the <code>loading, error and data</code> values it also provides a function to execute our query after a given event.</p>
<p>You can see that for this mutation hook we're passing an object as second parameter, containing the variables this mutation requires. In this case, it's the id of the pet register we want to delete.</p>
<pre><code class="lang-plaintext">const [deletePet, { loading: deleteLoading, error: deleteError, data: deleteData }] = useMutation(DELETE_PET, {
    variables: { deletePetId: petId }
})
</code></pre>
<p>Remember that when we declared our mutation in <code>mutations.js</code> we had already declared the variables this mutation would use.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> DELETE_PET = gql<span class="hljs-string">`
    mutation DeletePet($deletePetId: ID!) {
        deletePet(id: $deletePetId) {
            id
        }
    }
`</span>
</code></pre>
<h3 id="heading-addpetjsx"><strong>AddPet.jsx</strong></h3>
<p>This is the file responsible for adding a new pet to our register:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> { useMutation } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>
<span class="hljs-keyword">import</span> { ADD_PET } <span class="hljs-keyword">from</span> <span class="hljs-string">'../api/mutations'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AddPet</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [petName, setPetName] = useState()
    <span class="hljs-keyword">const</span> [petType, setPetType] = useState()
    <span class="hljs-keyword">const</span> [petAge, setPetAge] = useState()
    <span class="hljs-keyword">const</span> [petBreed, setPetBreed] = useState()

    <span class="hljs-keyword">const</span> [addPet, { loading, error, data }] = useMutation(ADD_PET, {
        <span class="hljs-attr">variables</span>: {
            <span class="hljs-attr">petToAdd</span>: {
                <span class="hljs-attr">name</span>: petName,
                <span class="hljs-attr">type</span>: petType,
                <span class="hljs-attr">age</span>: <span class="hljs-built_in">parseInt</span>(petAge),
                <span class="hljs-attr">breed</span>: petBreed
            }
        }
    })

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (data &amp;&amp; data?.addPet) <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">`/<span class="hljs-subst">${data?.addPet?.id}</span>`</span>
    }, [data])

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">justifyContent:</span> '<span class="hljs-attr">center</span>', <span class="hljs-attr">aligniItems:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Add Pet<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">'/'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Back to list<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>

            {loading || error ? (
                <span class="hljs-tag">&lt;&gt;</span>
                    {loading &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
                    {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error: {error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
                <span class="hljs-tag">&lt;/&gt;</span></span>
            ) : (
                <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petName}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetName(e.target.value)} /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet type<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petType}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetType(e.target.value)} /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet age<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petAge}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetAge(e.target.value)} /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet breed<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petBreed}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetBreed(e.target.value)} /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                        <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginTop:</span> <span class="hljs-attr">30</span> }}
                        <span class="hljs-attr">disabled</span>=<span class="hljs-string">{!petName</span> || !<span class="hljs-attr">petType</span> || !<span class="hljs-attr">petAge</span> || !<span class="hljs-attr">petBreed</span>}
                        <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> addPet()}
                    &gt;
                        Add pet
                    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                <span class="hljs-tag">&lt;/&gt;</span></span>
            )}
        &lt;/div&gt;
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AddPet
</code></pre>
<p>Here we have a component that loads a form to add a new pet and performs a mutation when the data is sent. It accepts the new pet info as parameter, in a similar way that the <code>deletePet</code> mutation accepted the pet id.</p>
<h3 id="heading-editpetjsx"><strong>EditPet.jsx</strong></h3>
<p>Finally, the file responsible for editing a pet register:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> { useMutation } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>
<span class="hljs-keyword">import</span> { EDIT_PET } <span class="hljs-keyword">from</span> <span class="hljs-string">'../api/mutations'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">EditPet</span>(<span class="hljs-params">{ petToEdit }</span>) </span>{
    <span class="hljs-keyword">const</span> [petName, setPetName] = useState(petToEdit?.name)
    <span class="hljs-keyword">const</span> [petType, setPetType] = useState(petToEdit?.type)
    <span class="hljs-keyword">const</span> [petAge, setPetAge] = useState(petToEdit?.age)
    <span class="hljs-keyword">const</span> [petBreed, setPetBreed] = useState(petToEdit?.breed)

    <span class="hljs-keyword">const</span> [editPet, { loading, error, data }] = useMutation(EDIT_PET, {
        <span class="hljs-attr">variables</span>: {
            <span class="hljs-attr">petToEdit</span>: {
                <span class="hljs-attr">id</span>: <span class="hljs-built_in">parseInt</span>(petToEdit.id),
                <span class="hljs-attr">name</span>: petName,
                <span class="hljs-attr">type</span>: petType,
                <span class="hljs-attr">age</span>: <span class="hljs-built_in">parseInt</span>(petAge),
                <span class="hljs-attr">breed</span>: petBreed
            }
        }
    })

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (data &amp;&amp; data?.editPet?.id) <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">`/<span class="hljs-subst">${data?.editPet?.id}</span>`</span>
    }, [data])

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">justifyContent:</span> '<span class="hljs-attr">center</span>', <span class="hljs-attr">aligniItems:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Edit Pet<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">'/'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Back to list<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>

            {loading || error ? (
                <span class="hljs-tag">&lt;&gt;</span>
                    {loading &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
                    {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error: {error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
                <span class="hljs-tag">&lt;/&gt;</span></span>
            ) : (
                <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petName}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetName(e.target.value)} /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet type<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petType}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetType(e.target.value)} /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet age<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petAge}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetAge(e.target.value)} /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet breed<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petBreed}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetBreed(e.target.value)} /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                        <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginTop:</span> <span class="hljs-attr">30</span> }}
                        <span class="hljs-attr">disabled</span>=<span class="hljs-string">{!petName</span> || !<span class="hljs-attr">petType</span> || !<span class="hljs-attr">petAge</span> || !<span class="hljs-attr">petBreed</span>}
                        <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> editPet()}
                    &gt;
                        Save changes
                    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                <span class="hljs-tag">&lt;/&gt;</span></span>
            )}
        &lt;/div&gt;
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> EditPet
</code></pre>
<p>Last, we have a component to edit a pet register through a form. It performs a mutation when the data is sent, and as parameters it accepts the new pet info.</p>
<p>And that's it! We're using all of our API queries and mutations in our front end app. =)</p>
<h1 id="heading-how-to-document-a-graphql-api-with-apollo-sandbox">How to Document a GraphQL API with Apollo Sandbox</h1>
<p>One of Apollo's coolest features is that it comes with a built-in sandbox you can use to test and document your API.</p>
<p>Apollo Sandbox is a web-based GraphQL IDE that provides a sandbox environment for testing GraphQL queries, mutations, and subscriptions. It is a free, online tool provided by Apollo that allows you to interact with your GraphQL API and explore its schema, data, and capabilities.</p>
<p>Here are some of the main features of Apollo Sandbox:</p>
<ol>
<li><p>Query Editor: A feature-rich GraphQL query editor that provides syntax highlighting, autocompletion, validation, and error highlighting.</p>
</li>
<li><p>Schema Explorer: A graphical interface that allows you to explore your GraphQL schema and see its types, fields, and relationships.</p>
</li>
<li><p>Mocking: Apollo Sandbox allows you to easily generate mock data based on your schema, which is useful for testing your queries and mutations without connecting to a real data source.</p>
</li>
<li><p>Collaboration: You can share your sandbox with others, collaborate on queries, and see real-time changes.</p>
</li>
<li><p>Documentation: You can add documentation to your schema and query results to help others understand your API.</p>
</li>
</ol>
<p>To use our sandbox, simply open your browser at <a target="_blank" href="http://localhost:4000/"><code>http://localhost:4000/</code></a>. You should see something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Apollo sandbox</em></p>
<p>From here you can see the API data schema and available mutations and queries, and also execute them and see how your API responds. For example, by executing the <code>pets</code> query, we can see that response on the right side panel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Executing a query</em></p>
<p>If you hop on to the schema section you could see a whole detail of the available queries, mutations object and input types in our API.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/image-9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The schema section</em></p>
<p>Apollo sandbox is a great tool that can be used both as self-documentation for our API and a great development and testing tool.</p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>Well everyone, as always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/tumblr_6eb166181e857e65bb472a1ba4bd450c_d935c3d9_500.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The REST API Handbook – How to Build, Test, Consume, and Document REST APIs ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this tutorial we're going to take a deep dive into REST APIs. I recently wrote this article where I explained the main differences between common API types nowadays. And this tutorial aims to show you an example of how you can fully i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-consume-and-document-a-rest-api/</link>
                <guid isPermaLink="false">66d45eee36c45a88f96b7cd9</guid>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Thu, 27 Apr 2023 13:55:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/pavan-trikutam-71CjSSB83Wo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this tutorial we're going to take a deep dive into REST APIs.</p>
<p>I recently wrote <a target="_blank" href="https://www.freecodecamp.org/news/rest-vs-graphql-apis/">this article</a> where I explained the main differences between common API types nowadays. And this tutorial aims to show you an example of how you can fully implement a REST API.</p>
<p>We'll cover basic setup and architecture with Node and Express, unit testing with Supertest, seeing how we can consume the API from a React front-end app and finally documenting the API using tools such as Swagger.</p>
<p>Keep in mind we won't go too deep into how each technology works. The goal here is to give you a general overview of how a REST API works, how its pieces interact, and what a full implementation might consist of.</p>
<p>Let's go!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-rest">What is REST?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-a-rest-api-with-node-and-express">How to Build a REST API with Node and Express</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-test-a-rest-api-with-supertest">How to Test a REST API with Supertest</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-consume-a-rest-api-on-a-front-end-react-app">How to Consume a REST API on a Front-end React App</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-document-a-rest-api-with-swagger">How to Document a REST API with Swagger</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></p>
</li>
</ul>
<h1 id="heading-what-is-rest">What is REST?</h1>
<p>Representational State Transfer (REST) is a widely used architectural style for building web services and APIs.</p>
<p>RESTful APIs are designed to be simple, scalable, and flexible. They are often used in web and mobile applications, as well as in Internet of Things (IoT) and microservices architectures.</p>
<p><strong>Main Characteristics:</strong></p>
<ol>
<li><p><strong>Stateless:</strong> REST APIs are stateless, which means that each request contains all the necessary information to process it. This makes it easier to scale the API and improves performance by reducing the need to store and manage session data on the server.</p>
</li>
<li><p><strong>Resource-based:</strong> REST APIs are resource-based, which means that each resource is identified by a unique URI (Uniform Resource Identifier) and can be accessed using standard HTTP methods such as GET, POST, PUT, and DELETE.</p>
</li>
<li><p><strong>Uniform Interface:</strong> REST APIs have a uniform interface that allows clients to interact with resources using a standardized set of methods and response formats. This makes it easier for developers to build and maintain APIs, and for clients to consume them.</p>
</li>
<li><p><strong>Cacheable:</strong> REST APIs are cacheable, which means that responses can be cached to improve performance and reduce network traffic.</p>
</li>
<li><p><strong>Layered System:</strong> REST APIs are designed to be layered, which means that intermediaries such as proxies and gateways can be added between the client and server without affecting the overall system.</p>
</li>
</ol>
<p><strong>Pros</strong> of REST APIs**:**</p>
<ul>
<li><p><strong>Easy to learn and use:</strong> REST APIs are relatively simple and easy to learn compared to other APIs.</p>
</li>
<li><p><strong>Scalability:</strong> The stateless nature of REST APIs makes them highly scalable and efficient.</p>
</li>
<li><p><strong>Flexibility:</strong> REST APIs are flexible and can be used to build a wide range of applications and systems.</p>
</li>
<li><p><strong>Wide support:</strong> REST APIs are widely supported by development tools and frameworks, making it easy to integrate them into existing systems.</p>
</li>
</ul>
<p><strong>Cons</strong> of REST APIs**:**</p>
<ul>
<li><p><strong>Lack of standards:</strong> The lack of strict standards for REST APIs can lead to inconsistencies and interoperability issues.</p>
</li>
<li><p><strong>Limited functionality:</strong> REST APIs are designed to handle simple requests and responses and may not be suitable for more complex use cases.</p>
</li>
<li><p><strong>Security concerns:</strong> REST APIs can be vulnerable to security attacks such as cross-site scripting (XSS) and cross-site request forgery (CSRF) if not implemented properly.</p>
</li>
</ul>
<p><strong>REST APIs are b</strong>est for:****</p>
<ul>
<li><p>REST APIs are well-suited for building web and mobile applications, as well as microservices architectures and IoT systems.</p>
</li>
<li><p>They are particularly useful in situations where scalability and flexibility are important, and where developers need to integrate with existing systems and technologies.</p>
</li>
</ul>
<p>In summary, REST APIs are a popular and widely used architectural style for building web services and APIs. They are simple, scalable, and flexible, and can be used to build a wide range of applications and systems.</p>
<p>While there are some limitations and concerns with REST APIs, they remain a popular and effective option for building APIs in many different industries and sectors.</p>
<h1 id="heading-how-to-build-a-rest-api-with-node-and-express">How to Build a REST API with Node and Express</h1>
<h2 id="heading-our-tools">Our tools</h2>
<p><a target="_blank" href="https://nodejs.org/"><strong>Node.js</strong></a> is an open-source, cross-platform, back-end JavaScript runtime environment that allows developers to execute JavaScript code outside of a web browser. It was created by Ryan Dahl in 2009 and has since become a popular choice for building web applications, APIs, and servers.</p>
<p>Node.js provides an event-driven, non-blocking I/O model that makes it lightweight and efficient, allowing it to handle large amounts of data with high performance. It also has a large and active community, with many libraries and modules available to help developers build their applications more quickly and easily.</p>
<p><a target="_blank" href="https://expressjs.com/"><strong>Express.js</strong></a> is a popular web application framework for Node.js, which is used to build web applications and APIs. It provides a set of features and tools for building web servers, handling HTTP requests and responses, routing requests to specific handlers, handling middleware, and much more.</p>
<p>Express is known for its simplicity, flexibility, and scalability, making it a popular choice for developers building web applications with Node.js.</p>
<p>Some of the key features and benefits of Express.js include:</p>
<ul>
<li><p><strong>Minimalistic and flexible:</strong> Express.js provides a minimalistic and flexible structure that allows developers to build applications the way they want to.</p>
</li>
<li><p><strong>Routing:</strong> Express.js makes it easy to define routes for handling HTTP requests and mapping them to specific functions or handlers.</p>
</li>
<li><p><strong>Middleware:</strong> Express.js allows developers to define middleware functions that can be used to handle common tasks such as authentication, logging, error handling, and more.</p>
</li>
<li><p><strong>Robust API:</strong> Express.js provides a robust API for handling HTTP requests and responses, allowing developers to build high-performance web applications.</p>
</li>
</ul>
<h2 id="heading-our-architecture">Our architecture</h2>
<p>For this project we'll follow a layers architecture in our codebase. Layers architecture is about dividing concerns and responsibilities into different folders and files, and allowing direct communication only between certain folders and files.</p>
<p>The matter of how many layers should your project have, what names should each layer have, and what actions should it handle is all a matter of discussion. So let's see what I think is a good approach for our example.</p>
<p>Our application will have five different layers, which will be ordered in this way:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-110.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Application layers</em></p>
<ul>
<li><p>The application layer will have the basic setup of our server and the connection to our routes (the next layer).</p>
</li>
<li><p>The routes layer will have the definition of all of our routes and the connection to the controllers (the next layer).</p>
</li>
<li><p>The controllers layer will have the actual logic we want to perform in each of our endpoints and the connection to the model layer (the next layer, you get the idea...)</p>
</li>
<li><p>The model layer will hold the logic for interacting with our mock database.</p>
</li>
<li><p>Finally, the persistence layer is where our database will be.</p>
</li>
</ul>
<p>An important thing to keep in mind is that in these kinds of architectures, <strong>there's a defined communication flow</strong> between the layers that has to be followed for it to make sense.</p>
<p>This means that a request first has to go through the first layer, then the second, then the third and so on. No request should skip layers because that would mess with the logic of the architecture and the benefits of organization and modularity it gives us.</p>
<blockquote>
<p>If you'd like to know some other API architecture options, I recommend <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-software-architecture-patterns/">you this software architecture article</a> I wrote a while ago.</p>
</blockquote>
<h2 id="heading-the-code">The code</h2>
<p>Before jumping to the code, let's mention what we'll actually build. We'll be building an API for a pet shelter business. This pet shelter needs to register the pets that are staying in the shelter, and for that we'll perform basic CRUD operations (create, read, update and delete).</p>
<p>Now yeah, let's get this thing going. Create a new directory, hop on to it and start a new Node project by running <code>npm init -y</code>.</p>
<p>Then install Express by running <code>npm i express</code> and install nodemon as a dev dependency by running <code>npm i -D nodemon</code> (<a target="_blank" href="https://nodemon.io/">Nodemon</a> is a tool we'll use to get our server running and test it). Lastly, also run <code>npm i cors</code>, which we'll use to be able to test our server locally.</p>
<h3 id="heading-appjs">App.js</h3>
<p>Cool, now create an <code>app.js</code> file and drop this code in it:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>
<span class="hljs-keyword">import</span> cors <span class="hljs-keyword">from</span> <span class="hljs-string">'cors'</span>

<span class="hljs-keyword">import</span> petRoutes <span class="hljs-keyword">from</span> <span class="hljs-string">'./pets/routes/pets.routes.js'</span>

<span class="hljs-keyword">const</span> app = express()
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>

<span class="hljs-comment">/* Global middlewares */</span>
app.use(cors())
app.use(express.json())

<span class="hljs-comment">/* Routes */</span>
app.use(<span class="hljs-string">'/pets'</span>, petRoutes)

<span class="hljs-comment">/* Server setup */</span>
<span class="hljs-keyword">if</span> (process.env.NODE_ENV !== <span class="hljs-string">'test'</span>) {
    app.listen(port, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`⚡️[server]: Server is running at https://localhost:<span class="hljs-subst">${port}</span>`</span>))
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> app
</code></pre>
<p>This would be the <strong>application layer</strong> of our project.</p>
<p>Here we're basically setting up our server and declaring that any request that hits the <code>/pets</code> direction should use the routes (endpoints) we have declared in the <code>./pets/routes/pets.routes.js</code> directory.</p>
<p>Next, go ahead and create this folder structure in your project:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-246.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Folder structure</em></p>
<h3 id="heading-routes">Routes</h3>
<p>Hop on to the routes folder, create a file called <code>pets.routes.js</code>, and drop this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;
<span class="hljs-keyword">import</span> {
  listPets,
  getPet,
  editPet,
  addPet,
  deletePet,
} <span class="hljs-keyword">from</span> <span class="hljs-string">"../controllers/pets.controllers.js"</span>;

<span class="hljs-keyword">const</span> router = express.Router();

router.get(<span class="hljs-string">"/"</span>, listPets);

router.get(<span class="hljs-string">"/:id"</span>, getPet);

router.put(<span class="hljs-string">"/:id"</span>, editPet);

router.post(<span class="hljs-string">"/"</span>, addPet);

router.delete(<span class="hljs-string">"/:id"</span>, deletePet);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> router;
</code></pre>
<p>In this file we're initializing a router (the thing that processes our request and directs them accordingly given the endpoint URL) and setting up each of our endpoints.</p>
<p>See that for each endpoint we declare the corresponding HTTP method (<code>get</code>, <code>put</code>, and so on) and the corresponding function that that endpoint will trigger (<code>listPets</code>, <code>getPet</code>, and so on). Each function name is quite explicit so we can easily know what each endpoint does without needing to see further code. ;)</p>
<p>Lastly, we also declare which endpoint will receive URL parameters on the requests like this: <code>router.get("/:id", getPet);</code> Here we're saying that we'll receive the <code>id</code> of the pet as an URL parameter.</p>
<h3 id="heading-controllers">Controllers</h3>
<p>Now go to the controllers folder, create a <code>pets.controllers.js</code> file, and put this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { getItem, listItems, editItem, addItem, deleteItem } <span class="hljs-keyword">from</span> <span class="hljs-string">'../models/pets.models.js'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getPet = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = getItem(<span class="hljs-built_in">parseInt</span>(req.params.id))
        res.status(<span class="hljs-number">200</span>).json(resp)

    } <span class="hljs-keyword">catch</span> (err) {
        res.status(<span class="hljs-number">500</span>).send(err)
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> listPets = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = listItems()
        res.status(<span class="hljs-number">200</span>).json(resp)

    } <span class="hljs-keyword">catch</span> (err) {
        res.status(<span class="hljs-number">500</span>).send(err)
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> editPet = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = editItem(<span class="hljs-built_in">parseInt</span>(req.params.id), req.body)
        res.status(<span class="hljs-number">200</span>).json(resp)

    } <span class="hljs-keyword">catch</span> (err) {
        res.status(<span class="hljs-number">500</span>).send(err)
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> addPet = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = addItem(req.body)
        res.status(<span class="hljs-number">200</span>).json(resp)

    } <span class="hljs-keyword">catch</span> (err) {
        res.status(<span class="hljs-number">500</span>).send(err)
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> deletePet = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> resp = deleteItem(<span class="hljs-built_in">parseInt</span>(req.params.id))
        res.status(<span class="hljs-number">200</span>).json(resp)

    } <span class="hljs-keyword">catch</span> (err) {
        res.status(<span class="hljs-number">500</span>).send(err)
    }
}
</code></pre>
<p>Controllers are the functions that each endpoint request will trigger. As you can see, they receive as parameters the request and response objects. In the request object we can read things such as URL or body parameters, and we'll use the response object to send our response after doing the corresponding computation.</p>
<p>Each controller calls a specific function defined in our models.</p>
<h3 id="heading-models">Models</h3>
<p>Now go to the models folder and create a <code>pets.models.js</code> file with this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> db <span class="hljs-keyword">from</span> <span class="hljs-string">'../../db/db.js'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getItem = <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> pet = db?.pets?.filter(<span class="hljs-function"><span class="hljs-params">pet</span> =&gt;</span> pet?.id === id)[<span class="hljs-number">0</span>]
        <span class="hljs-keyword">return</span> pet
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error'</span>, err)
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> listItems = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">return</span> db?.pets
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error'</span>, err)
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> editItem = <span class="hljs-function">(<span class="hljs-params">id, data</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> index = db.pets.findIndex(<span class="hljs-function"><span class="hljs-params">pet</span> =&gt;</span> pet.id === id)

        <span class="hljs-keyword">if</span> (index === <span class="hljs-number">-1</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Pet not found'</span>)
        <span class="hljs-keyword">else</span> {
            db.pets[index] = data
            <span class="hljs-keyword">return</span> db.pets[index]
        }        
    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error'</span>, err)
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> addItem = <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {  
        <span class="hljs-keyword">const</span> newPet = { <span class="hljs-attr">id</span>: db.pets.length + <span class="hljs-number">1</span>, ...data }
        db.pets.push(newPet)
        <span class="hljs-keyword">return</span> newPet

    } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error'</span>, err)
    }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> deleteItem = <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// delete item from db</span>
        <span class="hljs-keyword">const</span> index = db.pets.findIndex(<span class="hljs-function"><span class="hljs-params">pet</span> =&gt;</span> pet.id === id)

        <span class="hljs-keyword">if</span> (index === <span class="hljs-number">-1</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Pet not found'</span>)
        <span class="hljs-keyword">else</span> {
            db.pets.splice(index, <span class="hljs-number">1</span>)
            <span class="hljs-keyword">return</span> db.pets
        }
    } <span class="hljs-keyword">catch</span> (error) {

    }
}
</code></pre>
<p>These are the functions responsible for interacting with our data layer (database) and returning the corresponding information to our controllers.</p>
<h3 id="heading-database">Database</h3>
<p>We wont use a real database for this example. Instead we'll just use a simple array that will work just fine for example purposes, though our data will of course reset every time our server does.</p>
<p>In the root of our project, create a <code>db</code> folder and a <code>db.js</code> file with this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> db = {
    <span class="hljs-attr">pets</span>: [
        {
            <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Rex'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">3</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'labrador'</span>,
        },
        {
            <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Fido'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'poodle'</span>,
        },
        {
            <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Mittens'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">2</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'tabby'</span>,
        },
    ]
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> db
</code></pre>
<p>As you can see, our <code>db</code> object contains a <code>pets</code> property whose value is an array of objects, each object being a pet. For each pet, we store an id, name, type, age and breed.</p>
<p>Now go to your terminal and run <code>nodemon app.js</code>. You should see this message confirming your server is alive: <code>⚡️[server]: Server is running at [https://localhost:3000](https://localhost:3000)</code>.</p>
<h1 id="heading-how-to-test-a-rest-api-with-supertest">How to Test a REST API with Supertest</h1>
<p>Now that our server is up and running, let's implement a simple test suit to check if each of our endpoints behaves as expected.</p>
<p>If you're not familiar with automated testing, I recommend you read <a target="_blank" href="https://www.freecodecamp.org/news/test-a-react-app-with-jest-testing-library-and-cypress/">this introductory article I wrote a while ago</a>.</p>
<h2 id="heading-our-tools-1">Our tools</h2>
<p><a target="_blank" href="https://www.npmjs.com/package/supertest"><strong>SuperTest</strong></a> is a JavaScript library that is used for testing HTTP servers or web applications that make HTTP requests. It provides a high-level abstraction for testing HTTP, allowing developers to send HTTP requests and make assertions about the responses received, making it easier to write automated tests for web applications.</p>
<p>SuperTest works with any JavaScript testing framework, such as <a target="_blank" href="https://mochajs.org/">Mocha</a> or <a target="_blank" href="https://jestjs.io/">Jest</a>, and can be used with any HTTP server or web application framework, such as Express.</p>
<p>SuperTest is built on top of the popular testing library Mocha, and uses the <a target="_blank" href="https://www.chaijs.com/">Chai</a> assertion library to make assertions about the responses received. It provides an easy-to-use API for making HTTP requests, including support for authentication, headers, and request bodies.</p>
<p>SuperTest also allows developers to test the entire request/response cycle, including middleware and error handling, making it a powerful tool for testing web applications.</p>
<p>Overall, SuperTest is a valuable tool for developers who want to write automated tests for their web applications. It helps ensure that their applications are functioning correctly and that any changes they make to the codebase do not introduce new bugs or issues.</p>
<h2 id="heading-the-code-1">The code</h2>
<p>First we'll need to install some dependencies. To save up terminal commands, go to your <code>package.json</code> file and replace your <code>devDependencies</code> section with this. Then run <code>npm install</code></p>
<pre><code class="lang-javascript">  <span class="hljs-string">"devDependencies"</span>: {
    <span class="hljs-string">"@babel/core"</span>: <span class="hljs-string">"^7.21.4"</span>,
    <span class="hljs-string">"@babel/preset-env"</span>: <span class="hljs-string">"^7.21.4"</span>,
    <span class="hljs-string">"babel-jest"</span>: <span class="hljs-string">"^29.5.0"</span>,
    <span class="hljs-string">"jest"</span>: <span class="hljs-string">"^29.5.0"</span>,
    <span class="hljs-string">"jest-babel"</span>: <span class="hljs-string">"^1.0.1"</span>,
    <span class="hljs-string">"nodemon"</span>: <span class="hljs-string">"^2.0.22"</span>,
    <span class="hljs-string">"supertest"</span>: <span class="hljs-string">"^6.3.3"</span>
  }
</code></pre>
<p>Here we're installing the <code>supertest</code> and <code>jest</code> libraries, which we need for our tests to run, plus some <code>babel</code> stuff we need for our project to correctly identify which files are test files.</p>
<p>Still in your <code>package.json</code>, add this script:</p>
<pre><code class="lang-javascript">  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"jest"</span>
  },
</code></pre>
<p>To end with the boilerplate, in the root of your project, create a <code>babel.config.cjs</code> file and drop this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//babel.config.cjs</span>
<span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-attr">presets</span>: [
      [
        <span class="hljs-string">'@babel/preset-env'</span>,
        {
          <span class="hljs-attr">targets</span>: {
            <span class="hljs-attr">node</span>: <span class="hljs-string">'current'</span>,
          },
        },
      ],
    ],
  };
</code></pre>
<p>Now let's write some actual tests! Within your routes folder, create a <code>pets.test.js</code> file with this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> supertest <span class="hljs-keyword">from</span> <span class="hljs-string">'supertest'</span> <span class="hljs-comment">// Import supertest</span>
<span class="hljs-keyword">import</span> server <span class="hljs-keyword">from</span> <span class="hljs-string">'../../app'</span> <span class="hljs-comment">// Import the server object</span>
<span class="hljs-keyword">const</span> requestWithSupertest = supertest(server) <span class="hljs-comment">// We will use this function to mock HTTP requests</span>

describe(<span class="hljs-string">'GET "/"'</span>, <span class="hljs-function">() =&gt;</span> {
    test(<span class="hljs-string">'GET "/" returns all pets'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> requestWithSupertest.get(<span class="hljs-string">'/pets'</span>)
        expect(res.status).toEqual(<span class="hljs-number">200</span>)
        expect(res.type).toEqual(expect.stringContaining(<span class="hljs-string">'json'</span>))
        expect(res.body).toEqual([
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Rex'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'labrador'</span>,
            },
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Fido'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'poodle'</span>,
            },
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Mittens'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'tabby'</span>,
            },
        ])
    })
})

describe(<span class="hljs-string">'GET "/:id"'</span>, <span class="hljs-function">() =&gt;</span> {
    test(<span class="hljs-string">'GET "/:id" returns given pet'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> requestWithSupertest.get(<span class="hljs-string">'/pets/1'</span>)
        expect(res.status).toEqual(<span class="hljs-number">200</span>)
        expect(res.type).toEqual(expect.stringContaining(<span class="hljs-string">'json'</span>))
        expect(res.body).toEqual(
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Rex'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'dog'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'labrador'</span>,
            }
        )
    })
})

describe(<span class="hljs-string">'PUT "/:id"'</span>, <span class="hljs-function">() =&gt;</span> {
    test(<span class="hljs-string">'PUT "/:id" updates pet and returns it'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> requestWithSupertest.put(<span class="hljs-string">'/pets/1'</span>).send({
            <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Rexo'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'dogo'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">4</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'doberman'</span>
        })
        expect(res.status).toEqual(<span class="hljs-number">200</span>)
        expect(res.type).toEqual(expect.stringContaining(<span class="hljs-string">'json'</span>))
        expect(res.body).toEqual({
            <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Rexo'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'dogo'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">4</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'doberman'</span>
        })
    })
})

describe(<span class="hljs-string">'POST "/"'</span>, <span class="hljs-function">() =&gt;</span> {
    test(<span class="hljs-string">'POST "/" adds new pet and returns the added item'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> requestWithSupertest.post(<span class="hljs-string">'/pets'</span>).send({
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Salame'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">6</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'pinky'</span>
        })
        expect(res.status).toEqual(<span class="hljs-number">200</span>)
        expect(res.type).toEqual(expect.stringContaining(<span class="hljs-string">'json'</span>))
        expect(res.body).toEqual({
            <span class="hljs-attr">id</span>: <span class="hljs-number">4</span>,
            <span class="hljs-attr">name</span>: <span class="hljs-string">'Salame'</span>,
            <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
            <span class="hljs-attr">age</span>: <span class="hljs-number">6</span>,
            <span class="hljs-attr">breed</span>: <span class="hljs-string">'pinky'</span>
        })
    })
})

describe(<span class="hljs-string">'DELETE "/:id"'</span>, <span class="hljs-function">() =&gt;</span> {
    test(<span class="hljs-string">'DELETE "/:id" deletes given pet and returns updated list'</span>, <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> requestWithSupertest.delete(<span class="hljs-string">'/pets/2'</span>)
        expect(res.status).toEqual(<span class="hljs-number">200</span>)
        expect(res.type).toEqual(expect.stringContaining(<span class="hljs-string">'json'</span>))
        expect(res.body).toEqual([
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Rexo'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'dogo'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'doberman'</span>
            },
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Mittens'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'tabby'</span>,
            },
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">'Salame'</span>,
                <span class="hljs-attr">type</span>: <span class="hljs-string">'cat'</span>,
                <span class="hljs-attr">age</span>: <span class="hljs-number">6</span>,
                <span class="hljs-attr">breed</span>: <span class="hljs-string">'pinky'</span>
            }
        ])
    })
})
</code></pre>
<p>For each endpoint, the tests send HTTP requests and check the responses for three things: the HTTP status code, the response type (which should be JSON), and the response body (which should match the expected JSON format).</p>
<ul>
<li><p>The first test sends a GET request to the /pets endpoint and expects the API to return an array of pets in JSON format.</p>
</li>
<li><p>The second test sends a GET request to the /pets/:id endpoint and expects the API to return the pet with the specified ID in JSON format.</p>
</li>
<li><p>The third test sends a PUT request to the /pets/:id endpoint and expects the API to update the pet with the specified ID and return the updated pet in JSON format.</p>
</li>
<li><p>The fourth test sends a POST request to the /pets endpoint and expects the API to add a new pet and return the added pet in JSON format.</p>
</li>
<li><p>Finally, the fifth test sends a DELETE request to the /pets/:id endpoint and expects the API to remove the pet with the specified ID and return the updated list of pets in JSON format.</p>
</li>
</ul>
<p>Each test checks whether the expected HTTP status code, response type, and response body are returned. If any of these expectations are not met, the test fails and provides an error message.</p>
<p>These tests are important for ensuring that the API is working correctly and consistently across different HTTP requests and endpoints. The tests can be run automatically, which makes it easy to detect any issues or regressions in the API's functionality.</p>
<p>Now go to your terminal, run <code>npm test</code>, and you should see all your tests passing:</p>
<pre><code class="lang-javascript">&gt; restapi@<span class="hljs-number">1.0</span><span class="hljs-number">.0</span> test
&gt; jest

 PASS  pets/routes/pets.test.js
  GET <span class="hljs-string">"/"</span>
    ✓ GET <span class="hljs-string">"/"</span> returns all pets (<span class="hljs-number">25</span> ms)
  GET <span class="hljs-string">"/:id"</span>
    ✓ GET <span class="hljs-string">"/:id"</span> returns given pet (<span class="hljs-number">4</span> ms)
  PUT <span class="hljs-string">"/:id"</span>
    ✓ PUT <span class="hljs-string">"/:id"</span> updates pet and returns it (<span class="hljs-number">15</span> ms)
  POST <span class="hljs-string">"/"</span>
    ✓ POST <span class="hljs-string">"/"</span> adds <span class="hljs-keyword">new</span> pet and returns the added item (<span class="hljs-number">3</span> ms)
  DELETE <span class="hljs-string">"/:id"</span>
    ✓ DELETE <span class="hljs-string">"/:id"</span> deletes given pet and returns updated list (<span class="hljs-number">3</span> ms)

Test Suites: <span class="hljs-number">1</span> passed, <span class="hljs-number">1</span> total
<span class="hljs-attr">Tests</span>:       <span class="hljs-number">5</span> passed, <span class="hljs-number">5</span> total
<span class="hljs-attr">Snapshots</span>:   <span class="hljs-number">0</span> total
<span class="hljs-attr">Time</span>:        <span class="hljs-number">1.611</span> s
Ran all test suites.
</code></pre>
<h1 id="heading-how-to-consume-a-rest-api-on-a-front-end-react-app">How to Consume a REST API on a Front-end React App</h1>
<p>Now we know our server is running and our endpoints are behaving as expected. Let's see some more realistic example of how our API might be consumed by a front end app.</p>
<p>For this example, we'll use a React application, and two different tools to send and process our requests: the Fetch API and the Axios library.</p>
<h2 id="heading-our-tools-2">Our tools</h2>
<p><a target="_blank" href="https://react.dev/"><strong>React</strong></a> is a popular JavaScript library for building user interfaces. It allows developers to create reusable UI components and efficiently update and render them in response to changes in application state.</p>
<p>The <strong>Fetch API</strong> is a modern browser API that allows developers to make asynchronous HTTP requests from client-side JavaScript code. It provides a simple interface for fetching resources across the network, and supports a variety of request and response types.</p>
<p><a target="_blank" href="https://axios-http.com/docs/intro"><strong>Axios</strong></a> is a popular HTTP client library for JavaScript. It provides a simple and intuitive API for making HTTP requests, and supports a wide range of features, including request and response interception, automatic transforms for request and response data, and the ability to cancel requests. It can be used both in the browser and on the server, and is often used in conjunction with React applications.</p>
<h2 id="heading-the-code-2">The code</h2>
<p>Let's create our React app by running <code>yarn create vite</code> and following the terminal prompts. Once that's done, run <code>yarn add axios</code> and <code>yarn add react-router-dom</code> (which we'll use to setup basic routing in our app).</p>
<h3 id="heading-appjsx">App.jsx</h3>
<p>Put this code within your <code>App.jsx</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Suspense, lazy, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> { BrowserRouter <span class="hljs-keyword">as</span> Router, Routes, Route, Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-keyword">const</span> PetList = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span> (<span class="hljs-string">'./pages/PetList'</span>))
<span class="hljs-keyword">const</span> PetDetail = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span> (<span class="hljs-string">'./pages/PetDetail'</span>))
<span class="hljs-keyword">const</span> EditPet = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span> (<span class="hljs-string">'./pages/EditPet'</span>))
<span class="hljs-keyword">const</span> AddPet = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span> (<span class="hljs-string">'./pages/AddPet'</span>))

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">const</span> [petToEdit, setPetToEdit] = useState(<span class="hljs-literal">null</span>)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Router</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Pet shelter<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">'/add'</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Add new pet<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">PetList</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>}/&gt;

          <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/:petId'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">PetDetail</span> <span class="hljs-attr">setPetToEdit</span>=<span class="hljs-string">{setPetToEdit}</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>}/&gt;

          <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/:petId/edit'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">EditPet</span> <span class="hljs-attr">petToEdit</span>=<span class="hljs-string">{petToEdit}</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>}/&gt;</span>

          <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">'/add'</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span>}&gt;<span class="hljs-tag">&lt;<span class="hljs-name">AddPet</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>}/&gt;
        &lt;/Routes&gt;

      &lt;/Router&gt;
    &lt;/div&gt;
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Here we're just defining our routes. We'll have 4 main routes in our app, each corresponding to a different view:</p>
<ul>
<li><p>One to see the whole list of pets.</p>
</li>
<li><p>One to see the detail of a single pet.</p>
</li>
<li><p>One to edit a single pet.</p>
</li>
<li><p>One to add a new pet to the list.</p>
</li>
</ul>
<p>Besides, we have a button to add a new pet and a state that will store the information of the pet we want to edit.</p>
<p>Next, create a <code>pages</code> directory with these files in it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-281.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Folder structure</em></p>
<h3 id="heading-petlistjsx">PetList.jsx</h3>
<p>Let's start with the file responsible for rendering the whole list of pets:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PetList</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [pets, setPets] = useState([])

    <span class="hljs-keyword">const</span> getPets = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">/* FETCH */</span>
            <span class="hljs-comment">// const response = await fetch('http://localhost:3000/pets')</span>
            <span class="hljs-comment">// const data = await response.json()</span>
            <span class="hljs-comment">// if (response.status === 200) setPets(data)</span>

            <span class="hljs-comment">/* AXIOS */</span>
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'http://localhost:3000/pets'</span>)
            <span class="hljs-keyword">if</span> (response.status === <span class="hljs-number">200</span>) setPets(response.data)

        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'error'</span>, error)
        }
    }

    useEffect(<span class="hljs-function">() =&gt;</span> { getPets() }, [])

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Pet List<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            {pets?.map((pet) =&gt; {
                return (
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{pet?.id}</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{pet?.name} - {pet?.type} - {pet?.breed}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

                        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>`/${<span class="hljs-attr">pet</span>?<span class="hljs-attr">.id</span>}`}&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Pet detail<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                )
            })}
        <span class="hljs-tag">&lt;/&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PetList
</code></pre>
<p>As you can see, logic-wise we have 3 main things here:</p>
<ul>
<li><p>A state that stores the list of pets to render.</p>
</li>
<li><p>A function that executes the corresponding request to our API.</p>
</li>
<li><p>A useEffect that executes that function when the component renders.</p>
</li>
</ul>
<p>You can see that the syntax for making the HTTP request with fetch and Axios is rather similar, but Axios is a tiny bit more succinct. Once we make the request, we check if the status is 200 (meaning it was successful), and store the response in our state.</p>
<p>Once our state is updated, the component will render the data provided by our API.</p>
<blockquote>
<p>Remember that to make calls to our server, we must have it up and running by running <code>nodemon app.js</code> in our server project terminal.</p>
</blockquote>
<h3 id="heading-petdetailjsx">PetDetail.jsx</h3>
<p>Now let's go to the <code>PetDetail.jsx</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> { useParams, Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PetDetail</span>(<span class="hljs-params">{ setPetToEdit }</span>) </span>{

    <span class="hljs-keyword">const</span> [pet, setPet] = useState([])

    <span class="hljs-keyword">const</span> { petId } = useParams()

    <span class="hljs-keyword">const</span> getPet = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">/* FETCH */</span>
            <span class="hljs-comment">// const response = await fetch(`http://localhost:3000/pets/${petId}`)</span>
            <span class="hljs-comment">// const data = await response.json()</span>
            <span class="hljs-comment">// if (response.status === 200) {</span>
            <span class="hljs-comment">//     setPet(data)</span>
            <span class="hljs-comment">//     setPetToEdit(data)</span>
            <span class="hljs-comment">// }</span>

            <span class="hljs-comment">/* AXIOS */</span>
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">`http://localhost:3000/pets/<span class="hljs-subst">${petId}</span>`</span>)
            <span class="hljs-keyword">if</span> (response.status === <span class="hljs-number">200</span>) {
                setPet(response.data)
                setPetToEdit(response.data)
            }

        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'error'</span>, error)
        }
    }

    useEffect(<span class="hljs-function">() =&gt;</span> { getPet() }, [])

    <span class="hljs-keyword">const</span> deletePet = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">/* FETCH */</span>
            <span class="hljs-comment">// const response = await fetch(`http://localhost:3000/pets/${petId}`, {</span>
            <span class="hljs-comment">//     method: 'DELETE'</span>
            <span class="hljs-comment">// })</span>

            <span class="hljs-comment">/* AXIOS */</span>
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.delete(<span class="hljs-string">`http://localhost:3000/pets/<span class="hljs-subst">${petId}</span>`</span>)

            <span class="hljs-keyword">if</span> (response.status === <span class="hljs-number">200</span>) <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">'/'</span>
        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'error'</span>, error)
        }
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">justifyContent:</span> '<span class="hljs-attr">center</span>', <span class="hljs-attr">aligniItems:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Pet Detail<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            {pet &amp;&amp; (
                <span class="hljs-tag">&lt;&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pet name: {pet.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pet type: {pet.type}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pet age: {pet.age}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pet breed: {pet.breed}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">justifyContent:</span> '<span class="hljs-attr">center</span>', <span class="hljs-attr">aligniItems:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>

                        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>`/${<span class="hljs-attr">pet</span>?<span class="hljs-attr">.id</span>}/<span class="hljs-attr">edit</span>`}&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginRight:</span> <span class="hljs-attr">10</span> }}&gt;</span>Edit pet<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>

                        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                            <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginLeft:</span> <span class="hljs-attr">10</span> }}
                            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> deletePet()}
                        &gt;
                            Delete pet
                        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/&gt;</span></span>
            )}
        &lt;/div&gt;
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PetDetail
</code></pre>
<p>Here we have two different kind of requests:</p>
<ul>
<li><p>One that gets the information of the given pet (which behaves very similar to the previous request we saw). The only difference here is we're passing an URL parameter to our endpoint, which at the same time we're reading from the URL in our front-end app.</p>
</li>
<li><p>The other request is to delete the given pet from our register. The difference here is once we confirm that the request was successful, we redirect the user to the root of our app.</p>
</li>
</ul>
<h3 id="heading-addpetjsx">AddPet.jsx</h3>
<p>This is the file responsible for adding a new pet to our register:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AddPet</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-keyword">const</span> [petName, setPetName] = useState()
    <span class="hljs-keyword">const</span> [petType, setPetType] = useState()
    <span class="hljs-keyword">const</span> [petAge, setPetAge] = useState()
    <span class="hljs-keyword">const</span> [petBreed, setPetBreed] = useState()

    <span class="hljs-keyword">const</span> addPet = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> petData = {
                <span class="hljs-attr">name</span>: petName,
                <span class="hljs-attr">type</span>: petType,
                <span class="hljs-attr">age</span>: petAge,
                <span class="hljs-attr">breed</span>: petBreed
            }

            <span class="hljs-comment">/* FETCH */</span>
            <span class="hljs-comment">// const response = await fetch('http://localhost:3000/pets/', {</span>
            <span class="hljs-comment">//     method: 'POST',</span>
            <span class="hljs-comment">//     headers: {</span>
            <span class="hljs-comment">//         'Content-Type': 'application/json'</span>
            <span class="hljs-comment">//     },</span>
            <span class="hljs-comment">//     body: JSON.stringify(petData)</span>
            <span class="hljs-comment">// })</span>

            <span class="hljs-comment">// if (response.status === 200) {</span>
            <span class="hljs-comment">//     const data = await response.json()</span>
            <span class="hljs-comment">//     window.location.href = `/${data.id}`</span>
            <span class="hljs-comment">// }</span>

            <span class="hljs-comment">/* AXIOS */</span>
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.post(
                <span class="hljs-string">'http://localhost:3000/pets/'</span>,
                petData,
                { <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> } }
            )

            <span class="hljs-keyword">if</span> (response.status === <span class="hljs-number">200</span>) <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">`/<span class="hljs-subst">${response.data.id}</span>`</span>

        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'error'</span>, error)
        }
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">justifyContent:</span> '<span class="hljs-attr">center</span>', <span class="hljs-attr">aligniItems:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Add Pet<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petName}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetName(e.target.value)} /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet type<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petType}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetType(e.target.value)} /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet age<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petAge}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetAge(e.target.value)} /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet breed<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petBreed}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetBreed(e.target.value)} /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginTop:</span> <span class="hljs-attr">30</span> }}
                <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> addPet()}
            &gt;
                Add pet
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AddPet
</code></pre>
<p>Here we're rendering a form in which the user has to enter the new pet info.</p>
<p>We have a state for each piece of information to enter, and in our request we build an object with each state. This object will be the body of our request.</p>
<p>On our request, we check if the response is successful. If it is, we redirect to the detail page of the newly added pet. To redirect, we use the <code>id</code> returned in the HTTP response. ;)</p>
<h3 id="heading-editpetjsx">EditPet.jsx</h3>
<p>Finally, the file responsible for editing a pet register:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">EditPet</span>(<span class="hljs-params">{ petToEdit }</span>) </span>{

    <span class="hljs-keyword">const</span> [petName, setPetName] = useState(petToEdit?.name)
    <span class="hljs-keyword">const</span> [petType, setPetType] = useState(petToEdit?.type)
    <span class="hljs-keyword">const</span> [petAge, setPetAge] = useState(petToEdit?.age)
    <span class="hljs-keyword">const</span> [petBreed, setPetBreed] = useState(petToEdit?.breed)

    <span class="hljs-keyword">const</span> editPet = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> petData = {
                <span class="hljs-attr">id</span>: petToEdit.id,
                <span class="hljs-attr">name</span>: petName,
                <span class="hljs-attr">type</span>: petType,
                <span class="hljs-attr">age</span>: petAge,
                <span class="hljs-attr">breed</span>: petBreed
            }

            <span class="hljs-comment">/* FETCH */</span>
            <span class="hljs-comment">// const response = await fetch(`http://localhost:3000/pets/${petToEdit.id}`, {</span>
            <span class="hljs-comment">//     method: 'PUT',</span>
            <span class="hljs-comment">//     headers: {</span>
            <span class="hljs-comment">//         'Content-Type': 'application/json'</span>
            <span class="hljs-comment">//     },</span>
            <span class="hljs-comment">//     body: JSON.stringify(petData)</span>
            <span class="hljs-comment">// })</span>

            <span class="hljs-comment">/* AXIOS */</span>
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.put(
                <span class="hljs-string">`http://localhost:3000/pets/<span class="hljs-subst">${petToEdit.id}</span>`</span>,
                petData,
                { <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> } }
            )

            <span class="hljs-keyword">if</span> (response.status === <span class="hljs-number">200</span>) {
                <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">`/<span class="hljs-subst">${petToEdit.id}</span>`</span>
            }
        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'error'</span>, error)
        }
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">justifyContent:</span> '<span class="hljs-attr">center</span>', <span class="hljs-attr">aligniItems:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Edit Pet<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petName}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetName(e.target.value)} /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet type<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petType}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetType(e.target.value)} /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet age<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petAge}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetAge(e.target.value)} /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> '<span class="hljs-attr">flex</span>', <span class="hljs-attr">flexDirection:</span> '<span class="hljs-attr">column</span>', <span class="hljs-attr">margin:</span> <span class="hljs-attr">20</span> }}&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Pet breed<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{petBreed}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setPetBreed(e.target.value)} /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginTop:</span> <span class="hljs-attr">30</span> }}
                <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> editPet()}
            &gt;
                Save changes
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> EditPet
</code></pre>
<p>This behaves very similar to the <code>AddPet.jsx</code> file. The only difference is that our pet info states are initialized with the values of the pet we want to edit. When those values are updated by the user, we construct an object that will be our request body and send the request with the updated information. Quite straightforward. ;)</p>
<p>And that's it! We're using all of our API endpoints in our front end app. =)</p>
<h1 id="heading-how-to-document-a-rest-api-with-swagger">How to Document a REST API with Swagger</h1>
<p>Now that we have our server up and running, tested, and connected to our front end app, the last step in our implementation will be to document our API.</p>
<p>Documenting and API generally means declaring which endpoints are available, what actions are performed by each endpoint, and the parameters and return values for each of them.</p>
<p>This is useful not only to remember how our server works, but also for people who want to interact with our API.</p>
<p>For example, in companies it's very usual to have back-end teams and front-end teams. When an API is being developed and needs to be integrated with a front-end app, it would be very tedious to ask which endpoint does what, and what parameters should be passed. If you have all that info in a singe place, you can just go there and read it yourself. That's what documentation is.</p>
<h2 id="heading-our-tools-3">Our tools</h2>
<p><a target="_blank" href="https://swagger.io/"><strong>Swagger</strong></a> is a set of open-source tools that help developers build, document, and consume RESTful web services. It provides a user-friendly graphical interface for users to interact with an API and also generates client code for various programming languages to make API integration easier.</p>
<p>Swagger provides a comprehensive set of features for API development, including API design, documentation, testing, and code generation. It allows developers to define API endpoints, input parameters, expected output, and authentication requirements in a standardized way using the OpenAPI specification.</p>
<p>Swagger UI is a popular tool that renders OpenAPI specifications as an interactive API documentation that allows developers to explore and test APIs through a web browser. It provides a user-friendly interface that allows developers to easily view and interact with API endpoints.</p>
<h2 id="heading-how-to-implement-swagger">How to Implement Swagger</h2>
<p>Back in our server app, to implement Swagger we'll need two new dependencies. So run <code>npm i swagger-jsdoc</code> and <code>npm i swagger-ui-express</code>.</p>
<p>Next, modify the <code>app.js</code> file to look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>
<span class="hljs-keyword">import</span> cors <span class="hljs-keyword">from</span> <span class="hljs-string">'cors'</span>
<span class="hljs-keyword">import</span> swaggerUI <span class="hljs-keyword">from</span> <span class="hljs-string">'swagger-ui-express'</span>
<span class="hljs-keyword">import</span> swaggerJSdoc <span class="hljs-keyword">from</span> <span class="hljs-string">'swagger-jsdoc'</span>

<span class="hljs-keyword">import</span> petRoutes <span class="hljs-keyword">from</span> <span class="hljs-string">'./pets/routes/pets.routes.js'</span>

<span class="hljs-keyword">const</span> app = express()
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>

<span class="hljs-comment">// swagger definition</span>
<span class="hljs-keyword">const</span> swaggerSpec = {
    <span class="hljs-attr">definition</span>: {
        <span class="hljs-attr">openapi</span>: <span class="hljs-string">'3.0.0'</span>,
        <span class="hljs-attr">info</span>: {
            <span class="hljs-attr">title</span>: <span class="hljs-string">'Pets API'</span>,
            <span class="hljs-attr">version</span>: <span class="hljs-string">'1.0.0'</span>,
        },
        <span class="hljs-attr">servers</span>: [
            {
                <span class="hljs-attr">url</span>: <span class="hljs-string">`http://localhost:<span class="hljs-subst">${port}</span>`</span>,
            }
        ]
    },
    <span class="hljs-attr">apis</span>: [<span class="hljs-string">'./pets/routes/*.js'</span>],
}

<span class="hljs-comment">/* Global middlewares */</span>
app.use(cors())
app.use(express.json())
app.use(
    <span class="hljs-string">'/api-docs'</span>,
    swaggerUI.serve,
    swaggerUI.setup(swaggerJSdoc(swaggerSpec))
)

<span class="hljs-comment">/* Routes */</span>
app.use(<span class="hljs-string">'/pets'</span>, petRoutes)

<span class="hljs-comment">/* Server setup */</span>
<span class="hljs-keyword">if</span> (process.env.NODE_ENV !== <span class="hljs-string">'test'</span>) {
    app.listen(port, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`⚡️[server]: Server is running at https://localhost:<span class="hljs-subst">${port}</span>`</span>))
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> app
</code></pre>
<p>As you can see, we're importing the new dependencies, we're creating a <code>swaggerSpec</code> object that contains config options for our implementation, and then setting a middleware to render our documentation in the <code>/api-docs</code> directory of our app.</p>
<p>By now, if you open your browser and go to <a target="_blank" href="http://localhost:3000/api-docs/"><code>http://localhost:3000/api-docs/</code></a> you should see this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-325.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Documentation UI</em></p>
<p>The cool thing about Swagger is it provides an out-of-the-box UI for our docs, and you can easily access it in the URL path declared in the config.</p>
<p>Now let's write some actual documentation!</p>
<p>Hop on to the <code>pets.routes.js</code> file and replace its code with this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;
<span class="hljs-keyword">import</span> {
  listPets,
  getPet,
  editPet,
  addPet,
  deletePet,
} <span class="hljs-keyword">from</span> <span class="hljs-string">"../controllers/pets.controllers.js"</span>;

<span class="hljs-keyword">const</span> router = express.Router();

<span class="hljs-comment">/**
 * @swagger
 * components:
 *  schemas:
 *     Pet:
 *      type: object
 *      properties:
 *          id:
 *              type: integer
 *              description: Pet id
 *          name:
 *              type: string
 *              description: Pet name
 *          age:
 *              type: integer
 *              description: Pet age
 *          type:
 *              type: string
 *              description: Pet type
 *          breed:
 *              type: string
 *              description: Pet breed
 *     example:
 *          id: 1
 *          name: Rexaurus
 *          age: 3
 *          breed: labrador
 *          type: dog
 */</span>

<span class="hljs-comment">/**
 * @swagger
 * /pets:
 *  get:
 *     summary: Get all pets
 *     description: Get all pets
 *     responses:
 *      200:
 *         description: Success
 *      500:
 *         description: Internal Server Error
 */</span>
router.get(<span class="hljs-string">"/"</span>, listPets);

<span class="hljs-comment">/**
 * @swagger
 * /pets/{id}:
 *  get:
 *     summary: Get pet detail
 *     description: Get pet detail
 *     parameters:
 *       - in: path
 *         name: id
 *         schema:
 *           type: integer
 *         required: true
 *         description: Pet id
 *     responses:
 *      200:
 *         description: Success
 *      500:
 *         description: Internal Server Error
 */</span>
router.get(<span class="hljs-string">"/:id"</span>, getPet);

<span class="hljs-comment">/**
 * @swagger
 * /pets/{id}:
 *  put:
 *     summary: Edit pet
 *     description: Edit pet
 *     parameters:
 *       - in: path
 *         name: id
 *         schema:
 *           type: integer
 *         required: true
 *         description: Pet id
 *     requestBody:
 *       description: A JSON object containing pet information
 *       content:
 *         application/json:
 *           schema:
 *              $ref: '#/components/schemas/Pet'
 *           example:
 *              name: Rexaurus
 *              age: 12
 *              breed: labrador
 *              type: dog
 *     responses:
 *     200:
 *        description: Success
 *     500:
 *       description: Internal Server Error
 *
 */</span>
router.put(<span class="hljs-string">"/:id"</span>, editPet);

<span class="hljs-comment">/**
 * @swagger
 * /pets:
 *  post:
 *      summary: Add pet
 *      description: Add pet
 *      requestBody:
 *          description: A JSON object containing pet information
 *          content:
 *             application/json:
 *                 schema:
 *                    $ref: '#/components/schemas/Pet'
 *                 example:
 *                    name: Rexaurus
 *                    age: 12
 *                    breed: labrador
 *                    type: dog
 *      responses:
 *      200:
 *          description: Success
 *      500:
 *          description: Internal Server Error
 */</span>
router.post(<span class="hljs-string">"/"</span>, addPet);

<span class="hljs-comment">/**
 * @swagger
 * /pets/{id}:
 *  delete:
 *     summary: Delete pet
 *     description: Delete pet
 *     parameters:
 *       - in: path
 *         name: id
 *         schema:
 *           type: integer
 *         required: true
 *         description: Pet id
 *     responses:
 *     200:
 *        description: Success
 *     500:
 *       description: Internal Server Error
 */</span>
router.delete(<span class="hljs-string">"/:id"</span>, deletePet);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> router;
</code></pre>
<p>As you can see, we're adding a special kind of comment for each of our endpoints. This is the way Swagger UI identifies the documentation within our code. We've put them in this file since it makes sense to have the docs as close to the endpoints as possible, but you could place them wherever you want.</p>
<p>If we analyze the comments in detail you could see they're written in a YAML like syntax, and for each of them we specify the endpoint route, HTTP method, a description, the parameters it receives and the possible responses.</p>
<p>All comments are more or less the same except the first one. In that one we're defining a "schema" which is like a typing to a kind of object we can later on reuse in other comments. In our case, we're defining the "Pet" schema which we then use for the <code>put</code> and <code>post</code> endpoints.</p>
<p>If you enter <a target="_blank" href="http://localhost:3000/api-docs/"><code>http://localhost:3000/api-docs/</code></a> again, you should now see this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-327.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Documentation UI</em></p>
<p>Each of the endpoints can be expanded, like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-328.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Documentation UI</em></p>
<p>And if we click the "Try it out" button, we can execute an HTTP request and see what the response looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-329.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Documentation UI</em></p>
<p>This is really useful for developers in general and people who want to work with our API, and very easy to set up as you can see.</p>
<p>Having an out-of-the-box UI simplifies the interaction with the documentation. And having it within our codebase as well is a great bonus, as we can modify and update it without the need of touching anything else but our own code.</p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>As always, I hope you enjoyed the handbook and learned something new. If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>.</p>
<p>See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/5325cccb7a8a7ba25e7780d03c348b2f.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Primitive Values vs Reference Values – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In JavaScript, variables can hold two types of data: primitive values and reference values. Understanding the difference between these two types of data is crucial for writing efficient and bug-free code. In this short article, we will e... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-assigning-values-vs-assigning-references/</link>
                <guid isPermaLink="false">66d45f0b3dce891ac3a967f8</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Tue, 18 Apr 2023 16:31:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/pexels-pedro-figueras-681447.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In JavaScript, variables can hold two types of data: primitive values and reference values. Understanding the difference between these two types of data is crucial for writing efficient and bug-free code.</p>
<p>In this short article, we will explore the difference between values and references in JavaScript.</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-primitive-values">What are primitive values?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-reference-values">What are reference values?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-pass-values-and-references-as-function-arguments">How to pass values and references as function arguments</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-copies-of-objects-arrays-and-functions">How to create copies of objects, arrays and functions</a></p>
<ul>
<li><a target="_blank" href="shallow-vs-deep-copies">Shallow vs deep copies</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></p>
</li>
</ul>
<h1 id="heading-what-are-primitive-values">What are Primitive Values?</h1>
<p>Primitive values are data that are stored directly in a variable. These include numbers, booleans, strings, null, and undefined.</p>
<p>When we assign a primitive value to a variable, a copy of that value is created and stored in memory. Any changes made to the variable do not affect the original value.</p>
<p>For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> x = <span class="hljs-number">5</span>;
<span class="hljs-keyword">let</span> y = x;
y = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// Output: 5</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// Output: 10</span>
</code></pre>
<p>In the example above, the variable <code>y</code> is assigned a copy of the value of <code>x</code>. When we change the value of <code>y</code>, it does not affect the value of <code>x</code>. This is because <code>x</code> and <code>y</code> are separate variables with separate memory locations.</p>
<h1 id="heading-what-are-reference-values">What are Reference Values?</h1>
<p>Reference values, on the other hand, are objects that are stored in memory and accessed through a reference. These include arrays, objects, and functions.</p>
<p>When we assign a reference value to a variable, a reference to the original value is created and stored in memory. Any changes made to the variable affect the original value.</p>
<p>For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> array1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> array2 = array1;
array2.push(<span class="hljs-number">4</span>);
<span class="hljs-built_in">console</span>.log(array1); <span class="hljs-comment">// Output: [1, 2, 3, 4]</span>
<span class="hljs-built_in">console</span>.log(array2); <span class="hljs-comment">// Output: [1, 2, 3, 4]</span>
</code></pre>
<p>In the example above, the variable <code>array2</code> is assigned a reference to the original array <code>array1</code>. When we push a value to <code>array2</code>, it also affects <code>array1</code> because both variables reference the same memory location.</p>
<h1 id="heading-how-to-pass-values-and-references-as-function-arguments">How to Pass Values and References as Function Arguments</h1>
<p>When we pass a primitive value as an argument to a function, a copy of that value is created and passed to the function. Any changes made to the variable inside the function do not affect the original value.</p>
<p>For example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addOne</span>(<span class="hljs-params">x</span>) </span>{
    x++;
    <span class="hljs-keyword">return</span> x;
}

<span class="hljs-keyword">let</span> number = <span class="hljs-number">5</span>;
<span class="hljs-built_in">console</span>.log(addOne(number)); <span class="hljs-comment">// Output: 6</span>
<span class="hljs-built_in">console</span>.log(number); <span class="hljs-comment">// Output: 5</span>
</code></pre>
<p>In the example above, the function <code>addOne</code> receives a copy of the value of <code>number</code>. When we increment the value of <code>x</code> inside the function, it does not affect the value of <code>number</code>.</p>
<p>When we pass a reference value as an argument to a function, a reference to the original value is passed. Any changes made to the variable inside the function affect the original value.</p>
<p>For example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addToArray</span>(<span class="hljs-params">array</span>) </span>{
    array.push(<span class="hljs-number">4</span>);
    <span class="hljs-keyword">return</span> array;
}

<span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-built_in">console</span>.log(addToArray(myArray)); <span class="hljs-comment">// Output: [1, 2, 3, 4]</span>
<span class="hljs-built_in">console</span>.log(myArray); <span class="hljs-comment">// Output: [1, 2, 3, 4]</span>
</code></pre>
<p>In the example above, the function <code>addToArray</code> receives a reference to the original array <code>myArray</code>. When we push a value to <code>array</code> inside the function, it also affects <code>myArray</code> because both variables reference the same memory location.</p>
<h1 id="heading-how-to-create-copies-of-objects-arrays-and-functions">How to Create Copies of Objects, Arrays, and Functions</h1>
<p>Creating a copy of an object, array, or function can be useful when you want to modify the data without affecting the original. There are several ways to create a copy of an object in JavaScript.</p>
<p>One way to create a shallow copy of an object is to use the object spread syntax, which was introduced in ECMAScript 2018. The syntax is simple and looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalObj = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
<span class="hljs-keyword">const</span> copyObj = { ...originalObj };
</code></pre>
<p>In this example, <code>copyObj</code> is a new object with the same properties as <code>originalObj</code>. However, modifying <code>copyObj</code> will not affect <code>originalObj</code>.</p>
<p>For arrays, the <code>slice()</code> method can be used to create a shallow copy of an array. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-keyword">const</span> copyArr = originalArr.slice();
</code></pre>
<p>In this example, <code>copyArr</code> is a new array with the same values as <code>originalArr</code>.</p>
<p>When it comes to creating a copy of a function, things get a bit more complicated. One approach is to create a new function that simply calls the original function with the same arguments. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">originalFunc</span>(<span class="hljs-params">arg1, arg2</span>) </span>{
    <span class="hljs-comment">// function body here</span>
}
<span class="hljs-keyword">const</span> copyFunc = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-keyword">return</span> originalFunc.apply(<span class="hljs-built_in">this</span>, args);
};
</code></pre>
<p>In this example, <code>copyFunc</code> is a new function that calls <code>originalFunc</code> with the same arguments. But keep in mind that this only creates a shallow copy of the function. Any functions or objects used within <code>originalFunc</code> will still reference the original values.</p>
<p>As you can see, creating copies of objects, arrays, and functions can be a useful technique in JavaScript programming. Using the appropriate method for the data type you're working with will help ensure that your code behaves as expected and is more maintainable in the long run.</p>
<h2 id="heading-shallow-vs-deep-copies">Shallow vs Deep Copies</h2>
<p>In JavaScript, there are two ways to copy objects and arrays: shallow copy and deep copy. Understanding the difference between these two types of copies is important, as it can affect the behavior of your code.</p>
<p>A shallow copy creates a new object or array, but it only copies the references to the properties of the original object or array.</p>
<p>In other words, the new object or array has the same values for its properties as the original, but the properties themselves still reference the same values in memory. This means that any changes made to the properties of the new object or array will also affect the original object or array, and vice versa.</p>
<p>Here's an example of a shallow copy of an array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>]];
<span class="hljs-keyword">const</span> shallowCopyArr = [...originalArr];

shallowCopyArr[<span class="hljs-number">0</span>] = <span class="hljs-number">10</span>;
shallowCopyArr[<span class="hljs-number">3</span>][<span class="hljs-number">0</span>] = <span class="hljs-number">40</span>;

<span class="hljs-built_in">console</span>.log(originalArr); <span class="hljs-comment">// [1, 2, 3, [40, 5]]</span>
<span class="hljs-built_in">console</span>.log(shallowCopyArr); <span class="hljs-comment">// [10, 2, 3, [40, 5]]</span>
</code></pre>
<p>In this example, the spread operator is used to create a shallow copy of <code>originalArr</code>. Then, the first element of <code>shallowCopyArr</code> is changed to <code>10</code>, which does not affect <code>originalArr</code>. But when the first element of the nested array in <code>shallowCopyArr</code> is changed to <code>40</code>, it also changes in <code>originalArr</code>, because both arrays share a reference to the same nested array.</p>
<p>A deep copy, on the other hand, creates a new object or array. It also copies the values of the properties of the original object or array, rather than just the references. This means that any changes made to the new object or array will not affect the original object or array, and vice versa.</p>
<p>Here's an example of a deep copy of an array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>]];
<span class="hljs-keyword">const</span> deepCopyArr = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(originalArr));

deepCopyArr[<span class="hljs-number">0</span>] = <span class="hljs-number">10</span>;
deepCopyArr[<span class="hljs-number">3</span>][<span class="hljs-number">0</span>] = <span class="hljs-number">40</span>;

<span class="hljs-built_in">console</span>.log(originalArr); <span class="hljs-comment">// [1, 2, 3, [4, 5]]</span>
<span class="hljs-built_in">console</span>.log(deepCopyArr); <span class="hljs-comment">// [10, 2, 3, [40, 5]]</span>
</code></pre>
<p>In this example, <code>JSON.stringify()</code> is used to convert <code>originalArr</code> to a string, and then <code>JSON.parse()</code> is used to convert the string back into an array. This creates a new array with the same values as <code>originalArr</code>, but the new array is completely independent from the original array.</p>
<p>In conclusion, the main difference between a shallow copy and deep copy in JavaScript is whether the new object or array only copies the references to the properties of the original object or array, or whether it also copies the values of the properties.</p>
<p>When copying complex data types like objects and arrays, it's important to use the appropriate type of copy depending on your use case.</p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>In summary, understanding the difference between values and references in JavaScript is essential for writing efficient and bug-free code. By being aware of how data is stored and manipulated, you can avoid unexpected behavior and improve the performance of your applications.</p>
<p>Remember that primitive types are passed by value, while objects and arrays are passed by reference. Keep this in mind when working with functions and assigning variables.</p>
<p>Finally, it's worth noting that ECMAScript 6 introduced a new keyword called <code>let</code> which behaves more like traditional programming languages in regards to variable assignment. <code>let</code> allows you to declare a block-scoped variable, meaning that it is only accessible within the block of code it is declared in. This can help prevent confusion with referencing and values as the scope of the variable is limited.</p>
<p>In conclusion, while values and references may seem like a small detail in the grand scheme of JavaScript programming, they can have a significant impact on your code's behavior and efficiency. By understanding the differences and using the appropriate techniques for your particular situation, you can write cleaner, more effective, and less error-prone code.</p>
<p>As always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/monsters-inc-sully.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Linters and Code Formatters in Your Projects ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article we're going to take a look at two very useful tools we can use to make our lives easier when writing code: linting tools and code formatters. We're going to talk about what these tools are, how they work, why are they use... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/using-prettier-and-jslint/</link>
                <guid isPermaLink="false">66d45f27052ad259f07e4ad8</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 10 Apr 2023 22:02:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/alysa-bajenaru-88IV5AtWjB8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article we're going to take a look at two very useful tools we can use to make our lives easier when writing code: linting tools and code formatters.</p>
<p>We're going to talk about what these tools are, how they work, why are they useful, and finally see how we can implement them in a basic React project.</p>
<p>Let's go!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-about-linting-tools">About linting tools</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-linting-tools">What are Linting Tools?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-are-linting-tools-useful">Why are Linting Tools Useful?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-main-linting-tools-in-the-market">Main Linting Tools in the Market</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-about-code-formatters">About code formatters</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-code-formatters">What are Code Formatters?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-are-code-formatters-useful">Why are Code Formatters Useful?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-main-code-formatters-available">Main Code Formatters Available</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-eslint-and-prettier">How to Implement ESLint and Prettier</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-install-eslint">How to Install ESLint</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-install-prettier">How to Install Prettier</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></p>
</li>
</ul>
<h1 id="heading-about-linting-tools">About Linting Tools</h1>
<p>In the world of web development, linting tools have become an essential part of the developer's toolkit.</p>
<p>Linting tools are used to analyze source code for potential errors or stylistic issues, making it easier to maintain code quality and consistency across a project.</p>
<h2 id="heading-what-are-linting-tools">What are Linting Tools?</h2>
<p>Linting tools are automated tools that analyze source code to detect potential errors, security vulnerabilities, or coding style issues.</p>
<p>They are designed to help developers catch mistakes before they become a problem, and to promote best practices in coding.</p>
<p>The term "lint" comes from the name of the first lint tool, which was developed in the early 1970s by a team of Bell Labs researchers led by Stephen C. Johnson.</p>
<p>The original lint tool was designed to analyze C source code for potential errors and stylistic issues.</p>
<p>Since then, linting tools have evolved to work with a variety of programming languages, including JavaScript, Python, and Ruby.</p>
<h2 id="heading-why-are-linting-tools-useful">Why are Linting Tools Useful?</h2>
<p>Linting tools are useful for a number of reasons. Firstly, they help you catch errors early in the development process, when they are easier and cheaper to fix.</p>
<p>Secondly, they can help promote coding standards and best practices within a development team, ensuring that code is consistent and maintainable.</p>
<p>Finally, they can help you identify potential security vulnerabilities in your code, reducing the risk of a breach.</p>
<h2 id="heading-main-linting-tools-in-the-market">Main Linting Tools in the Market</h2>
<p>There are several linting tools available in the market today. Here are some of the most popular ones:</p>
<ol>
<li><p><strong>ESLint:</strong> <a target="_blank" href="https://eslint.org/">ESLint</a> is a widely used and highly configurable linter for JavaScript and TypeScript. It can be extended using plugins and supports various rule sets, making it a flexible tool for enforcing coding standards and preventing errors.</p>
</li>
<li><p><strong>JSHint:</strong> <a target="_blank" href="https://jshint.com/">JSHint</a> is a popular linter that has been around since 2010. It offers a simple configuration and a wide range of built-in rules to help developers avoid common pitfalls and improve code quality.</p>
</li>
<li><p><strong>JSLint:</strong> <a target="_blank" href="https://www.jslint.com/">JSLint</a> was one of the first linters to be developed for JavaScript, and it still sees some use today. It is known for its strictness and for enforcing a particular style of code, which can be helpful for maintaining consistency across a team.</p>
</li>
<li><p><strong>StandardJS:</strong> <a target="_blank" href="https://standardjs.com/">StandardJS</a> is a popular linter that aims to provide a "batteries included" approach to JavaScript linting. It has a minimal configuration and includes a set of opinionated rules designed to promote clean, readable code.</p>
</li>
</ol>
<p>And we should also talk about <strong>Typescript</strong>. When using <a target="_blank" href="https://www.typescriptlang.org/">TypeScript</a>, the TypeScript compiler itself acts as a linter. It checks the syntax of TypeScript code and provides warnings and errors when there are issues. This built-in linter can catch common mistakes and issues such as misspelled variable names, invalid method calls, and syntax errors.</p>
<p>The TypeScript compiler can be run using the <code>tsc</code> command in a terminal. When the <code>--noEmit</code> flag is used, the TypeScript compiler will only perform a syntax check without compiling the code to JavaScript. This allows the compiler to act as a linter and provide feedback on code quality without actually generating any output.</p>
<p>You can also configure the TypeScript compiler using a <code>tsconfig.json</code> file to specify various options, including the strictness of the checking. This can help catch even more potential issues and ensure that the code follows best practice</p>
<p>If you're not familiar with TypeScript, I recommend you <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-typescript/">this article I wrote a while ago</a>.</p>
<h1 id="heading-about-code-formatters">About Code Formatters</h1>
<p>In modern web development, code formatters have become an essential tool for developers. These tools automate the process of code formatting, making it easier to write and read code.</p>
<h2 id="heading-what-are-code-formatters">What are Code Formatters?</h2>
<p>Code formatters are automated tools that help you format source code automatically. The main purpose of code formatters is to standardize the formatting of code across a project or team, making it easier to read and understand code.</p>
<p>With code formatters, developers no longer need to spend time formatting code manually, which can save a lot of time and effort.</p>
<p>Code formatting tools have been around for decades. One of the earliest tools was the "indent" program, which was used to format C code in the early 1970s. But these early tools were limited and didn't have the same level of functionality as modern code formatters.</p>
<p>In the early 2000s, tools like "astyle" and "uncrustify" were developed, which introduced more advanced formatting capabilities.</p>
<h2 id="heading-why-are-code-formatters-useful">Why are Code Formatters Useful?</h2>
<p>Code formatters are useful for a variety of reasons. First and foremost, they help to standardize code formatting, which makes it easier to read and understand code. This is particularly important when working on large projects with multiple developers, where everyone needs to be able to read and understand each other's code.</p>
<p>Code formatters also help to ensure that code is consistent across a project or team, which can help to prevent errors and improve code quality. They also make it easier to maintain code over time, as the code is formatted consistently and is easier to read and understand.</p>
<h2 id="heading-main-code-formatters-available">Main Code Formatters Available</h2>
<p>There are several code formatting tools available in the market today. Here are some of the most popular ones:</p>
<ol>
<li><p><strong>Prettier:</strong> <a target="_blank" href="https://prettier.io/">Prettier</a> is a popular code formatter for JavaScript, TypeScript, and CSS. It's highly configurable and can be used in a variety of different environments, including editors, build tools, and code quality checkers.</p>
</li>
<li><p><strong>ESLint:</strong> While primarily known as a linting tool, <a target="_blank" href="https://eslint.org/">ESLint</a> can also be used as a code formatter. It has a <code>--fix</code> flag that can automatically format your code based on rules you define.</p>
</li>
<li><p><strong>Beautify:</strong> Beautify is a code formatter for JavaScript, HTML, and CSS that can be used in a variety of editors and IDEs. It allows you to customize your formatting options and has support for a wide range of languages.</p>
</li>
</ol>
<h1 id="heading-how-to-implement-eslint-and-prettier">How to Implement ESLint and Prettier</h1>
<p>Cool, so now let's see a linter and code formatter in action! We're going to implement the two most popular tools (ESLint and Prettier) in a simple React project to get an idea of how these things work.</p>
<p>First let's create our project by running this in our command line: <code>npm create vite@latest linternsAndFormatters --template react</code></p>
<p>Then <code>cd</code> into your project and run <code>npm install</code> so our dependencies get installed.</p>
<p>Now that we have our project up and running, we'll start by installing <strong>ESLint.</strong></p>
<h2 id="heading-how-to-install-eslint">How to Install ESLint</h2>
<p>To install ESLint, we can just run <code>npm init @eslint/config</code> in our console. This will fire a series of prompts asking how we want to use ESLint in our project and building the corresponding config. Your console might end up looking something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-72.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Installing ESLint</em></p>
<p>After all this, we'll see a new file called <code>.eslintrc.cjs</code> in the root of our project. Here's where ESLint's config lives and where we can customize the linter to our preferences. The initial config given the options I selected is the following:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-string">"env"</span>: {
        <span class="hljs-string">"browser"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-string">"es2021"</span>: <span class="hljs-literal">true</span>
    },
    <span class="hljs-string">"extends"</span>: [
        <span class="hljs-string">"eslint:recommended"</span>,
        <span class="hljs-string">"plugin:react/recommended"</span>
    ],
    <span class="hljs-string">"overrides"</span>: [
    ],
    <span class="hljs-string">"parserOptions"</span>: {
        <span class="hljs-string">"ecmaVersion"</span>: <span class="hljs-string">"latest"</span>,
        <span class="hljs-string">"sourceType"</span>: <span class="hljs-string">"module"</span>
    },
    <span class="hljs-string">"plugins"</span>: [
        <span class="hljs-string">"react"</span>
    ],
    <span class="hljs-string">"rules"</span>: {
    }
}
</code></pre>
<p>To see our linter in action, let's add the following script in our <code>package.json</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"lint"</span>: <span class="hljs-string">"eslint --fix . --ext .js,.jsx"</span>
</code></pre>
<p>This script executes the <code>eslint</code> command with the <code>--fix</code> option to automatically fix linting errors and warnings. The command is executed on all files with the <code>.js</code> or <code>.jsx</code> extension located in the root directory of the project, as specified by the <code>.</code> argument.</p>
<p>Now let's modify our <code>app.jsx</code> file to have the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">const</span> emptyVariable = <span class="hljs-string">''</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Vite + React<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Then run <code>npm run lint</code> and voilà! Your linter is screaming with red highlighted text that you have an unused variable in your code! =D</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-73.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-install-prettier">How to Install Prettier</h2>
<p>Cool, now let's hop on to our code formatter.</p>
<p>We're going to install it by running <code>npm install --save-dev --save-exact prettier</code>.</p>
<p>Then we're going to create and empty config file by running <code>echo {}&gt; .prettierrc.json</code>.</p>
<p>Since we're here, add the following options to your newly created config file:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"singleQuote"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"jsxSingleQuote"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"semi"</span>: <span class="hljs-literal">false</span>
}
</code></pre>
<p>What this does is assure single quotes are used whenever possible and semicolons are nowhere to be found (because, god, who likes semicolons...).</p>
<p>As we did with our linter, let's add the following script in our <code>package.json</code> file:</p>
<pre><code class="lang-javascript">    <span class="hljs-string">"format"</span>: <span class="hljs-string">"prettier --write ."</span>
</code></pre>
<p>The script runs the Prettier code formatter on all the files in the project directory and its sub-directories. When run with the <code>--write</code> option, it modifies the files in place, changing them to conform to Prettier's rules for indentation, line length, and other formatting options. The <code>.</code> argument specifies that all files in the project directory and its sub directories should be formatted.</p>
<p>Lastly, let's "uglify" the first line of our <code>app.jsx</code> file like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
</code></pre>
<p>Run <code>npm run format</code> and you should see it corrected right in front of you:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
</code></pre>
<p>You can breath easy now, those ugly semicolons won't come back to haunt you. ;)</p>
<p>As we've seen, the set up of these two tools isn't that complex, and they truly help to make our everyday jobs easier. ESLint will help us catch bugs and unnecessary/redundant code, and Prettier will help us standardize code format all across our codebase.</p>
<p>Another tip is that if you have a CI/CD pipeline in place, it's a good idea to implement the linting and formatting scripts as part of your workflow. This will help you ensure that every deployment is both automatically linted and formatted.</p>
<p>If you're not familiar with CI/CD or setting up a pipeline, I recently wrote <a target="_blank" href="https://www.freecodecamp.org/news/what-is-ci-cd/">an article about that</a>. ;)</p>
<h1 id="heading-wrapping-up">Wrapping up</h1>
<p>Linters and code formatters are powerful tools that can greatly benefit web developers.</p>
<p>Linters help you catch potential bugs and issues before they become serious problems, and encourage you to write more maintainable and readable code.</p>
<p>Code formatters help you enforce a consistent code style and format, saving time and reducing the chances of human error.</p>
<p>By using these tools in your web development workflow, you can improve your productivity and the quality of your code.</p>
<p>As always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/4M2n.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is CI/CD? Learn Continuous Integration/Continuous Deployment by Building a Project ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article you're going to learn about CI/CD (continuous integration and continuous deployment). We're going to review what this practice is about, how it compares to the previous approach in the software development industry, and f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-ci-cd/</link>
                <guid isPermaLink="false">66d45f2a706b9fb1c166b947</guid>
                
                    <category>
                        <![CDATA[ continuous deployment ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Continuous Integration ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Fri, 07 Apr 2023 19:31:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/jj-ying-4XvAZN8_WHo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article you're going to learn about CI/CD (continuous integration and continuous deployment).</p>
<p>We're going to review what this practice is about, how it compares to the previous approach in the software development industry, and finally see a practical example of how we can implement it in our projects.</p>
<p>Let's go!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-intro">Intro</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-cicd-works">How CI/CD works</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-key-benefits-of-cicd">The key benefits of CI/CD</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tools-for-cicd">Tools for CI/CD</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-a-cicd-pipeline-with-github-actions">How to set up a CI/CD pipeline with GitHub Actions</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-initializing-the-project">Initializing the project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-github-actions-and-how-do-they-work">What are GitHub Actions and how do they work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-setting-up-our-workflow">Setting up our workflow</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-magic">The magic</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></p>
</li>
</ul>
<h1 id="heading-intro">Intro</h1>
<p>Continuous Integration and Continuous Delivery (CI/CD) is a software development approach that aims to improve the speed, efficiency, and reliability of software delivery. This approach involves frequent code integration, automated testing, and continuous deployment of software changes to production.</p>
<p>Before the adoption of CI/CD in the software development industry, the common approach was a traditional, <strong>waterfall model</strong> of software development.</p>
<p>In this approach, developers worked in silos, with each stage of the software development life cycle completed in sequence. The process typically involved gathering requirements, designing the software, coding, testing, and deployment.</p>
<p><strong>The disadvantages of this traditional approach include:</strong></p>
<ol>
<li><p><strong>Slow Release Cycles:</strong> Since each stage of the software development life cycle was completed in sequence, the release cycle was slow, which made it difficult to respond quickly to changing customer needs.</p>
</li>
<li><p><strong>High Failure Rates:</strong> Software projects were prone to failure due to a lack of automated testing, which meant that developers had to rely on manual testing, leading to errors and bugs in the code.</p>
</li>
<li><p><strong>Limited Collaboration:</strong> The traditional approach did not encourage collaboration between developers, testers, and other stakeholders, which made it difficult to identify and fix issues.</p>
</li>
<li><p><strong>High Cost:</strong> The manual nature of software development meant that it was expensive, with high costs associated with testing, debugging, and fixing errors.</p>
</li>
<li><p><strong>Limited Agility:</strong> Since the traditional approach was linear, it was not possible to make changes to the software quickly or respond to customer needs in real-time.</p>
</li>
</ol>
<p>CI/CD emerged as a solution to these disadvantages, by introducing a more agile and collaborative approach to software development. CI/CD enables teams to work together, integrating their code changes frequently, and automating the testing and deployment process.</p>
<h1 id="heading-how-cicd-works">How CI/CD Works</h1>
<p>CI/CD is an automated process that involves frequent code integration, automated testing, and continuous deployment of software changes to production.</p>
<p>Let's explain each step in a little more detail:</p>
<h3 id="heading-code-integration">Code Integration</h3>
<p>The first step in the CI/CD pipeline is code integration. In this step, developers commit their code changes to a remote repository (like <a target="_blank" href="https://github.com/">GitHub</a>, <a target="_blank" href="https://about.gitlab.com/">GitLab</a> or <a target="_blank" href="https://bitbucket.org/product/">BitBucket</a>), where the code is integrated with the main codebase.</p>
<p>This step aims to ensure that the code changes are compatible with the rest of the codebase and do not break the build.</p>
<h3 id="heading-automated-testing">Automated Testing</h3>
<p>Once the code is integrated, the next step is automated testing. Automated testing involves running a suite of tests to ensure that the code changes are functional, meet the expected quality standards, and are free of defects.</p>
<p>This step helps identify issues early in the development process, allowing developers to fix them quickly and efficiently.</p>
<p>If you're not familiar with the topic of testing, you can refer <a target="_blank" href="https://www.freecodecamp.org/news/test-a-react-app-with-jest-testing-library-and-cypress/">to this article I wrote a while ago</a>.</p>
<h3 id="heading-continuous-deployment">Continuous Deployment</h3>
<p>After the code changes pass the automated testing step, the next step is continuous deployment. In this step, the code changes are automatically deployed to a staging environment for further testing.</p>
<p>This step aims to ensure that the software is continuously updated with the latest code changes, delivering new features and functionality to users quickly and efficiently.</p>
<h3 id="heading-production-deployment">Production Deployment</h3>
<p>The final step in the CI/CD pipeline is production deployment. In this step, the software changes are released to end-users. This step involves monitoring the production environment, ensuring that the software is running smoothly, and identifying and fixing any issues that arise.</p>
<p>The four steps of a CI/CD pipeline work together to ensure that software changes are tested, integrated, and deployed to production automatically. This automation helps to reduce errors, increase efficiency, and improve the overall quality of the software.</p>
<p>By adopting a CI/CD pipeline, development teams can achieve faster release cycles, reduce the risk of software defects, and improve the user experience.</p>
<p>Keep in mind that the pipeline stages might look different given the specific project or company we're talking about. Meaning, some teams might or might not use automated testing, some teams might or might not have a "staging" environment, and so on.</p>
<p>The key parts that make up the CI/CD practice are integration and deployment. This means that the code has to be continually integrated in a remote repository, and that this code has to be continually deployed to a given environment after each integration.</p>
<h1 id="heading-the-key-benefits-of-cicd">The Key Benefits of CI/CD</h1>
<p>The key benefits of CI/CD include:</p>
<ol>
<li><p><strong>Faster Release Cycles:</strong> By automating the testing and deployment process, CI/CD enables teams to release software more frequently, responding quickly to customer needs.</p>
</li>
<li><p><strong>Improved Quality:</strong> Automated testing ensures that software changes do not introduce new bugs or issues, improving the overall quality of the software.</p>
</li>
<li><p><strong>Increased Collaboration:</strong> Frequent code integration and testing require developers to work closely together, leading to better collaboration and communication.</p>
</li>
<li><p><strong>Reduced Risk:</strong> Continuous deployment allows developers to identify and fix issues quickly, reducing the risk of major failures and downtime.</p>
</li>
<li><p><strong>Cost-Effective:</strong> CI/CD reduces the amount of manual work required to deploy software changes, saving time and reducing costs.</p>
</li>
</ol>
<p>In summary, CI/CD emerged as a solution to the limitations of the traditional, linear approach to software development. By introducing a more agile and collaborative approach to software development, CI/CD enables teams to work together, release software more frequently, and respond quickly to customer needs.</p>
<h1 id="heading-tools-for-cicd">Tools for CI/CD</h1>
<p>There are several tools available for implementing CI/CD pipelines in software development. Each tool has its unique features, pros, and cons. Here are some of the most commonly used tools in CI/CD pipelines today:</p>
<h3 id="heading-jenkins">Jenkins</h3>
<p><a target="_blank" href="https://www.jenkins.io/">Jenkins</a> is an open-source automation server that is widely used in CI/CD pipelines. It is highly customizable and supports a wide range of plugins, making it suitable for various development environments. Some of its key features include:</p>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Highly customizable with a wide range of plugins</p>
</li>
<li><p>Supports integration with various tools and technologies</p>
</li>
<li><p>Provides detailed reporting and analytics</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Requires some technical expertise to set up and maintain</p>
</li>
<li><p>Can be resource-intensive, especially for large projects</p>
</li>
<li><p>Lack of a centralized dashboard for managing multiple projects</p>
</li>
</ul>
<p>If you want to learn more about Jenkins, <a target="_blank" href="https://www.freecodecamp.org/news/learn-jenkins-by-building-a-ci-cd-pipeline/">here's a full course for you</a>.</p>
<h3 id="heading-travis-ci">Travis CI</h3>
<p><a target="_blank" href="https://www.travis-ci.com/">Travis CI</a> is a cloud-based CI/CD platform that provides automated testing and deployment for software projects. It supports several programming languages and frameworks, making it suitable for various development environments. Some of its key features include:</p>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Easy to set up and use</p>
</li>
<li><p>Cloud-based, so there's no need to set up and maintain infrastructure</p>
</li>
<li><p>Supports a wide range of programming languages and frameworks</p>
</li>
<li><p>Provides detailed reporting and analytics</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Limited customization options</p>
</li>
<li><p>Not suitable for large projects with complex requirements</p>
</li>
<li><p>Limited support for on-premise installations</p>
</li>
</ul>
<p>Here's a helpful tutorial about <a target="_blank" href="https://www.freecodecamp.org/news/learn-how-to-automate-deployment-on-github-pages-with-travis-ci/">how to automate deployment on GitHub Pages with Travis CI</a>.</p>
<h3 id="heading-github-actions">GitHub actions</h3>
<p><a target="_blank" href="https://github.com/features/actions">GitHub Actions</a> is a powerful CI/CD tool that allows developers to automate workflows, run tests, and deploy code directly from their GitHub repositories.</p>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Integrated with GitHub</p>
</li>
<li><p>Easy to use</p>
</li>
<li><p>Provides large ecosystem and good documentation</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Limited build minutes</p>
</li>
<li><p>Complex YAML syntax</p>
</li>
</ul>
<p>Side comment: I mention GitHub actions here because it's a popular tool – but keep in mind that other online repository providers like GitLab and BitBucket also provide very similar options to GitHub actions.</p>
<h3 id="heading-built-in-cicd-features-by-hosts">Built-in CI/CD features by hosts</h3>
<p>Popular hosts such as <a target="_blank" href="https://vercel.com/">Vercel</a> or <a target="_blank" href="https://www.netlify.com/">Netlify</a> have built-in in CI/CD features that allow you to link an online repository to a given site, and deploy to that site after a given event occurs in that repo.</p>
<p><strong>Pros:</strong></p>
<ul>
<li>Very simple to set up and use</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>Limited customization options</li>
</ul>
<p>Each of these tools has its unique features, pros, and cons. The choice of tool will depend on the specific requirements of your project, your team's technical expertise, and your budget.</p>
<p>Here's a tutorial about <a target="_blank" href="https://www.freecodecamp.org/news/how-to-deploy-your-front-end-app/">how to deploy a front-end app with Netlify</a>. And in this tutorial, you'll <a target="_blank" href="https://www.freecodecamp.org/news/how-to-build-a-jamstack-site-with-next-js-and-vercel-jamstack-handbook/">learn how to use Vercel to deploy a Next.js app</a>.</p>
<h1 id="heading-how-to-set-up-a-cicd-pipeline-with-github-actions">How to Set Up a CI/CD Pipeline with GitHub Actions</h1>
<p>Cool, so now that we have a clear idea of what CI/CD is, let's see how we can implement a simple example with an actual project using <a target="_blank" href="https://github.com/features/actions">GitHub actions</a>.</p>
<h2 id="heading-initializing-the-project">Initializing the Project</h2>
<p>We'll start with a very basic React app built with <a target="_blank" href="https://www.freecodecamp.org/news/how-to-build-a-react-app-different-ways/#what-is-vite">Vite</a>. You can do that by running <code>yarn create vite</code> in your console.</p>
<p>We'll focus on the CI/CD pipeline here, so there will be no complexity in the actual app code. But just to have an idea, the <code>app.jsx</code> component will have this code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'App'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Vite + Reactooooo<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>And then we'll have a test file that will check for that text to render:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { describe, expect, it } <span class="hljs-keyword">from</span> <span class="hljs-string">'vitest'</span>;
<span class="hljs-keyword">import</span> { render, screen } <span class="hljs-keyword">from</span> <span class="hljs-string">'./utils/test-utils/test-utils.jsx'</span>;

<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'src/App.jsx'</span>;

describe(<span class="hljs-string">'App'</span>, <span class="hljs-keyword">async</span> () =&gt; {
    it(<span class="hljs-string">'should render while authenticating'</span>, <span class="hljs-function">() =&gt;</span> {
        render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);

        expect(screen.getByText(<span class="hljs-string">'Vite + Reactooooo'</span>)).toBeInTheDocument();
    });
});
</code></pre>
<p>This test will run each time we run the <code>yarn test</code> command.</p>
<p>Next step should be to push our code to a GitHub repo. Then, let's talk a bit more about what GitHub actions are and how they work.</p>
<h2 id="heading-what-are-github-actions-and-how-do-they-work">What are GitHub Actions and How Do They Work?</h2>
<p>GitHub Actions is a CI/CD (Continuous Integration/Continuous Deployment) service provided by GitHub. It allows developers to automate workflows by defining custom scripts, known as "actions", that can be triggered by events such as pushes to a repository, pull requests, or issues.</p>
<p>Actions are defined in a YAML file, also known as a "workflow", which specifies the steps required to complete a task. GitHub Actions workflows can run on Linux, Windows, and macOS environments and support a wide range of programming languages and frameworks.</p>
<p>When an event triggers a GitHub Actions workflow, the service creates a fresh environment, installs dependencies, and runs the defined steps in the order specified. This can include tasks such as building, testing, packaging, and deploying code.</p>
<p>GitHub Actions also provides several built-in actions that can be used to simplify common tasks, such as checking out code, building and testing applications, publishing releases, and deploying to popular cloud providers like AWS, Azure, and Google Cloud.</p>
<p>GitHub Actions workflows can be run on a schedule, manually, or automatically when a specific event occurs, such as a pull request being opened or a new commit being pushed to a branch.</p>
<h2 id="heading-setting-up-our-workflow">Setting Up Our Workflow</h2>
<p>Great, so as we've seen, basically GitHub actions are a feature that allows us to define workflows four our projects. These workflows are nothing but a series of tasks or steps that will execute on GitHub's cloud after a given event we declare.</p>
<p>The way GitHub reads and executes these workflows is by automatically reading files within the <code>.github/workflows</code> directory in the root of our project. These workflow files should have the <code>.yaml</code> extension and use the <a target="_blank" href="https://www.redhat.com/en/topics/automation/what-is-yaml">YAML</a> syntax.</p>
<p>To create a new workflow we just have to create a new YAML file within that directory. We'll call ours <code>prod.yaml</code> since we'll use it to deploy the production branch of our project.</p>
<p>Keep in mind a single project can have many different workflows that run different tasks on different occasions. For example, we could have a workflow for dev and staging branches as well, as those environments could require different tasks to execute and will probably deploy on different sites.</p>
<p>After creating this file, let's drop the following code in it:</p>
<pre><code class="lang-yaml"><span class="hljs-comment"># Name of our workflow</span>
<span class="hljs-attr">name:</span> <span class="hljs-string">Production</span> <span class="hljs-string">deploy</span>

<span class="hljs-comment"># Trigger the workflow on push to the main branch</span>
<span class="hljs-attr">on:</span>
  <span class="hljs-attr">push:</span>
    <span class="hljs-attr">branches:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">main</span>

<span class="hljs-comment"># List of jobs</span>
<span class="hljs-comment"># A "job" is a set of steps that are executed on the same runner</span>
<span class="hljs-attr">jobs:</span>
  <span class="hljs-comment"># Name of the job</span>
  <span class="hljs-attr">test-and-deploy-to-netlify:</span>
    <span class="hljs-comment"># Operating system to run on</span>
    <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>

    <span class="hljs-comment"># List of steps that make up the job</span>
    <span class="hljs-attr">steps:</span>
    <span class="hljs-comment"># Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Checkout</span> <span class="hljs-string">code</span>
      <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v2</span>

    <span class="hljs-comment"># Setup Node.js environment</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Use</span> <span class="hljs-string">Node.js</span> <span class="hljs-number">16.</span><span class="hljs-string">x</span>
      <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/setup-node@v2</span>
      <span class="hljs-attr">with:</span>
        <span class="hljs-attr">node-version:</span> <span class="hljs-string">'16.x'</span>

    <span class="hljs-comment"># Install dependencies</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">dependencies</span>
      <span class="hljs-attr">run:</span> <span class="hljs-string">yarn</span> <span class="hljs-string">install</span>

    <span class="hljs-comment"># Run tests</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Run</span> <span class="hljs-string">tests</span>
      <span class="hljs-attr">run:</span> <span class="hljs-string">yarn</span> <span class="hljs-string">test</span>

    <span class="hljs-comment"># Deploy to Netlify</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Netlify</span> <span class="hljs-string">Deploy</span>
      <span class="hljs-attr">uses:</span> <span class="hljs-string">jsmrcaga/action-netlify-deploy@v2.0.0</span>
      <span class="hljs-attr">with:</span>
        <span class="hljs-comment"># Auth token to use with netlify</span>
        <span class="hljs-attr">NETLIFY_AUTH_TOKEN:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.NETLIFY_AUTH_TOKEN</span> <span class="hljs-string">}}</span>
        <span class="hljs-comment"># Your Netlify site id</span>
        <span class="hljs-attr">NETLIFY_SITE_ID:</span>  <span class="hljs-string">${{</span> <span class="hljs-string">secrets.NETLIFY_SITE_ID</span> <span class="hljs-string">}}</span>
        <span class="hljs-comment"># Directory where built files are stored</span>
        <span class="hljs-attr">build_directory:</span> <span class="hljs-string">'./dist'</span>
        <span class="hljs-comment"># Command to install dependencies</span>
        <span class="hljs-attr">install_command:</span> <span class="hljs-string">yarn</span> <span class="hljs-string">install</span>
        <span class="hljs-comment"># Command to build static website</span>
        <span class="hljs-attr">build_command:</span> <span class="hljs-string">yarn</span> <span class="hljs-string">build</span>
</code></pre>
<p>So our workflow has the following tasks declared:</p>
<ol>
<li><p>"Checkout code" step that checks out the latest commit on the current branch.</p>
</li>
<li><p>"Use Node.js 16.x" step that sets up the Node.js environment to version 16.x.</p>
</li>
<li><p>"Install dependencies" step that installs the project dependencies using the Yarn package manager.</p>
</li>
<li><p>"Run tests" step that runs the project's tests using the Yarn package manager.</p>
</li>
<li><p>"Netlify Deploy" step that deploys the project to Netlify using the jsmrcaga/action-netlify-deploy action. This step uses the Netlify authentication token and site ID secrets stored in the GitHub repository's secrets. The build directory, install command, and build command are also specified.</p>
</li>
</ol>
<p>You probably noticed the first and last steps have the keyword <code>uses</code>. This keyword allows you to use actions or workflows developed by other GitHub users, and it's one of the best features of GitHub actions.</p>
<p>What's great is that by using this third party actions we can execute complex tasks such as deploying to an external host or building complex cloud infrastructure without the need to write every single line of necessary code.</p>
<p>As these tasks tend to be repetitive and frequently executed in many projects, we can just use a workflow developed by an official company account (such as Azure or AWS for example) or an independent open-source developer. Think about it as using a third party library. It's the same idea but taken to CI/CD workflows. Very convenient.</p>
<p>Another important thing to mention here is that in GitHub actions workflows tasks run <strong>sequentially</strong>, one after the other. And if a given task fails or throws and error, <strong>the next one won't execute</strong>. This is important because if we have a problem when installing our dependencies or a test fails, we don't want that code to be deployed.</p>
<p>Before we can push this code and see how the magic works, we first need to create a site on Netlify and get the <strong>NETLIFY_AUTH_TOKEN</strong> and <strong>NETLIFY_SITE_ID</strong>. This is quite straight forward even if you don't have previous experience with Netlify, so give it a try and Google a bit if you can't figure it out. ;)</p>
<p>Once you have these two tokens, you need to declare them as repository secrets in your GitHub repo. You can do this from the "settings" tab:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-32.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Configure both Netlify secret tokens in your repo</em></p>
<p>With this in place, now our <code>prod.yaml</code> file will be able to read these two tokens and execute the Netlify deploy action.</p>
<h2 id="heading-the-magic">The Magic</h2>
<p>Now that we have everything in place, let's push our code and see how it goes.</p>
<p>After pushing, if we go to the "actions" tabs of our repo, on the left we'll see a list of all the workflows we have in our repo. And on the right we'll see a list of each execution of the selected workflow. Since our workflow executes after each push, we should see a new execution each time we push.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A workflow execution</em></p>
<p>When the execution has a yellow light to the left of it, it means it's still running (executing tasks). If it has a green light it means it finished executing successfully and if the light is red, you know something went wrong, haha...</p>
<p>After clicking on the execution we can see a list of the workflow's jobs (we only had a single one).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The workflow's jobs</em></p>
<p>And after clicking on the job we can see a list of the job's tasks.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-35.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The tasks of the job</em></p>
<p>Each task is expansible and within it we can see logs corresponding to that task's execution. This is quite useful for debugging purposes. ;)</p>
<p>Now if we go to our previously set up Netlify site, we should see our app up and running!</p>
<p>And now that we have our CI/CD pipeline in place, we can deploy our app after each push to the main branch, all without lifting another finger. =D</p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>CI/CD is a software development approach that provides several benefits to software development teams, including faster time-to-market, improved quality, increased collaboration, reduced risk, and cost-effectiveness.</p>
<p>By automating the software delivery pipeline, teams can quickly deploy new features and bug fixes, while reducing the risk of major failures and downtime.</p>
<p>With the availability of several CI/CD tools, it has become easier for teams to implement this approach and improve their software delivery process.</p>
<p>Well everyone, as always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/giphy-1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Measure and Improve the Performance of a React App ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! React is a popular JavaScript library for building user interfaces. As applications built with React become more complex, their performance can start to degrade. Poor performance can lead to a frustrating user experience and a negative i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/measure-and-improve-performance-of-react-apps/</link>
                <guid isPermaLink="false">66d45f0f182810487e0ce19a</guid>
                
                    <category>
                        <![CDATA[ performance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web performance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 27 Mar 2023 17:18:19 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/nicolas-hoizey-poa-Ycw1W8U-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone!</p>
<p>React is a popular JavaScript library for building user interfaces. As applications built with React become more complex, their performance can start to degrade.</p>
<p>Poor performance can lead to a frustrating user experience and a negative impact on user engagement. So in this article, we will discuss how to measure and improve the performance of a React application.</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-define-performance">How to define performance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-measure-performance">How to measure performance</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-react-dev-tools">React dev tools</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-improve-performance">How to improve performance</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-optimizing-images">Optimizing images</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-code-splitting-and-lazy-loading">Code splitting and Lazy Loading</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-optimizing-the-dom">Optimizing the DOM</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-avoid-unnecessary-component-re-renders">Avoid unnecessary component re-renders</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rendering-patterns">Rendering patterns</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-content-delivery-network-cdn">CDNs</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h1 id="heading-how-to-define-performance">How to Define Performance</h1>
<p>In web development, "performance" generally refers to the speed and efficiency of a website or web application. It encompasses several different factors, including:</p>
<ol>
<li><p><strong>Page load time:</strong> This refers to the time it takes for a page to fully load and display all of its content. Faster load times generally lead to a better user experience.</p>
</li>
<li><p><strong>Responsiveness:</strong> This refers to the speed at which a website responds to user interactions, such as clicking a button or scrolling. A responsive website feels snappy and quick, which can also improve user experience.</p>
</li>
<li><p><strong>Resource usage:</strong> This refers to the amount of server resources (such as CPU and memory) that a website uses to serve pages and respond to requests. A well-optimized website will use resources efficiently, allowing the server to handle more traffic and reducing costs.</p>
</li>
<li><p><strong>Scalability:</strong> This refers to a website's ability to handle increased traffic and load without sacrificing performance. A scalable website can handle sudden spikes in traffic without slowing down or crashing.</p>
</li>
</ol>
<p>Optimizing website performance is important because it can directly impact user experience, search engine rankings, and even business revenue.</p>
<h1 id="heading-how-to-measure-performance">How to Measure Performance</h1>
<p>The first step in improving the performance of a React application is to measure its current performance. There are several tools available for measuring performance, including:</p>
<ol>
<li><p><strong>Lighthouse</strong> – <a target="_blank" href="https://chrome.google.com/webstore/detail/lighthouse/blipmdconlkpinefehnmjammfjpmpbjk?hl=es">Lighthouse</a> is an open-source tool from Google that audits web pages for performance, accessibility, and more. Lighthouse generates a report that includes suggestions for improving the performance of the application.</p>
</li>
<li><p><strong>WebPageTest</strong> – <a target="_blank" href="https://gercocca.vercel.app/">WebPageTest</a> is a free tool that allows you to test the speed of your website from multiple locations around the world. WebPageTest provides detailed reports on the performance of your website, including suggestions for improvement.</p>
</li>
<li><p><strong>Google PageSpeed Insights –</strong> <a target="_blank" href="https://pagespeed.web.dev/">Google PageSpeed Insights</a> analyzes the content of a web page and generates a report that identifies opportunities to improve the page's performance.</p>
</li>
</ol>
<p>All three tools work basically in the same way. You provide the URL of the site you'd like to analyze, and the tools will run through it and provide you with a detailed report covering improvement opportunities in performance, and also accessibility, SEO and general best practices.</p>
<p>These tools are nice to get an objective measure of our apps. Some of them can even be integrated into CI/CD pipelines so we can monitor how changes impact in performance through time.</p>
<h2 id="heading-react-dev-tools">React dev tools</h2>
<p>Another useful tool for measuring performance in a React app is the profiler of <a target="_blank" href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">React DevTools</a>. React DevTools is a browser extension that allows you to inspect and debug React applications in the Chrome, Firefox, or Edge browsers.</p>
<p>The "profiler" is a tool that allows you to record the activity in your app, and later on generate a report showing what components were rendered, how many times and when each component was rendered, and how long each render took.</p>
<p>It's quite useful for detecting unnecessary component re-renders and renders that take too long, generating performance bottlenecks.</p>
<p>If you'd like to get a deeper dive into how profiler works, I recommend <a target="_blank" href="https://www.youtube.com/watch?v=00RoZflFE34&amp;t=452s">this video</a>.</p>
<h1 id="heading-how-to-improve-performance">How to Improve Performance</h1>
<p>Now that we have an idea of how can we identify performance issues in our app, let's go through some of the optimization techniques we can use to make it better.</p>
<h2 id="heading-optimizing-images">Optimizing Images</h2>
<p>Images are one of the primary culprits for slow loading websites. You can optimize images by compressing them without compromising their quality. Tools like <a target="_blank" href="https://tinypng.com/">tinyPng</a> can compress your images and help you reduce the size of your website, and therefore it's load time.</p>
<p>Meta frameworks such as Next come with built-in image optimization.</p>
<h2 id="heading-code-splitting-and-lazy-loading">Code splitting and Lazy Loading</h2>
<p>Lazy loading involves loading content only when it is needed, instead of loading everything at once. This is done through something called <strong>"code splitting"</strong>. This is a bundling technique that allows you to break up code in smaller chunks that are downloaded only when needed, instead of downloading the whole code in the first render.</p>
<p>A classic example of when this technique can come in handy is when navigating through different routes. Let's say our website has two main routes, "Home" and "Contact".</p>
<p>We'd only want to download the code related to the "Home" page when we're in that route, and the "Contact" code to download when we are in that other route. Code splitting allows us to do that, and in this way help reduce the initial load time of the application and improve the user experience.</p>
<p>You can use tools such as <strong>React.lazy()</strong> and <strong>Suspense</strong> to implement lazy loading in your application. If you'd like a deeper dive into how these tools work, <a target="_blank" href="https://www.youtube.com/watch?v=JU6sl_yyZqs">check out this video</a>.</p>
<h2 id="heading-optimizing-the-dom">Optimizing the DOM</h2>
<p>The size of the Document Object Model (DOM) can impact the performance of the application. The bigger and more complex it is, the longer it'll take to load and be modified.</p>
<p>You can optimize the DOM by reducing the number of elements, removing unnecessary elements, and minimizing the use of CSS animations.</p>
<h3 id="heading-avoid-unnecessary-component-re-renders">Avoid unnecessary component re-renders</h3>
<p>As you may know, React is a library that allows us to build user interfaces. In React, each piece of the UI is represented in code by a component. When a piece of the UI needs to be modified, React re-renders the component with the updated information.</p>
<p>There are two things that trigger a component re-render: A change in state or a change in props. But sometimes, components can re-render unnecessarily, meaning there's no actual change in the information to be displayed.</p>
<p>To prevent unnecessary re-renders, we can implement some of the following techniques:</p>
<ul>
<li><p><strong>Memoization:</strong> In React, memoization allows a component to "remember" the value of the state and/or props it receives. Before re-rendering, it can check if the value has actually changed. If it hasn't, then it doesn't re-render. This technique can be achieved through hooks like <code>useMemo</code> and <code>useCallback</code>. If you'd like a deeper dive on that, <a target="_blank" href="https://www.freecodecamp.org/news/memoization-in-javascript-and-react/">check out this article I wrote</a>.</p>
</li>
<li><p><strong>Use key prop for lists:</strong> When rendering a list of items in React, it's important to provide a unique key prop for each item. This helps React identify which items have changed and need to be re-rendered. If you don't provide a key prop, React will use the index of the item in the array, which can lead to unnecessary re-renders if the order of the items changes.</p>
</li>
<li><p><strong>Keeping state as local as possible:</strong> By keeping state local, I mean that the state that a component uses should be (when possible) within the component itself or as close in the component tree as possible. This is because when a component re-renders, all children components will re-render as well. It's not necessarily a terrible thing, but if we can avoid it, we probably should. So It's not a good idea to centralize all state in a single parent component, unless that states needs to be used from multiple parts of the application down the component tree. Here's <a target="_blank" href="https://kentcdodds.com/blog/state-colocation-will-make-your-react-app-faster">a great article about this topic</a> if you're interested in learning more.</p>
</li>
</ul>
<h2 id="heading-rendering-patterns">Rendering patterns</h2>
<p>Another thing that can have an impact on the performance of your app is the rendering pattern it uses. A rendering pattern refers to the way in which the HTML, CSS, and JavaScript code is all processed and rendered in a web application or website.</p>
<p>Different rendering patterns are used to achieve different performance and user experience goals. The most common rendering patterns in web development are:</p>
<ol>
<li><p><strong>Client-side rendering (CSR)</strong>: In CSR, the client's browser generates the HTML content of a web page on the client-side using JavaScript. This approach can provide a fast and interactive user experience but can be slower for initial loading times and bad for SEO.</p>
</li>
<li><p><strong>Server-side rendering (SSR)</strong>: In SSR, the web server generates the HTML content of a web page on the server-side and sends it to the client's browser. This approach can improve initial loading times and SEO (search engine optimization) but can be slower for dynamic content.</p>
</li>
</ol>
<p>Server-Side Rendering (SSR) can help improve the initial load time of the application by rendering the initial page on the server-side. This can help improve the Time-to-Interactive (TTI) and First Contentful Paint (FCP) metrics. You can use tools such as Next.js or Gatsby to implement SSR in your application.</p>
<p>The choice of rendering pattern depends on the specific needs and requirements of a project, such as performance, SEO, user experience, and flexibility. If your priority is to provide users with a fluid, native-like experience, CSR is probably a good choice. If you need ultra fast page load times, SSR or SSG can be a better option.</p>
<p>For a deeper dive into rendering patterns, check out <a target="_blank" href="https://www.freecodecamp.org/news/rendering-patterns/">this article I recently wrote</a>.</p>
<h2 id="heading-content-delivery-network-cdn">Content Delivery Network (CDN)</h2>
<p>A CDN, or Content Delivery Network, is a system of distributed servers or nodes that work together to deliver web content, such as images, videos, and other files, to users based on their geographic location.</p>
<p>When a user requests content from a website, the CDN will serve the content from the server closest to the user, which helps to reduce latency and improve website performance. CDNs can also help to reduce the load on a website's origin server by caching frequently accessed content and delivering it from the CDN's servers instead of the origin server.</p>
<p>CDNs are normally used to host static content (meaning content that doesn't change frequently over time), such as images, videos, blog posts and so on. Also, if you're using Static Site Generation (SSG) as a rendering pattern, you could host your rendered sites in a CDN for an even faster delivery.</p>
<p>Some examples of popular CDNs are Cloudflare and Amazon CloudFront.</p>
<p>For more detail on how CDNs work, check out <a target="_blank" href="https://www.youtube.com/watch?v=RI9np1LWzqw">this awesome video</a>.</p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>Well everyine, in this article we've discussed how to measure and improve the performance of a React application.</p>
<p>We defined the concept of website performance, including page load time, responsiveness, resource usage, and scalability, and outlined how to measure performance using tools such as Lighthouse, WebPageTest, Google PageSpeed Insights and React dev tools.</p>
<p>Finally, we've seen some optimization techniques such as optimizing images, code splitting and lazy loading, optimizing the DOM, and avoiding unnecessary component re-renders.</p>
<p>As always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/AbsoluteAnnualKoi-size_restricted.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a React App – A Walkthrough of the Many Different Ways ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article we're going to take a look at some of the many ways you can build a React application these days. We'll compare their main characteristics, along with their pros and cons. We'll start by explaining what React is and what ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-react-app-different-ways/</link>
                <guid isPermaLink="false">66d45effd1ffc3d3eb89dde7</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 13 Mar 2023 19:01:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/randy-fath-ymf4_9Y9S_A-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article we're going to take a look at some of the many ways you can build a React application these days. We'll compare their main characteristics, along with their pros and cons.</p>
<p>We'll start by explaining what React is and what improvements it brought over the previous era of web development. Then we're going to build a React app from scratch to get a good idea of the libraries that conform React, and how it interacts with dependencies such as bundlers (like Webpack) and compilers (like Babel).</p>
<p>Finally, we're going to review more realistic approaches like CRA (create-react-app) and modern alternatives like Vite, Astro, Gatsby, Next and Remix.</p>
<p>This should be a longish but interesting article to read if you're wondering how React works under the hood, or if you want to know more about the differences between the many building tools available.</p>
<p>Let's hop on to it!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-react-and-what-does-it-do">What is React and what does it do?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-web-development-before-react">Web development before React</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-benefits-of-react">The benefits of React</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-react-works-under-the-hood">How React works under the hood</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-a-react-app">How to build a React app</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-build-a-react-app-from-scratch-using-webpack-and-babel">Build a React app from scratch using Webpack and Babel</a></p>
</li>
<li><p><a class="post-section-overview" href="#what-is-cra-create-react-app">What is CRA (create-react-app)?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-vite">What is Vite?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-client-side-rendering-csr-vs-server-side-rendering-ssr">Client side rendering (CSR) vs Server side rendering (SSR)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ssr-building-tools">SSR building tools</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-astro">What is Astro?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-gatsby">What is Gatsby?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-reacts-metaframeworks">React's metaframeworks</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-nextjs">What is Next?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-remix">What is Remix?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></p>
</li>
</ul>
<h1 id="heading-what-is-react-and-what-does-it-do">What is React and What Does it Do?</h1>
<p>React.js is a popular open-source JavaScript library for building user interfaces (UIs) that was developed by Facebook. It enables developers to create reusable UI components and declaratively specify how the UI should look and behave based on changes in the application state.</p>
<p>If you wonder what "declaratively" means, you might be interested in <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-programming-paradigms/">this article about programming paradigms</a> I wrote a while ago.</p>
<p>React follows a component-based architecture, where each UI element is represented as a separate component that can be reused throughout the application. React allows developers to create these components using a combination of HTML-like syntax called JSX and JavaScript code.</p>
<p>React uses a virtual DOM (Document Object Model) to efficiently update the actual DOM when the application state changes. This means that instead of updating the entire page every time a change occurs, React updates only the specific components that need to be changed. This makes React applications faster and more responsive compared to traditional JavaScript frameworks.</p>
<p>You can use React to build single-page applications, mobile applications, and even desktop applications using tools such as Electron. You can also combine it with other libraries and frameworks to build more complex applications.</p>
<p>React has a large and active community, with a wealth of resources and third-party libraries available to help developers get started quickly.</p>
<p>This all sounds pretty good, but it's tough to understand the value of a tool like React if you don't know how web development used to be before it. So let's take a quick look at that now.</p>
<h2 id="heading-web-development-before-react">Web Development Before React</h2>
<p>Before React.js, web development was heavily reliant on traditional client-side scripting using vanilla JavaScript and libraries like jQuery.</p>
<p>Web developers used to build web applications by directly manipulating the Document Object Model (DOM) of web pages using JavaScript. This approach was often time-consuming and error-prone, especially for complex applications.</p>
<p><a target="_blank" href="https://jquery.com/">jQuery</a>, a popular JavaScript library, was introduced as a way to simplify the process of manipulating the DOM and handling browser events. It provided a concise and easy-to-use syntax for selecting and manipulating HTML elements on a page.</p>
<p>jQuery was widely adopted by web developers due to its simplicity, and it helped to improve the efficiency of client-side scripting.</p>
<p>Other JavaScript frameworks such as <a target="_blank" href="https://angularjs.org/">AngularJS</a> and <a target="_blank" href="https://backbonejs.org/">Backbone.js</a> also gained popularity in the early 2010s.</p>
<p>AngularJS provided a more structured approach to building web applications and was heavily focused on <a target="_blank" href="https://www.youtube.com/watch?v=OoLI8nb-VH8">data binding</a> and <a target="_blank" href="https://www.youtube.com/watch?v=yunF2PgJlHU">dependency injection</a>. Backbone.js was a lightweight framework that allowed developers to create simple web applications with minimal overhead.</p>
<p>But despite their popularity, these JavaScript frameworks had various limitations. For example, they did not provide an efficient way of managing the state of web applications, which could lead to performance issues and slow page load times. They also did not provide an easy way to create reusable components, which could make it challenging to build complex web applications.</p>
<p>React.js addressed many of these limitations by introducing a new way of thinking about building web applications.</p>
<p>React.js allowed developers to create reusable UI components that could be composed together to build complex interfaces. It also introduced the concept of a virtual DOM, which improved the performance of web applications by minimizing the number of updates required to the actual DOM.</p>
<p>Overall, while vanilla JavaScript and libraries like jQuery were essential in the early days of web development, they were limited in their ability to handle complex applications. The emergence of frameworks like React.js has made it easier for developers to build scalable and efficient web applications.</p>
<h2 id="heading-the-benefits-of-react">The Benefits of React</h2>
<p>React.js brought several improvements over traditional client-side scripting using vanilla JavaScript and libraries like jQuery, as well as over other JavaScript frameworks like Backbone.js, AngularJS, and <a target="_blank" href="https://knockoutjs.com/">Knockout.js</a>. Some of these improvements include:</p>
<ol>
<li><p><strong>Component-Based Architecture:</strong> React.js introduced the concept of a component-based architecture, where UI elements are represented as separate reusable components that can be composed together to create complex interfaces. This approach makes it easier to manage complex web applications, improves code reusability, and allows for more efficient testing and debugging.</p>
</li>
<li><p><strong>Virtual DOM:</strong> React.js introduced the concept of a virtual DOM, which is a lightweight representation of the actual DOM. The virtual DOM makes it possible to update the user interface without re-rendering the entire page. This results in faster page load times and improved performance, especially for complex applications.</p>
</li>
<li><p><strong>JSX:</strong> React.js introduced JSX, a syntax extension that allows developers to write HTML-like code in JavaScript files. This makes it easier to write and maintain code, especially for developers who are more familiar with HTML than with JavaScript.</p>
</li>
<li><p><strong>A different way to separate concerns:</strong> In previous paradigms, we used to have HTML, CSS and JavaScript divided into different files. Under React's paradigm, using JSX we can have HTML, JS, and (optionally) CSS in the same file, and divide our files according to the UI components they're responsible for.</p>
</li>
<li><p><strong>Data Binding:</strong> React.js introduced a unidirectional data flow, which means that data flows in a single direction from parent components to child components. This approach simplifies data management and reduces the risk of data inconsistencies or bugs.</p>
</li>
<li><p><strong>Scalability:</strong> React.js is highly scalable and can be used to build applications of any size. It is particularly well-suited for building large-scale applications that require complex interfaces and frequent updates.</p>
</li>
<li><p><strong>Community Support:</strong> React.js has a large and active community that provides extensive documentation, third-party libraries, and tutorials. This makes it easy for developers to get started with React.js and to find solutions to common problems.</p>
</li>
</ol>
<p>Overall, React.js brought several significant improvements over traditional client-side scripting using vanilla JavaScript and libraries like jQuery, as well as over other JavaScript frameworks like Backbone.js, AngularJS, and Knockout.js. These improvements have made it easier for developers to build scalable, efficient, and maintainable web applications.</p>
<p>If you want to dig deeper into this transition that happened between previous tools and frameworks like React, I recommend <a target="_blank" href="https://youtu.be/Wm_xI7KntDs">this video by uidotdev</a>.</p>
<h2 id="heading-how-react-works-under-the-hood">How React Works Under the Hood</h2>
<p>React is a JavaScript library that works by creating a virtual representation of the user interface, called the Virtual DOM. This virtual representation is a lightweight copy of the actual DOM, and it allows React to efficiently manage and update the user interface.</p>
<p>When a React component is created, React generates a corresponding Virtual DOM tree that represents the component's current state. The Virtual DOM tree is essentially a JavaScript object that describes the structure of the user interface, including all of the HTML elements, their attributes, and their children.</p>
<p>When the state of a React component changes, React updates the corresponding Virtual DOM tree to reflect the new state. The updated Virtual DOM tree is then compared with the previous Virtual DOM tree to identify the differences between the two.</p>
<p>React then generates a list of minimal updates that need to be made to the actual DOM to bring it in sync with the new Virtual DOM tree. These updates are then applied to the actual DOM, resulting in an updated user interface.</p>
<p>One of the key benefits of this approach is that it allows React to update the user interface efficiently, without having to redraw the entire page. This can result in significant performance improvements, especially for complex applications with many components and frequent updates.</p>
<p>Another benefit of using a Virtual DOM is that it makes it easier to build reusable components. By abstracting away the details of the actual DOM, React components can be more easily composed together to build complex interfaces.</p>
<p>Overall, React's Virtual DOM approach allows for efficient and scalable user interface development, and it has played a significant role in the popularity of React as a front-end development framework.</p>
<h1 id="heading-how-to-build-a-react-app">How to Build a React App</h1>
<p>Cool, so now that we have a clear idea of what React is and the improvements it brings to web development, let's actually start building applications!</p>
<h2 id="heading-build-a-react-app-from-scratch-using-webpack-and-babel">Build a React App from Scratch using Webpack and Babel</h2>
<p>We're going to see many different options available, but first we're going to build one from scratch. This means we're going to manually install and configure all the dependencies React needs to actually work.</p>
<p>Keep in mind this is a rare approach to use at the moment, since most apps are created through scripts that quickly take care of all this boilerplate. But the idea here is to see and understand the different components that interact to make React work under the hood.</p>
<p>To build a React app we'll need to install the 4 following dependencies:</p>
<p><strong>Webpack:</strong> <a target="_blank" href="https://webpack.js.org/">Webpack</a> is a popular open-source module bundler for JavaScript applications. It takes multiple JavaScript files and their dependencies and packages them into a single optimized bundle for use in a web browser. It also has the capability to transform and bundle other types of assets such as CSS, images, and fonts.</p>
<p>Keep in mind that Webpack is just an option between many other available bundlers. We're going to use it because it's quite a standard option.</p>
<p>If you're interested in knowing more about JS modules and how to bundle them with Webpack, you can take a look at <a target="_blank" href="https://www.freecodecamp.org/news/modules-in-javascript/">this article I wrote</a>.</p>
<p><strong>Babel:</strong> <a target="_blank" href="https://babeljs.io/">Babel</a> is a popular open-source JavaScript compiler that allows developers to write code in the latest versions of JavaScript and translate it into code that can run on older browsers and environments. It supports the latest ECMAScript features and can also transpile other languages that compile to JavaScript, such as TypeScript and JSX.</p>
<p>Keep in mind Babel is just an option between many other available transpilers. We're going to use it because it's quite a standard option.</p>
<p><strong>React:</strong> React is a JavaScript library for building user interfaces. It's focused on providing a declarative and efficient way to build complex UIs by breaking them into smaller, reusable components.</p>
<p><strong>react-dom:</strong> React-DOM is a package that provides DOM-specific methods that React uses to interact with the browser's DOM (Document Object Model), such as rendering React components to the DOM, updating components, and handling user events.</p>
<p>So we have <code>react</code> and <code>react-dom</code> that provide the core functionalities of React, a bundler to unify all the different files into a few, and a transpiler to make our code compatible in most browsers. That's it. So now let's hop on to the code!</p>
<ol>
<li>Start a node project by running this command in your terminal:</li>
</ol>
<pre><code class="lang-plaintext">npm init -y
</code></pre>
<ol start="2">
<li>Install the following dependencies:</li>
</ol>
<pre><code class="lang-plaintext">npm i webpack babel-loader @babel/preset-react @babel/core babel-preset-react html-webpack-plugin webpack-dev-server css-loader style-loader @babel/plugin-proposal-class-properties webpack-cli -D &amp;&amp; npm i react react-dom -S
</code></pre>
<p>Here we're installing the 4 dependencies we previously mentioned and some extra plugins and stuff that help Webpack and Babel work.</p>
<p>Since we're doing this for theoretical foundation, we won't get too deep into these things. Just keep in mind the core dependencies are React's libraries, a bundler, and a transpiler (plus some other minor stuff).</p>
<p>If you're interested in a more detailed approach, you can take a look at <a target="_blank" href="https://medium.com/@JedaiSaboteur/creating-a-react-app-from-scratch-f3c693b84658">this article</a>.</p>
<ol start="3">
<li>Now create an SRC folder and two <code>index.js</code> and <code>index.html</code> files within it by running the next two commands:</li>
</ol>
<pre><code class="lang-plaintext">mkdir src &amp;&amp; cd src &amp;&amp; touch index.js
touch index.html
</code></pre>
<ol start="4">
<li>Hop onto the <code>index.html</code> file and put this within it:</li>
</ol>
<pre><code class="lang-plaintext">&lt;!doctype html&gt;
&lt;html lang=”en”&gt;
&lt;head&gt;
 &lt;meta charset=”utf-8"&gt;
 &lt;title&gt;My React App from Scratch&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
 &lt;div id=”app”&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>This is the single HTML file that will be present in our project. When we finally build it, this is the file that will be sent to the client. Initially it will be just like we coded it (almost empty), and then React will do its magic and render all the content through JavaScript.</p>
<ol start="5">
<li>Hop onto the <code>index.js</code> file and put this within it:</li>
</ol>
<pre><code class="lang-plaintext">import ReactDOM from ‘react-dom’;
import React from ‘react’;
const App = () =&gt; {
 return &lt;h1&gt;This is my React app!&lt;/h1&gt;;
 }
ReactDOM.render(&lt;App /&gt;, document.getElementById(‘app’));
</code></pre>
<p>Here we're creating a dummy component called <code>App</code> and telling <code>react-dom</code> to render it in the HTML element that has <code>app</code> as its id. See we just coded that element as a div in the previous step. ;)</p>
<ol start="6">
<li>Now we need to add some config files for Babel and Webpack. In your root directory run the following:</li>
</ol>
<pre><code class="lang-plaintext">touch .babelrc &amp;&amp; touch webpack.config.js
</code></pre>
<ol start="7">
<li>Inside your <code>webpack.config.js</code> file put the following:</li>
</ol>
<pre><code class="lang-plaintext">const HtmlWebPackPlugin = require(“html-webpack-plugin”);
const htmlPlugin = new HtmlWebPackPlugin({
 template: “./src/index.html”,
 filename: “./index.html”
});
module.exports = {
mode: ‘development’,
  module: {
    rules: [{
   test: /\.js$/,
   exclude: /node_modules/,
   use: {
     loader: “babel-loader”
   }
 },
  {
   test: /\.css$/,
   use: [“style-loader”, “css-loader”]
  }
]},
 plugins: [htmlPlugin]
};
</code></pre>
<ol start="6">
<li>Inside your <code>.babelrc</code> file put the following:</li>
</ol>
<pre><code class="lang-plaintext">{
 “presets”: [“@babel/preset-react”],
 “plugins”: [“@babel/plugin-proposal-class-properties”]
}
</code></pre>
<ol start="7">
<li>Finally, go to your <code>package.json</code> file and add the following within the <code>scripts</code> section:</li>
</ol>
<pre><code class="lang-plaintext">"start": "webpack serve --config webpack.config.js"
</code></pre>
<p>At the end of all this, your file structure should look like this:</p>
<pre><code class="lang-plaintext">my-app-from-scratch/
┣ node_modules/
┣ src/
 ┣ index.html
 ┗ index.js
┣ .babelrc
┣ package-lock.json
┣ package.json
┗ webpack.config.js
</code></pre>
<p>And your <code>package.json</code> file should have this within it:</p>
<pre><code class="lang-plaintext">{
 “name”: “my-app-from-scratch “,
 “version”: “1.0.0”,
 “description”: “”,
 “main”: “webpack.config.js”,
 “scripts”: {
   “test”: “echo \”Error: no test specified\” &amp;&amp; exit 1",
   "start": "webpack serve --config webpack.config.js"
},
 “keywords”: [],
 “author”: “”,
 “license”: “ISC”,
 “devDependencies”: {
 “@babel/preset-react”: “⁷.12.13”,
 “babel-core”: “⁶.26.3”,
 “babel-loader”: “⁸.2.2”,
 “babel-preset-react”: “⁶.24.1”,
 “css-loader”: “⁵.0.2”,
 “html-webpack-plugin”: “⁵.1.0”,
 “style-loader”: “².0.0”,
 “webpack”: “⁵.22.0”,
 “webpack-cli”: “⁴.5.0”,
 “webpack-dev-server”: “³.11.2”
 },
 “dependencies”: {
 “react”: “¹⁷.0.1”,
 “react-dom”: “¹⁷.0.1”
 }
}
</code></pre>
<p>Now if you run <code>npm run start</code> you should see your app coming alive! =D</p>
<h2 id="heading-what-is-cra-create-react-app">What is CRA (create-react-app)?</h2>
<p>As we've seen, setting up a React app from scratch is not THAT complicated. But it can be a pain in the butt to do all this every time you want to start a new project. Also, if you want some particular config for your bundler and transpilers, it can get tricky if you don't know your way around those tools.</p>
<p>And because of this problem, we got tools like Create-react-app (CRA). ;)</p>
<p><a target="_blank" href="https://create-react-app.dev/">Create-React-App (CRA)</a> is a popular and officially supported tool for creating React applications quickly and easily. It is a command-line interface (CLI) tool that automates the setup of a new React project by generating a basic file structure, configuration files, and build scripts.</p>
<p>CRA provides a streamlined development experience by setting up a preconfigured development server, live-reloading, and automatic build optimization for production. It also comes with a built-in tool for running tests and generating code coverage reports.</p>
<p>Using CRA, developers can create a new React application with a single command, without having to manually set up configuration files or install and configure build tools. This allows developers to focus on writing code and building their application, rather than spending time on setup and configuration.</p>
<p>CRA also provides a set of default project configurations, such as Webpack and Babel, which are optimized for creating React applications. This means that developers can get started quickly with a project that is optimized for performance, maintainability, and scalability.</p>
<p>Overall, Create-React-App is a powerful tool that simplifies the process of setting up and configuring a new React project.</p>
<h3 id="heading-how-to-build-an-app-with-create-react-app">How to build an app with create-react-app</h3>
<p>Starting a React app with CRA is dead easy. We just run <code>npx create-react-app &lt;appName&gt;</code> and on its own it will set up all the boilerplate for us.</p>
<p>After it runs, your folder structure should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And your <code>package.json</code> should contain the following:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"testapp"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"0.1.0"</span>,
  <span class="hljs-string">"private"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"@testing-library/jest-dom"</span>: <span class="hljs-string">"^5.16.5"</span>,
    <span class="hljs-string">"@testing-library/react"</span>: <span class="hljs-string">"^13.4.0"</span>,
    <span class="hljs-string">"@testing-library/user-event"</span>: <span class="hljs-string">"^13.5.0"</span>,
    <span class="hljs-string">"react"</span>: <span class="hljs-string">"^18.2.0"</span>,
    <span class="hljs-string">"react-dom"</span>: <span class="hljs-string">"^18.2.0"</span>,
    <span class="hljs-string">"react-scripts"</span>: <span class="hljs-string">"5.0.1"</span>,
    <span class="hljs-string">"web-vitals"</span>: <span class="hljs-string">"^2.1.4"</span>
  },
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"start"</span>: <span class="hljs-string">"react-scripts start"</span>,
    <span class="hljs-string">"build"</span>: <span class="hljs-string">"react-scripts build"</span>,
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"react-scripts test"</span>,
    <span class="hljs-string">"eject"</span>: <span class="hljs-string">"react-scripts eject"</span>
  },
  <span class="hljs-string">"eslintConfig"</span>: {
    <span class="hljs-string">"extends"</span>: [
      <span class="hljs-string">"react-app"</span>,
      <span class="hljs-string">"react-app/jest"</span>
    ]
  },
  <span class="hljs-string">"browserslist"</span>: {
    <span class="hljs-string">"production"</span>: [
      <span class="hljs-string">"&gt;0.2%"</span>,
      <span class="hljs-string">"not dead"</span>,
      <span class="hljs-string">"not op_mini all"</span>
    ],
    <span class="hljs-string">"development"</span>: [
      <span class="hljs-string">"last 1 chrome version"</span>,
      <span class="hljs-string">"last 1 firefox version"</span>,
      <span class="hljs-string">"last 1 safari version"</span>
    ]
  }
}
</code></pre>
<p>You might be wondering, well where are the Webpack and Babel things, right? Well, since CRA takes care of this stuff under the hood, they are initially hidden. If we want to see this hidden files and folders, we can run <code>npm run eject</code>.</p>
<p>You can now see that the folder structure has a few more things in it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-20.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And your <code>package.json</code> file contains the whole list of dependencies:</p>
<pre><code class="lang-javascript">
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"testapp"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"0.1.0"</span>,
  <span class="hljs-string">"private"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"@babel/core"</span>: <span class="hljs-string">"^7.16.0"</span>,
    <span class="hljs-string">"@pmmmwh/react-refresh-webpack-plugin"</span>: <span class="hljs-string">"^0.5.3"</span>,
    <span class="hljs-string">"@svgr/webpack"</span>: <span class="hljs-string">"^5.5.0"</span>,
    <span class="hljs-string">"@testing-library/jest-dom"</span>: <span class="hljs-string">"^5.16.5"</span>,
    <span class="hljs-string">"@testing-library/react"</span>: <span class="hljs-string">"^13.4.0"</span>,
    <span class="hljs-string">"@testing-library/user-event"</span>: <span class="hljs-string">"^13.5.0"</span>,
    <span class="hljs-string">"babel-jest"</span>: <span class="hljs-string">"^27.4.2"</span>,
    <span class="hljs-string">"babel-loader"</span>: <span class="hljs-string">"^8.2.3"</span>,
    <span class="hljs-string">"babel-plugin-named-asset-import"</span>: <span class="hljs-string">"^0.3.8"</span>,
    <span class="hljs-string">"babel-preset-react-app"</span>: <span class="hljs-string">"^10.0.1"</span>,
    <span class="hljs-string">"bfj"</span>: <span class="hljs-string">"^7.0.2"</span>,
    <span class="hljs-string">"browserslist"</span>: <span class="hljs-string">"^4.18.1"</span>,
    <span class="hljs-string">"camelcase"</span>: <span class="hljs-string">"^6.2.1"</span>,
    <span class="hljs-string">"case-sensitive-paths-webpack-plugin"</span>: <span class="hljs-string">"^2.4.0"</span>,
    <span class="hljs-string">"css-loader"</span>: <span class="hljs-string">"^6.5.1"</span>,
    <span class="hljs-string">"css-minimizer-webpack-plugin"</span>: <span class="hljs-string">"^3.2.0"</span>,
    <span class="hljs-string">"dotenv"</span>: <span class="hljs-string">"^10.0.0"</span>,
    <span class="hljs-string">"dotenv-expand"</span>: <span class="hljs-string">"^5.1.0"</span>,
    <span class="hljs-string">"eslint"</span>: <span class="hljs-string">"^8.3.0"</span>,
    <span class="hljs-string">"eslint-config-react-app"</span>: <span class="hljs-string">"^7.0.1"</span>,
    <span class="hljs-string">"eslint-webpack-plugin"</span>: <span class="hljs-string">"^3.1.1"</span>,
    <span class="hljs-string">"file-loader"</span>: <span class="hljs-string">"^6.2.0"</span>,
    <span class="hljs-string">"fs-extra"</span>: <span class="hljs-string">"^10.0.0"</span>,
    <span class="hljs-string">"html-webpack-plugin"</span>: <span class="hljs-string">"^5.5.0"</span>,
    <span class="hljs-string">"identity-obj-proxy"</span>: <span class="hljs-string">"^3.0.0"</span>,
    <span class="hljs-string">"jest"</span>: <span class="hljs-string">"^27.4.3"</span>,
    <span class="hljs-string">"jest-resolve"</span>: <span class="hljs-string">"^27.4.2"</span>,
    <span class="hljs-string">"jest-watch-typeahead"</span>: <span class="hljs-string">"^1.0.0"</span>,
    <span class="hljs-string">"mini-css-extract-plugin"</span>: <span class="hljs-string">"^2.4.5"</span>,
    <span class="hljs-string">"postcss"</span>: <span class="hljs-string">"^8.4.4"</span>,
    <span class="hljs-string">"postcss-flexbugs-fixes"</span>: <span class="hljs-string">"^5.0.2"</span>,
    <span class="hljs-string">"postcss-loader"</span>: <span class="hljs-string">"^6.2.1"</span>,
    <span class="hljs-string">"postcss-normalize"</span>: <span class="hljs-string">"^10.0.1"</span>,
    <span class="hljs-string">"postcss-preset-env"</span>: <span class="hljs-string">"^7.0.1"</span>,
    <span class="hljs-string">"prompts"</span>: <span class="hljs-string">"^2.4.2"</span>,
    <span class="hljs-string">"react"</span>: <span class="hljs-string">"^18.2.0"</span>,
    <span class="hljs-string">"react-app-polyfill"</span>: <span class="hljs-string">"^3.0.0"</span>,
    <span class="hljs-string">"react-dev-utils"</span>: <span class="hljs-string">"^12.0.1"</span>,
    <span class="hljs-string">"react-dom"</span>: <span class="hljs-string">"^18.2.0"</span>,
    <span class="hljs-string">"react-refresh"</span>: <span class="hljs-string">"^0.11.0"</span>,
    <span class="hljs-string">"resolve"</span>: <span class="hljs-string">"^1.20.0"</span>,
    <span class="hljs-string">"resolve-url-loader"</span>: <span class="hljs-string">"^4.0.0"</span>,
    <span class="hljs-string">"sass-loader"</span>: <span class="hljs-string">"^12.3.0"</span>,
    <span class="hljs-string">"semver"</span>: <span class="hljs-string">"^7.3.5"</span>,
    <span class="hljs-string">"source-map-loader"</span>: <span class="hljs-string">"^3.0.0"</span>,
    <span class="hljs-string">"style-loader"</span>: <span class="hljs-string">"^3.3.1"</span>,
    <span class="hljs-string">"tailwindcss"</span>: <span class="hljs-string">"^3.0.2"</span>,
    <span class="hljs-string">"terser-webpack-plugin"</span>: <span class="hljs-string">"^5.2.5"</span>,
    <span class="hljs-string">"web-vitals"</span>: <span class="hljs-string">"^2.1.4"</span>,
    <span class="hljs-string">"webpack"</span>: <span class="hljs-string">"^5.64.4"</span>,
    <span class="hljs-string">"webpack-dev-server"</span>: <span class="hljs-string">"^4.6.0"</span>,
    <span class="hljs-string">"webpack-manifest-plugin"</span>: <span class="hljs-string">"^4.0.2"</span>,
    <span class="hljs-string">"workbox-webpack-plugin"</span>: <span class="hljs-string">"^6.4.1"</span>
  },
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"start"</span>: <span class="hljs-string">"node scripts/start.js"</span>,
    <span class="hljs-string">"build"</span>: <span class="hljs-string">"node scripts/build.js"</span>,
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"node scripts/test.js"</span>
  },
  <span class="hljs-string">"eslintConfig"</span>: {
    <span class="hljs-string">"extends"</span>: [
      <span class="hljs-string">"react-app"</span>,
      <span class="hljs-string">"react-app/jest"</span>
    ]
  },
  <span class="hljs-string">"browserslist"</span>: {
    <span class="hljs-string">"production"</span>: [
      <span class="hljs-string">"&gt;0.2%"</span>,
      <span class="hljs-string">"not dead"</span>,
      <span class="hljs-string">"not op_mini all"</span>
    ],
    <span class="hljs-string">"development"</span>: [
      <span class="hljs-string">"last 1 chrome version"</span>,
      <span class="hljs-string">"last 1 firefox version"</span>,
      <span class="hljs-string">"last 1 safari version"</span>
    ]
  },
  <span class="hljs-string">"jest"</span>: {
    <span class="hljs-string">"roots"</span>: [
      <span class="hljs-string">"&lt;rootDir&gt;/src"</span>
    ],
    <span class="hljs-string">"collectCoverageFrom"</span>: [
      <span class="hljs-string">"src/**/*.{js,jsx,ts,tsx}"</span>,
      <span class="hljs-string">"!src/**/*.d.ts"</span>
    ],
    <span class="hljs-string">"setupFiles"</span>: [
      <span class="hljs-string">"react-app-polyfill/jsdom"</span>
    ],
    <span class="hljs-string">"setupFilesAfterEnv"</span>: [
      <span class="hljs-string">"&lt;rootDir&gt;/src/setupTests.js"</span>
    ],
    <span class="hljs-string">"testMatch"</span>: [
      <span class="hljs-string">"&lt;rootDir&gt;/src/**/__tests__/**/*.{js,jsx,ts,tsx}"</span>,
      <span class="hljs-string">"&lt;rootDir&gt;/src/**/*.{spec,test}.{js,jsx,ts,tsx}"</span>
    ],
    <span class="hljs-string">"testEnvironment"</span>: <span class="hljs-string">"jsdom"</span>,
    <span class="hljs-string">"transform"</span>: {
      <span class="hljs-string">"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$"</span>: <span class="hljs-string">"&lt;rootDir&gt;/config/jest/babelTransform.js"</span>,
      <span class="hljs-string">"^.+\\.css$"</span>: <span class="hljs-string">"&lt;rootDir&gt;/config/jest/cssTransform.js"</span>,
      <span class="hljs-string">"^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)"</span>: <span class="hljs-string">"&lt;rootDir&gt;/config/jest/fileTransform.js"</span>
    },
    <span class="hljs-string">"transformIgnorePatterns"</span>: [
      <span class="hljs-string">"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$"</span>,
      <span class="hljs-string">"^.+\\.module\\.(css|sass|scss)$"</span>
    ],
    <span class="hljs-string">"modulePaths"</span>: [],
    <span class="hljs-string">"moduleNameMapper"</span>: {
      <span class="hljs-string">"^react-native$"</span>: <span class="hljs-string">"react-native-web"</span>,
      <span class="hljs-string">"^.+\\.module\\.(css|sass|scss)$"</span>: <span class="hljs-string">"identity-obj-proxy"</span>
    },
    <span class="hljs-string">"moduleFileExtensions"</span>: [
      <span class="hljs-string">"web.js"</span>,
      <span class="hljs-string">"js"</span>,
      <span class="hljs-string">"web.ts"</span>,
      <span class="hljs-string">"ts"</span>,
      <span class="hljs-string">"web.tsx"</span>,
      <span class="hljs-string">"tsx"</span>,
      <span class="hljs-string">"json"</span>,
      <span class="hljs-string">"web.jsx"</span>,
      <span class="hljs-string">"jsx"</span>,
      <span class="hljs-string">"node"</span>
    ],
    <span class="hljs-string">"watchPlugins"</span>: [
      <span class="hljs-string">"jest-watch-typeahead/filename"</span>,
      <span class="hljs-string">"jest-watch-typeahead/testname"</span>
    ],
    <span class="hljs-string">"resetMocks"</span>: <span class="hljs-literal">true</span>
  },
  <span class="hljs-string">"babel"</span>: {
    <span class="hljs-string">"presets"</span>: [
      <span class="hljs-string">"react-app"</span>
    ]
  }
}
</code></pre>
<p>Once again, if you run <code>npm start</code> you'll see your app coming alive. ;)</p>
<h2 id="heading-what-is-vite">What is Vite?</h2>
<p>CRA sounds pretty cool, right? It was a really helpful tool for React devs, since it brought a big improvement over building apps from scratch.</p>
<p>But the problem with create-react-app is it's kind of slow. Especially in large applications, that have thousands of lines of code and hundreds of components and files, tools like Webpack take a long time to bundle and build the application. This is the kind of problem that tools like Vite.js have come to solve.</p>
<p>For further info on why CRA is not the best building tool available today, I recommend <a target="_blank" href="https://youtu.be/kvkAoCbTM3Q">this video</a> and <a target="_blank" href="https://youtu.be/7m14f0ZzMyY">this video</a>.</p>
<p><a target="_blank" href="https://vitejs.dev/">Vite.js</a> is a build tool and development server that is designed to optimize the development experience for modern web applications. It was created by <a target="_blank" href="https://twitter.com/youyuxi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Evan You</a>, the creator of the popular JavaScript framework <a target="_blank" href="https://vuejs.org/">Vue.js</a>.</p>
<p>Vite.js is built on top of native ES modules, which allows for faster and more efficient module loading during development. This means that the development server can start up quickly and changes to the code can be reflected instantly in the browser, without the need for a full page reload.</p>
<p>Vite.js also includes a number of other features that are designed to streamline the development process. For example, it includes built-in support for TypeScript, CSS preprocessors, and hot module replacement. This allows for changes to be made to the code without the need for a full page reload.</p>
<p>Another key feature of Vite.js is its optimized production build process. Vite.js generates highly optimized production builds that leverage modern browser features such as code splitting, lazy loading, and tree shaking to reduce the size of the final bundle and improve performance.</p>
<p>Overall, Vite.js is a powerful and modern build tool that is designed to streamline the development process and improve performance for modern web applications. While it was originally designed for use with Vue.js, you can use it with other modern front-end frameworks such as React and <a target="_blank" href="https://svelte.dev/">Svelte</a>.</p>
<h3 id="heading-vitejs-vs-create-react-app">Vite.js vs Create React App</h3>
<p>Vite.js and Create React App (CRA) are both build tools and development servers that are designed to improve the development experience for React applications. While there is some overlap in their functionality, there are also some key differences between the two tools.</p>
<p>Some of the improvements that Vite.js brings over Create React App include:</p>
<ol>
<li><p><strong>Faster development server:</strong> Vite.js leverages native ES modules to provide a faster and more efficient development server. This means that changes to the code can be reflected instantly in the browser without the need for a full page reload. CRA, on the other hand, uses Webpack to power its development server, which can be slower and less efficient.</p>
</li>
<li><p><strong>Faster build times:</strong> Vite.js generates highly optimized production builds that leverage modern browser features such as code splitting, lazy loading, and tree shaking to reduce the size of the final bundle and improve performance. This can result in significantly faster build times compared to CRA.</p>
</li>
<li><p><strong>Support for other frameworks:</strong> While CRA is designed specifically for React applications, Vite.js can be used with other modern front-end frameworks such as Vue.js, Svelte, and others. This makes Vite.js a more versatile tool for front-end development.</p>
</li>
<li><p><strong>Built-in support for TypeScript:</strong> Vite.js includes built-in support for TypeScript, which can simplify the development process for projects that use TypeScript.</p>
</li>
<li><p><strong>Simplified configuration:</strong> Vite.js uses a simple and intuitive configuration format that makes it easy to get started with the tool. CRA, on the other hand, can require more complex configuration for some use cases.</p>
</li>
</ol>
<p>Overall, Vite.js provides a number of improvements over Create React App in terms of performance, versatility, and ease of use. But both tools have their strengths and weaknesses, and the best tool for a particular project will depend on the specific requirements and constraints of that project.</p>
<h3 id="heading-how-to-build-an-app-with-vite">How to build an app with Vite</h3>
<p>To create a React app with Vite, go to your command line and run <code>npm createvite@latest</code>.</p>
<p>Then follow the prompts in your command line (it will ask you to provide the project name and the kind of template you'd like to start with). After selecting the options of using React and JavaScript, your folder structure should look somewhat like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-49.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>See that it's quite similar to the one generated by CRA.</p>
<p>And this will be your <code>package.json</code>:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"vite-project"</span>,
  <span class="hljs-string">"private"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"0.0.0"</span>,
  <span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span>,
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"dev"</span>: <span class="hljs-string">"vite"</span>,
    <span class="hljs-string">"build"</span>: <span class="hljs-string">"vite build"</span>,
    <span class="hljs-string">"preview"</span>: <span class="hljs-string">"vite preview"</span>
  },
  <span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"react"</span>: <span class="hljs-string">"^18.2.0"</span>,
    <span class="hljs-string">"react-dom"</span>: <span class="hljs-string">"^18.2.0"</span>
  },
  <span class="hljs-string">"devDependencies"</span>: {
    <span class="hljs-string">"@types/react"</span>: <span class="hljs-string">"^18.0.27"</span>,
    <span class="hljs-string">"@types/react-dom"</span>: <span class="hljs-string">"^18.0.10"</span>,
    <span class="hljs-string">"@vitejs/plugin-react"</span>: <span class="hljs-string">"^3.1.0"</span>,
    <span class="hljs-string">"vite"</span>: <span class="hljs-string">"^4.1.0"</span>
  }
}
</code></pre>
<p>To start your app, just run <code>npm run dev</code> and you're ready to go!</p>
<p>Vite is a great option for building React apps nowadays. It gives us all the simplicity and convenience that CRA gave us, plus some big optimizations over what CRA did. But one thing it doesn't have is out of the box support for SSR (server side rendering).</p>
<p>To understand why that matters, we're going to go through a brief explanation of what CSR (client side rendering) and SSR are, and in which situations one might be more beneficial than the other. And then we're going to take a look at two tools that actually provide support for SSR with React.</p>
<h1 id="heading-client-side-rendering-csr-vs-server-side-rendering-ssr">Client Side Rendering (CSR) vs Server Side Rendering (SSR)</h1>
<p>Client-side rendering (CSR) and server-side rendering (SSR) are two approaches to rendering web pages in web development.</p>
<p>Client-side rendering involves generating HTML and rendering a web page entirely in the client's web browser using JavaScript.</p>
<p>In CSR, the client requests a minimal HTML file that includes links to JavaScript and CSS files. The client's browser then fetches the necessary files, executes the JavaScript, and updates the DOM to render the web page.</p>
<p>This approach is often used for single-page applications (SPAs) where the content is dynamically generated and changes frequently. Client-side rendering can provide a faster and more interactive user experience as the browser can update the UI without reloading the page.</p>
<p>Server-side rendering, on the other hand, involves generating the complete HTML of a web page on the server-side before sending it to the client's browser.</p>
<p>In SSR, the server processes the request, fetches the data, generates the HTML, and sends the fully-rendered HTML to the client. This approach is often used for content-heavy websites that require search engine optimization (SEO) or where the content changes infrequently.</p>
<p>Server-side rendering can provide a better initial loading speed and SEO as the search engine crawlers can read the complete HTML content.</p>
<p>The choice between CSR and SSR depends on the specific requirements and constraints of a project.</p>
<p>Client-side rendering might be more convenient for applications that require dynamic content and interactive user interfaces. On the other hand, server-side rendering might be more suitable for content-heavy websites that need to be SEO-friendly or for projects that require good initial loading times, especially for users with slow internet connections or older devices.</p>
<p>Some projects might even use a hybrid approach, where they combine both CSR and SSR to achieve the best of both worlds.</p>
<p>If you're interested in further exploring the many rendering options available in web development, you can refer to <a target="_blank" href="https://www.freecodecamp.org/news/rendering-patterns/">the article I recently wrote about rendering patterns.</a></p>
<h1 id="heading-ssr-building-tools">SSR Building Tools</h1>
<h2 id="heading-what-is-astro">What is Astro?</h2>
<p><a target="_blank" href="https://astro.build/">Astro</a> is a modern static site generator and web development framework that allows developers to build fast and efficient websites and web applications using a combination of server-side rendering and client-side rendering.</p>
<p>Astro uses a modular architecture that allows developers to mix and match different rendering strategies, allowing for maximum flexibility and performance.</p>
<p>For example, Astro supports server-side rendering (SSR) for initial page loads, which can improve performance and SEO, while also supporting client-side rendering (CSR) for subsequent interactions, which can provide a more interactive and dynamic user experience.</p>
<p>In addition to its flexible rendering capabilities, Astro also includes a number of other features that make it a powerful tool for web development. These include:</p>
<ol>
<li><p>Built-in support for popular front-end frameworks such as React, Vue.js, and Svelte.</p>
</li>
<li><p>A powerful build system that is designed to optimize performance and minimize bundle sizes.</p>
</li>
<li><p>A flexible component model that allows developers to build reusable UI components and layouts.</p>
</li>
<li><p>A built-in development server and hot reloading that allows for fast and efficient development.</p>
</li>
<li><p>Support for a wide range of web technologies, including HTML, CSS, JavaScript, Markdown, and more.</p>
</li>
</ol>
<p>Overall, Astro is a powerful and versatile tool for building modern static sites and web applications. Its flexible rendering model, powerful build system, and support for popular front-end frameworks make it a great choice for developers who want to build fast, efficient, and engaging web experiences.</p>
<h3 id="heading-how-to-build-an-app-with-astro">How to build an app with Astro</h3>
<p>To build an app with Astro we can run the command <code>npm create astro@latest</code>.</p>
<p>Then follow the prompts in your command line (it will ask you to provide the project name and the kind of template you'd like to start with). After completing that, your folder structure will look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-50.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And this will be your <code>package.json</code>:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"satellite-series"</span>,
  <span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"0.0.1"</span>,
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"dev"</span>: <span class="hljs-string">"astro dev"</span>,
    <span class="hljs-string">"start"</span>: <span class="hljs-string">"astro dev"</span>,
    <span class="hljs-string">"build"</span>: <span class="hljs-string">"astro build"</span>,
    <span class="hljs-string">"preview"</span>: <span class="hljs-string">"astro preview"</span>,
    <span class="hljs-string">"astro"</span>: <span class="hljs-string">"astro"</span>
  },
  <span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"@astrojs/react"</span>: <span class="hljs-string">"^2.0.2"</span>,
    <span class="hljs-string">"@types/react"</span>: <span class="hljs-string">"^18.0.28"</span>,
    <span class="hljs-string">"@types/react-dom"</span>: <span class="hljs-string">"^18.0.11"</span>,
    <span class="hljs-string">"astro"</span>: <span class="hljs-string">"^2.0.17"</span>,
    <span class="hljs-string">"react"</span>: <span class="hljs-string">"^18.2.0"</span>,
    <span class="hljs-string">"react-dom"</span>: <span class="hljs-string">"^18.2.0"</span>
  }
}
</code></pre>
<p>From the <a target="_blank" href="https://docs.astro.build/en/core-concepts/project-structure/">Astro docs</a> we can see how the project structure works:</p>
<blockquote>
<p><strong>src/components</strong>: Components are reusable units of code for your HTML pages. These could be Astro components, or UI framework components like React or Vue. It is common to group and organize all of your project components together in this folder. <strong>src/layouts</strong>: Layouts are a special kind of component that wrap some content in a larger page layout. These are most often used by Astro pages and Markdown or MDX pages to define the layout of the page. Just like src/components, this directory is a common convention but not required. <strong>src/pages</strong>: Pages are a special kind of component used to create new pages on your site. A page can be an Astro component, or a Markdown file that represents some page of content for your site. src/pages is a required sub-directory in your Astro project. Without it, your site will have no pages or routes! <strong>src/styles</strong>: It is a common convention to store your CSS or Sass files in a src/styles directory, but this is not required. As long as your styles live somewhere in the src/ directory and are imported correctly, Astro will handle and optimize them. <strong>public/</strong>: The public/ directory is for files and assets that do not need to be processed during Astro’s build process. These files will be copied into the build folder untouched. This behavior makes public/ ideal for common assets like images and fonts, or special files such as robots.txt and manifest.webmanifest. You can place CSS and JavaScript in your public/ directory, but be aware that those files will not be bundled or optimized in your final build.</p>
</blockquote>
<p>As you can see, Astro adds features on top of what React offers (like bundling optimization, Astro components, and out-of-the-box routing). This is what people call a "metaframework" (we'll take a closer look at that later on).</p>
<p>If you'd like to get a more detailed overview of how Astro works, I recommend you <a target="_blank" href="https://docs.astro.build/en/getting-started/">check out their docs</a>. They're really well-written and easy to follow.</p>
<h2 id="heading-what-is-gatsby">What is Gatsby?</h2>
<p><a target="_blank" href="https://www.gatsbyjs.com/">Gatsby</a> is a modern web framework based on React that allows developers to build fast, dynamic websites and applications using the latest web technologies. It was initially released in 2015 by <a target="_blank" href="https://twitter.com/kylemathews?lang=es">Kyle Mathews</a>, and has since grown to become one of the most popular static site generators and web frameworks in the world.</p>
<p>One of the main characteristics of Gatsby is its focus on performance and speed. Gatsby uses a technique called pre-rendering to generate static HTML, CSS, and JavaScript files that can be served to users almost instantly, resulting in a faster and more responsive user experience.</p>
<p>Also, Gatsby's use of React.js allows developers to create highly dynamic and interactive web applications that feel like native apps.</p>
<p>Gatsby also offers a powerful plugin system that makes it easy to add new features and functionality to your website or application. Gatsby plugins can help with everything from optimizing images and improving performance to integrating with external services and databases.</p>
<p>Some of the pros of using Gatsby include:</p>
<ul>
<li><p>Fast and responsive user experience: Gatsby's use of pre-rendering and React.js makes for a highly performant and responsive user experience.</p>
</li>
<li><p>Large and active community: Gatsby has a large and active community of developers and contributors, which means there are plenty of resources and support available.</p>
</li>
<li><p>Plugin system: Gatsby's plugin system makes it easy to add new features and functionality to your website or application without having to write custom code.</p>
</li>
<li><p>Integration with external services: Gatsby can easily integrate with external services and databases, making it a good choice for applications that need to access and process data from a variety of sources.</p>
</li>
</ul>
<p>Some of the cons of using Gatsby include:</p>
<ul>
<li><p>Steep learning curve: Gatsby can be complex and difficult to learn for developers who are new to React or web development in general.</p>
</li>
<li><p>Limited server-side rendering: Gatsby's use of pre-rendering means that it may not be the best choice for applications that require extensive server-side rendering.</p>
</li>
<li><p>Static site limitations: Because Gatsby generates static files, it may not be the best choice for applications that require frequent database updates or real-time data.</p>
</li>
</ul>
<p>Gatsby is a good choice for a wide variety of web applications, including blogs, e-commerce sites, marketing sites, and other content-driven websites. It is particularly well-suited for applications that require fast page loads and a highly performant user experience, as well as applications that need to integrate with external services and databases.</p>
<h3 id="heading-how-to-build-an-app-with-gatsby">How to build an app with Gatsby</h3>
<p>To initiate a Gatsby project, run <code>npm init gatsby</code> and follow the CLI prompts.</p>
<p>Your folder structure might look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-51.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Within the <code>pages</code> folder we have a file for each of the site's pages. Gatsby works with out-of-the box routing just like Astro.</p>
<p>A typical React front-end application project that uses Gatsby.js as the static site generator will have the following structure:</p>
<ol>
<li><p><code>src/</code> folder: This folder contains all the source code of the application. It usually includes sub-folders for pages, components, images, styles, and data.</p>
</li>
<li><p><code>gatsby-config.js</code>: This file contains the configuration settings for Gatsby. It includes metadata such as the site title, description, and author, as well as settings for plugins and other features.</p>
</li>
<li><p><code>public/</code> folder: This folder contains the compiled static assets that Gatsby generates when the site is built. These assets can be deployed to a web server or CDN.</p>
</li>
</ol>
<h1 id="heading-reacts-metaframeworks">React's Metaframeworks</h1>
<p>React's metaframeworks are high-level frameworks that provide additional abstractions and functionality <strong>on top</strong> of the React library.</p>
<p>They are designed to simplify the development of complex applications and provide additional features and functionality that are not available in the React library alone.</p>
<p>Some examples of React.js metaframeworks include:</p>
<ol>
<li><p><strong>Next.js:</strong> <a target="_blank" href="https://nextjs.org/">Next.js</a> is a metaframework that provides server-side rendering, automatic code splitting, and simplified client-side routing. It also includes built-in support for static site generation, API routes, and other advanced features.</p>
</li>
<li><p><strong>Remix:</strong> <a target="_blank" href="https://remix.run/">Remix</a> is a metaframework for building server-rendered React applications. It provides a unified data management system, a simple and intuitive routing system, and other features that can simplify building complex web applications. Remix aims to improve developer productivity by providing a simpler, more streamlined development experience for building large, complex web applications.</p>
</li>
</ol>
<p>Overall, React.js metaframeworks provide powerful abstractions and functionality that can simplify the development of complex applications and help developers to build high-quality, efficient, and maintainable code.</p>
<p>Side comment: Astro and Gatsby might be considered metaframeworks as well. I just put them in a different section to introduce what SSR is, and also considering that Next and Remix provide more extra features on top of React than the other two.</p>
<h2 id="heading-what-is-nextjs">What is Next.js?</h2>
<p>Next.js is a popular metaframework for building server-side rendered (SSR) React applications. It is an open-source project developed by <a target="_blank" href="https://vercel.com/">Vercel</a> (formerly Zeit) and has gained popularity due to its ease of use, performance, and flexibility.</p>
<p>Next.js provides a number of features out of the box, such as automatic code splitting, server-side rendering, and hot module replacement. It also has built-in support for various front-end features, including client-side routing, static file serving, and API routes.</p>
<p>One of the main advantages of Next.js is its support for server-side rendering, which can improve the performance and SEO of web applications. With Next.js, the initial HTML is generated on the server, which can then be quickly hydrated with JavaScript on the client side.</p>
<p>If you wander what "hydration" means, again you can refer to <a target="_blank" href="https://www.freecodecamp.org/news/rendering-patterns/#the-concept-of-hydration">the article I wrote about rendering patterns</a>. ;)</p>
<p>Next.js also supports static site generation, where pages can be pre-built and served statically for faster performance and reduced server load. This feature makes it easy to build fast, scalable, and SEO-friendly sites with Next.js.</p>
<p>In addition to these features, Next.js has a large and active community that provides many plugins and tools to extend its functionality. It is also designed to be easy to use, with a simple setup process and a well-documented API.</p>
<p>Another interesting thing to mention is that the Next developer team works hand-in-hand with the React developer team, so both the Next framework and the React library are very well integrated and take advantage of each other's latest features.</p>
<p>Overall, Next.js is a powerful and flexible tool for building modern web applications with React. Its support for server-side rendering and static site generation make it a popular choice for developers looking to optimize their web applications for performance and SEO.</p>
<h3 id="heading-how-to-build-an-app-with-nextjs">How to build an app with Next.js</h3>
<p>To create a Next app, we can run the following command: <code>npx create-next-app@latest &lt;appName&gt;</code>. Then follow the prompts in your command line.</p>
<p>Your folder structure might look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-131.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A typical React front-end application project that uses Next.js as the framework will have the following structure:</p>
<ol>
<li><p><code>pages/</code> folder: This folder contains all the pages of the application. Each file in this folder represents a route in the application, and the file name corresponds to the route path. For example, a file named <code>index.js</code> represents the root route (<code>/</code>), and a file named <code>about.js</code> represents the <code>/about</code> route.</p>
</li>
<li><p><code>public/</code> folder: This folder contains the static assets that are served directly by the web server, such as images, videos, and fonts.</p>
</li>
<li><p><code>styles/</code> folder: This folder contains all the styles of the application. It includes global styles, such as the font family and color scheme, as well as component-specific styles.</p>
</li>
<li><p><code>next.config.js</code>: This file contains the configuration settings for Next.js. It can be used to customize features such as webpack, CSS, and image handling.</p>
</li>
</ol>
<p>For a deeper dive into how Next works, refer to <a target="_blank" href="https://nextjs.org/learn/foundations/about-nextjs">their awesome docs</a>.</p>
<h2 id="heading-what-is-remix">What is Remix?</h2>
<p>Remix is a metaframework for building server-rendered React applications. It is an open-source project developed by the team at Remix Software, and it aims to provide a simpler and more unified approach to building server-rendered React applications.</p>
<p>One of the main features of Remix is its focus on code splitting and lazy loading. It automatically code splits your application into small chunks that are loaded on demand. This can improve performance and reduce the initial load time of your application.</p>
<p>Remix also provides a unified data management system, which makes it easy to manage the data your application needs to function. With Remix, you can define your data requirements in one place and fetch them on the server or client as needed.</p>
<p>Another key feature of Remix is its routing system, which is designed to be simple and intuitive. You can define your routes using a declarative API, and Remix will automatically generate the necessary code to handle client-side and server-side rendering.</p>
<p>Remix also provides built-in support for authentication, authorization, and other common web application features. It is highly extensible, with a plugin system that makes it easy to add custom functionality to your application.</p>
<p>Overall, Remix is a powerful and flexible metaframework for building server-rendered React applications. Its focus on code splitting, data management, and routing make it easy to build fast, scalable, and maintainable applications.</p>
<h3 id="heading-how-to-build-an-app-with-remix">How to build an app with Remix</h3>
<p>To create a Remix app, we can run the following command: <code>npx create-remix@latest</code> Then follow the prompts in your command line.</p>
<p>Your folder structure might look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-132.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A typical React front-end application project that uses Remix as the framework will have the following structure:</p>
<ul>
<li><p><code>public/</code>: This directory contains the publicly accessible files of the application, such as the index.html file and other assets like images, fonts, etc.</p>
</li>
<li><p><code>app/</code>: This directory contains the source code of the application.</p>
</li>
<li><p><code>routes.js</code>: This file defines the routes of the application and maps them to the corresponding page components.</p>
</li>
<li><p><code>remix.config.js</code>: This file contains configuration options for Remix.js, such as setting up server-side rendering and defining routes.</p>
</li>
</ul>
<p>For a deeper dive into how Next works, refer to <a target="_blank" href="https://remix.run/docs/en/1.14.1/tutorials/blog">their docs</a>.</p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>There are several popular React.js build tools available, each with its own unique set of features and advantages.</p>
<p>Here is a comparison of the main characteristics, pros, and cons of five popular React.js build tools: create-react-app, Vite, Astro, Gatsby, Next.js, and Remix.</p>
<h3 id="heading-create-react-app">create-react-app:</h3>
<ul>
<li><p><strong>Characteristics</strong>: A command-line tool that sets up a basic React application with a simple file structure and build process.</p>
</li>
<li><p><strong>Pros</strong>: Easy to use, with a simple setup process and no configuration required. Provides a good starting point for new React projects.</p>
</li>
<li><p><strong>Cons</strong>: Limited flexibility and customization options. May not be suitable for larger or more complex projects.</p>
</li>
<li><p><strong>Best for</strong>: Small to medium-sized projects with straightforward requirements.</p>
</li>
</ul>
<h3 id="heading-vite">Vite:</h3>
<ul>
<li><p><strong>Characteristics</strong>: A fast build tool that leverages modern browser features to provide fast development and build times.</p>
</li>
<li><p><strong>Pros</strong>: Extremely fast, with instant hot module replacement and other optimizations for faster builds. Supports a wide range of front-end frameworks and technologies.</p>
</li>
<li><p><strong>Cons</strong>: Less mature than some other tools, with a smaller community and fewer available plugins.</p>
</li>
<li><p><strong>Best for</strong>: Modern, fast-paced development workflows with a focus on speed and efficiency.</p>
</li>
</ul>
<h3 id="heading-astro">Astro:</h3>
<ul>
<li><p><strong>Characteristics</strong>: A static site generator that can be used with React and other front-end frameworks.</p>
</li>
<li><p><strong>Pros</strong>: Extremely fast, with a focus on generating static sites that can be deployed anywhere. Provides a simple, intuitive API for building static sites.</p>
</li>
<li><p><strong>Cons</strong>: Less mature than some other tools, with a smaller community and fewer available plugins. May not be suitable for dynamic applications or complex routing needs.</p>
</li>
<li><p><strong>Best for</strong>: Static sites or simple web applications that can be generated and served statically.</p>
</li>
</ul>
<h3 id="heading-gatsby">Gatsby:</h3>
<ul>
<li><p><strong>Main characteristics:</strong> Gatsby is a popular static site generator that uses React to create fast and performant websites and applications. It includes a powerful plugin system for adding new features and functionality, and supports features like server-side rendering and data sourcing from a variety of APIs and databases.</p>
</li>
<li><p><strong>Pros:</strong> Highly performant, powerful plugin system, good for content-driven websites and applications.</p>
</li>
<li><p><strong>Cons:</strong> May be more limited in terms of dynamic data updates and real-time data.</p>
</li>
<li><p><strong>Best for:</strong> Projects that require fast and performant content-driven websites or applications, or for developers who prefer a static site architecture.</p>
</li>
</ul>
<h3 id="heading-nextjs">Next.js:</h3>
<ul>
<li><p><strong>Characteristics</strong>: A metaframework for building server-rendered React applications.</p>
</li>
<li><p><strong>Pros</strong>: Provides built-in support for server-side rendering, static site generation, and other features that can improve performance and SEO. Has a large and active community with many available plugins and tools.</p>
</li>
<li><p><strong>Cons</strong>: Can be more complex to set up and configure than some other tools. May not be suitable for smaller or simpler projects.</p>
</li>
<li><p><strong>Best for</strong>: Large, complex web applications with complex routing, data management, or SEO requirements.</p>
</li>
</ul>
<h3 id="heading-remix">Remix:</h3>
<ul>
<li><p><strong>Characteristics</strong>: A metaframework for building server-rendered React applications.</p>
</li>
<li><p><strong>Pros</strong>: Provides a unified data management system, a simple and intuitive routing system, and other features that can simplify building complex web applications. Has a plugin system that makes it easy to add custom functionality to your application.</p>
</li>
<li><p><strong>Cons</strong>: Less mature than some other tools, with a smaller community and fewer available plugins.</p>
</li>
<li><p><strong>Best for</strong>: Large, complex web applications with complex data management, routing, or other requirements.</p>
</li>
</ul>
<p>Overall, the best choice of React.js build tool depends on the specific needs of your project.</p>
<p>For small to medium-sized projects with straightforward requirements and fast-paced development workflows with a focus on speed and efficiency, Vite may be the best choice due to its simplicity and ease of use.</p>
<p>For static sites or simple web applications that can be generated and served statically, Astro may be the best choice.</p>
<p>And for larger, more complex projects with complex routing, data management, or SEO requirements, Next.js may be a better choice.</p>
<p>Well everyone, that's all for today. As always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/23b4b79490fdda967ee0fcc8d9c57402_w200.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Different Types of APIs – SOAP vs REST vs GraphQL ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article we're going to take a good look at APIs, a core concept in modern software development. We're going to talk about the main kinds of APIs used nowadays (SOAP, REST and GraphQL), their characteristics, pros and cons, and si... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rest-vs-graphql-apis/</link>
                <guid isPermaLink="false">66d45f1fd1ffc3d3eb89ddfc</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Tue, 07 Mar 2023 23:24:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/john-towner-p-rN-n6Miag-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article we're going to take a good look at APIs, a core concept in modern software development.</p>
<p>We're going to talk about the main kinds of APIs used nowadays (SOAP, REST and GraphQL), their characteristics, pros and cons, and situations in which each of them might be more beneficial.</p>
<p>Let's go! 🙃</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-soap-apis-work">How SOAP APIs Work</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-about-xml">About XML</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-consume-a-soap-api">How to Consume a SOAP API</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-rest-apis-work">How REST APIs Work</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-consume-a-rest-api">How to Consume a REST API</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-graphql-apis-work">How GraphQL APIs work</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-consume-a-graphql-api">How to Consume a GraphQL API</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-intro">Intro</h2>
<p>In <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-software-architecture-patterns/">a recent article</a> I talked briefly about two very important concepts in modern software development: the client-server model and APIs.</p>
<p><strong>Client-server</strong> is a model that structures the tasks or workloads of an application between a resource or service <strong>provider</strong> (server) and a service or resource requester (client).</p>
<p>Put simply, the client is the application that requests some kind of information or performs actions, and the server is the program that sends information or performs actions according to what the client does.</p>
<p>Most applications nowadays use a client-server model. The most important concept to remember about it is that <strong>clients request resources or services</strong> that <strong>the server performs</strong>. The way in which these two parts usually communicate is through an <strong>API</strong> (application programming interface).</p>
<p>An API is nothing more than a <strong>set of defined rules that establishes how one application can communicate with another</strong>. It's like a contract between the two parts that says "If you send A, I'll always respond B. If you send C, I'll always respond D..." and so on.</p>
<p>Having this set of rules, the client knows exactly what it has to require in order to complete a certain task, and the server knows exactly what the client will require when a certain action has to be performed.</p>
<p>APIs are absolutely everywhere in current software development. Almost any kind of application will use a client-server model enabled by API communication. That's why I think it's a very good idea for us as developers to get to know them well.</p>
<p>The most popular ways to implement APIs nowadays are REST and GraphQl. We'll also take a look at SOAP, which was quite popular some years ago and is still used in some niche sectors.</p>
<p>If you'd like a deeper intro to what APIs are, <a target="_blank" href="https://www.youtube.com/watch?v=yBZO5Rb4ibo">here's an awesome video about it</a>.</p>
<p>With all this in mind, let's get into the details of how SOAP, REST and GraphQL APIs work.</p>
<h1 id="heading-how-soap-apis-work">How SOAP APIs Work</h1>
<p>Simple Object Access Protocol (SOAP) is a messaging protocol used for exchanging structured data between different systems over the internet. SOAP is an XML-based protocol and is considered one of the earliest web service protocols.</p>
<p>SOAP was first introduced in 1998 by Microsoft as a successor to Common Object Request Broker Architecture (CORBA) and Distributed Component Object Model (DCOM).</p>
<p>SOAP was designed to provide a platform-independent way to exchange data between different systems over the internet. SOAP was later standardized by the World Wide Web Consortium (W3C) in 2003.</p>
<p><strong>Main Characteristics:</strong></p>
<ol>
<li><p><strong>Protocol-Independent:</strong> SOAP is designed to work with any protocol that supports the transmission of messages over the internet, including HTTP, SMTP, and FTP.</p>
</li>
<li><p><strong>Platform-Independent:</strong> SOAP is designed to work with any programming language or platform that supports XML and can send and receive HTTP messages.</p>
</li>
<li><p><strong>Messaging:</strong> SOAP is a messaging protocol and defines a set of rules for exchanging structured data between different systems.</p>
</li>
<li><p><strong>Security:</strong> SOAP supports several security standards, including encryption, digital signatures, and authentication.</p>
</li>
<li><p><strong>Extensibility:</strong> SOAP allows for the creation of custom extensions to the protocol to support specific requirements.</p>
</li>
</ol>
<p><strong>Pros:</strong></p>
<ol>
<li><p><strong>Standardization:</strong> SOAP is a well-established and standardized protocol, making it a reliable choice for exchanging data between different systems.</p>
</li>
<li><p><strong>Security:</strong> SOAP provides built-in support for several security standards, making it a secure choice for transmitting sensitive data.</p>
</li>
<li><p><strong>Extensibility:</strong> SOAP is highly extensible and allows for the creation of custom extensions to support specific requirements.</p>
</li>
</ol>
<p><strong>Cons:</strong></p>
<ol>
<li><p><strong>Complexity:</strong> SOAP can be complex to implement and may require specialized expertise.</p>
</li>
<li><p><strong>Overhead:</strong> SOAP messages can be large and can require significant processing resources, resulting in increased overhead.</p>
</li>
<li><p><strong>Performance:</strong> SOAP can be slower compared to other API protocols due to its messaging nature.</p>
</li>
</ol>
<p><strong>Best for:</strong></p>
<ol>
<li><p><strong>When you need to transmit sensitive data:</strong> SOAP supports several security standards, making it a secure choice for transmitting sensitive data.</p>
</li>
<li><p><strong>When you need to support complex data structures:</strong> SOAP supports complex data structures, making it a good choice for transmitting and exchanging data between different systems.</p>
</li>
<li><p><strong>When you need a reliable and standardized protocol:</strong> SOAP is a well-established and standardized protocol, making it a reliable choice for exchanging data between different systems.</p>
</li>
</ol>
<p>SOAP APIs were widely used in the early days of web services and are still used in several industries and sectors today, although REST and GraphQL have become more popular in recent years.</p>
<p>Here are some industries, sectors, and types of applications in which SOAP is still the main option:</p>
<ol>
<li><p><strong>Healthcare:</strong> SOAP is still widely used in healthcare applications, especially in electronic health records (EHR) and health information exchanges (HIE). This is because SOAP provides a secure and reliable way to transmit sensitive patient information between different systems.</p>
</li>
<li><p><strong>Finance:</strong> SOAP is still used in financial applications, such as payment gateways and trading platforms, because it provides a secure and reliable way to transmit financial data.</p>
</li>
<li><p><strong>Enterprise applications:</strong> SOAP is still used in enterprise applications, such as customer relationship management (CRM) and enterprise resource planning (ERP) systems, because it provides a standardized and reliable way to exchange data between different systems.</p>
</li>
<li><p><strong>Legacy systems:</strong> Many older systems and applications still use SOAP APIs, and it can be costly and time-consuming to migrate them to newer technologies.</p>
</li>
</ol>
<p>In conclusion, SOAP APIs have been around for a long time and are still used in several industries to exchange data between different systems.</p>
<p>SOAP might be the most beneficial option for developing an API when you need to transmit sensitive data, support complex data structures, or need a reliable and standardized protocol.</p>
<h2 id="heading-about-xml">About XML</h2>
<p>As mentioned, SOAP APIs use XML as the main format for data transmission, so let's explain how XML works.</p>
<p>XML stands for Extensible Markup Language. It is a markup language that allows users to create custom tags and attributes to describe the structure and content of data.</p>
<p>XML uses a set of rules for encoding documents in a format that is both human-readable and machine-readable. This is achieved by using tags to define elements of a document, similar to HTML.</p>
<p>For example, an XML document may have a tag called <code>&lt;person&gt;</code> to define an element representing a person, with nested tags for properties such as <code>&lt;name&gt;</code>, <code>&lt;age&gt;</code>, and <code>&lt;address&gt;</code>. XML also allows users to define custom tags to describe their data in a way that is specific to their needs.</p>
<p>XML is widely used in various industries, including finance, healthcare, and government. It is often used for data exchange between different applications and systems, as it provides a standardized way of representing data that can be easily parsed by computers. XML is also used for storing configuration files and metadata for various applications.</p>
<p>Overall, XML provides a flexible and extensible way of describing and exchanging data that can be easily processed by computers. However, its use has declined in recent years with the rise of more modern formats such as JSON and YAML, which are more lightweight and easier to use for many applications.</p>
<h2 id="heading-how-to-consume-a-soap-api">How to Consume a SOAP API</h2>
<p>Here's an example of how you can make a simple request to a SOAP API from a JavaScript front-end application:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// specify the URL of the SOAP API endpoint</span>
<span class="hljs-keyword">const</span> url = <span class="hljs-string">'http://www.example.com/soap-api'</span>;

<span class="hljs-comment">// specify the SOAP message to send</span>
<span class="hljs-keyword">const</span> soapMessage = <span class="hljs-string">'&lt;?xml version="1.0" encoding="UTF-8"?&gt;'</span> +
                    <span class="hljs-string">'&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com"&gt;'</span> +
                    <span class="hljs-string">'&lt;SOAP-ENV:Header/&gt;'</span> +
                    <span class="hljs-string">'&lt;SOAP-ENV:Body&gt;'</span> +
                    <span class="hljs-string">'&lt;ns1:GetData&gt;'</span> +
                    <span class="hljs-string">'&lt;ns1:Id&gt;123&lt;/ns1:Id&gt;'</span> +
                    <span class="hljs-string">'&lt;/ns1:GetData&gt;'</span> +
                    <span class="hljs-string">'&lt;/SOAP-ENV:Body&gt;'</span> +
                    <span class="hljs-string">'&lt;/SOAP-ENV:Envelope&gt;'</span>;

<span class="hljs-comment">// set the content type of the SOAP message</span>
<span class="hljs-keyword">const</span> contentType = <span class="hljs-string">'text/xml'</span>;

<span class="hljs-comment">// make the fetch request</span>
fetch(url, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>, <span class="hljs-comment">// SOAP uses the HTTP POST method to send requests to a server.</span>
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: contentType,
    <span class="hljs-string">'SOAPAction'</span>: <span class="hljs-string">'http://example.com/GetData'</span>
  },
  <span class="hljs-attr">body</span>: soapMessage
})
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.text())
  .then(<span class="hljs-function"><span class="hljs-params">xml</span> =&gt;</span> {
    <span class="hljs-comment">// handle the XML response</span>
    <span class="hljs-keyword">const</span> parser = <span class="hljs-keyword">new</span> DOMParser();
    <span class="hljs-keyword">const</span> xmlDoc = parser.parseFromString(xml, <span class="hljs-string">'text/xml'</span>);
    <span class="hljs-keyword">const</span> value = xmlDoc.getElementsByTagName(<span class="hljs-string">'Value'</span>)[<span class="hljs-number">0</span>].childNodes[<span class="hljs-number">0</span>].nodeValue;
    <span class="hljs-built_in">console</span>.log(value);
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>Let's break down what each line does:</p>
<ol>
<li><p><code>const url = 'http://www.example.com/soap-api';</code> specifies the URL of the SOAP API endpoint.</p>
</li>
<li><p><code>const soapMessage = '&lt;?xml version="1.0" encoding="UTF-8"?&gt;' + ...</code> specifies the SOAP message to send to the API endpoint. This is a string that contains the XML markup for the SOAP message.</p>
</li>
<li><p><code>const contentType = 'text/xml';</code> specifies the content type of the SOAP message.</p>
</li>
<li><p><code>fetch(url, { ... })</code> makes a fetch request to the API endpoint using the specified URL and options.</p>
</li>
<li><p><code>method: 'POST',</code> specifies the HTTP method to use for the request.</p>
</li>
<li><p><code>headers: { ... }</code> specifies the headers to include in the request.</p>
</li>
<li><p><code>'Content-Type': contentType,</code> sets the content type of the request header to the value of <code>contentType</code>.</p>
</li>
<li><p><code>'SOAPAction': 'http://example.com/GetData'</code> sets the SOAPAction header to the value of the SOAP action that corresponds to the API method being called.</p>
</li>
<li><p><code>body: soapMessage</code> sets the body of the request to the value of <code>soapMessage</code>.</p>
</li>
<li><p><code>.then(response =&gt; response.text())</code> converts the response to text format.</p>
</li>
<li><p><code>.then(xml =&gt; { ... })</code> handles the response from the server.</p>
</li>
</ol>
<p>A typical response might look like this:</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">SOAP-ENV:Envelope</span> <span class="hljs-attr">xmlns:SOAP-ENV</span>=<span class="hljs-string">"http://schemas.xmlsoap.org/soap/envelope/"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">SOAP-ENV:Body</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ns1:GetDataResponse</span> <span class="hljs-attr">xmlns:ns1</span>=<span class="hljs-string">"http://example.com"</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">ns1:Result</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ns1:Id</span>&gt;</span>123<span class="hljs-tag">&lt;/<span class="hljs-name">ns1:Id</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ns1:Value</span>&gt;</span>42<span class="hljs-tag">&lt;/<span class="hljs-name">ns1:Value</span>&gt;</span>
         <span class="hljs-tag">&lt;/<span class="hljs-name">ns1:Result</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ns1:GetDataResponse</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">SOAP-ENV:Body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">SOAP-ENV:Envelope</span>&gt;</span>
</code></pre>
<p>To access the values in the XML response, you can use the DOMParser API to parse the response into an XML document object, and then use DOM traversal methods to navigate the document and extract the values.</p>
<p>For example, the following code extracts the value of the <code>Value</code> element from the XML document object:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> parser = <span class="hljs-keyword">new</span> DOMParser();
<span class="hljs-keyword">const</span> xmlDoc = parser.parseFromString(xml, <span class="hljs-string">'text/xml'</span>);
<span class="hljs-keyword">const</span> value = xmlDoc.getElementsByTagName(<span class="hljs-string">'Value'</span>)[<span class="hljs-number">0</span>].childNodes[<span class="hljs-number">0</span>].nodeValue;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// output: 42</span>
</code></pre>
<p>Here's what each line does:</p>
<ol>
<li><p><code>const parser = new DOMParser();</code> creates a new instance of the DOMParser object, which is used to parse the XML response.</p>
</li>
<li><p><code>const xmlDoc = parser.parseFromString(xml, 'text/xml');</code> parses the XML response into an XML document object.</p>
</li>
<li><p><code>const value = xmlDoc.getElementsByTagName('Value')[0].childNodes[0].nodeValue;</code> retrieves the value of the <code>Value</code> element from the XML document object. This line uses the <code>getElementsByTagName()</code> method to get all elements with the tag name <code>Value</code>, and then accesses the first element (assuming there's only one), and gets the value of its first child node. The value is then assigned to the <code>value</code> variable.</p>
</li>
<li><p><code>console.log(value); // output: 42</code> logs the value of the <code>Value</code> element to the console.</p>
</li>
</ol>
<p>Overall, SOAP responses tend to be more verbose and complex than responses from REST or GraphQL APIs, due to their use of XML and the envelope format. But this format provides a standardized way of exchanging information that can be useful in certain industries and use cases.</p>
<h1 id="heading-how-rest-apis-work">How REST APIs Work</h1>
<p>Representational State Transfer (REST) is a widely used architectural style for building web services and APIs.</p>
<p>REST was first introduced in 2000 by Roy Fielding in his doctoral dissertation, "Architectural Styles and the Design of Network-based Software Architectures." Fielding, who was also one of the primary authors of the HTTP protocol, defined REST as an architectural style that is based on the principles of the web.</p>
<p>RESTful APIs are designed to be simple, scalable, and flexible. They are often used in web and mobile applications, as well as in Internet of Things (IoT) and microservices architectures.</p>
<p><strong>Main Characteristics:</strong></p>
<ol>
<li><p><strong>Stateless:</strong> REST APIs are stateless, which means that each request contains all the necessary information to process it. This makes it easier to scale the API and improves performance by reducing the need to store and manage session data on the server.</p>
</li>
<li><p><strong>Resource-based:</strong> REST APIs are resource-based, which means that each resource is identified by a unique URI (Uniform Resource Identifier) and can be accessed using standard HTTP methods such as GET, POST, PUT, and DELETE.</p>
</li>
<li><p><strong>Uniform Interface:</strong> REST APIs have a uniform interface that allows clients to interact with resources using a standardized set of methods and response formats. This makes it easier for developers to build and maintain APIs, and for clients to consume them.</p>
</li>
<li><p><strong>Cacheable:</strong> REST APIs are cacheable, which means that responses can be cached to improve performance and reduce network traffic.</p>
</li>
<li><p><strong>Layered System:</strong> REST APIs are designed to be layered, which means that intermediaries such as proxies and gateways can be added between the client and server without affecting the overall system.</p>
</li>
</ol>
<p><strong>Pros:</strong></p>
<ul>
<li><p><strong>Easy to learn and use:</strong> REST APIs are relatively simple and easy to learn compared to other APIs.</p>
</li>
<li><p><strong>Scalability:</strong> The stateless nature of REST APIs makes them highly scalable and efficient.</p>
</li>
<li><p><strong>Flexibility:</strong> REST APIs are flexible and can be used to build a wide range of applications and systems.</p>
</li>
<li><p><strong>Wide support:</strong> REST APIs are widely supported by development tools and frameworks, making it easy to integrate them into existing systems.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p><strong>Lack of standards:</strong> The lack of strict standards for REST APIs can lead to inconsistencies and interoperability issues.</p>
</li>
<li><p><strong>Limited functionality:</strong> REST APIs are designed to handle simple requests and responses and may not be suitable for more complex use cases.</p>
</li>
<li><p><strong>Security concerns:</strong> REST APIs can be vulnerable to security attacks such as cross-site scripting (XSS) and cross-site request forgery (CSRF) if not implemented properly.</p>
</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li><p>REST APIs are well-suited for building web and mobile applications, as well as microservices architectures and IoT systems.</p>
</li>
<li><p>They are particularly useful in situations where scalability and flexibility are important, and where developers need to integrate with existing systems and technologies.</p>
</li>
</ul>
<p>In summary, REST APIs are a popular and widely used architectural style for building web services and APIs. They are simple, scalable, and flexible, and can be used to build a wide range of applications and systems.</p>
<p>While there are some limitations and concerns with REST APIs, they remain a popular and effective option for building APIs in many different industries and sectors.</p>
<h2 id="heading-how-to-consume-a-rest-api">How to Consume a REST API</h2>
<p>Here's an example of how to make a simple GET request to a REST API from a JavaScript front-end application, and how to access the values within the response:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
    <span class="hljs-comment">// Access the values within the response here</span>
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>Here's what each line does:</p>
<ol>
<li><p><code>fetch('https://jsonplaceholder.typicode.com/todos/1')</code> initiates a GET request to the specified URL.</p>
</li>
<li><p><code>.then(response =&gt; response.json())</code> converts the response from JSON format to a JavaScript object.</p>
</li>
<li><p><code>.then(data =&gt; { ... })</code> defines a function that will be executed when the response has been successfully converted to a JavaScript object. This function will have access to the JavaScript object containing the response data.</p>
</li>
<li><p><code>console.log(data);</code> logs the response data to the console. You can inspect the response data to determine how to access the values within the response.</p>
</li>
</ol>
<p>To access the values within the response, you can use standard JavaScript object traversal techniques, such as dot notation or bracket notation. For example, if the response from the REST API is in the following format:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"userId"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"title"</span>: <span class="hljs-string">"delectus aut autem"</span>,
  <span class="hljs-string">"completed"</span>: <span class="hljs-literal">false</span>
}
</code></pre>
<p>You can access the <code>title</code> value using dot or bracket notation like this:</p>
<pre><code class="lang-plaintext">console.log(data.title); // output: "delectus aut autem"
console.log(data['title']); // output: "delectus aut autem"
</code></pre>
<p>Here, <code>data</code> refers to the JavaScript object that contains the response data.</p>
<p>REST API responses are generally simpler and more lightweight than SOAP responses, and they are often formatted in either JSON or XML. The use of standard formats makes it easier for clients to parse the response and extract the relevant data.</p>
<p>Additionally, REST APIs often use standard HTTP status codes to indicate the success or failure of a request, which can simplify error handling on the client side.</p>
<p>Overall, REST APIs are a popular and widely used approach to building web APIs due to their simplicity, flexibility, and ease of use.</p>
<h1 id="heading-how-graphql-apis-work">How GraphQL APIs Work</h1>
<p>GraphQL is a query language and runtime for APIs that was developed by Facebook in 2012. It was released to the public in 2015 and has since gained popularity as an alternative to REST APIs.</p>
<p>GraphQL was originally developed by Facebook as a way to simplify data fetching for their mobile applications. They needed a way to make complex data requests from the server without causing performance issues or over-fetching data. GraphQL was born out of the need to solve these problems.</p>
<p>GraphQL was released as an open-source project in 2015 and has since gained popularity in the developer community. It is now supported by many development tools and frameworks, including Apollo, Prisma, and Hasura.</p>
<p><strong>Main Characteristics:</strong></p>
<ol>
<li><p><strong>Strongly Typed:</strong> GraphQL APIs are strongly typed, which means that each field has a specific data type. This makes it easier to validate and handle data on the client and server sides.</p>
</li>
<li><p><strong>Query Language:</strong> GraphQL has its own query language that allows clients to specify exactly what data they need. This reduces over-fetching of data and improves performance.</p>
</li>
<li><p><strong>Single Endpoint:</strong> GraphQL APIs have a single endpoint, which means that clients can fetch all the data they need from a single request.</p>
</li>
<li><p><strong>Declarative:</strong> GraphQL APIs are declarative, which means that clients specify what they want, not how to get it. This allows for more efficient and flexible data fetching.</p>
</li>
<li><p><strong>Schema-Driven:</strong> GraphQL APIs are schema-driven, which means that the schema defines the structure of the data and the available queries and mutations. This makes it easier for developers to understand and work with the API.</p>
</li>
</ol>
<p><strong>Pros:</strong></p>
<ul>
<li><p><strong>Efficient Data Fetching:</strong> GraphQL APIs allow clients to fetch only the data they need, reducing over-fetching and improving performance.</p>
</li>
<li><p><strong>Strongly Typed:</strong> GraphQL APIs are strongly typed, making it easier to validate and handle data.</p>
</li>
<li><p><strong>Single Endpoint:</strong> GraphQL APIs have a single endpoint, reducing the complexity of the API and making it easier to work with.</p>
</li>
<li><p><strong>Schema-Driven:</strong> GraphQL APIs are schema-driven, which makes it easier for developers to understand and work with the API.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p><strong>Complexity:</strong> GraphQL APIs can be more complex to set up and work with compared to REST APIs.</p>
</li>
<li><p><strong>Caching:</strong> Caching can be more challenging with GraphQL APIs due to the flexible nature of the API.</p>
</li>
<li><p><strong>Learning Curve:</strong> GraphQL requires a learning curve for both developers and clients, as it has its own query language and approach to data fetching.</p>
</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li><p><strong>Efficient and flexible needs:</strong> GraphQL is well-suited for building applications that require efficient and flexible data fetching, such as mobile and web applications.</p>
</li>
<li><p><strong>Complex data requirements:</strong> It is particularly useful in situations where there are complex data requirements and where over-fetching data can cause performance issues.</p>
</li>
</ul>
<p>In conclusion, GraphQL is a query language and runtime for APIs that provides efficient and flexible data fetching capabilities.</p>
<p>While it can be more complex to set up and work with compared to REST APIs, it offers benefits such as strongly typed data, single endpoints, and schema-driven development. It is well-suited for building applications with complex data requirements and where efficient data fetching is important.</p>
<h2 id="heading-how-to-consume-a-graphql-api">How to Consume a GraphQL API</h2>
<p>Here's an example of how to make a simple request to retrieve information from a GraphQL API from a JavaScript front-end application, and how to access the values within the response:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.example.com/graphql'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">query</span>: <span class="hljs-string">`
      query {
        user(id: 123) {
          name
          email
          posts {
            title
          }
        }
      }
    `</span>
  })
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data);
  <span class="hljs-comment">// Access the values within the response here</span>
})
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>Here's what each line does:</p>
<ol>
<li><p><code>fetch('https://api.example.com/graphql', { ... })</code> initiates a POST request to the specified GraphQL API endpoint. The second argument to the <code>fetch()</code> function is an options object that specifies the HTTP method, headers, and request body.</p>
</li>
<li><p><code>method: 'POST'</code> specifies that the HTTP method for the request is <code>POST</code>.</p>
</li>
<li><p><code>headers: { 'Content-Type': 'application/json' }</code> specifies the <code>Content-Type</code> header for the request, which is <code>application/json</code> to indicate that the request body is in JSON format.</p>
</li>
<li><p><code>body: JSON.stringify({ ... })</code> specifies the request body as a JSON-encoded string. In this example, the request body is a GraphQL query that retrieves information about a user with the ID <code>123</code>.</p>
</li>
<li><p><code>.then(response =&gt; response.json())</code> converts the response from JSON format to a JavaScript object.</p>
</li>
<li><p><code>.then(data =&gt; { ... })</code> defines a function that will be executed when the response has been successfully converted to a JavaScript object. This function will have access to the JavaScript object containing the response data.</p>
</li>
<li><p><code>console.log(data);</code> logs the response data to the console. You can inspect the response data to determine how to access the values within the response.</p>
</li>
</ol>
<p>To access the values within the response, you can use standard JavaScript object traversal techniques, such as dot notation or bracket notation. For example, if the response from the GraphQL API is in the following format:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"data"</span>: {
    <span class="hljs-string">"user"</span>: {
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"John Doe"</span>,
      <span class="hljs-string">"email"</span>: <span class="hljs-string">"john.doe@example.com"</span>,
      <span class="hljs-string">"posts"</span>: [
        { <span class="hljs-string">"title"</span>: <span class="hljs-string">"Post 1"</span> },
        { <span class="hljs-string">"title"</span>: <span class="hljs-string">"Post 2"</span> }
      ]
    }
  }
}
</code></pre>
<p>You can access the <code>name</code> value using dot or bracket notation like this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(data.data.user.name); <span class="hljs-comment">// output: "John Doe"</span>
<span class="hljs-built_in">console</span>.log(data[<span class="hljs-string">'data'</span>][<span class="hljs-string">'user'</span>][<span class="hljs-string">'name'</span>]); <span class="hljs-comment">// output: "John Doe"</span>
</code></pre>
<p>Here, <code>data</code> refers to the JavaScript object that contains the response data. The response data is wrapped in a <code>data</code> object, and the values can be accessed by traversing the object using dot notation or bracket notation.</p>
<p>GraphQL API responses are typically more focused and specific than REST API responses because the client can specify exactly what data they want to receive. This makes it easier to avoid overfetching or underfetching data, and can improve performance by reducing the amount of data transferred over the network.</p>
<p>Additionally, GraphQL APIs can provide a more flexible schema that can be easily modified over time without breaking existing clients. Overall, GraphQL APIs are a popular choice for building modern web applications due to their flexibility, efficiency, and ease of use.</p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>Well everyone, as always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/giphy.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Rendering Patterns for Web Apps – Server-Side, Client-Side, and SSG Explained ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article we're going to take a look at the different rendering pattern options available nowadays for web applications. I'll start by explaining what a rendering pattern is, then go through each of the main options available. Fina... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rendering-patterns/</link>
                <guid isPermaLink="false">66d45f1dd1ffc3d3eb89ddfa</guid>
                
                    <category>
                        <![CDATA[ Web Applications ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 06 Mar 2023 18:22:40 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/sebastian-svenson-8QgqOLJAL8k-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article we're going to take a look at the different rendering pattern options available nowadays for web applications.</p>
<p>I'll start by explaining what a rendering pattern is, then go through each of the main options available. Finally we'll compare them, explaining the pros and cons and when one might be more beneficial than another.</p>
<p>Let's go!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-whats-a-rendering-pattern">What's a rendering pattern?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-different-rendering-pattern-options">Different rendering pattern options</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-static-websites">Static websites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-single-page-applications-spas-with-client-side-rendering-csr">Single page applications (SPAs) with client side rendering (CSR)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-server-side-rendering-ssr">Server side rendering (SSR)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-static-site-generation-ssg">Static site generation (SSG)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-incremental-static-regeneration-isr">Incremental static regeneration (ISR)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-concept-of-hydration">The concept of hydration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-islands">Islands</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-streaming-ssr">Streaming SSR</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-comparing-the-different-patterns">Comparing the different patterns</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrap-up">Wrap up</a></p>
</li>
</ul>
<h1 id="heading-whats-a-rendering-pattern">What's a Rendering Pattern?</h1>
<p>In web development, a rendering pattern refers to the way in which the HTML, CSS, and JavaScript code is all processed and rendered in a web application or website.</p>
<p>Different rendering patterns are used to achieve different performance and user experience goals. The most common rendering patterns in web development are:</p>
<ol>
<li><p><strong>Server-side rendering (SSR)</strong>: In SSR, the web server generates the HTML content of a web page on the server-side and sends it to the client's browser. This approach can improve initial loading times and SEO (search engine optimization) but can be slower for dynamic content.</p>
</li>
<li><p><strong>Client-side rendering (CSR)</strong>: In CSR, the client's browser generates the HTML content of a web page on the client-side using JavaScript. This approach can provide a fast and interactive user experience but can be slower for initial loading times and bad for SEO.</p>
</li>
<li><p><strong>Static site generation (SSG)</strong>: In SSG, the HTML content of a web page is generated at build time and served to the client as a static file. This approach can provide excellent performance and security but can be less flexible for dynamic content.</p>
</li>
</ol>
<p>In summary, a rendering pattern is a strategy for processing and rendering web content in web development. The choice of rendering pattern depends on the specific needs and requirements of a project, such as performance, SEO, user experience, and flexibility.</p>
<p>Now that we have an idea of what a rendering pattern is, let's examine in detail the many options available nowadays.</p>
<h1 id="heading-different-rendering-pattern-options">Different Rendering Pattern Options</h1>
<h2 id="heading-static-websites">Static Websites</h2>
<p>A static website is a type of website that consists of a set of HTML, CSS, and JavaScript files that are served to the client's browser without any server-side processing or database integration.</p>
<p>Static websites are typically created using static site generators, such as <a target="_blank" href="https://jekyllrb.com/">Jekyll</a>, <a target="_blank" href="https://gohugo.io/">Hugo</a>, or <a target="_blank" href="https://www.gatsbyjs.com/">Gatsby.js</a>. These generators compile templates, markdown files, or other data sources into a set of static files that are then deployed to a web server or <a target="_blank" href="https://www.youtube.com/watch?v=RI9np1LWzqw">content delivery network (CDN)</a>.</p>
<p>Static websites are often used for small to medium-sized websites that do not require complex dynamic features or server-side processing. They are easy to deploy, scale, and maintain, as they do not require a server-side application or database.</p>
<p>They also provide excellent security and performance, as the content is served directly from a web server or CDN without any server-side processing.</p>
<p>Static websites can be enhanced with client-side JavaScript, such as React or Vue, to provide interactive features or dynamic content. But any data that is required for these features must be loaded through client-side API requests, as there is no server-side processing to generate or retrieve the data.</p>
<p>In summary, a static website is a type of website that consists of a set of static files that are served to the client's browser without any server-side processing or database integration. They are simple, fast, secure, and scalable, and are suitable for small to medium-sized websites that do not require complex dynamic features or server-side processing.</p>
<h2 id="heading-single-page-applications-spas-with-client-side-rendering-csr">Single Page Applications (SPAs) with Client Side Rendering (CSR)</h2>
<p>A Single Page Application (SPA) is a type of web application rendered with Client-side rendering (CSR). This means that all necessary HTML, CSS, and JavaScript files are loaded at once when the user first loads the page. Then Javascript dynamically updates the content as the user interacts with the page, without requiring a full page reload.</p>
<p>In an SPA, the client-side JavaScript application is responsible for rendering the HTML and processing the user's interactions. The JavaScript application interacts with a backend API to retrieve data and update the user interface dynamically. Typically, this interaction is achieved using AJAX (Asynchronous JavaScript and XML) requests or Fetch API requests.</p>
<p>SPAs provide a fast and interactive user experience because only the necessary content is loaded and rendered dynamically, reducing the need for full page reloads. They also provide a more fluid user experience because the application can respond to user input without refreshing the entire page.</p>
<p>However, SPAs require a more complex setup and may have longer initial loading times compared to server-side rendering (SSR) or static site generation (SSG) approaches.</p>
<p>They also require additional considerations for search engine optimization (SEO) and accessibility, as search engines and assistive technologies may have difficulty indexing or navigating the content.</p>
<p>In summary, a Single Page Application (SPA) or Client-side rendering (CSR) is a type of web application that loads all necessary HTML, CSS, and JavaScript files at once and then dynamically updates the content as the user interacts with the page, without requiring a full page reload.</p>
<p>They provide a fast and interactive user experience but require a more complex setup and additional considerations for SEO and accessibility.</p>
<h2 id="heading-server-side-rendering-ssr">Server Side Rendering (SSR)</h2>
<p>Server-side rendering (SSR) is a technique for rendering web pages on the server-side before sending them to the client's browser. In SSR, the server generates the HTML content of a web page based on the requested URL and data, and sends it to the client's browser as a complete HTML document.</p>
<p>SSR provides several benefits, including improved performance, better SEO, and more robust accessibility.</p>
<p>By rendering the HTML on the server-side, SSR reduces the amount of JavaScript code that needs to be loaded and executed on the client's browser. This results in faster initial loading times and better performance on low-end devices or slow networks.</p>
<p>Additionally, SSR enables search engines and social media crawlers to index the web pages more accurately, as the complete HTML content is available on the initial page load. This can improve the visibility and ranking of the website in search engine results pages.</p>
<p>SSR also ensures that the web pages are accessible to users with assistive technologies, such as screen readers or keyboard navigation, as the HTML content is available from the initial page load.</p>
<p>However, SSR has some limitations, such as increased server-side processing requirements and limited interactivity compared to client-side rendering (CSR) or single-page applications (SPAs).</p>
<p>In summary, Server-side rendering (SSR) is a technique for rendering web pages on the server-side before sending them to the client's browser. It provides improved performance, better SEO, and more robust accessibility, but requires more server-side processing and has some limitations in interactivity.</p>
<h2 id="heading-static-site-generation-ssg">Static Site Generation (SSG)</h2>
<p>Static site generation (SSG) is a technique for building web pages by pre-generating HTML, CSS, and JavaScript files at build time instead of rendering them on the server or client-side.</p>
<p>In SSG, a static site generator tool like Jekyll, Hugo, or Gatsby.js is used to compile the website's content from data sources such as markdown files, JSON files, or <a target="_blank" href="https://www.youtube.com/watch?v=nrbpOmNC_mM">CMS</a> data, and generate a set of static files that can be served directly to the browser without any server-side processing.</p>
<p>The generated static files can be deployed on a web server or a content delivery network (CDN) and served quickly to the end-users with low latency. SSG offers several benefits such as fast loading times, improved security, and scalability.</p>
<p>Since SSG renders web pages at build time, there is no need to generate pages dynamically on the server or client-side. This reduces the processing overhead and enables faster loading times.</p>
<p>Static sites are also less vulnerable to server-side attacks and require fewer server resources, making them more scalable and easier to maintain.</p>
<p>But SSG has some limitations in terms of dynamic content and interactivity. Since the content is generated at build time, any dynamic data or user interactions need to be handled by client-side JavaScript code or serverless functions.</p>
<p>In summary, Static Site Generation (SSG) is a technique for building web pages by pre-generating HTML, CSS, and JavaScript files at build time instead of rendering them on the server or client-side. It offers several benefits such as fast loading times, improved security, and scalability, but has some limitations in terms of dynamic content and interactivity.</p>
<h2 id="heading-incremental-static-regeneration-isr">Incremental Static Regeneration (ISR)</h2>
<p>Incremental Static Regeneration (ISR) is a technique for building static sites that combines the benefits of both Server-Side Rendering (SSR) and Static Site Generation (SSG).</p>
<p>In ISR, the static site generator tool pre-generates a set of static pages at build time, but also includes additional metadata that enables the pages to be re-generated dynamically on the server-side when requested by the user. This metadata could include information such as expiration times or dependencies on specific data sources.</p>
<p>When a user requests a page that has expired or has dependencies that have changed, the server-side logic can regenerate the page with the updated content and serve it to the user, without requiring a full rebuild of the site.</p>
<p>This enables the site to maintain the benefits of static site generation, such as fast load times and low server processing overhead, while also allowing for dynamic content and personalized experiences for users.</p>
<p>ISR is particularly useful for sites that have content that changes frequently or for sites with a large number of pages that would be inefficient to rebuild in their entirety each time a change is made.</p>
<p>It allows for the best of both worlds: the performance and security benefits of static sites combined with the flexibility and personalization of server-side rendering.</p>
<p>In summary, Incremental Static Regeneration (ISR) is a technique for building static sites that combines the benefits of both Server-Side Rendering (SSR) and Static Site Generation (SSG). It allows for dynamic content and personalized experiences for users while maintaining the performance and security benefits of static sites.</p>
<h2 id="heading-the-concept-of-hydration">The Concept of Hydration</h2>
<p>In web development, "hydration" refers to the process of taking an HTML document that was initially rendered on the server and adding dynamic interactivity to it on the client-side.</p>
<p>Hydration is commonly used in Single-Page Applications (SPAs) that use client-side rendering (CSR).</p>
<p>During hydration, the browser parses the HTML document generated by the server and constructs a Document Object Model (DOM) tree, which represents the page's structure and content.</p>
<p>The browser then executes the JavaScript code that is responsible for adding dynamic behavior to the page, such as event handling, data fetching, and component rendering.</p>
<p>The JavaScript code retrieves the initial state and props of the components from the server-generated HTML and uses them to rehydrate the components on the client-side, effectively turning them into interactive elements.</p>
<p>This process ensures that the initial state of the page on the client-side matches the server-generated HTML and provides a seamless transition from the initial server-rendered view to the interactive client-side view.</p>
<p>Hydration is important for several reasons. First, it provides better performance and user experience by minimizing the time to interactive and enabling the user to interact with the page immediately.</p>
<p>Second, it enables search engine crawlers to access the page's content and metadata, improving SEO.</p>
<p>Finally, it ensures that the content is accessible and usable even if JavaScript is disabled in the user's browser.</p>
<p>In summary, hydration is the process of taking an HTML document that was initially rendered on the server and adding dynamic interactivity to it on the client-side.</p>
<p>It is commonly used in Single-Page Applications (SPAs) that use client-side rendering (CSR) and provides better performance, SEO, and accessibility.</p>
<h2 id="heading-islands">Islands</h2>
<p>The Islands pattern is a web development technique that involves breaking down a large, complex web page into smaller, self-contained components, each with its own HTML, CSS, and JavaScript code.</p>
<p>Each component is rendered independently on the server and is then rehydrated on the client-side, allowing it to become interactive.</p>
<p>The term "islands" refers to the individual components, each of which represents a separate island of content and functionality within the larger page.</p>
<p>By breaking the page into smaller islands, each with its own state and behavior, the application becomes more modular, easier to reason about and maintain, and can provide a more seamless user experience.</p>
<p>The Islands pattern is closely related to the concept of hydration because it relies on the same basic principle: rendering static HTML on the server and then hydrating it on the client-side with JavaScript to add interactivity.</p>
<p>In this case, each individual island is rendered on the server with its own static HTML, which is then hydrated on the client-side to enable dynamic functionality.</p>
<p>Hydration in the Islands pattern typically involves using a client-side framework or library to attach event handlers, manage state, and render dynamic content within each component. The framework or library must be capable of rehydrating the component on the client-side, ensuring that the initial state and behavior of the component matches that of the server-rendered HTML.</p>
<p>One benefit of using the Islands pattern with hydration is that it can improve the performance of large, complex web applications by reducing the amount of JavaScript that needs to be downloaded and executed on the client-side. By rendering each component independently on the server and rehydrating it on the client-side, the application can provide a more seamless user experience without sacrificing performance or scalability.</p>
<p>In summary, the Islands pattern is a web development technique that involves breaking down a large, complex web page into smaller, self-contained components, each with its own HTML, CSS, and JavaScript code. It relies on the same principle of hydration as other rendering patterns, rendering static HTML on the server and then adding interactivity with JavaScript on the client-side.</p>
<p>The Islands pattern can improve the performance and scalability of large web applications by reducing the amount of JavaScript that needs to be downloaded and executed on the client-side.</p>
<h2 id="heading-streaming-ssr">Streaming SSR</h2>
<p>Streaming Server-Side Rendering (SSR) is a rendering pattern for web development that involves sending the server-generated HTML to the client as soon as it becomes available, rather than waiting for the entire page to be rendered before sending it.</p>
<p>With traditional SSR, the server would wait for the entire page to be rendered before sending it to the client, resulting in a longer time to first byte (TTFB) and a slower user experience.</p>
<p>Streaming SSR allows the server to send the HTML to the client in chunks as it is generated, providing a faster TTFB and a more responsive user experience.</p>
<p>Streaming SSR is particularly useful for rendering large or complex web pages that take a long time to render, such as e-commerce product pages or news articles.</p>
<p>With streaming SSR, the user can start interacting with the page as soon as the first chunk of HTML is received, without having to wait for the entire page to be rendered.</p>
<p>To implement streaming SSR, the server must use a technique called "chunking" to break the server-generated HTML into smaller chunks and send them to the client as they become available. The client then uses JavaScript to append each chunk of HTML to the page as it is received, effectively streaming the content to the user.</p>
<p>One challenge with streaming SSR is ensuring that the chunks of HTML are sent to the client in the correct order and that the page remains coherent as it is rendered.</p>
<p>To address this, developers may use techniques such as critical CSS, which involves identifying and rendering the most important styles first, or template-based chunking, which involves breaking the HTML into smaller chunks based on templates or components.</p>
<p>In summary, Streaming Server-Side Rendering (SSR) is a rendering pattern for web development that involves sending the server-generated HTML to the client in chunks as it is generated, providing a faster TTFB and a more responsive user experience. It is particularly useful for rendering large or complex web pages.</p>
<p>To implement streaming SSR, the server must use a technique called "chunking" to break the HTML into smaller chunks, and the client must use JavaScript to append each chunk to the page as it is received.</p>
<h1 id="heading-comparing-the-different-patterns">Comparing the Different Patterns</h1>
<p>Awesome, so now we have a clear idea of each of the common options available. Let's now quickly go through the main characteristics of each pattern and mention the situations in which each of them might be more beneficial.</p>
<h3 id="heading-static-websites-1">Static Websites</h3>
<p><strong>Main characteristics:</strong></p>
<ul>
<li><p>Pre-built HTML, CSS, and JavaScript files that are served to the client as-is.</p>
</li>
<li><p>No dynamic content, as all content is pre-rendered and does not change.</p>
</li>
<li><p>Fast load times due to the lack of server processing.</p>
</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Extremely fast load times and low server costs.</p>
</li>
<li><p>Great for sites with little to no dynamic content, such as portfolios or blogs.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Limited interactivity and functionality, as all content is pre-rendered.</p>
</li>
<li><p>Not suitable for sites that require dynamic content or user input.</p>
</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li>Sites with limited dynamic content or sites that do not require dynamic functionality.</li>
</ul>
<h3 id="heading-single-page-applications-spas">Single Page Applications (SPAs)</h3>
<p><strong>Main characteristics:</strong></p>
<ul>
<li><p>All content is dynamically rendered client-side through JavaScript.</p>
</li>
<li><p>Only a single page is loaded, with content updates handled by JavaScript.</p>
</li>
<li><p>Dynamic content can be easily added through APIs.</p>
</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p>High interactivity and functionality, as all content is dynamic and can be updated without refreshing the page.</p>
</li>
<li><p>Ideal for complex, data-driven applications that require frequent content updates.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Slower initial load times due to the need to load JavaScript and dynamically render content.</p>
</li>
<li><p>Can be difficult to implement proper SEO techniques due to the lack of pre-rendered content.</p>
</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li>Applications that require complex interactivity or frequent content updates.</li>
</ul>
<h3 id="heading-server-side-rendering-ssr-1">Server Side Rendering (SSR):</h3>
<p><strong>Main characteristics:</strong></p>
<ul>
<li><p>Server Side Rendering (SSR) is a process in which web pages are generated on the server and sent to the client as fully rendered HTML.</p>
</li>
<li><p>The server sends a complete HTML response to the client, which includes all the dynamic content, after processing the data on the server.</p>
</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Improved SEO because search engine crawlers can easily parse the complete HTML content.</p>
</li>
<li><p>Better performance because the initial HTML is sent in a single response, which reduces the time for the browser to load and display the content.</p>
</li>
<li><p>Works well for content-rich applications or dynamic web applications that require data to be fetched from APIs.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Higher server overhead because every request is processed on the server.</p>
</li>
<li><p>More complex to set up because it requires a server-side framework that supports SSR.</p>
</li>
<li><p>Less interactive because interactions require additional server requests.</p>
</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li><p>Applications with content that changes frequently.</p>
</li>
<li><p>Applications with dynamic data that needs to be processed on the server before sending the response.</p>
</li>
</ul>
<h3 id="heading-static-site-generation-ssg-1">Static Site Generation (SSG):</h3>
<p><strong>Main characteristics:</strong></p>
<ul>
<li><p>Static Site Generation (SSG) is a process in which web pages are pre-built as static files during the build process and served to the client as static HTML pages.</p>
</li>
<li><p>The server sends static HTML pages to the client, which includes all the content, without processing any data on the server.</p>
</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Very fast and efficient because static pages can be served from a CDN or cache.</p>
</li>
<li><p>Lower server overhead because the server only needs to serve static files.</p>
</li>
<li><p>Can be deployed on a static file host or serverless environments like AWS Lambda.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Not suitable for dynamic content that changes frequently.</p>
</li>
<li><p>Interactions require additional client-side JavaScript.</p>
</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li><p>Applications with mostly static content and few interactions.</p>
</li>
<li><p>Applications with limited interactivity.</p>
</li>
</ul>
<h3 id="heading-incremental-static-regeneration-isr-1">Incremental Static Regeneration (ISR):</h3>
<p><strong>Main characteristics:</strong></p>
<ul>
<li>Incremental Static Regeneration (ISR) is a hybrid approach between SSG and SSR, where pages are pre-rendered as static HTML pages during the build process, and then the content is regenerated periodically or on-demand as required.</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Faster time-to-content because static pages are served initially, but content can be updated quickly.</p>
</li>
<li><p>Lower server overhead because static pages can be served from a CDN or cache, and dynamic content is regenerated only when required.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Limited dynamic content because content regeneration requires a server request.</p>
</li>
<li><p>Requires a complex caching strategy to ensure that stale content is not served to clients.</p>
</li>
</ul>
<p><strong>Situations:</strong></p>
<ul>
<li><p>Applications with content that changes frequently but can tolerate some latency.</p>
</li>
<li><p>Applications with limited dynamic content.</p>
</li>
</ul>
<h3 id="heading-islands-1">Islands:</h3>
<p><strong>Main Characteristics:</strong></p>
<ul>
<li><p>The Island rendering pattern refers to rendering parts of the page on the server while other parts are rendered on the client-side.</p>
</li>
<li><p>The server renders the critical content, while the client fetches the rest of the content.</p>
</li>
<li><p>The server-side rendering can improve the initial page load speed and improve SEO.</p>
</li>
<li><p>The client-side rendering can improve the interactivity and reduce server overhead.</p>
</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Faster page load times because the server renders critical content while the client fetches the rest.</p>
</li>
<li><p>Works well for applications that require partial server-side rendering and partial client-side rendering.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>More complex to set up because it requires a hybrid framework that can support both server-side and client-side rendering.</p>
</li>
<li><p>May result in inconsistencies if the server and client render different versions of the content.</p>
</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li><p>Applications with dynamic content that require some server-side processing.</p>
</li>
<li><p>Applications that require a fast initial page load.</p>
</li>
</ul>
<h3 id="heading-streaming-ssr-1">Streaming SSR:</h3>
<p><strong>Main Characteristics:</strong></p>
<ul>
<li><p>The server sends the HTML response in a streaming fashion, which enables the client to start rendering the content as soon as possible.</p>
</li>
<li><p>The client can see content being rendered progressively, which improves the user experience.</p>
</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Improved time-to-content because the client can start rendering the content while the server is still processing the request.</p>
</li>
<li><p>Better user experience because the client can see content being rendered progressively.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>More complex to set up because it requires a server framework that supports streaming.</li>
</ul>
<p><strong>Best for:</strong></p>
<ul>
<li><p>Applications with large pages or media that require a long time to load.</p>
</li>
<li><p>Applications that require a smooth user experience with minimal waiting time.</p>
</li>
</ul>
<h1 id="heading-wrap-up">Wrap up</h1>
<p>Well everyone, as always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/out-disappear.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
