<?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 Parham on Medium]]></title>
        <description><![CDATA[Stories by Parham on Medium]]></description>
        <link>https://medium.com/@pazel?source=rss-53d14bb89815------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JPjeZfnzpVoSsblh-DuO6g.png</url>
            <title>Stories by Parham on Medium</title>
            <link>https://medium.com/@pazel?source=rss-53d14bb89815------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:21:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pazel/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[Risk-Based Authentication using Auth0 Actions and Have I Been Pwned APIs]]></title>
            <link>https://javascript.plainenglish.io/risk-based-authentication-using-auth0-actions-and-have-i-been-pwned-apis-fd3cb65c040a?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd3cb65c040a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Sat, 29 Jan 2022 23:32:43 GMT</pubDate>
            <atom:updated>2022-01-31T13:26:00.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_mkTx6eGle7bdcTS" /></figure><p>In this article, we look at how to improve the security of a system by implementing Risk-based Authentication. To achieve this we will integrate the <a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> APIs into our login flow using Auth0 Actions.</p><h3>What is Risk-based Authentication?</h3><p>To put it simply, Risk-based Authentication or RBA uses real-time intelligence about a user to decide if their activity is normal (low-risk) or suspicious (high-risk).</p><p>RBA estimates a risk score based on login behaviour. The calculation of risk score typically happens for any given access attempt in real-time, based on a predefined set of rules. Users are then presented with authentication options appropriate to that risk level.</p><p>Many factors are considered when assessing the risk of login activity. For example:</p><ul><li>Location of the user</li><li>Device/browser</li><li>IP and network information</li><li>Number of attempts to log in</li></ul><p>Or factors related to a user and their context. For example, a login attempt to the company’s HR system at 2 am can be considered suspicious (high risk).</p><p>And many more factors that might make sense in a particular context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*678Ml-PmVKLAOMgJ" /></figure><p>Most Authentication providers support RBA.</p><p>Here are links to a few examples, <a href="https://auth0.com/docs/secure/multi-factor-authentication/adaptive-mfa">Auth0</a>, <a href="https://help.okta.com/en/prod/Content/Topics/Security/behavior-detection/faq-behavior-detection.htm">Okta</a>, <a href="https://docs.microsoft.com/en-us/azure/active-directory/authentication/tutorial-risk-based-sspr-mfa">Azure AD</a>, <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-adaptive-authentication.html">AWS Cognito</a> and <a href="https://support.google.com/a/answer/6002699?hl=en">Google</a> support RBA.</p><p>Using RBA you do not need to always enforce MFA and can only ask for additional authentication if it’s required based on the risk score. This helps to improve the user experience of the login flow and make it easier for low-risk logins to happen with less friction.</p><h3>Built-in Auth0 features for Risk-based Authentication</h3><p>Luckily, Auth0 has some features to support you here</p><ul><li><a href="https://auth0.com/docs/secure/multi-factor-authentication/adaptive-mfa">Adaptive MFA</a> — this feature triggers MFA and asks the user to complete an MFA Challenge when the confidence is low (activity is high-risk).</li></ul><p>Auth0 also provides a range of <a href="https://auth0.com/docs/secure/attack-protection">Attack Protection</a> features that goes hand in hand with the RBA.</p><ul><li><a href="https://auth0.com/docs/secure/attack-protection/breached-password-detection">Breached Password Detection</a> — Auth0 tracks large security breaches that are happening on major third-party sites. If a user password is leaked in a data breach, they will be notified and also they might get blocked from logging in.</li><li><a href="https://auth0.com/docs/secure/attack-protection/bot-detection">Bot Detection</a> — Bot detection mitigates scripted attacks by detecting when a request is likely to be coming from a bot and presenting a Captcha challenge that blocks the Bot attack.</li></ul><p>These features support most of the typical scenarios for Risk-based Authentication and you can further customise them to best match your usage.</p><h3>What is <a href="https://haveibeenpwned.com/">have i been pwned</a> and how can it help?</h3><p>Created by security expert <a href="https://en.wikipedia.org/wiki/Troy_Hunt">Troy Hunt</a>, <a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> is a website that allows Internet users to check whether their data has been compromised by data breaches.</p><p>As a user, you can go to this website, enter your email and get a list of data breaches that your email address has been involved in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*epor0QNEOeMkL_es" /></figure><p><a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> also offers REST APIs that you can use to make the same queries through code.</p><p>For example, this is the response for an API that returns the list of data breaches for an email address.</p><p>Request:</p><pre><a href="https://haveibeenpwned.com/api/v3/breachedaccount/%7Baccount%7D?truncateResponse=false">https://haveibeenpwned.com/api/v3/breachedaccount/{account}?truncateResponse=false</a></pre><p>Response:</p><pre>[<br>    {<br>        &quot;Name&quot;: &quot;XYZ&quot;,<br>        &quot;Title&quot;: &quot;XYZ&quot;,<br>        &quot;Domain&quot;: &quot;xyz.com&quot;,<br>        &quot;BreachDate&quot;: &quot;2020-03-22&quot;,<br>        &quot;AddedDate&quot;: &quot;2020-11-15T00:59:50Z&quot;,<br>        &quot;ModifiedDate&quot;: &quot;2020-11-15T01:07:10Z&quot;,<br>        &quot;Description&quot;: &quot;In March 2020, the stock photo site .....&quot;,<br>        &quot;LogoPath&quot;: &quot;.../Images/PwnedLogos/xyz.png&quot;,<br>        &quot;DataClasses&quot;: [<br>            &quot;Email addresses&quot;,<br>            &quot;IP addresses&quot;,<br>            &quot;Names&quot;,<br>            &quot;Passwords&quot;,<br>            &quot;Phone numbers&quot;,<br>            &quot;Physical addresses&quot;,<br>            &quot;Usernames&quot;<br>        ],<br>        &quot;IsVerified&quot;: true,<br>        &quot;IsFabricated&quot;: false,<br>        &quot;IsSensitive&quot;: false,<br>        &quot;IsRetired&quot;: false,<br>        &quot;IsSpamList&quot;: false,<br>        &quot;IsMalware&quot;: false<br>    },<br>...<br>]</pre><p>I think you can guess where I am going with all this by now. I want to use <a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> REST APIs as part of my login flow to detect if a username (email) has been listed in a data breach and react appropriately based on the risk factor.</p><p>For example, if the user (email address) is listed in a recent data breach, I will send the user a change (reset) password email and ask them to complete an MFA challenge. I will further describe the login flow in the rest of this article.</p><p>To use the APIs you will need to purchase an API key. Please read <a href="https://haveibeenpwned.com/API/Key">these instructions</a> to get your HIBP API key.</p><h3>Use Auth0 Actions to extend the Risk-based Authentication</h3><p>As mentioned Auth0 built-in features already provide a solid ground for Risk-based Authentication but based on your business requirement you might need to consider more factors as part of your risk assessment.</p><p>This is where Auth0 Actions shine and let you extend the capabilities of Auth0 beyond what is defined.</p><p><a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> provides data for <a href="https://haveibeenpwned.com/FAQs">data breaches</a> and also <a href="https://haveibeenpwned.com/Pastes">Pastes</a> and usually has the data before other sources. So it can be a good accompanying source to secure your system.</p><p>However, using the <a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> REST APIs is just an example to demonstrate how you can use other data sources to enhance your risk assessment. So please do your research before adopting this data source.</p><h3>What are Auth0 Actions?</h3><blockquote>Auth0 Actions are secure, tenant-specific, versioned functions written in Node.js that execute at certain points during the Auth0 runtime. Actions are used to customize and extend Auth0’s capabilities with custom logic. <a href="http://auth0.com/docs/customize/actions">auth0.com/docs/customize/actions</a></blockquote><p>So the idea for this integration is to use a Login Action and write a Node.js function to:</p><ul><li>Call <a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> REST APIs to figure out if the email address (username) is listed in a data breach.</li><li><a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> response will give me a list of data breaches for a given email address.</li><li>I will pick the most recent breach.</li><li>Then I check to see if the user has changed their password after the most recent data breach.</li><li>If so user can login without extra authentication.</li><li>If Not, the user needs to complete an MFA challenge and they receive an email to change(reset) their password.</li></ul><p>This flow chart shows what the new login flow looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tNO_MtmqyiEEgWm8" /></figure><blockquote>Note: Users signing in with <a href="https://auth0.com/docs/authenticate/identity-providers/social-identity-providers">social</a> or <a href="https://auth0.com/docs/authenticate/identity-providers/enterprise-identity-providers">enterprise</a> connections must reset their passwords with the identity provider (such as Google or Facebook).</blockquote><p>In the case of social users, you might want to limit their access to sensitive data in the system or warn them about the breach. So they can take any required actions. (not in the scope of this example)</p><p>Examples of other things you can do are:</p><ul><li>Completely block user access if you are dealing with a high-risk activity. For example, if the leaked account belongs to a company’s Finance department staff that can do high valued monetary transactions. In this case, you might take more drastic measures involving in-person account recovery or using <a href="https://en.wikipedia.org/wiki/Know_your_customer">KYC</a> services like <a href="https://onfido.com/">Onfido</a> to make sure of the user identity.</li></ul><p>For sake of this blog, we will stick with a simpler REST API integration example.</p><h3><a href="https://auth0.com/docs/customize/actions/write-your-first-action">Create your first Action</a></h3><p>To start you need an Auth0 account. If you don’t already have one, follow <a href="https://auth0.com/docs/get-started">these instructions</a> to set up one.</p><p>After you log in to your Auth0 account click on the Actions &gt; Flows &gt; Login to create the login Action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6W3mIim2mu0BloFb" /></figure><p>This creates a <a href="https://auth0.com/docs/customize/actions/triggers/post-login">post-login</a> trigger that runs as part of the Login flow. It is executed after a user logs in and when a Refresh Token is requested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z2TSqCGEgFG_7lsJ" /></figure><p>Click on the + button in Add Action and select Build Custom. Call it <em>have I been pwned</em> and leave the rest as is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yIJGjG-yIJrqg2Hm" /></figure><p>After Creation, you come to the edit screen. Here you can write the code for your Action, test it and deploy it.</p><p>Next, we write the logic to call <a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> APIs to check if the user email address has been involved in a data breach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m3eaI4ebUVOSaow5" /></figure><p>We will use the <em>onExecutePostLogin</em> function which is a handler that will be called during the execution of a <a href="https://auth0.com/docs/customize/actions/triggers/post-login">PostLogin flow</a>.</p><p><em>onExecutePostLogin</em> function receives two parameters, <em>API</em> (of type <a href="https://auth0.com/docs/customize/actions/triggers/post-login/api-object">PostLoginApi</a>) and <em>event</em> (of type <a href="https://auth0.com/docs/customize/actions/triggers/post-login/event-object">Event</a>)</p><p>For this example, we will use the event.user to find the user&#39;s email address. event.user contains information on the user on whose behalf the current transaction was initiated, like email, identities and more.</p><p>We also use the event.client to get the client id. Knowing the client id we can send a reset password email to the user.</p><p>You can read more on the full capabilities of the api and event in the <a href="https://auth0.com/docs/customize/actions/triggers/post-login">Auth0 documentation</a>.</p><p>We will use two APIs from <a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a>:</p><ul><li>Get the list of data breaches for an email address. This will return an array of breach names that are sorted by date already. So the first item on the list is the most recent breach.</li><li>Get the details of a particular breach. We will use the name of the first breach from the previous list to get the details of it. This includes the BreachDate.</li></ul><p>You can read about the capabilities of <em>have i been pwned</em> APIs <a href="https://haveibeenpwned.com/API/v3">here</a></p><h3>Code for Login Action</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1895f6204497e0bc39581ee497fa64d9/href">https://medium.com/media/1895f6204497e0bc39581ee497fa64d9/href</a></iframe><h3>Test your action</h3><p>On the left side of the Actions editor, you have 3 more options. The one that looks like a play button is Test. If you click on it give you an example login payload and once you hit run it will simulate a call to the action with the same body that you would get on a Login / Post Login flow.</p><p>You can edit the payload as you like. For example, I changed the email address to account-exists@hibp-integration-tests.com.</p><p>This is a test email address provided in <a href="https://haveibeenpwned.com/"><em>have i been pwned</em></a> API documentation for the scenario that the user has data breaches.</p><p>After you run the action you can see the results in the bottom right panel.</p><p>Here is an example from my test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S9zrca0MwYN01eLH" /></figure><p>You can use console.log to see the result of each step in your function call.</p><p>Actions editor saves your code automatically and once you are happy you can click the deploy button.</p><p>Now when a user tries to log in they will go through our login Action and need to successfully get through our enhanced Risk-based Authentication before they can successfully log in.</p><h3>Other features of Actions</h3><p>Actions have more to offer. You get a secret manager, a package manager (for npm packages) and the version history of the code built-in.</p><p>This makes up for a better developer experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Z7yXHCUx1Nm5ErR" /></figure><h3>Actions limitations</h3><p>Actions give you an excellent way to customise and extend Auth0 capabilities but there are some limitations. For example, each execution of a flow must complete in 10 seconds or less or the processing will end in an error.</p><p>Some of these limitations are in place to ensure that the user experience stays smooth as you add more code and capabilities.</p><p>Make sure to check these <a href="https://auth0.com/docs/customize/actions/limitations">limitations</a> before you start.</p><h3>Conclusion</h3><p>Auth0 Actions provide an easy way for development teams to implement authentication and authorisation based on their unique needs and open the door to many possibilities.</p><p>We only scratched the surface with this Login Action example. Actions offer more hooks and there are plenty of examples for each. The same goes for our risk calculation function. For example, we can make use of the type of breach (e.g: email, password, …) and more data that is available in <a href="https://haveibeenpwned.com/API/v3"><em>have i been pwned</em></a> response to having a more meaningful risk calculation.</p><p>If this looks like something you have been looking for, I encourage you to read the Actions <a href="https://auth0.com/docs/customize/actions">documentation</a> to learn more about the capabilities of different Actions and find more examples.</p><p>Thanks for reading this article. Please reach out here or on <a href="https://twitter.com/_pazel">Twitter</a> if you have any feedback or questions.</p><h3>References</h3><ul><li><a href="https://auth0.com/docs/customize/actions">Auth0 Action docs</a></li><li><a href="https://haveibeenpwned.com/API/v3">have i been pwned</a></li></ul><p><em>More content at </em><a href="http://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>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3cb65c040a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/risk-based-authentication-using-auth0-actions-and-have-i-been-pwned-apis-fd3cb65c040a">Risk-Based Authentication using Auth0 Actions and Have I Been Pwned APIs</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Capture and Verify User’s Phone Number Using Auth0 Actions]]></title>
            <link>https://javascript.plainenglish.io/how-to-capture-and-verify-users-phone-number-using-auth0-action-3bd48d0d6d6c?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd48d0d6d6c</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 03:23:00 GMT</pubDate>
            <atom:updated>2022-01-19T08:41:38.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEJCWWPCPjtkvHWgamPsNg.png" /></figure><p>For various scenarios, a business might need to record &amp; verify a user’s phone number before they can provide a service.</p><p>This example demonstrates how you can capture and verify the user’s phone number as part of Sign up (first login) using Auth0 Actions.</p><blockquote>Auth0 Actions are secure, tenant-specific, versioned functions written in Node.js that execute at certain points during the Auth0 runtime. <br>Actions are used to customize and extend Auth0’s capabilities with custom logic.<br><a href="https://auth0.com/docs/customize/actions">https://auth0.com/docs/customize/actions</a></blockquote><p>Here is a diagram showing how the solution works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*5cbTHAveIaThVMW_IR9MQA.png" /></figure><h4><strong>Disclaimer</strong></h4><p>If you are looking for <a href="https://auth0.com/docs/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa">Multi-Factor Authentication using SMS</a>, it’s supported out of the box with Auth0.</p><p>This solution is just a suggestion to get around the mobile verification issue.<br>I found some users on the Auth0 forum asking for this feature so I decided to see if I can use Auth0 Actions to provide a solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pm6E7XwbnSsnjhQPJ871Xw.png" /><figcaption><a href="https://community.auth0.com/t/mobile-verification/65206">https://community.auth0.com/t/mobile-verification/65206</a></figcaption></figure><h3>The solution brekdown</h3><p>We need the following pieces to make this flow work:</p><ul><li>A Twilio account. Twillio provides the APIs that we need to send the verification SMS and also to verify the code after the user submits it.</li><li>Custom signup form with an extra field to record the user’s phone number.</li><li>Auth0 Action that will execute on login and make use of the recorded phone number to send a verification code to the user’s device using SMS.<br>This Action is also responsible for the redirect to the code verification form.</li><li>A simple web application that will host the form to get the verification code from the user and redirect the user along with the code to Auth0 to finish the login.</li></ul><h4>1- Creating a Twilio account and the verification service</h4><p>To create an account go to <a href="https://www.twilio.com/try-twilio">https://www.twilio.com/try-twilio</a> and create a free account.</p><p>After login, click on the verify from the side menu. This is where we can add a verification service. This service will help us to send an SMS to the user phone number and use the code in that SMS for verifying the number.</p><p>Click <strong>Verify -&gt; Try it out </strong>and create a new service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3XQQ1hDkTFjKI2T8XO1Iw.png" /></figure><p>In the second and third steps, you get a chance to test your newly created service in the console. This helps you to verify the <em>URL</em> you need to call and the parameters you need to pass for the payload.<br>After you have tested your new service and you are happy that it all works, we are done with the Twillio setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEeqMyjcrWZ5V_2CoIq45w.png" /></figure><p>If you need to see your service id at any later stage you can come back to verify and it will be listed under services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEMilk0SXEq9VOyS3HuAOg.png" /></figure><h4>2- Custom signup form with an extra field to record the user’s phone number</h4><p>There are multiple ways you can customise your login/signup form. <br>In this example, I am using the Auth0 lock and passing the configuration for extra fields.</p><p>To learn more about other ways you can customise the signup experience check <a href="https://auth0.com/docs/libraries/custom-signup">this page</a>.<br>This is the configuration you can pass to the Auth0 lock to add an extra field.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f41e44b70ee9b652304d1ffe16e3e3ef/href">https://medium.com/media/f41e44b70ee9b652304d1ffe16e3e3ef/href</a></iframe><p>And You will get a signup form like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*HY82fVbQQToFEDKi-yKzHg.png" /></figure><p>Now after the user signs up, the phone number will be added to the user profile under the user_metadata . <br>At this stage, we have not verified the phone number yet.</p><h4>3- Create a Login Action to verify the phone number</h4><p>Next step we need a login Action to read the phone number from the user profile and send a verification SMS to the user’s phone number.</p><p>Among the Auth0 Action triggers Login is the only one that supports <a href="https://auth0.com/docs/customize/actions/triggers/post-login/redirect-with-actions">redirect</a> which is what we need for this flow. Since the phone number verification happens only once users will only go through it the first time they log in.</p><p>For the subsequent logins, the Action will check if the phone number exists and is verified for a particular user and if so it will just ignore the rest.</p><p>To start you need an Auth0 account. If you don’t already have one, follow <a href="https://auth0.com/docs/get-started">these instructions</a> for setting up one.</p><p>To create the login Action Click on the <strong>Actions &gt; Flows &gt; Login</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8B3xqIO_aBWy6RHSl22HwA.png" /></figure><p>This creates a post-login trigger that runs as part of the Login flow. <br>It is executed after a user logs in and when a Refresh Token is requested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CpHXYElEf12N_VySTSk4A.png" /></figure><p>Click on the + button in Add Action and select Build Custom. Call it <strong><em>Verify phone number</em></strong> and leave the rest as is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBaMdDz1Wnw4AxVitEvdew.png" /></figure><p>After Creation, you come to the edit screen.<br>Here you can edit the code and write the logic to call Twilio APIs to send a verification code and verify it.</p><p>To do this we need to write two separate functions.</p><ul><li>onExecutePostLogin — Handler that will be called during the execution of a PostLogin flow.</li><li>onContinuePostLogin — Handler that will be invoked when this Action is resuming after an external redirect.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izMj2YbBGvdOPd0tezrmYw.png" /></figure><p>1- In onExecutePostLogin function Code is simply reading the phone number from the user user_metadata and sending an SMS to the phone number using Twilio REST API.<br>After sending the SMS successfully, this function will redirect the user to the webform to enter the verification code we just sent them. <br>This webform is simply a web application that you need to create and host yourself.<br>It doesn&#39;t need to be anything fancy, as long as it can get the verification code and redirect the user back to Auth0.</p><p>2- The onContinuePostLogin comes into play after the user is redirected back to Auth0. At this point, you will have the verification code sent to the function from the webform using a redirect. <br>So we can use the code and call another REST API from Twilio to verify it. <br>If all goes well and you get a successful response from Twillio the phone number is verified and we will add this information to the user profile but this time under the app_metadata .</p><p><em>Tip: </em><em>user_metadata can be edited by the logged-in user but the user cannot edit </em><em>app_metadata.</em></p><p>Here is the code for the Action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f5c577bbd2b4786732c1e2d13b6562c/href">https://medium.com/media/8f5c577bbd2b4786732c1e2d13b6562c/href</a></iframe><h4>4- Example webform to get the verification code and perform the redirect</h4><p>The code verification form is a basic HTML page with a small bit of JavaScript to handle the form submission. (based on <a href="https://github.com/dylanswartz/actions-consent-form-example">Dylan Swartz example</a> for consent form)</p><p>In this example, we will use <a href="https://vercel.com/">Vercel</a> to host the form but you use any hosting provider.</p><ol><li>If you haven’t done so already, <a href="https://vercel.com/signup">sign up for a Vercel account</a> and install the <a href="https://github.com/vercel/vercel/tree/main/packages/cli">Vercel CLI</a> with npm i -g vercel.</li><li>While you’re in the same directory as the index.html, simply run the following command to spin it up in Vercel:</li></ol><pre>$ vercel</pre><p>Press enter for each prompt the vercel command gives you to select the defaults. The output of this command will contain the URL of your newly hosted code verification form.</p><ol><li>In your Action’s code be sure to delete the existing VERIFY_FORM_URL and replace it with the value that is the URL that was output in the previous step.</li><li>If you want to make changes to the code verification form, you can upload a new version simply by running the same vercel command you did before.</li></ol><p>Here is the code for this web application.</p><p><a href="https://github.com/pazel-io/auth0-twilio-phone-verification">GitHub - pazel-io/auth0-twilio-phone-verification: This sample demonstrates a minimal implementation of the `redirect` protocol. It contains an Auth0 Action (https://auth0.com/docs/customize/actions) that will redirect the user to a simple form so they can enter a verification code recieved by SMS in order to verify their phone number.</a></p><p>There you have an end-to-end solution to verify phone numbers as part of your Auth0 login and account creation.</p><h4>Final notes</h4><p>There are more things to consider to make this a production-ready solution.</p><ul><li><strong>Error handling</strong><br>You need to consider and handle different errors that can happen.<br>The example Action code makes use of api.access.deny() to reject the login in case an error happens.</li><li><strong>Setting up different environments(tenants) for different stages. </strong><br>When you set up Auth0 tenant or Twilio service you need to separate your dev and prod environments.</li><li><strong>Keeping your Secret(API) keys safe<br></strong>All the secrets used in this solution only exist on the server-side of the code (action.js and verify.js) which makes it easier to keep them safe.<br>Make sure you do not expose the sensitive keys in your client-side code or commit them to your repo.<br>Actions have secret management built-in to keep your secrets safe and provide a convenient way to access them in your action code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FDCF-ydTV9i045uCd3ZDg.png" /></figure><p>and you can access them like this</p><pre>event.secrets.SESSION_TOKEN_SECRET</pre><ul><li><strong>Trusted Callback URL (</strong>quoting from <a href="https://github.com/dylanswartz/actions-consent-form-example">Dylan Swartz example</a><strong>)<br></strong>Our sample Action and consent form makes one security compromise for the sake of convenience: the rule passes the Auth0 domain (i.e. your-tenant.auth0.com) to the form website and the form uses that to construct a callback URL (i.e. https://your-tenant.auth0.com/continue) for returning to the rule. This is essentially an <a href="https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet">open redirect</a> and should not be used in production scenarios.<br>You can lock this down by configuring your form website implementation to only return to a specific URL (i.e. just your Auth0 tenant) instead of one that’s generated from a query param. You can then simplify the rule too so it no longer passes the Auth0 domain.</li><li><strong>Data Integrity (</strong>quoting from <a href="https://github.com/dylanswartz/actions-consent-form-example">Dylan Swartz example</a><strong>)<br></strong>As stated, this is a very basic example of using an Action Redirect to invoke a consent form. That said, at Auth0 we take security very seriously. The confirm field (which has the value of yes) that is being passed back to auth0 as a signed token using a shared SESSION_TOKEN_SECRET.<br>In production scenarios where you need assurances of the integrity of the data being returned by the external website (in this case in our hosted code verification form). For example, if you want to be sure that the data truly came from a trusted source, then it should be signed. If the data is sensitive, then it should be encrypted. A good mechanism for doing this is to use a <a href="http://jwt.io/">JWT</a> (JSON Web Token). You can build a JWT with claims (that you can optionally encrypt) and then sign it with either a secret shared with your Auth0 Action or with a private key, whose public key is known by the action. The Action can then verify that the claims are legit and decrypt them, if necessary.</li><li><strong>Social logins<br></strong>This solution needs some adjusting if you want to offer social logins/signup.<br>In the case of social login, users will not use our signup form, so we need to capture the phone number through a separate form in our application.</li></ul><p>Thanks for reading this article. <br>Please reach out here or on <a href="https://twitter.com/_pazel">Twitter</a> if you have any feedback or questions.</p><p>Here is the link to my example code repository:<br><a href="https://github.com/pazel-io/auth0-twilio-phone-verification">https://github.com/pazel-io/auth0-twilio-phone-verification</a></p><p>References:</p><ul><li><a href="https://auth0.com/docs/customize/actions">Auth0 Action docs</a></li><li><a href="https://auth0.com/docs/customize/actions/triggers/post-login/redirect-with-actions">Redirect with Actions</a></li><li><a href="https://github.com/dylanswartz/actions-consent-form-example">Dylan Swartz example</a> for consent form</li><li><a href="https://www.twilio.com/docs/verify">Twilio verify service</a></li></ul><p><em>More content at </em><a href="http://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>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd48d0d6d6c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-capture-and-verify-users-phone-number-using-auth0-action-3bd48d0d6d6c">How to Capture and Verify User’s Phone Number Using Auth0 Actions</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Keep Your Secrets from Your Source Code in an Angular Project ]]></title>
            <link>https://javascript.plainenglish.io/how-to-keep-your-secrets-from-your-source-code-in-an-angular-project-6963374b464e?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/6963374b464e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 02:49:47 GMT</pubDate>
            <atom:updated>2021-10-02T09:32:45.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOuy1ua7BoQjnG8mWyXbpA.png" /></figure><p>Let’s face it, we all have secrets, but that’s not what I want to talk about.</p><p>This article shows you a technique to easily use Angular’s environment.ts file to access sensitive data without revealing your secrets.</p><h3>What is a secret?</h3><p>Secret refers to any sensitive values that are not supposed to be pushed as part of the source code. This can be things like API keys, OAuth tokens, certificates, and passwords.</p><p>These secrets are often required to integrate with other providers or services as part of the build or deployments.</p><p>Secrets can be different based on deployment environments as well.</p><p>For example, you might use a test account for development with a different API key to your production.</p><h3>Why should you care about secrets?</h3><p>Many projects utilise cloud-based Git and CI/CD tools to manage the source code, build and deploy. So keeping secrets from leaking into your source code is essential.</p><p>You typically deal with two types of secrets in client-side projects.</p><h4>1. Secrets that your client-side app needs to use when talking to a provider.</h4><p>These secrets are still visible in the JS bundle or API calls.<br>These are secrets like your Google API key that needs to be sent in an HTTP request to Google, for example.</p><p>For these types of secret usually, you need accompanying security measures. For example, Google lets you limit an API key to a domain or limit it to specific Google services.</p><p>Even for this type, it is a good practice not to hardcode in the source.<br>hardcoding them makes the secret management based on the environment difficult.</p><p>Let’s say you have a Test and Production environment which use different Google API keys.</p><p>If the secret is part of the source code you need to remember to change the code each time you want to change it from Test API key to Production one.</p><p>In the same way, updating your secret to rotate it can be more challenging.</p><p>Now let’s add the fact that source code will spread across branches and devices.</p><p>I guess you get the picture. This is important and for that reason, there are best practices and tools to help you.</p><p>For example, Google has <a href="https://support.google.com/googleapi/answer/6310037?hl=en">“Best practices for securely using API keys.”</a><br>Which suggest not to store API keys in source code.</p><p>Or Github will send you a warning email if you push your Google API key.<br>They have this <a href="https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning">Automatic secret scanning</a> going on.</p><h4>2. Secrets that are just required as part of the build but not after that.</h4><p>For example, if my build process can query my content repository(headless CMS) to pre-render some pages to generate static pages.</p><p>In that case, I do not need the content repository’s API key after the build is done. I will only take the results (static pages) to deploy them.<br>So I can genuinely secure my key by not putting in the source code.</p><p>If you are not convinced, read <a href="https://blog.gitguardian.com/secrets-credentials-api-git/">Why secrets in git are such a problem — Secrets in source code</a>.</p><h3>Utilise Angular environment.ts file to access secrets</h3><p>The Angular official way to manage the environment configurations is to use the provided <a href="https://angular.io/guide/build">environment.ts file</a>.</p><p>You can create a file for each environment.</p><pre>└──myProject/src/environments/<br>                   └──environment.ts<br>                   └──environment.prod.ts<br>                   └──environment.stage.ts</pre><p>and provide the configs of each environment like this</p><pre>export const environment = {<br>  production: true,<br>  apiUrl: &#39;http://my-prod-url&#39;<br>};</pre><p>You can easily access this configuration in your code.</p><pre>import { environment } from &#39;../environments/environment&#39;;</pre><pre>  public getBooks() {<br>    const url = `${environment.apiUrl}/books`;<br>    return this.http.get&lt;Book&gt;(url);<br>  }</pre><p>To get environment-specific configs, you can use the env name in the build.</p><p>ng build --configuration=stage or use angular.json to define the same thing based on the environment.</p><pre>&quot;serve&quot;: {<br>  &quot;builder&quot;: &quot;@angular-devkit/build-angular:dev-server&quot;,<br>  &quot;options&quot;: {<br>    &quot;browserTarget&quot;: &quot;your-project-name:build&quot;<br>  },<br>  &quot;configurations&quot;: {<br>    &quot;production&quot;: {<br>      &quot;browserTarget&quot;: &quot;your-project-name:build:production&quot;<br>    },<br>    &quot;staging&quot;: {<br>      &quot;browserTarget&quot;: &quot;your-project-name:build:staging&quot;<br>    }<br>  }<br>},</pre><p>These configs are pushed to your source code to support the build. So anyone who has access to source code can see these configs in plain text.</p><p>This technique is completely fine for typical configs like the apiUrl but not good enough for secrets.</p><h3>Solution</h3><p>We can provide secrets through the environemnt.ts files without pushing it to source code using the <a href="https://en.wikipedia.org/wiki/Environment_variable#:~:text=An%20environment%20variable%20is%20a,in%20which%20a%20process%20runs">Environment variable</a>.</p><p>An environment variable is a dynamic-named value that can affect how running processes will behave on a computer. They are part of the environment in which a process runs. For example, a running process can query the value of the TEMP environment variable to discover a suitable location to store temporary files, or the HOME or USERPROFILE variable to find the directory structure owned by the user running the process.</p><p>These Environment variables are set up on the build machine which your Angular build runs.</p><p>There are different ways to set up Environment variables, which can differ based on the context.</p><p>We don’t want to set up these variables manually, so we use a <a href="https://www.freecodecamp.org/news/nodejs-custom-env-files-in-your-apps-fa7b3e67abe1/">.env file</a>. You can easily set multiple environment variables and values in one go.</p><p>Later you can use the .env file to read these variables based on the environment. The content of .env looks like this.</p><pre>GOOGLE_API_KEY=34232423423423234233fsajgsaagdda<br>AUTH0_CLIENT_ID=54235nfgde24gbdf235432<br>PASSWORD=adjkvknh29827;nbv_</pre><p>So the idea is that you load the .env file related to an environment (Test, Production) and somehow provide them to the Angular environment.ts file.</p><h4>How is this approach more secure?</h4><p>This approach is more secure because simply the .env file, which contains the sensitive values, only exists on your build machine (private server).</p><p>So only the person who has access to the build server can read the file. Sensitive values are no longer part of the source code.</p><h4>What about the cloud-based CI/CD?</h4><p>All the cloud-based CI/CDs already provide a way to define and manage Environment variables.</p><p>Once you set them up, the Environment variables will be available at runtime when the build is running, and we can access them the same way as if it&#39;s our server. Plus, the Environment variables will be secure since they are only available through the cloud-based CI/CD admin dashboard.</p><p>Here are some examples from some of the popular cloud-based CI/CDs.</p><p><a href="https://vercel.com/docs/concepts/projects/environment-variables">Vercel</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jQxcSSJiLNX2__4O" /></figure><p><a href="https://docs.github.com/en/actions/learn-github-actions/environment-variables">Github Actions</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_wYYh2GnnobO_h9u" /></figure><p><a href="https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html">AWS Amplify</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KY4j0fiTCGFVBvvx" /></figure><h3>How to access the Environment variable in Angular environment.ts files?</h3><p>Angular build already utilises Node.js at runtime to do the build, and we can add an npm script to generate the environement.ts as part of the build.</p><p>This script will read the environment variables and generate the environement.ts file. This script is simply JavaScript, so write any logic you need to generate the output.</p><p>Here is the code for the script.</p><pre>const setEnv = () =&gt; {<br>  const fs = require(&#39;fs&#39;);<br>  const writeFile = fs.writeFile;<br>// Configure Angular `environment.ts` file path<br>  const targetPath = &#39;./src/environments/environment.ts&#39;;<br>// Load node modules<br>  const colors = require(&#39;colors&#39;);<br>  const appVersion = require(&#39;../../package.json&#39;).version;<br>  require(&#39;dotenv&#39;).config({<br>    path: &#39;src/environments/.env&#39;<br>  });<br>// `environment.ts` file structure<br>  const envConfigFile = `export const environment = {<br>  googleApiKey: &#39;${process.env.GOOGLE_API_KEY}&#39;,<br>  auth0ClientId: &#39;${process.env.AUTH0_CLIENT_ID}&#39;,<br>  appVersion: &#39;${appVersion}&#39;,<br>  production: true,<br>};<br>`;<br>  console.log(colors.magenta(&#39;The file `environment.ts` will be written with the following content: \n&#39;));<br>  writeFile(targetPath, envConfigFile, (err) =&gt; {<br>    if (err) {<br>      console.error(err);<br>      throw err;<br>    } else {<br>      console.log(colors.magenta(`Angular environment.ts file generated correctly at ${targetPath} \n`));<br>    }<br>  });<br>};</pre><pre>setEnv();</pre><p>Let’s see what is happening here.</p><ul><li>process.env provides access to the Environment variable in Node.js. So any variable that exists on the build machine will be available through it.</li><li>fs.writeFile let us create a file and write content to it. In this case, to generate the environment.ts file.</li><li>As a bonus, I am reading the package.json so I can get its version. This way, we can have a version number to display in our UI. This technique is convenient when for providing versioning as part of a release cycle.</li><li>targetPath is pointing to where the target file should exist.</li><li>envConfigFile constant is a template literal that provides the template and content of the environment.ts file. You can specify the variables you want to have in your environment.ts here.</li><li>console.log are there to make it easy to see the output of the file generation for debugging. Make sure not to log sensitive data here. Logs usually stay around long after the build is complete.</li><li>dotenv package can load a .env file so you can access the variable you have defined in that file. This trick helps manage a private build server or even building on your local development machine. The script won&#39;t fail if dotenv does not find the file in the specified location. So you can leave it there to support both local machine builds and cloud-based CI/CDs.</li></ul><h3>Automate it</h3><p>To glue things together, we need to do two more things.</p><ul><li>Firstly, we need to add an npm script that can run our newly added code. Here the new config npm script will run our code. We also update the npm script for build to run the config before build.</li></ul><pre>{<br>  &quot;name&quot;: &quot;ionic-angular-cesium-3d-map&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;,<br>  &quot;author&quot;: &quot;Ionic Framework&quot;,<br>  &quot;homepage&quot;: &quot;https://ionicframework.com/&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;ng&quot;: &quot;ng&quot;,<br>    &quot;start&quot;: &quot;ng serve&quot;,<br>    &quot;build&quot;: &quot;npm run config &amp;&amp; ng build&quot;,<br>    &quot;config&quot;: &quot;ts-node src/environments/set-env.ts&quot;,<br>    &quot;test&quot;: &quot;ng test&quot;,<br>    &quot;lint&quot;: &quot;ng lint&quot;,<br>    &quot;e2e&quot;: &quot;ng e2e&quot;<br>  }<br>}</pre><ul><li>Last but not least, we need to ignore the generated environment.ts file and the .env file from the source code. Update your .gitignore to include these files.</li></ul><pre>src/environments/environment.ts <br>src/environments/.env</pre><p>After following these steps, when you run the build or config npm scripts, it will generate an environment.ts and place it in the environment folder. File content will be like this.</p><pre>export const environment = {<br>    googleApiKey: &#39;YOUR_ACTUAL_GOOGLE_API_KEY_FROM_ENV_VARIABLES&#39;,<br>    auth0ClientId: &#39;YOUR_ACTUAL_AUTH0_CLIENT_ID_FROM_ENV_VARIABLES&#39;,<br>    appVersion: &#39;1.0.0&#39;,<br>    production: true,<br>};</pre><p>That’s it. Now you access these environment configs in your Angular project.</p><h3>Conclusion</h3><p>We learned how we can integrate the operating level Environment variables with Angular environment.ts to get the best of both worlds and secure our secrets.</p><p>There are more ways to make keeping and sharing secrets more convenient for secrets that might need to be shared on different build machines. What we read in this article is just the first step.</p><p>Thanks for reading. As usual, if you have any questions, please leave me a comment here or DM me on Twitter.</p><h3>Resources</h3><p>if you need an example project that utilises this solution please refer to my ionic &amp; Cesium 3D map example.</p><p>This project uses the same technique to hide the cesiumAccessToken which is used in the code from the source code.</p><p>This project builds on Vercel and uses the Vercel Environment variable to provide the cesiumAccessToken.</p><p>Here is the code repository: <a href="https://github.com/pazel-io/ionic-angular-cesium-3d-map">ionic-angular-cesium-3d-map</a></p><h3>Contact</h3><p>Twitter: <a href="https://twitter.com/home">_pazel</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6963374b464e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-keep-your-secrets-from-your-source-code-in-an-angular-project-6963374b464e">How to Keep Your Secrets from Your Source Code in an Angular Project 🤫</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3D Map For Your Ionic App]]></title>
            <link>https://javascript.plainenglish.io/3d-map-for-your-ionic-app-6ea2b41cc178?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea2b41cc178</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Sat, 25 Sep 2021 11:45:17 GMT</pubDate>
            <atom:updated>2021-09-27T13:27:23.851Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use CesiumJS to add a 3D map to your Ionic app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2ruG7BKtokILzj6PIkRnQ.png" /></figure><p>Hi, friends! 👋</p><p>Parham here, with another step-by-step guide.</p><p>In this article, we will create an Ionic/Angular app that uses CesiumJS to render a 3D map and render some 3D layers on top of it to show terrain and buildings.</p><p>3D maps are excellent 😎 and visualising your data in 3D can take it to the next level. 🤭</p><p>What if you can have a 3D map rendered in your browser with just writing one line of code.</p><p>That’s right, using CesiumJS, you can easily have a 3D map in your app.</p><p>A quick preview of what is the final results:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FY2ItrXnEitc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DY2ItrXnEitc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FY2ItrXnEitc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9ed3caa9ebb91e5a6adc1d7ee01edf9/href">https://medium.com/media/c9ed3caa9ebb91e5a6adc1d7ee01edf9/href</a></iframe><h3>What is CesiumJS?</h3><blockquote>CesiumJS is an open-source JavaScript library for creating world-class 3D globes and maps with the best possible performance, precision, visual quality, and ease of use.</blockquote><p>To get an idea of CesiumJS Capabilities, check some of their <a href="https://sandcastle.cesium.com/">examples</a>.</p><p>Here is what you can expect to learn from this tutorial and the difficulty level of each part:</p><ul><li>Create a blank app using Ionic CLI.<br>You will learn how to use Ionic CLI to create an Ionic/Angular app. (Difficulty level: simple)</li><li>Use CesiumJS to render a map<br>You will learn how to implement a basic map integration with Ionic, Cesium &amp; Angular. (Difficulty level: Intermediate)</li><li>Use Cesium Camera<br>You will learn how to use the Cesium Camera flyTo method to fly to a destination. (Difficulty level: Intermediate)</li></ul><p>Here is the final demo link: <br><a href="https://ionic-angular-cesium-3d-map.vercel.app/">ionic-angular-cesium-3d-map.vercel.app</a></p><p>And here is the Git repo: <br><a href="https://github.com/pazel-io/ionic-angular-cesium-3d-map">github.com/pazel-io/ionic-angular-cesium-3d..</a></p><h3>Let’s start</h3><h3>1. Create the base app using Ionic CLI</h3><p>If you have not installed Ionic CLI before, please head to <a href="https://ionicframework.com/docs/intro/cli">ionicframework.com/docs/intro/cli</a> and follow the instructions to install the CLI.</p><p>Next, let’s create an app using CLI by running ionic start ionic-angular-cesium-3d-map. CLI should prompt you to choose the front end tech and more options.</p><p>I am going with Angular and the blank starter project.</p><p>Ionic CLI asks if you like Capacitor integration, which is not required for this tutorial. After selecting the options, CLI will download all required npm packages. (this might take few minutes) You will eventually see some logs indicating that the setup is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_pxQYQ0-qEnLN2By" /></figure><p>Let’s cd to the new project we just created and run ionic serve. This command will run a local web server and open the app in your default browser. (by default port 8100)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jI9aN59uxEGZTSsn" /></figure><h3>2. Use CesiumJS to render a map</h3><p>There are three pieces involved here to make it work.</p><ul><li>Cesium JavaScript file</li><li>Cesium CSS file</li><li>Cesium assets file</li></ul><p>Start by adding the Cesium npm package npm install --save cesium</p><h4>Configure Cesium in Angular</h4><p>Now that we have installed Cesium, we need to include its files (CSS and necessary assets) in our project. We can use angular.json located at the root directory of the project to add these files. Open angular.json and add the CSS file in the styles section and the whole build Cesium folder in the assets array.</p><pre>&quot;assets&quot;: [<br>{<br>&quot;glob&quot;: &quot;**/*&quot;,<br>&quot;input&quot;: &quot;node_modules/cesium/Build/Cesium&quot;,<br>&quot;output&quot;: &quot;./assets/cesium&quot;<br>},<br>],<br>&quot;styles&quot;: [<br>&quot;node_modules/cesium/Build/Cesium/Widgets/widgets.css&quot;,<br>&quot;styles.css&quot;<br>]</pre><h4>Display the Viewer</h4><p>We will use the home component to host the Cesium viewer. All Cesium needs is to have a reference to a DOM element that is designated to render the map.</p><p>The easiest way to do this in Angular is to use the @ViewChild property decorator that configures a view query. View queries are set before the ngAfterViewInit callback is called.</p><p>This is what you need to add to the home.component.html</p><pre>&lt;div class=&quot;my-cesium&quot; #myCesium&gt;&lt;/div&gt;</pre><p>and this is the code for accessing the myCesium element in home.component.ts.</p><pre>@ViewChild(&#39;myCesium&#39;)<br>public myCesium: ElementRef;</pre><p>The next thing is to initialise the Cesium viewer. We use the Angular AfterViewInit hook for this to make sure our ElementRef is initialised first.</p><p>Next, you need to pass the DOM reference to the Cesium.Viewer constructor.</p><pre>import * as Cesium from &#39;cesium&#39;;</pre><pre>public ngAfterViewInit(): void {<br>    const viewer = new Cesium.Viewer(this.myCesium.nativeElement);<br>}</pre><p>Congrats! Now you should see a 3D globe rendered on your home page with some default Cesium controls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*oblCuG7QcauLNwyP" /></figure><p>We can pass some more configurations to customise the Cesium viewer. Check <a href="https://cesium.com/learn/ion-sdk/ref-doc/Viewer.html#.ConstructorOptions">Cesium docs</a> for a full list of options.</p><p>To simply my view for mobile I will disable some of these default options. Here is the updated code.</p><pre>public ngAfterViewInit(): void {<br>    if (environment.cesiumAccessToken) {<br>    Cesium.Ion.defaultAccessToken = environment.cesiumAccessToken;<br>}<br>this.viewer = new Cesium.Viewer(this.myCesium.nativeElement, {<br>    //Use Cesium World Terrain<br>    terrainProvider: Cesium.createWorldTerrain(),<br>    //Hide the base layer picker<br>    baseLayerPicker: false,<br>    // homeButton: false,<br>    geocoder: false,<br>    timeline: false,<br>    animation: false,<br>    fullscreenButton: false,<br>});<br>}</pre><p>A couple of things to notice</p><ul><li>terrainProvider adds terrain data to your globe so you can see these terrains when you look at the surface. Pretty neat.</li><li>defaultAccessToken remove the message that is displayed when you use the default access token.</li></ul><p>You can create an account and <a href="https://cesium.com/ion/tokens">get the access token for free</a> for non-commercial use.</p><p>Here is the result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*IomNRngWgijCVWxQ" /></figure><h3>3. Use Cesium Camera</h3><p>Next stop, we will add some 3D building data to the globe and fly from the initial location to the buildings.</p><p>When we created a Cesium Viewer, we implicitly built a <a href="https://cesium.com/learn/ion-sdk/ref-doc/Scene.html">Cesium.Scene</a>.</p><p>Cesium.Scene is the container for all 3D graphical objects and state in a Cesium virtual scene, and it has a reference to the <a href="https://cesium.com/learn/ion-sdk/ref-doc/Camera.html">Cesium.Camera</a></p><p>Cesium.Camera let us to flyTo a location.</p><pre>this.viewer.scene.camera.flyTo({<br>    destination: Cesium.Cartesian3.fromDegrees(-74.019, 40.6912, 750),<br>    orientation: {<br>        heading: Cesium.Math.toRadians(20),<br>        pitch: Cesium.Math.toRadians(-20),<br>    },<br>})</pre><p>In the code above, we are telling Cesium to fly from the current location to the destination. In this example, the destination is provided in Degrees (longitude, latitude, height). We are also setting the orientation of the camera.</p><p>Next, let’s add some 3D building data. Cesium already has a built-in layer for this, and you can add your data as well.</p><p>The built-in one is called the Cesium OSM Buildings layer, a global base layer with over 350 million buildings derived from OpenStreetMap data. It&#39;s served as 3D Tiles, an open standard created by Cesium.</p><pre>this.viewer.scene.primitives.add(Cesium.createOsmBuildings());</pre><p>Next, we add an Ionic Fab button to fly us to the destination.</p><pre>&lt;ion-content [fullscreen]=&quot;true&quot;&gt;<br>    &lt;div class=&quot;my-cesium&quot; #myCesium&gt;&lt;/div&gt;<br>    &lt;ion-fab vertical=&quot;bottom&quot; horizontal=&quot;end&quot; slot=&quot;fixed&quot;&gt;<br>        &lt;ion-fab-button (click)=&quot;letsGo()&quot;&gt;<br>            &lt;ion-icon name=&quot;airplane&quot;&gt;&lt;/ion-icon&gt;<br>        &lt;/ion-fab-button&gt;<br>    &lt;/ion-fab&gt;<br>&lt;/ion-content&gt;</pre><p>and here is the code for the component</p><pre>public letsGo() {<br>    const slow$ = of(this.viewer);<br>    slow$<br>        .pipe(<br>            take(1),<br>            tap(() =&gt; this.viewer.scene.camera.flyTo({<br>                destination: Cesium.Cartesian3.fromDegrees(-74.019, 40.6912, 750),<br>                orientation: {<br>                    heading: Cesium.Math.toRadians(20),<br>                    pitch: Cesium.Math.toRadians(-20),<br>                },<br>            })),<br>            delay(2000),<br>            tap(() =&gt; {<br>                if (!this.osmBuildingInit) {<br>                    this.viewer.scene.primitives.add(Cesium.createOsmBuildings());<br>                }<br>            }),<br>            tap(() =&gt; this.osmBuildingInit = true),<br>        )<br>        .subscribe();<br>}</pre><p>I am using RxJS to add some delays between flying and adding building data, but you can do them at once.</p><p>Now, if you click the fab button, you will fly to the destination and see some building data in 3D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*QjX6_RztltpFq0At" /></figure><p>If you are interested in adding your 3D data, refer to this Cesium article <a href="https://cesium.com/learn/cesiumjs-learn/cesiumjs-interactive-building/">Visualise a Proposed Building in a 3D City</a></p><h3>Conclusion</h3><p>CesiumJS is one of the most advanced 3D libraries when it comes to maps and Geo-Spatial data.</p><p>We learned how we could use it to integrate a 3D map experience into our Ionic application easily.</p><p>This example uses Angular, but as you can see, all the heavy lifting is done by Cesium, so what JS framework you use with your Ionic is your preference.</p><p>Thanks for reading. As usual, if you have any questions, please leave me a comment here or DM me on Twitter.</p><h3>Resources</h3><p>Here is the demo: <a href="https://ionic-angular-cesium-3d-map.vercel.app/">demo deployed using Vercel</a></p><p>Here is the code repository: <a href="https://github.com/pazel-io/ionic-angular-cesium-3d-map">ionic-angular-cesium-3d-map</a></p><h3>Contact</h3><p>Twitter: <a href="https://twitter.com/_pazel">_pazel</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea2b41cc178" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/3d-map-for-your-ionic-app-6ea2b41cc178">3D Map For Your Ionic App</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an Offline Map using Ionic and Leaflet]]></title>
            <link>https://javascript.plainenglish.io/use-ionic-angular-leaflet-to-build-a-pwa-to-show-a-map-that-works-offline-part-1-b69126386ce6?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/b69126386ce6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[ionic]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Sun, 18 Jul 2021 02:19:29 GMT</pubDate>
            <atom:updated>2021-07-29T14:29:44.608Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build a PWA Map application using Ionic and Leaflet 🗺 🧭</h4><p>Featuring Google address search integration, GPS and layer switcher. (Step by step guide)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V44KKR8bjY188HE_LGnPEA.png" /></figure><p>Hello friends, Parham here with another step-by-step guide.</p><p>This time, we will build an Ionic PWA app that shows a map, but that is not all.</p><p>A quick preview of what is the final results:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjN44U2voLwc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjN44U2voLwc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjN44U2voLwc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cad067b6359485e452c0bf8e92506014/href">https://medium.com/media/cad067b6359485e452c0bf8e92506014/href</a></iframe><p>Here are the app features, what you can expect to learn implementing each part and the difficulty level of each part:</p><h4>1. Create a blank app using Ionic CLI.</h4><p>You will learn how to use Ionic CLI to create an Ionic/Angular app. (Difficulty level: simple)</p><h4>2. Adding a leaflet map to your Ionic app.</h4><p>You will learn how to implement a basic map integration with Ionic, Leaflet &amp; Angular. (Difficulty level: simple)</p><h4>3. Add a base layer switcher to switch between different base maps</h4><p>You will learn how to interact with basic Leaflet APIs like TileLayer, LayerGroup and Map methods. (Difficulty level: Intermediate)</p><h4>4. Geolocation API integration to use device GPS and find user current location</h4><p>You will learn how to use Geolocation API to find device locations and handle related errors. (Difficulty level: Intermediate)</p><h4>5. Address search to find a location using google address search.</h4><p>You will learn how to use Google Places APIs to address search and find the coordinates related to an address. (Difficulty level: Intermediate)</p><h4>6. Make it a PWA</h4><p>You will learn how to use @angular/pwa to make your app an installable PWA. (Difficulty level: Intermediate)</p><h4>7. Bring it all home</h4><p>What is the point of building all this if we cannot show it off? Let’s deploy your new app using <a href="https://vercel.com/">Vercel</a> and show it off to our friends 😀 (Difficulty level: simple)</p><p>Here is the part one demo: <a href="https://ionic-angular-leaflet-offline-map-pwa-one.vercel.app/#/home">demo deployed using Vercel</a></p><p>Here is the Github code repository: <a href="https://github.com/pazel-io/ionic-angular-leaflet-offline-map-pwa.git">ionic-angular-leaflet-offline-map-pwa</a></p><p>This article was originally published on <a href="https://pazel.dev/ionic-angular-leaflet-pwa-offline-maps-part-1">pazel.dev</a></p><h3>Let’s start</h3><h4>1. Create the base app using Ionic CLI</h4><p>If you have not installed Ionic CLI before, please head to <a href="https://ionicframework.com/docs/intro/cli">ionicframework.com/docs/intro/cli</a> and follow the instructions to install the CLI.</p><p>Next, let’s create an app using CLI by running ionic start ionic-leaflet-offline-map-pwa. CLI should prompt you to choose the front end tech and more options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YyvFm0jwsyQe4hXz" /></figure><p>I am going with Angular and the blank starter project. Ionic CLI asks if you like Capacitor integration. It’s not required for this tutorial. After selecting the options, CLI will download all required npm packages. (this might take few minutes)</p><p>Ionic CLI asks if you would like a free Ionic account after the npm package install. It’s not required for this tutorial. You will eventually see some logs indicating that the setup is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cxaJ-ha8Ot-O_15S" /></figure><p>Let’s cd to the new project we just created and run ionic serve. This will run a local web server and open the app in your default browser. (by default port 8100)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oLl97Psfeqc_1_Rb" /></figure><h4>2. Add a map using Leaflet</h4><p><a href="https://leafletjs.com/">Leaflet</a> is an open-source JavaScript library for mobile-friendly interactive maps. It offers heaps of cool features to work with maps. Using the features we need to show the map, and we are gonna just scratch the surface. So it’s relatively easy.</p><p>We use the Angular Leaflet wrapper for easier integration here. We will use the @asymmetrik/ngx-leaflet project. This package is not an official part of Angular, but it is reliable, and I have used it in many prod apps.</p><p>Run npm i leaflet @asymmetrik/ngx-leaflet to install both leaflet and ngx-leaflet.</p><p>We love TypeScript so let’s add appropriate typings for Leaflet.</p><p>Run npm i @types/leaflet -D to install the typings as a dev dependency.</p><p>OK, we are done with the installation. Let’s add a map to our Angular app!</p><p>I will add the map to our HomePage(home.page.ts) component. This is easy.</p><h4>Add LeafletModule to the imports array in HomePageModule(home.module.ts)</h4><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { LeafletModule } from &#39;@asymmetrik/ngx-leaflet&#39;;<br>import { IonicModule } from &#39;@ionic/angular&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { HomePage } from &#39;./home.page&#39;;</pre><pre>import { HomePageRoutingModule } from &#39;./home-routing.module&#39;;<br></pre><pre>@NgModule({<br>  imports: [<br>    CommonModule,<br>    FormsModule,<br>    IonicModule,<br>    LeafletModule,<br>    HomePageRoutingModule<br>  ],<br>  declarations: [HomePage]<br>})<br>export class HomePageModule {}</pre><h4>Add map options and OnMapReady</h4><p>options define things like map centre, maxZoom, baseLayer and more.</p><p>onMapReady will be called when the leaflet map is ready and receive the map instance. We will need this instance to interact with the map later.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Map as LMap, TileLayer } from &#39;leaflet&#39;;</pre><pre>@Component({<br>  selector: &#39;app-home&#39;,<br>  templateUrl: &#39;home.page.html&#39;,<br>  styleUrls: [&#39;home.page.scss&#39;],<br>})<br>export class HomePage {</pre><pre>  public map: LMap;<br>  public center = [<br>    -28.690259,<br>    131.5190514,<br>  ];</pre><pre>  public options = {<br>    zoom: 5,<br>    maxZoom: 18,<br>    zoomControl: false,<br>    preferCanvas: true,<br>    attributionControl: true,<br>    center: this.center,<br>    layers: [<br>      new TileLayer(&#39;http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png&#39;)<br>    ],<br>  };</pre><pre>  constructor() {}</pre><pre>  public async onMapReady(lMap: LMap) {<br>    this.map = lMap;<br>    setTimeout(() =&gt; lMap.invalidateSize(true), 0);<br>  }</pre><pre>}</pre><h4>Add the map container in our home.page.html.</h4><pre>&lt;ion-header [translucent]=&quot;true&quot;&gt;<br>  &lt;ion-toolbar&gt;<br>    &lt;ion-title&gt;<br>      Ionic Leaflet Map<br>    &lt;/ion-title&gt;<br>  &lt;/ion-toolbar&gt;<br>&lt;/ion-header&gt;</pre><pre>&lt;ion-content [fullscreen]=&quot;true&quot;&gt;<br>  &lt;div class=&quot;leaflet&quot; leaflet<br>       [leafletOptions]=&quot;options&quot;<br>       (leafletMapReady)=&quot;onMapReady($event)&quot;&gt;<br>  &lt;/div&gt;<br>&lt;/ion-content&gt;</pre><h4>Add the leaflet CSS to the list of our global CSS.</h4><p>Open the angular.json file in the root of the project and update line 34 from</p><p>&quot;styles&quot;: [&quot;src/theme/variables.scss&quot;, &quot;src/global.scss&quot;], to:</p><pre>&quot;styles&quot;: [&quot;src/theme/variables.scss&quot;, &quot;src/global.scss&quot;, &quot;./node_modules/leaflet/dist/leaflet.css&quot;],</pre><p>And add the map container CSS to home.page.scss. The updated file looks like this.</p><pre>.leaflet {<br>  height: 100%;<br>  width: 100%;<br>  position: absolute;<br>  z-index: 0;<br>}</pre><p>Restart your server to make sure the new CSS loads properly. You should see a screen like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ULdyUzJuDSW99irX" /></figure><p>Congrats! We have now integrated a map into our Ionic app.</p><h3>3. Add the ability to switch base maps</h3><p>We have already added one base map in the options we defined. I want to change it and use Cycling and Transport base maps and use a button to switch between them.</p><p>Let’s be fancy and add a FAB button from Ionic to do the layer switching. Go ahead and add a FAB button with a list of options inside your &lt;ion-content&gt;. The updated code looks like this.</p><pre>&lt;ion-header [translucent]=&quot;true&quot;&gt;<br>  &lt;ion-toolbar&gt;<br>    &lt;ion-title&gt;<br>      Ionic Leaflet Map<br>    &lt;/ion-title&gt;<br>  &lt;/ion-toolbar&gt;<br>&lt;/ion-header&gt;</pre><pre>&lt;ion-content [fullscreen]=&quot;true&quot;&gt;<br>  &lt;ion-fab vertical=&quot;top&quot; horizontal=&quot;end&quot; slot=&quot;fixed&quot;&gt;<br>    &lt;ion-fab-button&gt;<br>      &lt;ion-icon name=&quot;layers-outline&quot;&gt;&lt;/ion-icon&gt;<br>    &lt;/ion-fab-button&gt;<br>    &lt;ion-fab-list side=&quot;bottom&quot;&gt;<br>      &lt;ion-fab-button color=&quot;danger&quot;&gt;<br>        &lt;ion-icon name=&quot;bicycle&quot;&gt;&lt;/ion-icon&gt;<br>      &lt;/ion-fab-button&gt;<br>      &lt;ion-fab-button&gt;<br>        &lt;ion-icon name=&quot;car&quot;&gt;&lt;/ion-icon&gt;<br>      &lt;/ion-fab-button&gt;<br>    &lt;/ion-fab-list&gt;<br>  &lt;/ion-fab&gt;<br>  &lt;div class=&quot;leaflet&quot; leaflet<br>       [leafletOptions]=&quot;options&quot;<br>       (leafletMapReady)=&quot;onMapReady($event)&quot;&gt;<br>  &lt;/div&gt;<br>&lt;/ion-content&gt;</pre><p>The updated screen will have a FAB button on the top right with two options (cycling &amp; transport) for selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*690BG5sPBgIxWuIR" /></figure><p>We need to add the code to actually switch the base map when we click our new buttons. Don’t worry. I have got you!</p><p>I will show you the updated code, and we will go through the changes one by one. This is the new home.page.ts file.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { LayerGroup, Map as LMap, TileLayer } from &#39;leaflet&#39;;<br>import { BaseLayer } from &#39;./BaseLayer.enum&#39;;</pre><pre>@Component({<br>  selector: &#39;app-home&#39;,<br>  templateUrl: &#39;home.page.html&#39;,<br>  styleUrls: [&#39;home.page.scss&#39;],<br>})<br>export class HomePage {</pre><pre>  public map: LMap;<br>  public center = [<br>    -37.8182711,<br>    144.9648731<br>  ];</pre><pre>  public options = {<br>    zoom: 15,<br>    maxZoom: 18,<br>    zoomControl: false,<br>    preferCanvas: true,<br>    attributionControl: true,<br>    center: this.center,<br>  };</pre><pre>  public baseMapUrls = {<br>    [BaseLayer.cycling]: &#39;http://c.tile.thunderforest.com/cycle/{z}/{x}/{y}.png&#39;,<br>    [BaseLayer.transport]: &#39;http://c.tile.thunderforest.com/transport/{z}/{x}/{y}.png&#39;,<br>  };</pre><pre>  public selectedBaseLayer = BaseLayer.cycling;</pre><pre>  public baseLayer = BaseLayer;</pre><pre>  private baseMapLayerGroup = new LayerGroup();</pre><pre>  constructor() {<br>  }</pre><pre>  public async onMapReady(lMap: LMap) {<br>    this.map = lMap;<br>    this.map.addLayer(this.baseMapLayerGroup);<br>    this.switchBaseLayer(this.selectedBaseLayer);<br>    setTimeout(() =&gt; lMap.invalidateSize(true), 0);<br>  }</pre><pre>  public switchBaseLayer(baseLayerName: string) {<br>    this.baseMapLayerGroup.clearLayers();<br>    const baseMapTileLayer = new TileLayer(this.baseMapUrls[baseLayerName]);<br>    this.baseMapLayerGroup.addLayer(baseMapTileLayer);<br>    this.selectedBaseLayer = BaseLayer[baseLayerName];<br>  }</pre><pre>}</pre><p>I removed the layers array from the map options, and instead, I have added the baseMapUrls, an object. Keys are the map name, and values are the URL for map tiles. For keys, I am using a TypeScript Enum to make it easier when reusing the same string. Enum is in a new file called BaseLayer.enum.ts, and here is the code:</p><pre>export enum BaseLayer {<br>  cycling = &#39;cycling&#39;,<br>  transport = &#39;transport&#39;,<br>}</pre><p>Next, we have the selectedBaseLayer property to keep track of which the user selects the base layer. I have initialised it with the cycling base map using the same Enum.</p><p>Next, we have the baseLayer property pointing to the BaseLayer enum. This is to make the enum available to our map HTML template and use it there.</p><p>Next, we have the private baseMapLayerGroup = new LayerGroup();. LayerGroup is a Leaflet way to group multiple layers and separate them from the rest of the layers on the map. Using it here makes it easier to manage base layers. We will use more LayerGroups later to add the address search and GPS search results.</p><p>Next, we have the switchBaseLayer method. It takes a base layer name and can switch the base layer. It first clears any layers in the layer group and then adds the new layer by finding the config from the baseMapUrls object. Notice that the layer we add is of type TileLayer. This special type of layer in Leaflet world can show tiles used for the base map.</p><p>And here are the changes you need in the HTML. Basically adding the click functions to buttons. Also, check the selectedBaseLayer to highlight the colour of the button representing the selected base layer by changing it to red(danger). Notice I am using the same BaseLayer enum values to maximise reuse and not repeat myself.</p><pre>&lt;ion-header [translucent]=&quot;true&quot;&gt;<br>  &lt;ion-toolbar&gt;<br>    &lt;ion-title&gt;<br>      Ionic Leaflet Map<br>    &lt;/ion-title&gt;<br>  &lt;/ion-toolbar&gt;<br>&lt;/ion-header&gt;</pre><pre>&lt;ion-content [fullscreen]=&quot;true&quot;&gt;<br>  &lt;ion-fab vertical=&quot;top&quot; horizontal=&quot;end&quot; slot=&quot;fixed&quot;&gt;<br>    &lt;ion-fab-button&gt;<br>      &lt;ion-icon name=&quot;layers-outline&quot;&gt;&lt;/ion-icon&gt;<br>    &lt;/ion-fab-button&gt;<br>    &lt;ion-fab-list side=&quot;bottom&quot;&gt;<br>      &lt;ion-fab-button [color]=&quot;selectedBaseLayer === baseLayer.cycling ? &#39;danger&#39; : &#39;primary&#39;&quot;<br>                      (click)=&quot;switchBaseLayer(baseLayer.cycling)&quot;&gt;<br>        &lt;ion-icon name=&quot;bicycle&quot;&gt;&lt;/ion-icon&gt;<br>      &lt;/ion-fab-button&gt;<br>      &lt;ion-fab-button [color]=&quot;selectedBaseLayer === baseLayer.transport ? &#39;danger&#39; : &#39;primary&#39;&quot;<br>                      (click)=&quot;switchBaseLayer(baseLayer.transport)&quot;&gt;<br>        &lt;ion-icon name=&quot;car&quot;&gt;&lt;/ion-icon&gt;<br>      &lt;/ion-fab-button&gt;<br>    &lt;/ion-fab-list&gt;<br>  &lt;/ion-fab&gt;<br>  &lt;div class=&quot;leaflet&quot; leaflet<br>       [leafletOptions]=&quot;options&quot;<br>       (leafletMapReady)=&quot;onMapReady($event)&quot;&gt;<br>  &lt;/div&gt;<br>&lt;/ion-content&gt;</pre><h3>4. Use device GPS and find the user current location</h3><p>We will use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API">Geolocation API</a> to find the device location. This is a standard web API. For privacy reasons, users will be asked to grant access to their location. So the user can grant access or deny, and we need to handle the potential errors in this process.</p><p>First, let’s add a method to read the device’s location.</p><pre>public async locate() {<br>    this.locationLayerGroup.clearLayers();<br>    if (!navigator.geolocation) {<br>      console.error(&#39;Geolocation is not supported by your browser&#39;);<br>      return;<br>    }<br>    await this.presentLoading();<br>    navigator.geolocation.getCurrentPosition(<br>      (position) =&gt; this.onLocationSuccess(position),<br>      (error) =&gt; this.onLocateError(error),<br>      {enableHighAccuracy: true}<br>    );<br>  }</pre><p>As you might have noticed, I have added another LayerGroup for the GPS location to the map called locationLayerGroup.</p><p>Next, I am checking if the navigator.geolocation is supported. Notice, If it is not supported, I log an error and use the return statement to exit the function. This is a nicer alternative compared to doing if/else and makes your code more readable.</p><p>If it is supported, I show a loading message. Then, I call getCurrentPosition, which returns the device&#39;s current location (there is another method if you like to watch the location, which is good for tracking use case).</p><p>getCurrentPosition takes three parameters. First, the success callback function, which is called when the location is successfully fetched. The second is the error callback which will be called if there is an error. Like location access denied or timeout error if GPS satellite is not available. And third, the PositionOptions, which I use to enable the HighAccuracy location. Enabling this option will cause the location reading to take longer but will make it more accurate.</p><p>Here is the code for success callback</p><pre>private onLocationSuccess(position: GeolocationPosition) {<br>    const {accuracy, latitude, longitude} = position.coords;<br>    const latlng = [latitude, longitude];<br>    this.hideLoading();<br>    this.map.setView(latlng, 18);<br>    const accuracyValue = accuracy &gt; 1000 ? accuracy / 1000 : accuracy;<br>    const accuracyUnit = accuracy &gt; 1000 ? &#39;km&#39; : &#39;m&#39;;<br>    placeLocationMarker(this.locationLayerGroup, latlng, `Accuracy is ${accuracyValue} ${accuracyUnit}`);<br>    const locationCircle = circle(latlng, accuracy);<br>    this.locationLayerGroup.addLayer(locationCircle);<br>  }</pre><p>Here I read some properties from the GeolocationPosition I receive. I use the latitude and longitude to create a Leaflet LatLng array that can centre the map. I use the map&#39;s setView method for that, passing a LatLng and zoom level (18).</p><p>The accuracy we receive here is in metres, so I convert it to KM if it’s bigger than 1000 so it’s more readable when presented to the user.</p><p>I use placeLocationMarker to display a marker on the map for device location. I have extracted this function because I want to show a tooltip on the marker, which shows the accuracy. And since this is a Leaflet tooltip and the whole DOM creation is handled by Leaflet, there is a bit of complication around how to handle the touch events. This complexity is handled inplaceLocationMarker function.</p><p>And at last, I use the Leaflet circle function to draw a circle on the map, which shows the accuracy visually to the user. This circle is centred on the device location, and the radius is as big as accuracy.</p><p>Before you get too bored, here is the result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4eJVrm4B4RcyPOam" /></figure><p>Notice that I am using Chrome Devtools to fake the GPS location. You can access this feature in the console tab by clicking three dots next to Console and choose Sensors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eFcbdLM5hWUJftCA" /></figure><p>Ok, Let’s have a quick look at the error callback. This one is simple. On error, we hide the loading and use the Ionic’s Alert component to notify the user about the problem. 3 errors can happen. PERMISSION_DENIED, TIMEOUT , POSITION_UNAVAILABLE. The first two are obvious, and the third can happen when there is a faulty GPS hardware. For each error, you get a message and code. If you need to customise the message, use the code and draft your own message.</p><pre>private async onLocateError(error) {<br>    this.hideLoading();<br>    const alert = await this.alertController.create({<br>      header: &#39;GPS error&#39;,<br>      message: error.message,<br>      buttons: [&#39;OK&#39;]<br>    });</pre><pre>    await alert.present();<br>  }</pre><p>And finally, here is the code for the placeLocationMarker function. This code is located in a separate file with the same name. It does three things.</p><ul><li>Creates a Leaflet marker using a custom icon.</li><li>Binds a leaflet popup to the marker that shows accuracy value and a delete link button. Why do we need the delete? Because when the user adds a marker to the map, they need a way to remove it when they are done.</li><li>Listen to the click event on a specific marker popup to handle the delete button click. As mentioned, the DOM operations here are totally happening outside of the Angular world, so I use RxJS fromEvent function to filter and receive the click events from this delete button.</li></ul><p>The subscription to the click event only happens when the popup is open and it will unsubscribe as soon as it is closed.</p><p>Another good practice here is extracting the placeLocationMarker. This has made it as pure as possible. So this function only relies on its inputs to operate.</p><pre>import { LatLng, LayerGroup, marker, Marker } from &#39;leaflet&#39;;<br>import { fromEvent, Subscription } from &#39;rxjs&#39;;<br>import { filter, map, tap } from &#39;rxjs/operators&#39;;<br>import { markerIcon } from &#39;./markerIcon&#39;;</pre><pre>const subscribeToDeleteLocationMarker = (id: string, marco: Marker, layerGroup: LayerGroup): Subscription =&gt; {<br>  return fromEvent(document, &#39;click&#39;)<br>    .pipe(<br>      tap((event) =&gt; event.stopPropagation()),<br>      map((event) =&gt; event.target),<br>      filter((target: HTMLElement) =&gt; target.id === id),<br>    )<br>    .subscribe(($event) =&gt; layerGroup.clearLayers());<br>};</pre><pre>const bindMarkerPopup = (marco: Marker, text: string, layerGroup: LayerGroup) =&gt; {<br>  const id = `location-marker-${Date.now()}`;<br>  marco.bindPopup(`<br>        &lt;p&gt;${text}&lt;/p&gt;<br>        &lt;div class=&quot;location-marker-popup__buttons&quot;&gt;<br>            &lt;a class=&quot;location-marker-popup__button&quot; id=&quot;${id}&quot;&gt;delete&lt;/a&gt;<br>        &lt;/div&gt;<br>      `,          {<br>    maxWidth: 200,<br>    maxHeight: 120,<br>    className: &#39;location-marker-popup&#39;,<br>  });<br>  let deleteMarkerSubscription;<br>  marco.on(&#39;popupopen&#39;, () =&gt; deleteMarkerSubscription = subscribeToDeleteLocationMarker(id, marco, layerGroup));<br>  marco.on(&#39;popupclose&#39;, () =&gt; deleteMarkerSubscription.unsubscribe());<br>  marco.openPopup();<br>};</pre><pre>export const placeLocationMarker = (layerGroup: LayerGroup, latLng: LatLng, text: string) =&gt; {<br>  layerGroup.clearLayers();<br>  const marco = marker(latLng, {icon: markerIcon()});<br>  layerGroup.addLayer(marco);<br>  bindMarkerPopup(marco, text, layerGroup);<br>};</pre><h3>6. Make it a PWA</h3><p>This step is easy because Angular CLI does all the heavy lifting for you. Just run npx ng add @angular/pwa. This command will add all the required packages to your project, configure your service worker, and add the default assets for caching. The only file that you might need to interact with is the ngsw-config.json.</p><p>This file tells the Angular service worker, what assets to cache and what caching strategy to use.</p><p>For example, all JS files are cached eagerly when all the image assets are cached lazily. You can read more about managing this file in Angular docs for <a href="https://angular.io/guide/service-worker-config#assetgroups">Service worker configuration</a>.</p><pre>{<br>  &quot;$schema&quot;: &quot;./node_modules/@angular/service-worker/config/schema.json&quot;,<br>  &quot;index&quot;: &quot;/index.html&quot;,<br>  &quot;assetGroups&quot;: [<br>    {<br>      &quot;name&quot;: &quot;app&quot;,<br>      &quot;installMode&quot;: &quot;prefetch&quot;,<br>      &quot;resources&quot;: {<br>        &quot;files&quot;: [<br>          &quot;/favicon.ico&quot;,<br>          &quot;/index.html&quot;,<br>          &quot;/manifest.webmanifest&quot;,<br>          &quot;/*.css&quot;,<br>          &quot;/*.js&quot;<br>        ]<br>      }<br>    },<br>    {<br>      &quot;name&quot;: &quot;assets&quot;,<br>      &quot;installMode&quot;: &quot;lazy&quot;,<br>      &quot;updateMode&quot;: &quot;prefetch&quot;,<br>      &quot;resources&quot;: {<br>        &quot;files&quot;: [<br>          &quot;/assets/**&quot;,<br>          &quot;/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)&quot;<br>        ]<br>      }<br>    }<br>  ]<br>}</pre><p>And as always, make sure to test your PWA locally. To do this, run the build command ionic build.</p><p>This will generate the www folder. The application in this folder is a PWA. You can use a local server like serve to run it.</p><p>Service Workers require the app to be hosted in a secure context. To serve the build, we use a local node server. Install the npmjs.com/package/serve by running npm i serve -g.</p><p>Next, we can run the serve www command. This runs the app on <a href="http://localhost:5000/">localhost:5000</a>, and luckily, with localhost is considered safe, and you do not need HTTPS origin to test our PWA now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s7HS7A_ByLgY9WjP" /></figure><p>Open an incognito window in chrome and open the http://localhost:5000. You will notice another issue. When you refresh the page, the app will not load. This is because the serve tries to find localhost:5000/home and expect a home folder with an index.html file in it, and this file does not exist. There are multiple ways to fix this issue. For this tutorial, I will use hash routing.</p><p>All you need to change is to go to your app-routing.module.ts file and add useHash: true to your router options. Now page URL will look like localhost:5000/#/home, and you can refresh without an issue.</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { PreloadAllModules, RouterModule, Routes } from &#39;@angular/router&#39;;</pre><pre>const routes: Routes = [<br>  {<br>    path: &#39;home&#39;,<br>    loadChildren: () =&gt; import(&#39;./home/home.module&#39;).then( m =&gt; m.HomePageModule)<br>  },<br>  {<br>    path: &#39;&#39;,<br>    redirectTo: &#39;home&#39;,<br>    pathMatch: &#39;full&#39;<br>  },<br>];</pre><pre>@NgModule({<br>  imports: [<br>    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules, useHash: true })<br>  ],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><p>After fixing the routing issue, open the `localhost:5000`. Then open Chrome Devtools, open the Lighthouse tab and generate a report for the Progressive web app. This is my test result which shows the PWA app has an issue that needs to be fixed.</p><ul><li>There is no apple-touch-icon.</li></ul><p>Add the following code to your index.html in the head tag to fix the second and third issues.</p><pre>&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;%PUBLIC_URL%/assets/icon/icon-192x192.png&quot;&gt;</pre><p>We are all set. Let’s build and test the PWA app one more time. Run ionic build and then serve www. Open the Chrome incognito window and test using Lighthouse.</p><p>You should see a result like this one, indicating that your PWA is ready and installable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*me7Ijqd2Yi-hEHTf" /></figure><p>If you want to test the install, you can open your app on a normal window (not incognito), and you should be able to see the install button in the Chrome address bar.</p><h3>7. Deploy your new app using Vercel in less than 5 mins</h3><p>To test our PWA on the phone, it would be easier to deploy the app to access it through a URL over HTTPS easily. I will use Vercel for this. Vercel is a zero-configuration cloud CI/CD that can understand the structure of our Ionic project and deploy it out of the box.</p><p>To do this, please go to <a href="http://vercel.com/">vercel.com</a> and register for a free account.</p><p>Log in, and you have the option to import a project from your Git repo. I am using Github, as mentioned before. So I will import the project from my Github.</p><p>Vercel already knows that your project is Ionic Angular and knows what command to run to build it. Just go ahead and click deploy. This will run the build and give you a URL that your project will be available on.</p><p>Simply click the button that says “Visit” to access your deployed app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g5a8D0g7El5gm51t" /></figure><h3>Conclusion</h3><p>Congratulations if you have made it this far through the tutorial. 👏</p><p>Thanks for reading. I will wrap up part one here, and I hope you follow up for more exciting features in part two.</p><p>As usual, if you have any questions, please leave me a comment here or DM me on Twitter.</p><p>Here is the demo: <a href="https://ionic-angular-leaflet-offline-map-pwa-one.vercel.app/#/home">demo deployed using Vercel</a></p><p>Here is the code repository: <a href="https://github.com/pazel-io/ionic-angular-leaflet-offline-map-pwa.git">ionic-angular-leaflet-offline-map-pwa</a></p><p>Twitter: <a href="https://twitter.com/_pazel">_pazel</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b69126386ce6" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/use-ionic-angular-leaflet-to-build-a-pwa-to-show-a-map-that-works-offline-part-1-b69126386ce6">Build an Offline Map using Ionic and Leaflet</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Ionic and React with Auth0 Login to Build a PWA for Web and Mobile (no plugin…]]></title>
            <link>https://javascript.plainenglish.io/ionic-react-pwa-with-auth0-login-for-web-and-mobile-no-plugin-required-d627f52d8e97?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/d627f52d8e97</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 11:04:40 GMT</pubDate>
            <atom:updated>2021-07-13T11:08:06.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*sILSjwUqrM3dJMAdgIBQ8A.png" /></figure><h3>How to Integrate Ionic and React with Auth0 Login to Build a PWA for Web and Mobile</h3><p>This article builds an Ionic <a href="https://web.dev/progressive-web-apps/">PWA</a> app that uses Auth0 for authentication.</p><p>We will go through a step-by-step guide on how to do this.</p><p>Here is the <a href="https://ionic-auth0-react-pwa-deploy.vercel.app/#/home">final demo</a>.</p><p>Git repo: <a href="https://github.com/pazel-io/ionic-auth0-react-pwa">github.com/pazel-io/ionic-auth0-react-pwa</a></p><p>This article was originally published on <a href="https://pazel.dev/ionic-react-pwa-with-auth0-login-for-web-and-mobile-no-plugin-required">pazel.dev</a></p><h3>Configuring Auth0</h3><p>Before anything, let’s set you up with Auth0. Please head to <a href="https://auth0.com/">auth0.com</a> and register for a free account. After signing up, you can log in to your account. You will land on the Auth0 dashboard. From the menu on the left, choose the Applications page and click the “Create Application” button.</p><p>Click on the option that says a new Single Page Web Applications, choose a name, and click create (PWAs are web apps that behave like a native app).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M8JYyN7mkF0zILc4" /></figure><p>Choose the technology you are using for your front end, or go with the pure JavaScript version. I will go with React here. This selection helps Auth0 to provide relevant examples and code snippets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VImKuzRBYoTE4AaC" /></figure><p>After choosing your front-end technology, you land on a quick start guide that walks you through integrating Auth0 into your web app. Before doing that, let’s create our Ionic app using the Ionic CLI. The code from this app is pretty much what I will use for my Ionic PWA integration.</p><p>If you have not installed Ionic CLI before, please head to <a href="https://ionicframework.com/docs/intro/cli">ionicframework.com/docs/intro/cli</a> and follow the instructions to install the CLI.</p><p>Next, let’s create an app using CLI by running ionic start ionic-auth0-pwa. CLI should prompt you to choose the front end tech and more options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0oaFxSWqTWfiRxg0" /></figure><p>I am going with React and the blank starter project. After selecting the options, CLI will download all required npm packages. (this might take few minutes)</p><p>Ionic CLI asks if you would like a free Ionic account after the npm package install. It’s not required for this tutorial. You will eventually see some logs indicating that the setup is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y_NqVKSli9apN7x-" /></figure><p>Let’s cd to the new project we just created and run ionic serve. This will run a local web server and open the app in your default browser. (by default port 8100)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b3U8GdauSm8QDZyi" /></figure><p>Now we can add the Auth service based on the example. I am going to follow the instruction from Auth0 React example to add the Auth0 login.</p><p>The first step adds the Auth0 React package to my Ionic app.</p><pre>npm install @auth0/auth0-react</pre><p>Next open index.tsx and wrap the &lt;App&gt; component in the Auth0Provider like this.</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import App from &#39;./App&#39;;<br>import { Auth0Provider } from &#39;@auth0/auth0-react&#39;;</pre><pre>ReactDOM.render(<br>    &lt;React.StrictMode&gt;<br>        &lt;Auth0Provider<br>            domain=&quot;REPLACE_WITH_YOUR_DOMAIN&quot;<br>            clientId=&quot;REPLACE_WITH_YOUR_CLIENT_ID&quot;<br>            redirectUri={window.location.origin}<br>        &gt;<br>            &lt;App/&gt;<br>        &lt;/Auth0Provider&gt;<br>    &lt;/React.StrictMode&gt;,<br>    document.getElementById(&#39;root&#39;)<br>);</pre><p>The values for ClientId and Domain are populated based on your application. You can also find them in the setting section of your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LG5F_mxwLP_NPbfI" /></figure><p>Next, we create two components for Login and Logout.</p><pre>import React from &quot;react&quot;;<br>import { useAuth0 } from &quot;@auth0/auth0-react&quot;;<br>import { IonButton, IonIcon } from &quot;@ionic/react&quot;;<br>import { logIn } from &quot;ionicons/icons&quot;;</pre><pre>const LoginButton = () =&gt; {<br>    const { loginWithRedirect, loginWithPopup } = useAuth0();</pre><pre>    return &lt;IonButton onClick={() =&gt; loginWithPopup()}&gt;<br>        &lt;IonIcon slot=&quot;start&quot; icon={logIn} /&gt;<br>        Log In<br>    &lt;/IonButton&gt;;<br>};</pre><pre>export default LoginButton;</pre><p>The Login component in the Auth0 example uses the redirect method, which leaves your app for the Auth0 website, does the login and comes back to your app with Auth token. There is another method for loginWithPopup, which I will use for this example. loginWithPopup does not leave your app and makes auth flow a bit simpler.</p><p>And here is our LogoutButton component.</p><pre>import React from &quot;react&quot;;<br>import { useAuth0 } from &quot;@auth0/auth0-react&quot;;<br>import { IonButton, IonIcon } from &quot;@ionic/react&quot;;<br>import { logOut } from &quot;ionicons/icons&quot;;</pre><pre>const LogoutButton = () =&gt; {<br>    const { logout } = useAuth0();</pre><pre>    return (<br>        &lt;IonButton onClick={() =&gt; logout({ returnTo: window.location.origin })}&gt;<br>            &lt;IonIcon slot=&quot;start&quot; icon={logOut} /&gt;<br>            Log Out<br>        &lt;/IonButton&gt;<br>    );<br>};</pre><pre>export default LogoutButton;</pre><p>Let’s make use of our newly created components. I will replace the content of ExploreContainer.tsx, which is the default homepage of our Ionic app, with the following code.</p><pre>import &#39;./ExploreContainer.css&#39;;<br>import LoginButton from &quot;./LoginButton&quot;;<br>import LogoutButton from &quot;./LogoutButton&quot;;<br>import { useAuth0 } from &quot;@auth0/auth0-react&quot;;</pre><pre>interface ContainerProps {<br>}</pre><pre>const ExploreContainer: React.FC&lt;ContainerProps&gt; = () =&gt; {<br>    const {isAuthenticated} = useAuth0();<br>    if (isAuthenticated) {<br>        return (<br>            &lt;div className=&quot;container&quot;&gt;<br>                &lt;LogoutButton/&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>    return (<br>        &lt;div className=&quot;container&quot;&gt;<br>            &lt;LoginButton/&gt;<br>        &lt;/div&gt;<br>    );</pre><pre>};</pre><pre>export default ExploreContainer;</pre><p>This is to check the isAuthenticated flag and decide to show LoginButton or LogoutButton. The result should be something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XURlER8serlUDGl9" /></figure><h3>Test the Login</h3><p>Clicking the login button should open a popup and show the login form. If instead of the login form, you see a message saying, “Oops! something went wrong”. You have probably missed the step to set up the callback URLs for your Auth0 app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*fIJWPVNoxk1iP_PH" /></figure><p>To do this, go to your app settings. Scroll down to the section that says “Allowed Callback URLs” and enter your app URL there. We need to add http://localhost:8100 for the &quot;Allowed Callback URLs&quot;, &quot;Allowed Web Origins&quot;, and &quot;Allowed Logout URLs&quot;.</p><p>If you click the login now, you should see this screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*Z6wp6YbGPJOt6PCo" /></figure><p>You can signup &amp; log in with a username/password or use a google account to log in. The login options provided are based on the default settings when you added your application in Auth0. You can obviously change these through Auth0 to add other social logins like Facebook, Apple or enable Multi-factor authentication.</p><h3>Add a User Profile to show user info</h3><p>Now that we have a login and logout, let’s add a UserProfile component to show some user details.</p><pre>import React from &quot;react&quot;;<br>import { useAuth0 } from &quot;@auth0/auth0-react&quot;;</pre><pre>const UserProfile = () =&gt; {<br>    const {user, isAuthenticated, isLoading} = useAuth0();</pre><pre>    if (isLoading) {<br>        return &lt;div&gt;Loading ...&lt;/div&gt;;<br>    }</pre><pre>    if (isAuthenticated) {<br>        return &lt;div&gt;<br>            &lt;img src={user?.picture} alt={user?.name}/&gt;<br>            &lt;h2&gt;Hello, {user?.name}&lt;/h2&gt;<br>        &lt;/div&gt;<br>    }<br>    return &lt;p&gt;Tap the login button&lt;/p&gt;<br>};</pre><pre>export default UserProfile;</pre><p>I will use the new UserProfile component in the ExploreContainer. The new updated code is:</p><pre>import &#39;./ExploreContainer.css&#39;;<br>import LoginButton from &quot;./LoginButton&quot;;<br>import LogoutButton from &quot;./LogoutButton&quot;;<br>import UserProfile from &quot;./UserProfile&quot;;<br>import { useAuth0 } from &quot;@auth0/auth0-react&quot;;</pre><pre>interface ContainerProps {<br>}</pre><pre>const ExploreContainer: React.FC&lt;ContainerProps&gt; = () =&gt; {<br>    const {isAuthenticated} = useAuth0();<br>    if (isAuthenticated) {<br>        return (<br>            &lt;div className=&quot;container&quot;&gt;<br>                &lt;UserProfile/&gt;<br>                &lt;LogoutButton/&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>    return (<br>        &lt;div className=&quot;container&quot;&gt;<br>            &lt;UserProfile/&gt;<br>            &lt;LoginButton/&gt;<br>        &lt;/div&gt;<br>    );</pre><pre>};</pre><pre>export default ExploreContainer;</pre><p>Now, after you log in, you should see your name, avatar and a logout button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uU3nDFjI2SFtFTOD" /></figure><h3>Make it a PWA</h3><p>We are almost there. All we need to do is to make this Ionic app a PWA. That is very easy. Open your index.tsx file and find the serviceWorkerRegistration.unregister(); on line 24 and change it to serviceWorkerRegistration.register();</p><p>To make sure our PWA is ready, we need to build the app and test it using Lighthouse. Run the ionic build to build the app. This should create a build directory with all of the build files, including the PWA&#39;s service worker and manifest file.</p><p>Service Workers require the app to be hosted in a secure context. To serve the build, we use a local node server. Install the <a href="https://www.npmjs.com/package/serve">npmjs.com/package/serve</a> by running npm i serve -g.</p><p>Next, we can run the serve build command. This runs the app on http://localhost:5000 And luckily with localhost is considered safe, and you do not need HTTPS origin to test our PWA now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nYwoYXmaQbXMAVQj" /></figure><p>Open an incognito window in chrome and open the http://localhost:5000. You will notice another issue. When you refresh the page, the app will not load. This is because the serve tries to find localhost:5000/home and expect a home folder with an index.html file in it, and this file does not exist. There are multiple ways to fix this issue. For this tutorial, I will use hash routing.</p><p>All you need to change is to go to your App.tsx file and replace IonReactRouter with IonReactHashRouter. Now page URL will look like this localhost:5000/#/home, and you can refresh without an issue.</p><p>After fixing the routing issue, open the http://localhost:5000.Then, open Chrome Devtools, open the Lighthouse tab and generate a report for the Progressive web app. This is my test result which shows the PWA app has a couple of issues that need to be fixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EIDXWXPTn7zdmeO4" /></figure><p>Issues are:</p><ul><li>Some icon sizes are not provided.</li><li>There is no apple-touch-icon.</li><li>There is not theme-color specified in meta tags.</li></ul><p>To fix the first one, we need to provide icons for all sizes in the manifest.json file. This file is located in the public folder of your project. I will use an online PWA manifest &amp; icon generator (<a href="https://www.simicart.com/manifest-generator.html">simicart.com/manifest-generator.html</a>)</p><p>Just specify your app icon with a minimum (512px x 512px) and a name here. Then click generate the manifest to download a zip file. It should contain all the icons we need. I will use the default icon provided by Ionic in the asset folder. Your zip file content should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OfCVogLHoSVXgH2e" /></figure><p>Go ahead and copy all icons to your project under the public -&gt; assets -&gt; icon folder.</p><p>Your new manifest.json will include these icons, and it should be like this:</p><pre>{<br>  &quot;short_name&quot;: &quot;Ionic App&quot;,<br>  &quot;name&quot;: &quot;My Ionic App&quot;,<br>  &quot;icons&quot;: [<br>    {<br>      &quot;src&quot;: &quot;assets/icon/icon-192x192.png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;purpose&quot;: &quot;maskable any&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;assets/icon/icon-256x256.png&quot;,<br>      &quot;sizes&quot;: &quot;256x256&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;purpose&quot;: &quot;maskable any&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;assets/icon/icon-384x384.png&quot;,<br>      &quot;sizes&quot;: &quot;384x384&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;purpose&quot;: &quot;maskable any&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;assets/icon/icon-512x512.png&quot;,<br>      &quot;sizes&quot;: &quot;512x512&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;purpose&quot;: &quot;maskable any&quot;<br>    }<br>  ],<br>  &quot;start_url&quot;: &quot;.&quot;,<br>  &quot;display&quot;: &quot;standalone&quot;,<br>  &quot;theme_color&quot;: &quot;#ffffff&quot;,<br>  &quot;background_color&quot;: &quot;#ffffff&quot;<br>}</pre><p>That is the fix for the first issue.</p><p>Add the following code to your index.html in the head tag to fix the second and third issues.</p><pre>&lt;link rel=&quot;apple-touch-icon&quot; href=&quot;%PUBLIC_URL%/assets/icon/icon-192x192.png&quot;&gt;</pre><pre>&lt;meta name=&quot;theme-color&quot; content=&quot;#ffffff&quot;/&gt;</pre><p>We are all set. Let’s build and test the PWA app one more time. Run ionic build and then serve build. Open the Chrome incognito window and test using Lighthouse.</p><p>You should see a result like this one, indicating that your PWA is ready and installable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lPWsO0mkCa-hweqE" /></figure><p>If you want to test the install, you can open your app on a normal window (not incognito), and you should be able to see the install button in the Chrome address bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tiOpACJ_7uAq8KIl" /></figure><p>If you try to log in on the installed version of the app, you will notice that you get the same error as before, saying, “Oops! something went wrong”. This is because the origin is changed to localhost:5000. You can add the new origin to Auth0 settings or specify the port when running the server. serve build -p 8100</p><p>Some screenshots of how the app works after installing on desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ShCuYYI0poOyz0QW" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hfTQXFOZg5BMk1cH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oPSbZext2nWuXkjs" /></figure><p>Congrats!! 🥳 🎉 👏 🥂</p><p>Now you have a functional PWA app with Auth0 login!</p><p>You can use this the same on the phone and install it as a PWA app.</p><p>You can download the code (project) I build as part of this blog from Github.</p><p><a href="https://github.com/pazel-io/ionic-auth0-react-pwa">github.com/pazel-io/ionic-auth0-react-pwa</a></p><h3>Bonus point — Deploy your new app using Vercel in less than 5 mins</h3><p>To test our PWA on the phone, it would be easier if we deploy the app to easily access it through a URL over HTTPS. I will use <a href="https://vercel.com/">Vercel</a> for this. Vercel is a zero-configuration cloud CI/CD that can understand the structure of our Ionic project and deploy it out of the box.</p><p>To do this, please go to <a href="https://vercel.com/">vercel.com</a> and register for a free account.</p><p>Log in, and you have the option to import a project from your Git repo. I am using Github, as mentioned before. So I will import the project from my Github.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k7ldhH5UHYgh23Sy" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pCsNi1Q4ItnlFdfI" /></figure><p>Vercel already knows that your project is Ionic React and knows what command to run to build it. Just go ahead and click deploy. This will run the build and give you a URL that your project will be available on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L8sSRkBAytaH9QIL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*24DWWAHYg8f_7xxG" /></figure><p>Simply click the button that says “Visit” to access your deployed app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I0hrvpdaxGvNGZfg" /></figure><p>Remember you will need to add the new origin (Vercel deployment domain) to Auth0 settings for Allowed Callback URLs, Allowed Logout URLs and Allowed Web Origins so you login successfully. You can add the new one like this. Replace the YOUR_APP_NAME with your own Vercel app.</p><pre>http://localhost:8100, <a href="https://{your_app_name}.vercel.app/">https://{YOUR_APP_NAME}.vercel.app</a></pre><p>Now I can test it on the phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rlA40DNLMltqReEU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5v7sLrw3uOhLay3l" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M4kdNTwxAt6X1p1X" /></figure><p>Go ahead, open the installed version of the app and try to log in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wm5n6CqQWsd9PmaC" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_or8xQLYxBG1mqIa" /></figure><p>That’s it for this tutorial. This implementation is good enough for Web and Mobile as long as you run it in a browser or installed it as PWA.</p><p>I will be writing on Ionic &amp; Capacitor integration with Auth0 as a native app in my next article.</p><p>Thanks for reading. I am available if you have any questions. Leave me a comment here or DM me on Twitter.</p><p>Git repo: <a href="https://github.com/pazel-io/ionic-auth0-react-pwa">github.com/pazel-io/ionic-auth0-react-pwa</a></p><p>Demo: <a href="https://ionic-auth0-react-pwa-deploy.vercel.app/#/home">ionic-auth0-react-pwa-deploy.vercel.app/#/h..</a></p><p>Twitter: <a href="https://twitter.com/_pazel">_pazel</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d627f52d8e97" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/ionic-react-pwa-with-auth0-login-for-web-and-mobile-no-plugin-required-d627f52d8e97">How to Integrate Ionic and React with Auth0 Login to Build a PWA for Web and Mobile (no plugin…</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Debug Ionic Mobile Apps in Production]]></title>
            <link>https://javascript.plainenglish.io/how-to-debug-ionic-apps-in-production-202bb10f7c55?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/202bb10f7c55</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[capacitorjs]]></category>
            <category><![CDATA[sentryio]]></category>
            <category><![CDATA[ionic-framework]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 10:51:08 GMT</pubDate>
            <atom:updated>2021-06-14T03:17:35.060Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is the second part of a <a href="https://pazel.medium.com/how-to-debug-ionic-apps-d73c6667c0e7">two-part article</a> on how to debug ionic apps. The techniques described here are helpful if your app is in release mode. If you are looking for ways to debug an app during development(debug version), please look at the <a href="https://pazel.medium.com/how-to-debug-ionic-apps-during-development-19d5df51c6bf">first part of this article</a>.</p><p>The downside of all the methods I explained in the <a href="https://pazel.medium.com/how-to-debug-ionic-apps-during-development-19d5df51c6bf">first part of this article</a> is that they are only available as long as the app is in debug mode (not the release version).</p><p>When you sign the app for Release, the app cannot be debugged using remote debugging anymore or using the Native IDE. So You need an alternative way to see your application logs. Let’s explore some of the options.</p><h4>1. Use device logs</h4><p>This method is not my favourite, but it can be handy sometimes to look at the device logs. You can connect your iOS or Android device to a computer to see the logs written to the console by all applications.</p><p>It’s not the friendliest debugging experience, but sometimes it is a good option since some of the issues can be at the OS level and not related to code, so WebView might not be much of help.</p><p>If you go down this path, you need to learn how to filter the logs to see the logs related to your application. You can use your app bundle id or some specific keywords to filter the logs and see your application logs.<br>Still, this will be a very low-level debugging experience compared to the experience you can get from Chrome DevTools.</p><p>Here is an example of Android debug logs by running the adb logcat command.</p><p>Tip: use a consistent structure in your application logs. This way, you can always use grep to filter the device logs. <br>Here I am usingadb logcat grep | &#39;File manager&#39; to get all logs starting with that keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BoPgAwFYt6JanKiTyIIWA.png" /><figcaption>Viewing Android debug logs using adb logcat</figcaption></figure><p>If you decide to go down this path, you should use Android Studio since looking at adb logs is not much helpful. This way, you can set the log level as you wish and filter by relevant keywords you know, like your bundle id.</p><p>Here an example of adb logs for the Spotify app with bundle id com.spotify.music. To access the logs open Android Studio, click the logcat in the bottom toolbar and then in the logcat window, select your device and provide the filtering options and log level(info, error).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zqKRNVFBLk9_0OMgoAWZA.png" /><figcaption>Viewing Android debug logs using adb logcat in Android studio.</figcaption></figure><p>Here is an example of iOS debug logs using Xcode. You will get a lot of logs, but you can filter by application. The nice thing is that you can access crash logs to give you an insight into why the app is crashing. To access these logs, open Xcode, then go to window menu and select Device and Simulators (or use cmd+shit+2 as shortcut) and select your device or simulator from the list to see its related logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpAdNY35Z_N8xhoJXHC1iA.png" /><figcaption>Looking at device logs from the prod app using Xcode</figcaption></figure><p>Some other limitations are that you need access to the device. This can be problematic since your mobile app is distributed to an extensive range of Android and iOS devices that you do not physically have access to them.</p><p>Usually, when an issue happens in production, you have no clue until an upset customer reaches out and tells you about it.</p><p>Even then, replicating the issue might be very difficult considering all the environment settings you may need. (OS version, Device model, Runtime issue related to lack of resources like memory or storage on the user device and bad network issues, to name a few.)</p><p>All you will get is that your app doesn’t work! If you are lucky and dealing with an experienced user, you may get some more details on the workflow leading to the issue. I think you agree that this sort of debugging is very inefficient, and you can go forth and back with the user many times to pinpoint the issue.</p><h4>2. Create an on-screen logger</h4><p>This method is very similar to the previous solution but a little easier to access the logs. Instead of connecting the device to a computer and looking at runtime logs, you can show a human-readable version of all the logs on a debug page in your app. This method is helpful, especially during internal QA when the app is tested as a proper release version by your own QA in-house. <br>Here is an example of the on-screen logger in one of our older Ionic app, which uses AngularJS. These logs are categorised for easy access to errors and have a specific format.</p><p>It might not look obvious at first, but in the hands of an experienced dev who knows the app’s workflow, this is good information for debugging.</p><p>Also, the user can send a copy of logs by sending the dump file to an API or email address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtxsfvHJKOS3lcTZe5JZvw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTTAq3wzqzucd0nxkqwD4g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZqLg7z7Th9rBjorWSdFOAA.jpeg" /><figcaption>On-screen debugger page showing application logs</figcaption></figure><p>The easiest way to implement this is to override the console methods and add logs to an array so you can print them on your page.</p><p>Even this method has its limitations. You can only write a limited number of logs on the screen, which is not easy to read through or search.<br>Also, you cannot keep too many logs on the device since it can turn into a large file quickly. So look at it as an option that you want to only enable temporarily for debugging a specific flow. The chances are that you might miss some errors that might be happening earlier in the workflow.</p><p>So are there any better ways to efficiently debug the Ionic apps in production?</p><p>Yes!</p><h4>3. Solutions that can record the whole user session</h4><p>So the idea is that you record whatever the user does (interaction in the app like click or visiting pages) and send it to a remote server. Then you can access an admin dashboard and replay the user’s session. Several platforms provide this type of solution.</p><h4><a href="http://logrocket.com/">LogRocket</a></h4><p>LogRocket lets you replay what users do on your site or hybrid mobile app, helping you reproduce bugs and fix issues faster. With LogRocket, you can replay problems as if they happened in your own browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jet6Y8OCSnlQa30q.png" /></figure><p>LogRocket lets you:</p><ul><li><strong>Session replay</strong><br>See a pixel-perfect replay of what the user saw. LogRocket can recreate the UI/UX of your app for you in its admin console.</li><li><strong>Redux<br></strong>Inspect actions and state at any point in time.</li><li><strong>Network activity<br></strong>View every network request and response, including the error code. Quickly find that nasty CORS error or the error related to API.</li><li><strong>Console and errors<br></strong>Inspect console logs and JavaScript errors</li></ul><p>Plus, you can add a user identifier to logs, so you know which session belongs to which user. This method is beneficial during UAT testing. Also, Logrocket provides easy integration with your favourite framework and even Redux state management (it has a middleware for NgRX). So you can see the state changes as if you have access to the browser in debug mode.</p><p>Sounds great! Isn’t it? Well, there are some pitfalls!</p><ul><li>There is no offline support out of the box. Meaning if a user is offline, LogRocket has no means to keep the device&#39;s data and send it later.<br>You can add a service worker to your app and proxy the LogRocket request to provide the offline storage yourself.</li><li>If you have a sizeable redux state, it can affect your app&#39;s performance and hug too much bandwidth. LogRocket will show you a warning if your state is too large and let you selectively ignore reporting parts of the state.</li><li>LogRocket has a free tier and very flexible pricing. So if you have not tried it, I highly recommend it.</li></ul><p>I have used LogRocket in many of our Ionic apps, and it makes prod debugging much easier for us. To avoid unnecessary data capture and respect user privacy, we usually avoid sending sensitive data by removing it from the payload that is sending to the LogRocket.</p><p>LogRocket session recording is disabled by default in our prod. We only enable it when debugging a specific user problem.</p><p>Enabling LogRocket for a specific user is usually triggered by the user by accessing a debug menu in the app. This way, the user will be in control of when their session is recorded.</p><p>There is another service called <a href="https://www.fullstory.com/">Fullstory</a>, which provides session replay, and I have not used it personally. Also, the pricing seems more expensive than LogRocket.</p><h4>4. Solutions that can handle runtime errors</h4><p>There are multiple solutions known as JS error trackers, which can send any runtime error in the JS runtime to a remote server. These errors are usually accompanied by helpful environment and user-session information. Like browser spec, the stack trace of error, time, location, user id and more.</p><p>Also, you can integrate them with other notification services like Slack so you can get real-time feedback from your production and act as quickly as possible to fix the user issues.</p><p>I usually have Sentry as part of most of the app I build to make it easier for me to address user issue proactively.</p><h4><a href="http://sentry.io/">Sentry.io</a></h4><p>Sentry provides self-hosted and cloud-based error monitoring that helps all software teams discover, triage, and prioritise errors in real-time. Sentry integrates with all major frontend frameworks easily and also has a free tier for you to start with.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNuFEsUGK93g%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNuFEsUGK93g&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNuFEsUGK93g%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4ecd2010d20b5611a2bb19a3ccd71b9/href">https://medium.com/media/b4ecd2010d20b5611a2bb19a3ccd71b9/href</a></iframe><h4><a href="https://trackjs.com/how/">TRACKJS</a></h4><p>JavaScript Error Logging from TrackJS monitors your web applications for JavaScript errors, alerting you with excellent context about how the user, application, and network got into trouble. Find and fix your bugs fast with TrackJS. Here is a good video by Bas explaining how TRACKJS works.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAKbzIPFZLy4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAKbzIPFZLy4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAKbzIPFZLy4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0944ada30f92b8e4d8a069b9542fa303/href">https://medium.com/media/0944ada30f92b8e4d8a069b9542fa303/href</a></iframe><h4>5. Use google analytics to track exceptions</h4><p><strong>Google Analytics</strong> is a <a href="https://en.wikipedia.org/wiki/Web_analytics">web analytics</a> service offered by <a href="https://en.wikipedia.org/wiki/Google">Google</a> that tracks and reports website traffic.</p><p>Google Analytics is used to <a href="https://en.wikipedia.org/wiki/Web_tracking">track</a> website activity such as <a href="https://en.wikipedia.org/wiki/Session_(web_analytics)">session</a> duration, pages per session, <a href="https://en.wikipedia.org/wiki/Bounce_rate">bounce rate</a>, etc., of individuals using the site and the traffic source information.</p><p>To use Google Analytics for exception reporting, you can send data of any exceptions you are interested in along with custom metrics that you have defined. Then you can make use of Google Analytics reports understanding what type of exceptions happen or how many users get a specific kind of exception.</p><p>An example of this use-case can be if many users are searching for a product in your shopping app that you do not provide. This exception is not necessarily an error, but at the same time, it’s a valuable stats for you to improve the UI/UX to give the user a better error message or maybe even consider adding that product to your offering.</p><h4>Conclusion</h4><p>I hope you have enjoyed reading this article, and please check the <a href="https://pazel.medium.com/how-to-debug-ionic-apps-during-development-19d5df51c6bf">first part of this article</a>.</p><p>Please leave a comment if you have questions or need help with some specific topic in the Ionic apps debugging.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=202bb10f7c55" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-debug-ionic-apps-in-production-202bb10f7c55">How to Debug Ionic Mobile Apps in Production</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to debug ionic apps during development?]]></title>
            <link>https://medium.com/codex/how-to-debug-ionic-apps-during-development-19d5df51c6bf?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d5df51c6bf</guid>
            <category><![CDATA[cordova]]></category>
            <category><![CDATA[ionic-framework]]></category>
            <category><![CDATA[capacitor]]></category>
            <category><![CDATA[safari-inspector]]></category>
            <category><![CDATA[chrome-dev-tools]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 10:48:09 GMT</pubDate>
            <atom:updated>2021-04-07T04:07:58.442Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to debug Ionic mobile apps during development?</h3><p>This article is the first part of a <a href="https://pazel.medium.com/how-to-debug-ionic-apps-d73c6667c0e7">two-part article</a> on how to debug ionic apps. The techniques described here are helpful if your app is in debug mode. If you are looking for ways to debug an app in prod(signed release), please look at <a href="https://pazel.medium.com/how-to-debug-ionic-apps-in-production-202bb10f7c55">part two of this article</a>.</p><h4>1- Remote debugging during development using Web View</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7PMXkw-jrU9Rnakb.png" /><figcaption>from Ionic website: <a href="https://ionicframework.com/docs/core-concepts/webview">Web Views power web apps on native devices</a></figcaption></figure><p>Ionic apps (native apps) are web apps that run in an embedded browser, so you can use remote debugging with chrome dev tools on Android or Safari Web Inspector on iOS to debug JavaScript, HTML and CSS.</p><p>You can use remote debugging with an actual device or simulator. If you use a real device, ensure that debugging is enabled both from the device and on the remote browser.</p><p>In Android, you need to go to the settings and enable developer mode first and then USB Debugging under the developer options menu. <br>If you do not see the Developer options menu, you need first to enable it. To do that, go to About phone &gt; Software information find the build number and tap on it until you get the confirmation for enabling developer options. Then the Developer options menu will be available at the same level as About phone menu option.</p><p>To enable remote debugging for android. Open a new chrome tab and type in chrome://inspect this will show you all the web views available for debugging, grouped by app name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLC93fV6FxxPEhzZOjfF_w.png" /><figcaption>Chrome inspect devices tab, showing apps that can be debugged on Simulator and Actual Device</figcaption></figure><p>iOS is very similar. Open Safari and find the menu that reads Develop from there; find the device you want to debug. Open the device menu, and you will see all available apps(Web Views) to debug. If you do not see the Develop menu, you need to go to Safari preferences and enable developer mode from the advanced settings. Also, make sure that the developer option is enabled on the actual device you use for debugging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pT6kPjfm9TMkriNmuw5Rfw.png" /><figcaption>Develop menu in Safari Desktop</figcaption></figure><p>You can use console methods like console.log and look at runtime logs to see how your app works. Also, you can use the JS debugger as you would do with a standard web application. You can inspect DOM and manipulate HTML and CSS for debugging.</p><p>Here is an example of remote debugging using Safari web inspector running the app on iOS simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZAzpXbOPdtDn3N4PBp8vg.png" /><figcaption>Remote debugging using Safari web inspector running the app on iOS simulator</figcaption></figure><p>Here is an example of remote debugging using Chrome DevTools running the app on Android simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nb3uaNY6oN575da7JNodLQ.png" /><figcaption>Remote debugging using Chrome DevTools running the app on Android simulator</figcaption></figure><p>If you prefer remote debugging using your IDE, VSCode already supports this feature. So instead of putting a debugger in JS or adding console logs, you can simply put a breakpoint in your code in IDE and runtime will pause that your breakpoints. There is a section in the Ionic debugging guide about this method.<br><a href="https://ionicframework.com/docs/troubleshooting/debugging#debugging-with-visual-studio-locally-in-chrome-both-android-ios-">https://ionicframework.com/docs/troubleshooting/debugging#debugging-with-visual-studio-locally-in-chrome-both-android-ios-</a></p><h4>2- Debugging during development using a browser</h4><p>If you use Ionic with Cordova or Capacitor, some of the native features will be only available when the app runs natively on a device or simulator. This limitation means you cannot simply serve the app using a desktop browser. To avoid this issue, I usually try to wrap my native service calls. Many plugins already provide a web implementation like Geolocation which falls back to use the browser Geolocation API. With other plugins, you can mock the plugin behaviour for the web or wrap the plugin calls in a service/function that ignores the web calls.</p><p>The following code is an example of using the Capacitor Haptics plugin on the device and ignoring the call on the web. This way, I will not get errors for the Haptics call in the console if I serve the app in a desktop browser. Alternatively, I could have used the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/vibrate">Navigator.vibrate()</a> to replicate the same behaviour, but in this case, I did not have a web target for deployment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d3fb21179c1fc446af513d86f27bc18/href">https://medium.com/media/8d3fb21179c1fc446af513d86f27bc18/href</a></iframe><p>Debugging on a regular browser like chrome helps you to use your favourite debugging tools and extensions. For example, I use redux DevTools to see how my state is changing as I navigate my application workflow. It’s much easier to simulate different screen sizes for testing your UI and the app layout responsiveness using the chrome dev tools.<br>Another benefit of this approach is the faster feedback loop since changes are just a refresh away. Not suitable for debugging that involves native apis access.</p><p>Other useful extra tools available compared to remote debugging are the performance audit tab(lighthouse) to test your performance, accessibility, PWA scores, or animation debugger.</p><p>Here is an example of debugging an app, which uses ionic v5 and Angular v9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQ2TTeWGo0kGXjMXT8M4Sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgfY6iMoWfSLay_4RG4Ryg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmyHI5Mt8tsi5NYlDomTJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHamiVjiPd0JWcSRKoxceg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJyAjFd-nwDrJ1Elah5MOw.png" /><figcaption>Debugging app layout using Chrome DevTools</figcaption></figure><h4>3- Debugging during development using native IDEs</h4><p>If you use Xcode or Android Studio to run your app on an actual device or simulator, you can look at debug logs output in IDE. This method is beneficial to debug issues that happen at the native level. Sometimes these issues happen early on app startup, which means your Web View does not even get a chance to load. So previous methods will not work.</p><p>Plus, if you use plugins to access native capabilities, you can quickly put a breakpoint in the Swift (Objective C) or Java code to find out issues caused by a bug in that plugin.</p><p>Running the app using native IDE’s is the primary way Ionic &amp; Capacitor works. With Ionic &amp; Cordova, you will need to go to generated iOS or Android project and open it in the respected IDE to debug it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1BAdsWn5E0v6bw3fE9gxA.png" /><figcaption>Debugging using Xcode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpoWXdsozxd3vC4-bzs3GA.png" /><figcaption>Debugging using Android Studio</figcaption></figure><p>There are many more tools for debugging. For example, using the desktop browser or native simulators, you throttle the network to simulate intermittent network condition or mock GPS location for debugging related to a device moving on a path or at a certain speed.</p><p>I hope you have enjoyed reading through this article, and please check <a href="https://pazel.medium.com/how-to-debug-ionic-apps-in-production-202bb10f7c55">part two of this article</a>.</p><p>Please leave a comment if you have questions or need help with some specific topic in the Ionic apps debugging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d5df51c6bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/how-to-debug-ionic-apps-during-development-19d5df51c6bf">How to debug ionic apps during development?</a> was originally published in <a href="https://medium.com/codex">CodeX</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 debug Ionic apps?]]></title>
            <link>https://medium.com/lapis/how-to-debug-ionic-apps-d73c6667c0e7?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73c6667c0e7</guid>
            <category><![CDATA[capacitorjs]]></category>
            <category><![CDATA[logrocket]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[ionic-framework]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 10:43:23 GMT</pubDate>
            <atom:updated>2021-04-06T00:07:16.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOyzJ7yr3TAVc-vbB-4L6w.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@kevin-ku-92347?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Kevin Ku</a> from <a href="https://www.pexels.com/photo/black-farmed-eyeglasses-in-front-of-laptop-computer-577585/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Debugging a mobile application is an essential part of development and maintenance.<br>Using Ionic to create mobile apps gives us a lot of leverage when it comes to debugging.<br>In this article, I share some of the techniques I use to debug Ionic apps and some example from the projects that I have done.</p><p>The article is broken into two parts:</p><ul><li><a href="https://pazel.medium.com/how-to-debug-ionic-apps-during-development-19d5df51c6bf"><strong>How to debug Ionic mobile apps during development?</strong></a></li><li><a href="https://pazel.medium.com/how-to-debug-ionic-apps-in-production-202bb10f7c55"><strong>How to debug Ionic mobile apps in production?</strong></a></li></ul><p>Apart from what I have explained in my article, there are several guides in Ionic docs around debugging that I encourage you to read.</p><p><a href="https://ionicframework.com/docs/troubleshooting/debugging">Debugging - Ionic Documentation</a></p><p>Also, there is a good video by <a href="https://medium.com/u/bca45c04dc66">Simon Grimm</a> that covers a lot of good techniques and tips for debugging.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fakh6V6Yw1lw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dakh6V6Yw1lw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fakh6V6Yw1lw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe7934eab146595186ac6c96c0e470b2/href">https://medium.com/media/fe7934eab146595186ac6c96c0e470b2/href</a></iframe><p>Depending on which framework you use along with Ionic, make sure to check the debugging guide for that specific framework as well.</p><p>Here is a blog by <a href="https://medium.com/u/314f82b7e8">Emma Twersky</a> on debugging published on the Angular blog.</p><p><a href="https://blog.angular.io/angular-debugging-guides-dfe0ef915036">Angular Debugging Guides</a></p><p>By all means, there are many more issues that you may run into when building Ionic mobile apps. Like how to manage signing and deployment? How to avoid common problems with app store reviews?<br>How to deploy code updates without going through app stores? <br>How to avoid common pitfalls with PWAs? And many more topics.</p><p>I have spent years on this platform from the early days of Cordova up to now. So if there is anything else you would like me to cover and write about, please leave me a comment and let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73c6667c0e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lapis/how-to-debug-ionic-apps-d73c6667c0e7">How to debug Ionic apps?</a> was originally published in <a href="https://medium.com/lapis">Code道</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Others! A story of MacOs temp files.]]></title>
            <link>https://pazel.medium.com/the-others-a-story-of-macos-temp-files-52694919e24?source=rss-53d14bb89815------2</link>
            <guid isPermaLink="false">https://medium.com/p/52694919e24</guid>
            <category><![CDATA[macos-catalina]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[large-file]]></category>
            <dc:creator><![CDATA[Parham]]></dc:creator>
            <pubDate>Fri, 23 Oct 2020 01:29:11 GMT</pubDate>
            <atom:updated>2020-10-23T02:06:07.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Others! A story of macOS temp files.</h3><p>This is not a guide but rather my personal experience and struggle with macOS temp files and how I resolved it. I am not sure if it matters but I use the latest update of macOS Catalina (10.15.7)</p><p>I had 884GB of my 1TB hard disk taken by macOS temp files.<br>These files plus my files, apps and projects had reduced the free space to less than 100 MB (out of 1 TB) and nothing was working properly. I was getting disk space alert constantly.</p><p>These temp files are hidden so you will not find them in any reports. like when you look at storage analysis in macOS. It just comes under the category of Other which does not tell you what or where the files are.If you google these many people have the same issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqUA2rnxPVySS-28nnCrBQ.png" /><figcaption>macOS storage analysis example showing others</figcaption></figure><p>Googling I found the “Other” category includes the following types of files:</p><ul><li>System temporary files</li><li>macOS system folders</li><li>Archives and disk images (.zip, .iso, etc.)</li><li>Personal user data</li><li>Files from the user’s library (Application Support, iCloud files, screensavers, etc.)</li><li>Cache files</li><li>Fonts, plugins, extensions</li><li>Hidden files</li><li>Other files that are not recognized by a Spotlight search</li></ul><p>I tried multiple techniques to make these hidden files visible.</p><ul><li>I restarted the machine and that seemed to release some disk. I got to 4GB free space.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*M3OtrQSOuuUn3mRr.jpeg" /></figure><ul><li>Using <a href="https://dev.yorhel.nl/ncdu">ncdu</a> with command sudo ncdu /<br>ncdu is a disk usage analyzer with a ncurses interface. It is designed to find space hogs on a remote server where you don’t have an entire graphical setup available, but it is a useful tool even on regular desktop systems. <br>It takes a long time to analyse and for me was crashing halfway. I believe the size of disk or data was too big for this tool. Also for some reason, it was showing the size of the drive as 3.9 TiB which is way more than 1TB.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOdwzVe4hTwp99kMakrHpw.png" /><figcaption>ncdu tool scanning my HD</figcaption></figure><ul><li>Next tried <a href="https://daisydiskapp.com/">DiskDaisy</a> and after analysis, it showed that there are 881GB of hidden files but I needed to pay and buy a licence to see the hidden files. It’s a premium feature.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBqjAGVkx4FidP655dMQmA.png" /><figcaption>DiskDaisy scan results on the free version</figcaption></figure><ul><li>Next tried <a href="https://cleanmymac.com/">CleanMyMac</a>. It’s a nice software and has some free feature but it was only finding 7.5 GB of junk to clear. Things like app caches, unneeded download files and some more junk. I removed the IMovie through CleanMyMac since I don’t use it and that gave me another extra 2GB disk space.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U77Vr2BP46_-nMIT.jpg" /><figcaption>CleanMyMac UI example — I did not save the actual one from my test</figcaption></figure><ul><li>Then tried the <a href="https://www.omnigroup.com/more">OmniDiskSweeper</a> and when I ran the analysis It found 110GB of used disk space. Failed to see the hidden files. I used the GUI but apparently, you can use it as command line as well.<br>Install with HomeBrew using brew cask install omnidisksweeper</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lBKiPrt_88yzDdvq.png" /><figcaption>OmniDiskSweeper UI example — I did not save the actual one from my test</figcaption></figure><ul><li>Looking at Mac DiskUtility I could see the same info on disk space usage but no more info on what or where are those files.</li><li>Last hope was going back to DiskDaisy and purchasing a licence. Hoping it can show what are those hidden files finally. Good news! It worked and it showed that the hidden files are located under private/var/tmp and there they were!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmuBc9Fkzv9kk69xrz1Epg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zI-pgRCMM5_OQCC90asEuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KavQlxh0Y_zIeivn8O87Ug.png" /><figcaption>DiskDaisy showing the hidden file in the premium version</figcaption></figure><ul><li>Then after reading more on the forums, I found these are macOS temp files. Articles I read were primarily suggesting 2 solutions. <br>1- Restart your machine and macOS should get rid of temp files. <br>2- If the first solution does not work, start in safe mode and then restart in normal mode and that should remove the temp file. <br>None of them worked for me. I even kept the machine in safe mode for a couple of hours to give the so-called macOS cleanup task enough of the time. Still no luck!</li><li>Then I used macOS built-in Disk utility in safe mode and the First Aid and hoping it can clean up any temp files. It did not find any errors and did not delete any files. So no luck here either!</li><li>Last resort was to manually delete the files. <br>If you read on this manual deletion topic you will find a lot of ppl warning not to mess around with files in private/var/folders and also private/var/tmp since they are managed by OS and can cause irreversible damage to files. <br>Since I was out of options and HD space I relied on one article that was claiming removing temp files manually will not harm anything. <br>I removed the files using DiskDaisy and freed up space. <br>Then restarted and all looks good so far 🤞.</li></ul><p>It took a good 40mins to remove all the files and my computer is alive.<br>It was like choking the resources before.<br>Disk space is one problem and also this issue was causing my BitDefender to go crazy and upload a lot to its server (I guess BitDefender does send some data about file for scanning to its server). So it was using a lot of bandwidth as well.</p><p>I still am not sure if what I did was right and if you should have manually deleted the temp files.<br>The main question is why the OS didn’t clear out the temp files in that folder in the first place as expected. I will keep an eye on things in that area for the next few weeks and make sure it cleans up after itself.</p><p>The <a href="https://daisydiskapp.com/#">DiskDaisy</a> licence did cost me AUD 15 and saved me a lot of time on this diagnosis. Also, I can use it on my other machines.</p><p>My machine is much faster now and I have not heard the fan sound today. <br>BitDefender network activity is reduced significantly as well.</p><p>I was so focused on solving the issue and did not think about checking how old these files were or potentially try to find out if they belong to any specific programs which might have caused the issue.</p><p>So if you have more information on the macOS temp files, please share it here with me.</p><p>ps: I have used my machine for 5 days since and so far no signs of anything missing after the cleanup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52694919e24" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>