<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joseph Ayobami on Medium]]></title>
        <description><![CDATA[Stories by Joseph Ayobami on Medium]]></description>
        <link>https://medium.com/@mayorscript?source=rss-c8014bf82d7d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-wlW5GeiCpIi3LD02RGzmw.jpeg</url>
            <title>Stories by Joseph Ayobami on Medium</title>
            <link>https://medium.com/@mayorscript?source=rss-c8014bf82d7d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 22 May 2026 02:11:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mayorscript/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Data Structure And Algorithm: Binary Search — Strategies for Solving Complex Problems]]></title>
            <link>https://mayorscript.medium.com/data-structure-and-algorithm-binary-search-strategies-for-solving-complex-problems-3ad80b714dc6?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ad80b714dc6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Sat, 18 May 2024 16:49:06 GMT</pubDate>
            <atom:updated>2024-05-30T15:50:14.330Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Structure And Algorithm: Binary Search — Strategies for Solving Complex Problems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*8PZpnUCQkeXgoAxo.png" /></figure><p>Binary search is a fundamental algorithm used in computer science to efficiently search for a specific value in a sorted dataset. It follows the divide-and-conquer approach, which means it repeatedly divides the dataset in half until the desired value is found or determined to be absent. This algorithm is of great importance in computer science as it provides a fast and efficient way to search for data, especially in large datasets.</p><h3>Key Takeaways</h3><ul><li>Binary search is a powerful algorithm for solving complex problems.</li><li>It works by dividing a sorted array in half and eliminating half of the remaining elements with each iteration.</li><li>Binary search has several advantages over other search algorithms, including faster performance and lower memory usage.</li><li>It is commonly used in a variety of applications, including search engines, databases, and scientific simulations.</li><li>To implement binary search in code, you need to understand the basic algorithm and follow best practices for optimization and error handling.</li></ul><h3>Understanding the Binary Search Algorithm</h3><p>To understand how binary search works, let’s go through the step-by-step process. First, we start with a sorted dataset and define the lower and upper bounds of the search range. Then, we calculate the middle element of the range and compare it with the target value we are searching for. If the middle element is equal to the target value, we have found our desired value and the search ends. If the middle element is greater than the target value, we update the upper bound to be one less than the middle index. Conversely, if the middle element is less than the target value, we update the lower bound to be one more than the middle index. We repeat this process until either the target value is found or the lower bound becomes greater than the upper bound.</p><p>Let’s consider an example to illustrate binary search in action. Suppose we have a sorted array [1, 3, 5, 7, 9, 11] and we want to find the index of value 7. We start with a lower bound of 0 and an upper bound of 5. The middle index is calculated as (0 + 5) / 2 = 2. Since the middle element is 5, which is less than 7, we update the lower bound to be one more than the middle index (3). Now our new range is [7, 9, 11]. We repeat this process until we find the target value or determine it is not present. In this case, the next middle index is 4, and the middle element is 9. Since 9 is greater than 7, we update the upper bound to be one less than the middle index (3). Now our new range is [7]. The final middle index is 3, and the middle element is 7, which is equal to our target value. Therefore, the index of value 7 in the array is 3.</p><h3>Advantages of Binary Search</h3><p>One of the main advantages of binary search is its efficiency compared to other search algorithms. Binary search has a time complexity of O(log n), where n is the size of the dataset. This means that as the dataset grows larger, the time taken to perform a binary search increases at a much slower rate compared to linear search algorithms. For example, if we have a dataset with one million elements, binary search would require at most 20 comparisons to find the desired value, while linear search would require up to one million comparisons.</p><p>Another advantage of binary search is its ability to quickly search sorted data. Since binary search relies on dividing the dataset in half at each step, it can quickly narrow down the search range and eliminate large portions of the dataset. This makes binary search particularly useful when dealing with large datasets or when searching for values in real-time applications where speed is crucial.</p><h3>Common Applications of Binary Search</h3><p>Binary search has numerous applications in various fields. One common application is searching for a specific value in a large dataset. For example, in a database containing millions of records, binary search can efficiently locate a specific record based on a unique identifier such as an ID number.</p><p>Another application of binary search is finding the closest match to a given value. This can be useful in scenarios such as searching for the nearest location based on geographical coordinates or finding the closest match to a user’s input in a recommendation system.</p><p>Binary search is also commonly used in implementing autocomplete functionality. As a user types in a search query, binary search can quickly narrow down the possible suggestions based on the partially entered text, providing real-time suggestions that match the user’s input.</p><h3>How to Implement Binary Search in Code</h3><p>Implementing binary search in code is relatively straightforward. Here is a sample code snippet in Python:</p><pre>def binary_search(arr, target):<br>  low = 0<br>  high = len(arr) - 1<br>  while low &lt;= high:<br>    mid = (low + high) // 2<br>    if arr[mid] == target:<br>      return mid<br>    elif arr[mid] &lt; target:<br>      low = mid + 1<br>    else:<br>      high = mid - 1<br>  return -1</pre><p>In this code, we define the lower bound (`low`) and upper bound (`high`) of the search range. We then enter a while loop that continues until the lower bound becomes greater than the upper bound. Inside the loop, we calculate the middle index (`mid`) using integer division. We compare the middle element with the target value and update the lower or upper bound accordingly. If the target value is found, we return the index. If the loop ends without finding the target value, we return -1 to indicate that it is not present in the dataset.</p><h3>Binary Search vs. Linear Search: Which is Better?</h3><p>When comparing binary search and linear search algorithms, it is important to consider their advantages and disadvantages. Binary search has a time complexity of O(log n), making it significantly faster than linear search algorithms, which have a time complexity of O(n). This means that as the dataset grows larger, binary search outperforms linear search by a wide margin.</p><p>However, binary search requires the dataset to be sorted beforehand, which can be a disadvantage in certain scenarios. If the dataset is frequently updated or modified, maintaining the sorted order can be time-consuming and may negate the benefits of binary search. In contrast, linear search does not require any specific order of the dataset and can be performed on unsorted data.</p><p>Another factor to consider is the memory usage. Binary search requires less memory compared to linear search, as it only needs to store the lower and upper bounds and a few variables for indexing. Linear search, on the other hand, needs to iterate through the entire dataset, which can be memory-intensive for large datasets.</p><p>In conclusion, binary search is generally more efficient than linear search for searching sorted data, especially in large datasets. However, the choice between the two algorithms depends on the specific requirements of the application and the characteristics of the dataset.</p><h3>Tips for Optimizing Binary Search Performance</h3><p>While binary search is already an efficient algorithm, there are several tips and techniques that can further optimize its performance:</p><p>1. Ensure the dataset is sorted: Binary search relies on a sorted dataset, so it is crucial to ensure that the data is properly sorted before performing a binary search. Sorting algorithms such as quicksort or mergesort can be used to achieve this.</p><p>2. Use appropriate data structures: Choosing the right data structure can significantly improve binary search performance. For example, using an array instead of a linked list can provide better cache locality and reduce memory access time.</p><p>3. Handle edge cases: It is important to handle edge cases such as empty datasets or datasets with only one element separately to avoid unnecessary iterations and improve efficiency.</p><p>4. Avoid unnecessary calculations: Minimize unnecessary calculations inside the loop to reduce computational overhead. For example, calculate `mid` outside the loop if it remains constant throughout the search.</p><p>5. Take advantage of language-specific optimizations: Different programming languages have their own optimizations for binary search. For instance, in C++, using `std::lower_bound` or `std::upper_bound` functions can provide a more efficient implementation.</p><h3>Common Mistakes to Avoid in Binary Search</h3><p>Implementing binary search correctly can be challenging, and there are several common mistakes to avoid:</p><p>1. Incorrectly updating the lower and upper bounds: It is crucial to update the lower and upper bounds correctly based on the comparison with the middle element. Failing to do so can result in an infinite loop or incorrect search results.</p><p>2. Not handling the case when the target value is not found: It is important to handle the case when the target value is not present in the dataset. Returning an appropriate value, such as -1, can indicate that the value was not found.</p><p>3. Not considering the mid element in the search: Failing to consider the middle element during the search can lead to incorrect results. The middle element should always be compared with the target value to determine whether it is equal, greater, or smaller.</p><p>4. Not sorting the dataset before performing binary search: Binary search requires a sorted dataset, so forgetting to sort it beforehand will lead to incorrect results.</p><p>5. Not considering overflow or underflow: When calculating the middle index, it is important to handle potential overflow or underflow issues that may occur with large datasets or extreme values.</p><p>By being aware of these common mistakes and taking precautions to avoid them, you can ensure a correct and efficient implementation of binary search.</p><h3>Variations of Binary Search: Interpolation Search and Exponential Search</h3><p>While binary search is a widely used algorithm, there are variations that offer different trade-offs in terms of performance and complexity. Two notable variations are interpolation search and exponential search.</p><p>Interpolation search improves upon binary search by estimating the position of the target value based on its value and the values at the ends of the dataset. Instead of always dividing the dataset in half, interpolation search calculates an approximate position for the target value and adjusts the search range accordingly. This can result in faster convergence to the target value, especially when the dataset is uniformly distributed. However, interpolation search requires a sorted dataset and may perform poorly on datasets with unevenly distributed values.</p><p>Exponential search, on the other hand, combines elements of both linear and binary search. It starts with a small range at the beginning of the dataset and exponentially increases the range until it encompasses the target value. Once the range is determined, binary search is performed within that range. Exponential search can be useful when the target value is likely to be found near the beginning of the dataset, as it reduces the number of iterations required compared to a full binary search. However, exponential search also requires a sorted dataset.</p><h3>Real-World Examples of Binary Search in Action</h3><p>Binary search finds applications in various industries and applications. Here are a few real-world examples:</p><p>1. Database systems: Binary search is commonly used in database systems to efficiently locate records based on unique identifiers or indexed values. This allows for fast retrieval of data from large databases.</p><p>2. Geographic information systems: Binary search is used in geographic information systems to find locations based on geographical coordinates. By indexing and sorting location data, binary search can quickly identify the nearest locations to a given point.</p><p>3. Spell checkers: Spell checkers often use binary search to suggest corrections for misspelled words. By maintaining a sorted dictionary, binary search can quickly identify similar words and provide suggestions based on their similarity to the misspelled word.</p><p>4. Financial applications: Binary search is used in financial applications to perform efficient searches on large datasets of stock prices or financial records. This allows for quick analysis and decision-making based on historical data.</p><h3>Mastering the Art of Binary Search</h3><p>In conclusion, binary search is a powerful algorithm that plays a crucial role in computer science and various real-world applications. Its efficiency, ability to search sorted data quickly, and versatility make it an essential tool for computer science professionals.</p><p>By understanding the step-by-step process of binary search, its advantages over other search algorithms, and its common applications, you can leverage this algorithm to solve complex problems efficiently. Implementing binary search correctly, avoiding common mistakes, and optimizing its performance using best practices will further enhance your skills in this area.</p><p>As you continue your journey in computer science, mastering binary search will provide you with a valuable skill set that can be applied in a wide range of domains. So keep learning, practicing, and exploring the possibilities of binary search to become a proficient problem solver and contribute to the advancement of computer science.</p><p>#DataStructures #Algorithms #Coding #Programming #ComputerScience #TechTalk #Python</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ad80b714dc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Startup Nuggets]]></title>
            <link>https://mayorscript.medium.com/startup-nuggets-8c6428790598?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c6428790598</guid>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 06:04:13 GMT</pubDate>
            <atom:updated>2024-01-17T06:04:13.985Z</atom:updated>
            <content:encoded><![CDATA[<h2>Just as there is a law of conservation of energy in physics, which states that energy is never created or destroyed but just repurposed into different forms, there is also a law of conservation with ideas: all new ideas are just the result of combining existing ideas 💡</h2><p>#startup #startuptips #startupgrowth</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c6428790598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is AWS Lambda?]]></title>
            <link>https://aws.plainenglish.io/what-is-aws-lambda-e97062d09bbb?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e97062d09bbb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 17:56:11 GMT</pubDate>
            <atom:updated>2023-07-10T01:03:37.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*eJ3hWEZZXFMwe8sX.png" /></figure><p><a href="https://aws.amazon.com/lambda/">AWS Lambda</a> is a serverless compute service provided by Amazon Web Services (AWS). It allows you to run your code without provisioning or managing servers, paying only for the compute time consumed by your application. Lambda is a fundamental building block of serverless application development, providing a scalable and event-driven architecture.</p><blockquote>Using AWS Lambda is like having a magical genie for your code. It’s like saying, ‘Poof!’ and your servers disappear, leaving you with more time to ponder life’s important questions, like why don’t ducks wear sandals? Lambda lets you focus on the fun part of coding, while AWS handles all the server sorcery behind the scenes. It’s serverless computing that’s so funny, even the laughing gas is jealous!</blockquote><p>Here are some key aspects and the role of <a href="https://aws.amazon.com/lambda/">AWS Lambda</a> in serverless application development:</p><ol><li>Event-driven computing: Lambda is designed to respond to events. An event can be a request from an API Gateway, changes to data in an Amazon S3 bucket, updates to a DynamoDB table, or any other event source supported by Lambda. When an event occurs, Lambda automatically runs your code in response, allowing you to build reactive applications that respond to real-time events.</li><li>No infrastructure management: With AWS Lambda, you don’t need to worry about server provisioning, capacity planning, or infrastructure management. AWS handles all the underlying infrastructure, including server maintenance, scaling, and availability. You can focus solely on writing your application code.</li><li>Pay-per-use pricing model: Lambda follows a pay-per-use pricing model, where you are billed only for the compute time consumed by your code. You don’t have to pay for idle time or overprovisioning. This makes Lambda cost-efficient and highly scalable, as it automatically scales based on the incoming workload.</li><li>Support for multiple programming languages: Lambda supports multiple programming languages, including Node.js, Python, Java, Ruby, C#, PowerShell, and Go. You can choose the language that best fits your application and development preferences.</li><li>Integration with other AWS services: Lambda seamlessly integrates with various AWS services, allowing you to build serverless applications that leverage the rich set of AWS offerings. You can easily connect Lambda functions with services like API Gateway, DynamoDB, S3, SNS (Simple Notification Service), SQS (Simple Queue Service), and more.</li><li>Automatic scaling: Lambda automatically scales your functions in response to incoming request traffic. It provisions the necessary resources to handle concurrent executions and scales down to zero when there is no traffic. This elastic scaling capability ensures that your application can handle any level of traffic without worrying about capacity planning or manual scaling.</li><li>Event-driven microservices architecture: AWS Lambda is a key component in building event-driven microservices architectures. You can break down your application into smaller, independent functions and trigger them based on specific events. Each Lambda function performs a specific task and can be managed and developed independently. This enables modularity, flexibility, and easy maintenance of your serverless applications.</li></ol><p>Overall, AWS Lambda simplifies the development and deployment of serverless applications by abstracting away the underlying infrastructure management. It provides a scalable and cost-effective solution for building event-driven, highly responsive applications that can integrate with various AWS services. With Lambda, developers can focus on writing business logic and delivering value, while AWS takes care of the operational aspects of running and scaling the code.</p><p>Ready to level up your development skills? Learn the secrets of Serverless architecture and how to implement it in real projects. Join me for a step-by-step tutorial that will demystify the process. Get ready to take your projects to new heights with Serverless. Check out this article and let’s dive into the world of Serverless together!</p><p>Hey Ninja, kindly follow to stay updated on my latest tutorials.</p><p>Cheers! 🥷🏻</p><p>#aws #serverless #awslamda</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e97062d09bbb" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/what-is-aws-lambda-e97062d09bbb">What is AWS Lambda?</a> was originally published in <a href="https://aws.plainenglish.io">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to connect your domain from Namecheap to Amazon Route 53]]></title>
            <link>https://aws.plainenglish.io/how-to-connect-your-domain-from-namecheap-to-amazon-route-53-840bc745ce67?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/840bc745ce67</guid>
            <category><![CDATA[route-53]]></category>
            <category><![CDATA[namecheap]]></category>
            <category><![CDATA[domain-hosting]]></category>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[aws-route53]]></category>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 01:22:20 GMT</pubDate>
            <atom:updated>2024-09-23T14:46:30.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Connect Your Domain From Namecheap to Amazon Route 53</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*yCkcYyyG7clQ8Ro7.jpg" /></figure><blockquote>Do You Know — No one wants a Domain with their name on it owned by somebody else <em>💡</em></blockquote><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><p>So you just bought a domain name on <a href="http://namecheap.com">Namecheap</a> and you’ve been wondering how on earth would you be able to host it on <a href="http://aws.amazon.com">Amazon</a>, then this tutorial is for you.</p><p><strong>What the heck is Route 53?</strong></p><blockquote><strong>Amazon Route 53</strong> is a highly accessible and scalable Domain Name System service. Domain registration, DNS routing, and h=Health testing are the three major functions that you can execute using Route 53 in any order. You must choose a name for your website, such <strong>example.com</strong>. You can register a domain name, also referred to as a name for your website or web application, on Route 53. The purpose of Route 53 is to manage DNS for devices and services placed on Amazon’s public cloud.</blockquote><p>Now that you know what Route 53 does, you might be having questions like:</p><p><strong>Why Should I choose Route 53 as my hosting provider?</strong></p><p>Well, maybe you have to read the above definition of Route 53 again 🤓.</p><p>Now let’s cut to the chase…</p><h4>How to connect my domain to Route 53?</h4><p>Firstly, you have to purchase a domain name on Namecheap.</p><blockquote>FYI — Namecheap is one of the best domain provider out there. The prices are flexible and their services are quite good.</blockquote><p>This tutorial won’t be showing you how to purchase a domain name. Our focus is to connect an existing domain to Route 53. Once you have purchased a domain, sign in to your namecheap account and click on <strong><em>Domain List</em></strong> on the left sidebar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eh9D7MVGLShU4CYvRk5iRQ.png" /></figure><p>Here, you’ll see the list of domains you’ve purchased so far.</p><p><em>You’d noticed I had to blur all my domains.. I don’t want to be hacked …hahah</em></p><p>Click on <strong><em>Manage.</em></strong></p><p>On the screen below, select <strong><em>Custom DNS:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaO0o6EurblAiKpPhON8mg.png" /></figure><p>Now, sign in to your AWS account, on the search bar, search for Route 53.</p><p>On the next page, click on <strong><em>Hosted Zone:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7-VCmTtGSjjc_7PmO7nFQ.png" /></figure><p>Click on <strong><em>Create hosted zone:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3T_8FoFlZ7N1pmsDopEUQ.png" /></figure><p>In the next page, enter your domain name in the input box and click on <strong><em>Create hosted zone:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7fqsUxhwWII_LDFZyW_Ww.png" /></figure><p>Wait for some seconds. Once it’s created, in the page that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A72vp3otc-JOSXj1X8880g.png" /></figure><p>Copy the NS records, go back to Namecheap and enter the NS records in the Nameserver input field in order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oA611kSvrrzlcl1_5HloA.png" /></figure><p>Click the green checkmark to save it.</p><p>Viola!! You have successfully connected your Namecheap Domain to Route 53.</p><p>You can go further to create several records like the A, TXT, etc on Route 53.</p><p>Cheers!</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=840bc745ce67" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/how-to-connect-your-domain-from-namecheap-to-amazon-route-53-840bc745ce67">How to connect your domain from Namecheap to Amazon Route 53</a> was originally published in <a href="https://aws.plainenglish.io">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Next.js Application on Amazon Amplify Service]]></title>
            <link>https://aws.plainenglish.io/deploy-a-next-js-application-on-amazon-amplify-service-d8ff0102ee85?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ff0102ee85</guid>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 00:11:58 GMT</pubDate>
            <atom:updated>2023-01-31T02:49:18.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oBs4NdfDbb1qGUkU" /></figure><h4>Introduction</h4><p>Next.js is a flexible <strong>React framework</strong> that gives you building blocks to create fast <strong>web applications. </strong>Source — <a href="https://nextjs.org/learn/foundations/about-nextjs/what-is-nextjs">Next Js</a></p><p>Since this tutorial isn’t an introduction to Next js, i wouldn’t go into much details on Next Js. You can read more <a href="https://nextjs.org/">here</a>.</p><p>I believe you already have some knowledge on Next Js, and you’re trying to deploy your application to Amazon Amplify.</p><h4><strong>Amplify</strong></h4><p>Frontend web and mobile developers can quickly create, launch, and host full-stack applications on AWS with the help of AWS Amplify. It’s a comprehensive solution that gives developers the freedom to take advantage of the breadth of AWS services as use cases change. Cloud knowledge is not required.</p><h4>Prerequisite</h4><ul><li>Have a basic knowledge on Next Js, CLI and Git.</li><li>Have an AWS account. You can create an account <a href="https://aws.amazon.com/">here</a> if you don’t have one.</li><li>Have Node and NPM installed. You can install from <a href="https://nodejs.org/en/">here</a>.</li><li>Have Git installed on your computer.</li><li>Your prefered code editor.</li></ul><h4><strong>Setup a basic Next Js Application</strong></h4><p>We need to have a next js application running.</p><p>First, let’s create a new next js application. Go over to the terminal and enter the commands below:</p><blockquote><strong>Note:</strong> I’m using Yarn package manager in this tutorial. You can subsitute it with <em>pnpm</em> or <em>npx.</em></blockquote><pre>yarn create next-app</pre><p>Enter your project name and follow the prompt. You have options to choose if you want to use TypeScript and EsLint with your application. After the installation is complete, run the command below to run the app on your local environment:</p><pre>yarn run dev</pre><p>Open uphttp://localhost:3000 to view your application in your browser.</p><p>You should see this screen below, if you’ve installed everything correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umW7uyHoui7B6zF0cTpm5Q.png" /></figure><h4>Deploy to Github</h4><p>Sign in to your github account and create an empty repository.</p><p>On your terminal, add the following commands to push our sample code to the created repo:</p><pre>git add remote origin &lt;YOUR_GITHUB_URL_&gt;<br>git remote set-url origin &lt;YOUR_GITHUB_URL_&gt;<br>git push origin main</pre><p>Once you have pushed the code to your repo. Then we can proceed to deploying to amplify.</p><h4><strong>Amplify</strong></h4><p>Sign in to your AWS account.</p><p>In the search bar, search for <strong><em>Amplify</em></strong> and click on<strong> <em>AWS Amplify.</em></strong></p><p>You should see something like this in the next page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53WpJagiGp3zF_i5hSO4JA.png" /></figure><p>Once you click on <strong><em>Get Started</em></strong><em>.</em></p><p>As i have explained initially, amplify really gives us awesome features to develop full stack apps. Especially developing a backend application for an existing app.</p><p>On the section below, there are two options, <strong>Amplify Studio</strong> and <strong>Amplify Hosting</strong>. We only need <strong>Amplify Hosting</strong> for this tutorial. We can use the <strong>Amplify Hosting</strong> to deploy React, Vue and Js apps. We’re deploying a Next js app, so we’re good to go.</p><p>Click on <strong><em>Get Started</em></strong><em>.</em></p><p>On the next page that shows, you should see a page like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xl2UMNsAewxfgpjvnem7_A.png" /></figure><p>Select <strong><em>Github</em></strong> to connect your repository to host your web app. As you can see, we have several other git repos, but for now, our focus is only Github.</p><p>Click on <strong><em>Continue</em></strong><em>.</em></p><p>On the next page, it’s asks you to login to you github account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVcevhFjOJHQfXBXaMETiA.png" /></figure><p>Select the existing repo in the dropdown. Then select the git branch you want to deploy from<strong><em> </em></strong>in the <strong>Branch</strong> dropdown. In our own case, we’ll select main.</p><p>Click on Next. You should see the next screen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXLg2qgYEYO9cR0h8QZOGA.png" /></figure><blockquote>Note: You can click on the advanced settings if you have a Dockerized application. Also, you can edit the build settings to suit your app needs.</blockquote><p>Click on Next. On the next screen below, click on <strong><em>Save and deploy</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRc6WPjHvDMjxCf1B1I56A.png" /></figure><p>Now the app creation is in progress. You should see a screen like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*El_kyepIXTb1A7tMgttrzw.png" /></figure><p>On the next screen, you should wait patiently for your app to be deployed successfully. Once it’s deployed, you’ll see a screen like the one below — You can now click on the link to your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jy_gUazxaH9lnNImKPpCCg.png" /></figure><p>Kudos Ninja 👏🏻…We have successfully deployed our Next Js app to Amplify.</p><p>Now this is one of the most easiest thing Amplify has to offer. There are tons of other things you can do with Amplify like i’ve mentioned earlier. I’ll probably have some other tutorials on that soon.</p><p>Cheers! 🥷🏻</p><p>#nextjs #nodejs #amplify #javascript #github</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ff0102ee85" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/deploy-a-next-js-application-on-amazon-amplify-service-d8ff0102ee85">Deploy a Next.js Application on Amazon Amplify Service</a> was originally published in <a href="https://aws.plainenglish.io">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deploy a Dockerized Node JS(TypeScript) Application to Amazon EC2 Service — 2023]]></title>
            <link>https://aws.plainenglish.io/how-to-deploy-a-dockerized-node-js-typescript-application-to-amazon-ec2-service-2023-e9df01261842?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9df01261842</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 20:06:55 GMT</pubDate>
            <atom:updated>2024-03-04T06:54:43.241Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Deploy a Dockerized Node.js (TypeScript) Application to Amazon EC2 Service — 2024</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nGsrrk7IxMCGDrjA.jpg" /></figure><h3><strong>1. Introduction</strong></h3><p>There are several options available once you’ve created a web application to publish it online and make it accessible to others. Elastic Compute Cloud, a well-known service, is one of the platform’s offerings from Amazon Web Services (AWS) (EC2).</p><p>It’s important to have a basic grasp of EC2 and how to deploy to it because it forms the foundation for many of AWS’ other services.</p><p>In this article, we’ll learn how to setup an EC2 instance, configure it, and deploy a straightforward Node.js application to it. Your Node project will be operating on AWS by the conclusion of this tutorial, and you’ll have a better grasp of how to connect with a fundamental system of AWS.</p><h3>2. <strong>Prerequisites</strong></h3><p>In order to follow through this tutorial, you’ll need the following:</p><ul><li><strong>An AWS Account</strong></li></ul><p>You can checkout this tutorial on how to create an AWS account.</p><ul><li><strong>Node and Npm</strong></li></ul><p>You need to have Node and Npm installed on your computer. You can install them <a href="https://nodejs.org/en/">here</a> .</p><ul><li><strong>Docker</strong></li></ul><p>Docker is a very lightweight virtual machine that comes with all the applications and dependencies needed to run your program. Docker allows us to group our programs into manageable parts that may be run everywhere Docker is deployed. This eliminates the excuse “but it works on my computer!”</p><p>Since i won’t be going into great detail, this tutorial will presume a basic understanding of Docker. If you want to learn more about docker, i’ll create an article very soon where i’ll teach you how to use docker for production ready applications.</p><p>Now, make sure you have docker downloaded on your machine. You can download <a href="https://www.docker.com/">here</a>.</p><ul><li><strong>Node Application</strong></li></ul><p>You need a server application running. Let’s qucikly setup a node application.</p><p>Open the terminal and run:</p><pre>mkdir node-ec2 <br>cd node-ec2 <br>npm init --yes</pre><p>Next, let’s install express and typescript.</p><pre>npm install express --save<br>npm i -D typescript @types/express @types/node ts-node</pre><h4>Generate a tsconfig.json:</h4><pre>npx tsc --init</pre><p>Go to the package.json file once these libraries have been installed to see a new dev dependencies object and also update it to have the <em>build</em> and <em>start</em> script:</p><pre>{<br>  &quot;name&quot;: &quot;node-ec2&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.ts&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;tsc --project ./&quot;,<br>    &quot;start&quot;: &quot;npm run build &amp;&amp; node build/index.js&quot;<br>  },<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.18.2&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@types/express&quot;: &quot;^4.17.15&quot;,<br>    &quot;@types/node&quot;: &quot;^18.11.18&quot;,<br>    &quot;ts-node&quot;: &quot;^10.9.1&quot;,<br>    &quot;typescript&quot;: &quot;^4.9.4&quot;<br>  }<br>}</pre><p>Open your prefered editor to create an <em>index.js file to setup Express and define a request handler.</em></p><pre>import express, {Express, Request, Response} from &quot;express&quot;;<br>const app: Express = express();<br>const port = 8080;<br><br>app.get(&#39;/status&#39;, (req: Request, res: Response) =&gt; {<br>    res.send({status: &quot;Server is healthy!&quot;});<br>});<br><br>app.listen(port, () =&gt; {<br>    console.log(`App is running at http://localhost:${port}!`)<br>});</pre><p>We can start up the server by running:</p><pre>npm start</pre><p>When we navigate to <a href="http://localhost:3000/status">http://localhost:8080/status</a>, we ought to receive a response with the status “Server is healthy!” As soon as that succeeds, be careful to shutdown the server by pressing CTRL+C.</p><p>Let’s create a Docker image of our straightforward Node application so that it can be deployed to EC2.</p><h3>3. Dockerizing our Node Application</h3><p>Create a file and name it <em>Dockerfile</em></p><pre>FROM node:16-alpine<br><br>WORKDIR /usr/src/app<br><br>COPY package*.json ./<br><br>RUN npm install<br><br>COPY . .<br><br>RUN npm run build<br><br>EXPOSE 8080<br>CMD [ &quot;node&quot;, &quot;build/index.js&quot; ]</pre><p>We can use the above docker script for simple node applications. Now let’s build the docker image using the command below:</p><pre>docker build . -t node-ec2<br>docker run -p 8080:8080 node-ec2</pre><p>If you navigate to <a href="http://localhost:3000/status">http://localhost:8080/status</a>, we ought to receive a response as before. Now shutdown the server by pressing CTRL+C.</p><p>Finally, let’s push our docker image to <a href="https://hub.docker.com/">Docker Hub</a>:</p><pre>docker login # Enter your Docker Hub credentials here<br>docker tag node-ec2 &lt;YOUR_DOCKER_USERNAME&gt;/node-ec2<br>docker push &lt;YOUR_DOCKER_USERNAME&gt;/node-ec2</pre><h3><strong>Deployment to EC2</strong></h3><p>Now that we’ve dockerized our application, we need to setup an ec2 instance for it to run on.</p><p>Head over to AWS and sign in.</p><p>On the navigation bar, click on the search box, search for <em>EC2.</em></p><p>You should see something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcJnTjPmfT9w89j6w-LiNQ.png" /></figure><p>On you open up the EC2 page, you’ll have a page that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHB95JF0LF2kW4b--vUtjw.png" /></figure><p>Click on <em>Launch Instance.</em></p><p>On the next page, you should have a view like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJEjOWihkvhth_IlYUxVdQ.png" /></figure><h4><strong>AMIs</strong></h4><p>Here is where we choose the AMI, or short for Amazon Machine Image. An AMI is a server that may be purchased in a variety of configurations.</p><p>For instance, we might choose an Amazon Linux 2 AMI, or if you scroll down, you’ll find other instances with Ubuntu running on them.</p><p>Each AMI is a copy of a machine’s operating system and possibly some other software that has been frozen.</p><p>Click on <em>Browse more AMIs to view the list of several AMIs available.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNwoYFL_qdm5U6tzl9azTQ.png" /></figure><p>To make things simple, we can utilize this to create an EC2 instance that is already set up using Docker!</p><p>To do this, we need to click “AWS Marketplace AMIs” on the left and then type “ECS” into the search bar. Several results ought to come up, however we want the “ECS Optimized Amazon Linux 2” image.</p><p>This image, which includes Docker, is designed specifically for running containers. The next page will open after you click “Select” on the selected picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGki4rLidxq6Q3tNTZtfFQ.png" /></figure><p>After clicking <em>Select</em>, a pop up will show, then you’ll click on C<em>ontinue</em>.</p><p>Enter your instance name. For example, <em>node-ec2.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sa4J1eQNLcc-ES4OsqT1OQ.png" /></figure><h4><strong>Instance Types</strong></h4><p>We decide what kind of instance we want on the next view. In general, this determines the resources that will be made available to the server that we’re launching, with scaling fees for machines with higher performance.</p><p>Scroll down the page to select the instance type — It is advised to utilize the <em>t2.micro</em> instance type since it qualifies for the free tier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-4Hu3CGpk1ESlTBc5gsdw.png" /></figure><h4>Key Pair</h4><p>It is important that you create a key pair before launching the application in order to be able to access it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKC0iQ2dVl6snXNgRtBWxw.png" /></figure><p>Click on create key pair and you should have a pop up like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HiNi6f2fO1W11C7q2wdMhw.png" /></figure><p>Enter your key pair name. Leave the Private key file format as <em>.pem</em>. Once you click on <em>Create key pair,</em> It will be downloaded automatically.</p><h4>Network Settings (Security Group)</h4><p>This signifies that any traffic utilizing the TCP protocol that enters through port 22 is permitted (0.0.0.0/0 denoting any location). To enable everyone to use our app at port 8080, we must add one more rule.</p><p>Make sure you select the check boxes for allowing Http and Https from anywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNRNy5XRoi9MBja4iRHJFA.png" /></figure><blockquote><strong>Note:</strong> There are some other advanced configurations that you can set up depending on your app needs. We don’t need to do that for now.</blockquote><p>You can now go ahead to launch the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiQNlOE0K2DcEfxrRwYvtQ.png" /></figure><p>On the next page that shows, please wait patiently for the instance to be launched successfuly.</p><p>Once the instance is launched successfully, you’ll see a page like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkKYuXZ4kcMIyoAWyrJ_8w.png" /></figure><p>Click on the <em>Instance Id</em>.</p><h4>Connecting to Your EC2 Instance</h4><p>Once you click on the Intance Id, a new tab is open and you see a page like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ktceNkwdOxgt1d8kFyuxw.png" /></figure><p>Click on the check box to view the instance details. On the section below, copy the Instant Public Ipv4 address.</p><p>Now, go to your computer terminal and enter the following commands:</p><pre>chmod 400 &lt;NAME_OF_KEYPAIR_FILE&gt;<br>ssh -i &lt;NAME_OF_KEYPAIR_FILE&gt; ec2-user@&lt;PUBLIC_IPV4_ADDRESS&gt;</pre><p>Once you’re logged into the server, enter the docker command below:</p><pre>docker run -p 8080:8080 &lt;YOUR_DOCKER_USERNAME&gt;/node-ec2</pre><blockquote><strong>Note: </strong>For M1 Mac users, you might experience an error like this:</blockquote><pre>WARNING: The requested image&#39;s platform (linux/arm64/v8) does not match the detected host platform (linux/amd64) and no specific platform was requested<br>exec /usr/local/bin/docker-entrypoint.sh:</pre><p>Just run the docker command like below:</p><pre>docker run --platform linux/amd64 -d -p 8080:8080 &lt;YOUR_DOCKER_USERNAME&gt;/node-ec2</pre><p>You should have your app running successfully by now. You’ll be able to reach the instance using the same address you used to SSH into the instance. Simply navigate in your browser to:</p><pre>&lt;Public_Ipv4_Address&gt;:8080/status</pre><h4><strong>Security</strong></h4><p>When it comes to securing your EC2 instance, there are several measures you should put in place.</p><ul><li>Using a <em>.pem</em> file: A pem file allows you to be able to authenticate to the instance direclty without public access.</li><li>Checking the security groups: You can make your instance available only via SSH or HTTPS protocol.</li></ul><p>There are other measures to put in place for securing our instance, but that’ll be a seperate tutorial for now.</p><h4><strong>Other AMIs</strong></h4><p>There are hundreds of different AMIs, many of which come from different communities and have pre-installed applications. It’s worth looking through them to see if there’s a simple method to set up anything you’ve wanted to work with.</p><h4><strong>Adding a Custom Domain</strong></h4><p>You might want to create a domain name and direct it at your application now that it is operating on a server.</p><h4><strong>Conclusion</strong></h4><p>Since RDS (AWS’ database service) is essentially simply highly optimized EC2 instances with a lovely dashboard, EC2 is the backbone of many AWS services.</p><p>Understanding this foundational tool in AWS’ armory will inevitably lead to the discovery of fresh ways to carry out concepts.</p><p>In this article, we’ve used Express to build a straightforward Node.js application, dockerized it, set up EC2 for deployment, and then deployed it to the EC2 instance.</p><p>If you want to learn how to architect an EC2 instance, with load balancers, docker and Amazon RDS, i’ll be uploading another tutorial next week.</p><p>Kindly follow to stay updated on my latest tutorials.</p><p>Cheers! 🥷🏻</p><p>#docker #nodejs #ec2 #express #typescript</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9df01261842" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/how-to-deploy-a-dockerized-node-js-typescript-application-to-amazon-ec2-service-2023-e9df01261842">How to deploy a Dockerized Node JS(TypeScript) Application to Amazon EC2 Service — 2023</a> was originally published in <a href="https://aws.plainenglish.io">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create and Configure the Auto Scaling Group in EC2]]></title>
            <link>https://mayorscript.medium.com/create-and-configure-the-auto-scaling-group-in-ec2-3830856fac7e?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3830856fac7e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[autoscaling]]></category>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 15:22:28 GMT</pubDate>
            <atom:updated>2024-04-03T17:53:20.731Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Auto Scaling</strong> is an Amazon Web Service that allows instances to scale when traffic or CPU load increases. Auto-scaling is a service that monitors all instances that are configured into the Auto-Scaling group and ensures that loads are balanced in all instances. Depending on the load scaling group, increase the instance according to the configuration. When we created the auto-scaling group, we configured the Desired capacity, Minimum capacity, maximum capacity, and CPU utilization. If CPU utilization increases by 60% in all instances, one more instance is created, and if CPU utilization decreases by 30% in all instances, one instance is terminated. These are totally up to us; what is our requirement? If any Instance fails due to any reason, then the Scaling group maintains the Desired capacity and starts another instance.</p><p>The auto-scaling group follows Horizontal Scaling. This service is very important for us nowadays because we do not need to create new instances manually and do not require manual monitoring.</p><p>AWS auto-scaling is used to scale up and scale down the EC2 instance depending on the incoming traffic. You can scale up and scale down the applications in a few minutes based on the traffic which will decrease the latency of the application to the end-users. You can integrate the AWS Auto Scaling with multiple services provided by AWS like Amazon traffic, Amazon DynamoDB, and Amazon Aurora. You can also decrease the cost of an application because of dynamic scaling. When there is traffic, only maximum resources are used other it will use minimum resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*mQvC7B4kfIHPqa9k.png" /></figure><ol><li><strong>Dynamical scaling: </strong>AWS auto-scaling service doesn’t require any type of manual intervention it will automatically scale the application down and up depending on the incoming traffic.</li><li><strong>Pay For You Use: </strong>Because of auto-scaling the resource will be utilized in the optimized way where the demand is low the resource utilization will be low and if the demand is high the resource utilization will increase so the AWS is going to charge you only for the number of resources you really used.</li><li><strong>Automatic Performance Maintenance: </strong>AWS autoscaling maintains the optimal application performance while considering the workloads it will ensure that the application is running to the desired level which will decrease the latency and also the capacity will be increased by based on your application</li></ol><h3>How AWS Auto Scaling Works?</h3><p>AWS autoscaling will scale the application based on the load of the application. Instead of scaling manually AWS auto scaling will scale the application automatically when the incoming traffic is high it will scale up the application and when the traffic is low it will scale down the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*DpvNks29-m_eqdub.png" /></figure><p>First, you should choose which service or an application you want to scale then select the optimization way like cost and performance and then keep track of how the scaling is working.</p><h3>Steps to Create Auto Scaling Launch Template</h3><p><strong>Step 9: </strong>Now you can see the template is <strong>created. </strong>Now, scroll down and click on the <strong>Auto Scaling Groups.</strong></p><h3>Create An Auto Scaling Group Using a Launch Template</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OwixLhtOnBY_6O5J.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HrVqc2RGrp02Oo4D.png" /></figure><p>Select as per your requirement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wz2AA5YCWu41m3Az.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DIYSxUXQL19St3ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*j4RB0RWEoCyLxRLu.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nvBHuUy2N3teEqEv.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BK4ZbiOAqyRYfd3e.png" /></figure><h3>FAQs On Create And Configure The Auto Scaling Group In EC2</h3><h3>1. What Is The Difference Between EC2 Auto Scaling And AWS Auto Scaling?</h3><blockquote><em>AWS Auto-scaling is used to scale the AWS EC2 instance for better availability and productivity</em></blockquote><h3>2. Why Do We Need Auto Scaling?</h3><blockquote><em>Auto scaling is essential to efficiently manage resources in response to varying workloads. It optimizes costs, ensures performance, and maintains availability by automatically adjusting resources up or down based on demand.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3830856fac7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Startup Nuggets]]></title>
            <link>https://mayorscript.medium.com/startup-nuggets-2a8e3ea5dd0?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a8e3ea5dd0</guid>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 01:20:25 GMT</pubDate>
            <atom:updated>2022-11-10T01:20:25.120Z</atom:updated>
            <content:encoded><![CDATA[<p>The three dashboards a startup needs are:</p><p>- stability dashboard: Does the product perform as promised without malfunctioning?</p><p>- product dashboard: 1–2 indicators that demonstrate how often users return to a product.</p><p>- revenue dashboard: You generate income so that you can grow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a8e3ea5dd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CRUD REST API with Node.js, Express, and PostgreSQL]]></title>
            <link>https://mayorscript.medium.com/crud-rest-api-with-node-js-express-and-postgresql-f99758fd4033?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f99758fd4033</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 12:00:01 GMT</pubDate>
            <atom:updated>2024-04-03T17:55:32.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*96mrJiSfHNhIa74j.png" /></figure><p>Working with APIs to facilitate communication between software systems is crucial for modern web developers. In this tutorial, we’ll create a CRUD RESTful API in a Node.js environment that runs on an Express server and uses a PostgreSQL database.</p><p>We’ll also walk through connecting an Express server with PostgreSQL using <a href="https://node-postgres.com/">node-postgres</a>. Our API will be able to handle the HTTP request methods that correspond to the PostgreSQL database from which the API gets its data. You’ll also learn how to install PostgreSQL and work with it through the CLI.</p><p>To follow along with this tutorial, you’ll need:</p><ul><li>Familiarity with the JavaScript syntax and fundamentals</li><li>Basic knowledge of working with the command line</li><li>Node.js and npm installed</li></ul><p>The complete code for the tutorial is available in this <a href="https://github.com/nemo0/node-postgres-crud-api">GitHub repo</a>. Let’s get started!</p><h3>What is a RESTful API?</h3><p>Representational State Transfer (REST) defines a set of standards for web services.</p><p>An API is an interface that software programs use to communicate with each other. Therefore, a RESTful API is an API that conforms to the REST architectural style and constraints.</p><p>REST systems are stateless, scalable, cacheable, and have a uniform interface.</p><h3>What is a CRUD API?</h3><p>When building an API, you want your model to provide four basic functionalities. It should be able to create, read, update, and delete resources. This set of essential operations is commonly referred to as CRUD.</p><ul><li>Create: Use the HTTP POST method to create a resource in a REST environment</li><li>Read: Use the GET method to read a resource, retrieving data without altering it</li><li>Update: Use the PUT method to update a resource</li><li>Delete: Use the DELETE method to remove a resource from the system</li></ul><h3>What is Express?</h3><p>According to the official <a href="https://expressjs.com/">Express documentation</a>, Express is a fast, unopinionated, minimalist web framework for Node.js. Express is one of the most popular frameworks for Node.js. In fact, each E in the MERN, MEVN, and MEAN stacks stands for Express.</p><p>Although Express is minimalist, it’s also very flexible. This supports the <a href="https://blog.logrocket.com/express-middleware-a-complete-guide/">development of various Express middlewares</a> that you can use to address almost any task or problem imaginable.</p><h3>What is PostgreSQL?</h3><p>PostgreSQL, commonly referred to as Postgres, is a free and open-source relational database management system. You might be familiar with a few other similar database systems, like MySQL, Microsoft SQL Server, or MariaDB, which compete with PostgreSQL.</p><p>PostgreSQL is a robust relational database that has been around since 1997. It’s available on all major operating systems — Linux, Windows, and macOS. Since PostgreSQL is known for stability, extensibility, and standards compliance, it’s a popular choice for developers and companies.</p><p>It’s also possible to create a Node.js RESTful CRUD API using Sequelize. <a href="https://blog.logrocket.com/using-sequelize-with-typescript/">Sequelize is a promise-based Node.js ORM</a> for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server.</p><p>For more on how to use Sequelize in a Node.js REST API, check out the video tutorial below:</p><h3>What is node-postgres?</h3><p><a href="https://www.npmjs.com/package/pg">node-postgres</a>, or pg, is a nonblocking PostgreSQL client for Node.js. Essentially, node-postgres is a collection of Node.js modules for interfacing with a PostgreSQL database.</p><p>node-postgres supports many features, including callbacks, promises, async/await, connection pooling, prepared statements, cursors, rich type parsing, and C/C++ bindings.</p><h3>Creating a PostgreSQL database</h3><p>We’ll begin this tutorial by installing PostgreSQL, creating a new user, creating a database, and initializing a table with a schema and some data.</p><h3>Installation</h3><p>If you’re using Windows, download a <a href="https://www.postgresql.org/download/windows/">Windows installer</a> of PostgreSQL.</p><p>If you’re using a Mac, this tutorial assumes you have <a href="https://brew.sh/">Homebrew</a> installed on your computer as a package manager for installing new programs. If you don’t, simply click on the link and follow the instructions.</p><p>Open up the terminal and install postgresql with brew:</p><pre>brew install postgresql</pre><p>You may see instructions on the web reading brew install postgres instead of PostgreSQL. Both options will install PostgreSQL on your computer.</p><p>After the installation is complete, we’ll want to get postgresql up and running, which we can do with services start:</p><pre>brew services start postgresql ==&gt; Successfully started `postgresql` (label: homebrew.mxcl.postgresql)</pre><p>If at any point you want to stop the postgresql service, you can run brew services stop postgresql.</p><p>With PostgreSQL installed, let’s next connect to the postgres command line where we can run SQL commands.</p><h3>PostgreSQL command prompt</h3><ul><li>-w or --no-password: Never prompt for password</li><li>-W or --password: Force password prompt, which should happen automatically</li></ul><p>We’ll connect to the default postgres database with the default login information and no option flags:</p><pre>psql postgres</pre><pre>postgres=#</pre><pre>postgres=# \conninfo You are connected to database &quot;postgres&quot; as user &quot;your_username&quot; via socket in &quot;/tmp&quot; at port &quot;5432&quot;.</pre><p>The reference table below includes a few common commands that we’ll use throughout this tutorial:</p><p>Let’s create a new database and user so we’re not using the default accounts, which have superuser privileges.</p><h3>Creating a role in Postgres</h3><p>First, we’ll create a role called me and give it a password of password. A role can function as a user or a group. In this case, we&#39;ll use it as a user:</p><pre>postgres=# CREATE ROLE me WITH LOGIN PASSWORD &#39;password&#39;;</pre><p>We want me to be able to create a database:</p><pre>postgres=# ALTER ROLE me CREATEDB;</pre><p>You can run \du to list all roles and users:</p><pre>me | Create DB | {} postgres | Superuser, Create role, Create DB | {}</pre><p>Now, we want to create a database from the me user. Exit from the default session with\q for quit:</p><pre>postgres=# \q</pre><p>We’re back in our computer’s default terminal connection. Now, we’ll connect postgres with me:</p><pre>psql -d postgres -U me</pre><p>Instead of postgres=#, our prompt now shows postgres=&gt; , meaning we&#39;re no longer logged in as a superuser.</p><h3>Creating a database in Postgres</h3><p>We can create a database with the SQL command as follows:</p><pre>postgres=&gt; CREATE DATABASE api;</pre><p>Use the \list command to see the available databases:</p><pre>Name | Owner | Encoding | Collate | Ctype | api | me | UTF8 | en_US.UTF-8 | en_US.UTF-8 |</pre><pre>postgres=&gt; \c api You are now connected to database &quot;api&quot; as user &quot;me&quot;. api=&gt;</pre><p>Our prompt now shows that we’re connected to api.</p><h3>Creating a table in Postgres</h3><pre>api=&gt; CREATE TABLE users ( ID SERIAL PRIMARY KEY, name VARCHAR(30), email VARCHAR(30) );</pre><p>Make sure not to use the backtick ` character when creating and working with tables in PostgreSQL. While backticks are allowed in MySQL, they&#39;re not valid in PostgreSQL. Also, ensure that you do not have a trailing comma in the CREATE TABLE command.</p><p>Let’s add some data to work with by adding two entries to users:</p><pre>INSERT INTO users (name, email) VALUES (&#39;Jerry&#39;, &#39;[email protected]&#39;), (&#39;George&#39;, &#39;[email protected]&#39;);</pre><p>Let’s make sure that the information above was correctly added by getting all entries in users:</p><pre>api=&gt; SELECT * FROM users; id | name | email ----+--------+-------------------- 1 | Jerry |[email protected] 2 | George |[email protected]</pre><p>Now, we have a user, database, table, and some data. We can begin building our Node.js RESTful API to connect to this data, stored in a PostgreSQL database.</p><p>At this point, we’re finished with all of our PostgreSQL tasks, and we can begin setting up our Node.js app and Express server.</p><h3>Setting up an Express server</h3><p>To set up a Node.js app and Express server, first create a directory for the project to live in:</p><pre>mkdir node-api-postgres cd node-api-postgres</pre><pre>{ &quot;name&quot;: &quot;node-api-postgres&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;description&quot;: &quot;RESTful API with Node.js, Express, and PostgreSQL&quot;, &quot;main&quot;: &quot;index.js&quot;, &quot;license&quot;: &quot;MIT&quot; }</pre><p>We’ll want to install Express for the server and node-postgres to connect to PostgreSQL:</p><pre>npm i express pg</pre><p>Now, we have our dependencies loaded into node_modules and package.json.</p><p>Create an index.js file, which we&#39;ll use as the entry point for our server. At the top, we&#39;ll require the express module, the built-in<a href="http://expressjs.com/en/resources/middleware/body-parser.html">body-parser middleware</a>, and we&#39;ll set our app and port variables:</p><pre>const express = require(&#39;express&#39;) const bodyParser = require(&#39;body-parser&#39;) const app = express() const port = 3000 app.use(bodyParser.json()) app.use( bodyParser.urlencoded({ extended: true, }) )</pre><p>We’ll tell a route to look for a GET request on the root/ URL and return some JSON:</p><pre>app.get(&#39;/&#39;, (request, response) =&gt; { response.json({ info: &#39;Node.js, Express, and Postgres API&#39; }) })</pre><p>Now, set the app to listen on the port you set:</p><pre>app.listen(port, () =&gt; { console.log(`App running on port ${port}.`) })</pre><p>From the command line, we can start the server by hitting index.js:</p><pre>node index.js App running on port 3000.</pre><p>Go to http://localhost:3000 in the URL bar of your browser, and you&#39;ll see the JSON we set earlier:</p><pre>{ info: &quot;Node.js, Express, and Postgres API&quot; }</pre><p>The Express server is running now, but it’s only sending some static JSON data that we created. The next step is to connect to PostgreSQL from Node.js to be able to make dynamic queries.</p><h3>Connecting to a Postgres database using a Client</h3><p>A popular client for accessing Postgres databases is the <a href="https://www.pgadmin.org/">pgAdmin</a> client. The pgAdmin application is available for various platforms. If you want to have a graphical user interface for your Postgres databases, you can go to the <a href="https://www.pgadmin.org/download/">download page</a> and download the necessary package.</p><p>Creating and querying your database using pgAdmin is simple. You need to click on the <strong>Object</strong> option available on the top menu, select <strong>Create</strong>, and choose <strong>Database</strong> to create a new connection. All the databases are available on the side menu. You can query or run SQL queries efficiently by selecting the proper database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*kZLjr97KtgN9TC3F.png" /></figure><h3>Connecting to a Postgres database from Node.js</h3><p>We’ll use the <a href="https://node-postgres.com/">node-postgres</a> module to create a pool of connections. Therefore, we don’t have to open and close a client each time we make a query.</p><p>A popular option for production pooling would be to use [pgBouncer](https://pgbouncer.github.io/), a lightweight connection pooler for PostgreSQL.</p><pre>const Pool = require(&#39;pg&#39;).Pool const pool = new Pool({ user: &#39;me&#39;, host: &#39;localhost&#39;, database: &#39;api&#39;, password: &#39;password&#39;, port: 5432, })</pre><p>In a production environment, you would want to put your configuration details in a separate file with restrictive permissions so that it is not accessible from version control. But, for the simplicity of this tutorial, we’ll keep it in the same file as the queries.</p><h3>Creating routes for CRUD operations</h3><p>We’ll create six functions for six routes, as shown below. First, create all the functions for each route. Then, export the functions so they’re accessible:</p><h3>GET all users</h3><pre>const getUsers = (request, response) =&gt; { pool.query(&#39;SELECT * FROM users ORDER BY id ASC&#39;, (error, results) =&gt; { if (error) { throw error } response.status(200).json(results.rows) }) }</pre><h3>GET a single user by ID</h3><pre>const getUserById = (request, response) =&gt; { const id = parseInt(request.params.id) pool.query(&#39;SELECT * FROM users WHERE id = $1&#39;, [id], (error, results) =&gt; { if (error) { throw error } response.status(200).json(results.rows) }) }</pre><h3>POST a new user</h3><p>The API will take a GET and POST request to the/users endpoint. In the POST request, we&#39;ll add a new user. In this function, we&#39;re extracting the name and email properties from the request body and inserting the values with INSERT:</p><pre>const createUser = (request, response) =&gt; { const { name, email } = request.body pool.query(&#39;INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *&#39;, [name, email], (error, results) =&gt; { if (error) { throw error } response.status(201).send(`User added with ID: ${results.rows[0].id}`) }) }</pre><h3>PUT updated data in an existing user</h3><p>The /users/:id endpoint will also take two HTTP requests, the GET we created for getUserById and a PUT to modify an existing user. For this query, we&#39;ll combine what we learned in GET and POST to use the UPDATE clause.</p><pre>const updateUser = (request, response) =&gt; { const id = parseInt(request.params.id) const { name, email } = request.body pool.query( &#39;UPDATE users SET name = $1, email = $2 WHERE id = $3&#39;, [name, email, id], (error, results) =&gt; { if (error) { throw error } response.status(200).send(`User modified with ID: ${id}`) } ) }</pre><h3>DELETE a user</h3><pre>const deleteUser = (request, response) =&gt; { const id = parseInt(request.params.id) pool.query(&#39;DELETE FROM users WHERE id = $1&#39;, [id], (error, results) =&gt; { if (error) { throw error } response.status(200).send(`User deleted with ID: ${id}`) }) }</pre><h3>Exporting CRUD functions in a REST API</h3><pre>module.exports = { getUsers, getUserById, createUser, updateUser, deleteUser, }</pre><p>Our complete queries.js file is below:</p><pre>const Pool = require(&#39;pg&#39;).Pool const pool = new Pool({ user: &#39;me&#39;, host: &#39;localhost&#39;, database: &#39;api&#39;, password: &#39;password&#39;, port: 5432, }) const getUsers = (request, response) =&gt; { pool.query(&#39;SELECT * FROM users ORDER BY id ASC&#39;, (error, results) =&gt; { if (error) { throw error } response.status(200).json(results.rows) }) } const getUserById = (request, response) =&gt; { const id = parseInt(request.params.id) pool.query(&#39;SELECT * FROM users WHERE id = $1&#39;, [id], (error, results) =&gt; { if (error) { throw error } response.status(200).json(results.rows) }) } const createUser = (request, response) =&gt; { const { name, email } = request.body pool.query(&#39;INSERT INTO users (name, email) VALUES ($1, $2)&#39;, [name, email], (error, results) =&gt; { if (error) { throw error } response.status(201).send(`User added with ID: ${results.insertId}`) }) } const updateUser = (request, response) =&gt; { const id = parseInt(request.params.id) const { name, email } = request.body pool.query( &#39;UPDATE users SET name = $1, email = $2 WHERE id = $3&#39;, [name, email, id], (error, results) =&gt; { if (error) { throw error } response.status(200).send(`User modified with ID: ${id}`) } ) } const deleteUser = (request, response) =&gt; { const id = parseInt(request.params.id) pool.query(&#39;DELETE FROM users WHERE id = $1&#39;, [id], (error, results) =&gt; { if (error) { throw error } response.status(200).send(`User deleted with ID: ${id}`) }) } module.exports = { getUsers, getUserById, createUser, updateUser, deleteUser, }</pre><h3>Setting up CRUD functions in a REST API</h3><p>Now that we have all of our queries, we need to pull them into the index.js file and make endpoint routes for all the query functions we created.</p><p>To get all the exported functions from queries.js, we&#39;ll require the file and assign it to a variable:</p><pre>const db = require(&#39;./queries&#39;)</pre><p>Now, for each endpoint, we’ll set the HTTP request method, the endpoint URL path, and the relevant function:</p><pre>app.get(&#39;/users&#39;, db.getUsers) app.get(&#39;/users/:id&#39;, db.getUserById) app.post(&#39;/users&#39;, db.createUser) app.put(&#39;/users/:id&#39;, db.updateUser) app.delete(&#39;/users/:id&#39;, db.deleteUser)</pre><p>Below is our complete index.js file, the entry point of the API server:</p><pre>const express = require(&#39;express&#39;) const bodyParser = require(&#39;body-parser&#39;) const app = express() const db = require(&#39;./queries&#39;) const port = 3000 app.use(bodyParser.json()) app.use( bodyParser.urlencoded({ extended: true, }) ) app.get(&#39;/&#39;, (request, response) =&gt; { response.json({ info: &#39;Node.js, Express, and Postgres API&#39; }) }) app.get(&#39;/users&#39;, db.getUsers) app.get(&#39;/users/:id&#39;, db.getUserById) app.post(&#39;/users&#39;, db.createUser) app.put(&#39;/users/:id&#39;, db.updateUser) app.delete(&#39;/users/:id&#39;, db.deleteUser) app.listen(port, () =&gt; { console.log(`App running on port ${port}.`) })</pre><p>With just these two files, we have a server, database, and API all setup. You can start up the server by hitting index.js again:</p><pre>node index.js App running on port 3000.</pre><p>To test our POST, PUT, and DELETE requests, we can use a tool like Postman or a VS Code extension like <a href="https://www.thunderclient.com/">Thunder Client</a> to send the HTTP requests. You can also use <a href="https://blog.logrocket.com/an-intro-to-curl-the-basics-of-the-transfer-tool/">curl, a command-line tool</a> that is already available on your terminal.</p><p>Using a tool like Postman or Thunder Client makes it simple to query endpoints with different HTTP methods. Simply enter your URL, choose the specific HTTP method, insert the JSON value if the endpoint is a PUT or POST route, and hit <strong>Send</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*8uaZEkJN-AIFI3VX.png" /></figure><p>Here’s an example of sending a POST request to the specified route to create a new user using Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*2Xj2wSoCaOfzBXFF.png" /></figure><p>Here’s an example of sending a PUT request to the specified route to modify a user by its ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*IiRIdi3oRX8M03Sb.png" /></figure><p>Here’s an example of sending a GET request to the specified route to retrieve a user by its ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*RxL7y8aaf9SgteRZ.png" /></figure><p>Here’s an example of sending a GET request to the specified route to retrieve all users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*hN2dZrTQ1vQCAfrV.png" /></figure><p>Finally, here’s an example of sending a DELETE request to the specified route to delete a user by its ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*IV80zqcq_jszZXHS.png" /></figure><h3>Solutions to common issues encountered while developing APIs</h3><p>Developing APIs can come with various challenges. Let’s go over the solutions to two common issues encountered during API development: CORS issues and unhandled errors due to middleware order.</p><h3>Handling CORS issues</h3><p>Browser security policies can block requests from different origins. To address this issue, use the cors middleware in Express to handle cross-origin resource sharing (CORS).</p><p>Run the following command to install cors:</p><pre>npm install cors</pre><p>To use it, do the following:</p><pre>var express = require(&#39;express&#39;) var cors = require(&#39;cors&#39;) var app = express() app.use(cors())</pre><p>This will enable CORS for all origins.</p><h3>Middleware order and error handling</h3><p>Middleware order can affect error handling, leading to unhandled errors. To address this issue, place error-handling middleware at the end of your middleware stack and use next(err) to pass errors to the error-handling middleware:</p><pre>app.use((req, res, next) =&gt; { const error = new Error(&#39;Something went wrong&#39;); next(error); }); // Error-handling Middleware app.use((err, req, res, next) =&gt; { console.error(&#39;Error:&#39;, err.message); res.status(500).send(&#39;Internal Server Error&#39;); });</pre><h3>Securing the API</h3><p>When it comes to securing APIs, we need to implement various mechanisms to ensure the confidentiality, and integrity of the application and its data. Let’s go over a few of these mechanisms now.</p><h3>Authentication</h3><p>I will recommend <a href="https://blog.logrocket.com/using-passport-authentication-node-js/">the Passport middleware for Node.js</a>, which makes it easy to implement authentication and authorization. Here’s an example of how to use Passport:</p><pre>const passport = require(&#39;passport&#39;); const LocalStrategy = require(&#39;passport-local&#39;).Strategy; passport.use(new LocalStrategy( function(username, password, done) { // Verify username and password // Call done(null, user) if authentication is successful } ));</pre><h3>Authorization</h3><p>It’s important to enforce proper access controls to restrict access to specific routes or resources based on the user’s role or permissions. For example, you can check if the user making a request has admin privileges before allowing or denying them permission to proceed with the request:</p><pre>function isAdmin(req, res, next) { if (req.user &amp;&amp; req.user.role === &#39;admin&#39;) { return next(); } else { return res.status(403).json({ message: &#39;Permission denied&#39; }); } }</pre><p>You can apply the isAdmin middleware defined above to any protected routes, thus restricting access to those routes.</p><h3>Input validation</h3><p>Validate and sanitize user inputs to prevent SQL injection, XSS, and other security vulnerabilities. For example:</p><pre>const { body, validationResult } = require(&#39;express-validator&#39;); app.post(&#39;/users&#39;, [ // add validation rules ], (req, res) =&gt; { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(422).json({ errors: errors.array() }); } // Process the request });</pre><p>The code above allows you to specify validation rules for POST requests to the /users endpoint. If the validation fails, it sends a response with the validation errors. If the incoming data is correct and safe, it proceeds with processing the request.</p><h3>Helmet middleware</h3><p>You can use <a href="https://blog.logrocket.com/using-helmet-node-js-secure-application/">the Helmet middleware</a> to set various HTTP headers for enhanced security:</p><pre>const helmet = require(&#39;helmet&#39;); app.use(helmet());</pre><p>Configuring HTTP headers with Helmet helps protect your app from security issues like XSS attacks, CSP vulnerabilities, and more.</p><h3>Additional notes and suggestions</h3><p>You can build on this tutorial by implementing the following suggestions:</p><ul><li><strong>Integration with frontend frameworks</strong>: Choose a frontend framework or library (e.g., React, Angular, Vue.js) to build a user interface for your application. Then, implement API calls from the frontend to interact with the backend CRUD operations. You can consider state management solutions (e.g., Redux, Vuex) for managing the state of your frontend application</li><li><strong>Containerizing the API</strong>: Write a Dockerfile to define the environment and dependencies needed to run your Node.js app. Create adocker-compose.yml file for managing multiple containers, such as the Node.js app and PostgreSQL database. This will make your Node.js application easier to deploy and set up on other machines</li><li><strong>Implementing unit/integration tests:</strong> Write unit tests for individual functions and components of your application to ensure that they work as expected. Use testing frameworks like Mocha, Jest, or Jasmine for writing and running tests. Implement integration tests to verify the interactions between different components in your front-end application and the overall functionality of your API</li><li><strong>Continuous integration/deployment (CI/CD)</strong>: Set up CI/CD pipelines to automate the testing and deployment processes. Use tools like Jenkins, Travis CI, or GitHub Actions to streamline the development/deployment workflow</li></ul><p>While implementing these next steps is beyond the scope of this tutorial, you can use these ideas to apply what we’ve discussed to a real use case.</p><h3>Conclusion</h3><p>You should now have a functioning API server that runs on Node.js and is hooked up to an active PostgreSQL database.</p><p>In this tutorial, we learned how to install and set up PostgreSQL in the command line, create users, databases, and tables, and run SQL commands. We also learned how to create an Express server that can handle multiple HTTP methods and use the pg module to connect to PostgreSQL from Node.js.</p><p>With this knowledge, you should be able to build on this API and utilize it for your own personal or professional development projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f99758fd4033" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Token Server for Agora Applications using NodeJS]]></title>
            <link>https://mayorscript.medium.com/how-to-build-a-token-server-for-agora-applications-using-nodejs-fd20f91dd768?source=rss-c8014bf82d7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd20f91dd768</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[agora]]></category>
            <category><![CDATA[live-streaming]]></category>
            <dc:creator><![CDATA[Joseph Ayobami]]></dc:creator>
            <pubDate>Fri, 31 Jul 2020 07:01:20 GMT</pubDate>
            <atom:updated>2024-04-03T18:14:02.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Td2QJuZ10EfEr9Ci.jpg" /></figure><p>Note: This article was updated on 20-Dec-21 to use v2.0.0 of the Node.js token server.</p><p>Security in video chat applications is a hot topic at the moment. As remote working and virtual events become more widespread, the need for security will increase.</p><p>In the <a href="https://www.agora.io/">Agora platform</a>, one layer of security comes in the form of token authentication. A token is a dynamic key that is generated using a set of given inputs. The Agora platform uses tokens to authenticate users.</p><p>Agora offers token security for its RTC and RTM SDKs. This guide will explain how to build a simple microservice using <a href="https://nodejs.org/">Node.js</a> and <a href="https://expressjs.com/">Express</a> to generate these tokens.</p><h3>Prerequisites</h3><ul><li>An Agora developer account (It’s free! <a href="https://www.agora.io/en/blog/how-to-get-started-with-agora">Sign up here</a>)</li><li>A basic understanding of JavaScript ES6, <a href="https://nodejs.org/">Node.js</a>, and <a href="https://www.npmjs.com/">NPM</a></li><li>A basic of how Express web servers function <em>(minimal knowledge needed)</em></li></ul><h3>Project Setup</h3><p>To start our project, we’ll create a new folder and open a terminal window in this folder. In the terminal, we’ll run npm init to set up the node project. The create project prompt will appear. I used the default settings, but feel free to customize this portion.</p><p>Now that the project has been created, we can add our NPM dependencies ( <a href="https://www.npmjs.com/package/express">express</a>, <a href="https://www.npmjs.com/package/agora-access-token">agora-access-token</a>, and <a href="https://www.npmjs.com/package/dotenv">dotenv</a>) using:</p><pre>npm install express agora-access-token dotenv</pre><h3>Build the Express Server</h3><p>Now that the project is set up, open the folder in your favorite code editor. Looking at the package.json, you&#39;ll notice that the entry file is index.js. This file doesn&#39;t exist in our project, so we&#39;ll have to create a new file and name it index.js.</p><p>In the index.js we&#39;ll start by requiring our modules. From Express, we&#39;ll need the Express object, and from agora-access-token we&#39;ll extract references to the RtcTokenBuilder and RtcRole objects. We&#39;ll also use dotenv from its package for our environment variables:</p><pre>const express = require(&#39;express&#39;);<br>const {RtcTokenBuilder, RtcRole} = require(&#39;agora-access-token&#39;);<br>const dotenv = require(&#39;dotenv&#39;);</pre><p>Let’s define our constants by creating a .env file and adding our Agora credentials and the port we&#39;re going to use to listen for requests:</p><pre>APP_ID=970XXXXX...<br>APP_CERTIFICATE=5CFXXXXX...<br>PORT=8080</pre><p>Next, we’ll define our app constant that will instantiate our Express object and allow us to set up our server:</p><pre>const app = express();</pre><p>Before we can set up the GET endpoint for our Express server, we’ll need to define the functions that are invoked when the endpoint is accessed. The first function ( nocache) will apply the response headers, which force the browser to never cache the response, ensuring that we always get a fresh token. You&#39;ll notice we call the next() method at the end because this function is a middleware function that is the first in the series, so we need to call next() to let Express know to continue to the next function in the series:</p><pre><br>const nocache = (_, resp, next) =&gt; {<br>  resp.header(&#39;Cache-Control&#39;, &#39;private, no-cache, no-store, must-revalidate&#39;);<br>  resp.header(&#39;Expires&#39;, &#39;-1&#39;);<br>  resp.header(&#39;Pragma&#39;, &#39;no-cache&#39;);<br>  next();<br>}</pre><p>The second function ( generateRTCToken) will handle the request and return the JSON response. We&#39;ll define the function now and add the body once we finish setting up the Express server. This is the last function in the series, so we don&#39;t need the next parameter/function:</p><pre><br>const generateRTCToken = (req, resp) =&gt; { };</pre><p>Let’s define a GET endpoint /rtc, passing in the nochache and generateRTCToken functions:</p><pre><br>app.get(&#39;/rtc/:channel/:role/:tokentype/:uid&#39;, nocache , generateRTCToken)</pre><p>You’ll notice the route contains :&lt;path&gt;. The colon (:) marks the path as a variable, and the user can pass in values like channel name, user role, type of token, and user UID to the route. We can access this data in our application.</p><p>As the last step in creating our Express server, we’ll implement the listen() method and pass in the port and a callback once the server is ready and listening on the given port:</p><pre>app.listen(PORT, () =&gt; {<br>  console.log(`Listening on port: ${PORT}`);<br>});</pre><h3>Generate the Agora RTC Token</h3><p>Now that we have our Express server set up, we are ready to add the functionality to the generateRTCToken function. We&#39;ll start by setting the response header to ensure that we don&#39;t run into any CORS issues:</p><pre>const generateRTCToken = (req, resp) =&gt; {<br>  resp.header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);</pre><h3>Get the Request Parameters</h3><p>Next, we’ll check for the channel in our request parameters. This is a required parameter, so if channelName is <em>undefined</em>, we need to return an error with a 500 response code and a JSON object with the error:</p><pre> const channelName = req.params.channel;<br>  if (!channelName) {<br>    return resp.status(500).json({ &#39;error&#39;: &#39;channel is required&#39; });<br>  }</pre><p>For uid and role we&#39;ll perform similar checks:</p><pre>  let uid = req.params.uid;<br>  if(!uid || uid === &#39;&#39;) {<br>    return resp.status(500).json({ &#39;error&#39;: &#39;uid is required&#39; });<br>  }<br>  // get role<br>  let role;<br>  if (req.params.role === &#39;publisher&#39;) {<br>    role = RtcRole.PUBLISHER;<br>  } else if (req.params.role === &#39;audience&#39;) {<br>    role = RtcRole.SUBSCRIBER<br>  } else {<br>    return resp.status(500).json({ &#39;error&#39;: &#39;role is incorrect&#39; });<br>  }</pre><p>Note: The only privilege enforced by the Agora platform by default is the join channel privilege. To enable the enforcement of other privileges, you need to make a request through Agora Support.</p><p>The user can optionally pass in an expiry query parameter that will set the time for the token to expire. We can access the value and check whether it exists. Otherwise, we set a suitable default of 3600 seconds:</p><pre> let expireTime = req.query.expiry;<br>  if (!expireTime || expireTime === &#39;&#39;) {<br>    expireTime = 3600;<br>  } else {<br>    expireTime = parseInt(expireTime, 10);<br>  }</pre><p>We’ll calculate the expiration time. It needs to be an integer that represents the time since <em>Jan 1, 1970</em>. We’ll use the current time and add our expiration time to it:</p><pre>  const currentTime = Math.floor(Date.now() / 1000);<br>  const privilegeExpireTime = currentTime + expireTime;</pre><h3>Build the Token</h3><p>Now that we have all the elements for our token, we are ready to use the RtcTokenBuilder object to generate the token. We&#39;ll check the tokenType and call the appropriate method on the object, passing in the required values:</p><pre>  let token;<br>  if (req.params.tokentype === &#39;userAccount&#39;) {<br>    token = RtcTokenBuilder.buildTokenWithAccount(APP_ID, APP_CERTIFICATE, channelName, uid, role, privilegeExpireTime);<br>  } else if (req.params.tokentype === &#39;uid&#39;) {<br>    token = RtcTokenBuilder.buildTokenWithUid(APP_ID, APP_CERTIFICATE, channelName, uid, role, privilegeExpireTime);<br>  } else {<br>    return resp.status(500).json({ &#39;error&#39;: &#39;token type is invalid&#39; });<br>  }</pre><h3>Return the Response</h3><p>The last step in generating our token is returning the JSON response that contains the token:</p><pre>...<br>  return resp.json({ &#39;rtcToken&#39;: token });<br>}</pre><h3>Test the Token Server</h3><p>Let’s go back to our package.json and add a command in the object. The start command will execute the <em>node index.js</em> command so that we can run our server instance:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node index.js&quot;<br>  },<br>}</pre><h3>Start the server</h3><p>Let’s go back to our Command Prompt window and use our new command: npm start</p><p>Once the server instance is listening, we’ll see <em>“Listening on port: 8080”</em> (or the port in your .env file) in our terminal window.</p><h3>Test the endpoint</h3><p>Now that our server instance is running, let’s open our web browser and test.</p><p>For example, pass “test” as the channel, &quot;publisher&quot; as the role, and &quot;uid&quot; as the tokenType with the UID of &quot;1&quot; :</p><pre>http://localhost:8080/rtc/test/publisher/uid/1</pre><p>This will display:</p><pre>{&quot;rtcToken&quot;:&quot;0062ec0d84c41c4442d88ba6f5a2eeb828bIAD9qg4N4hd04MvaY6A72m4BjYmO/7+xnRMinaI0ncLzkAx+f9gAAAAAEACS0zcn9gASXwEAAQCGvRBf&quot;}</pre><p>Other examples produce a similar output:2</p><pre>localhost:8080/rtc/test/publisher/uid/1 localhost:8080/rtc/test/publisher/uid/1?expiry=1000 localhost:8080/rtc/test/subscriber/userAccount/ekaansh</pre><h3>RTM Tokens</h3><p>We can use the same process to configure a route to generate RTM tokens. You can look at the generateRTMToken function in the <a href="https://github.com/AgoraIO-Community/Agora-Node-TokenServer">finished project</a> for generating RTM tokens. The /rtm route looks like this, passing in a UID as &quot;1&quot;:</p><pre>http://localhost:8080/rtm/1</pre><p>The response looks like:</p><pre>{&quot;rtmToken&quot;:&quot;0062ec0d84c41c4442d88ba6f5a2beb828bIAD9qg4N4hd04MvaY6A72m4BjYmO/7+xnRMinaI0ncLzkAx+f9gAAAAAEACS0zcn9gASXwEAAQCGvRBf&quot;}</pre><h3>Conclusion</h3><p>And just like that, we are done! In case you weren’t coding along or want to see the finished product together, you can find it on <a href="https://github.com/AgoraIO-Community/Agora-Node-TokenServer">GitHub</a>. You can deploy it to Heroku in two clicks using the button in the Readme.</p><p>There’s also a version written in Typescript available on the <a href="https://github.com/AgoraIO-Community/Agora-Node-TokenServer/tree/typescript">typescript branch</a>. If you see any room for improvement, feel free to fork the repo and make a pull request!</p><h3>Other Resources</h3><p>For more information about tokens for Agora applications, you can take a look at the <a href="https://docs.agora.io/en/Agora%20Platform/token?platform=All%20Platforms">Set up Authentication</a> guide. We also have a token server built with Golang and Gin that you can find <a href="https://github.com/AgoraIO-Community/agora-token-service">here</a>.</p><p>If you have any questions, I invite you to <a href="https://agora.io/en/join-slack">join the Agora Developer Slack community</a> and ask them there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd20f91dd768" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>