<?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 Danielle Fenske on Medium]]></title>
        <description><![CDATA[Stories by Danielle Fenske on Medium]]></description>
        <link>https://medium.com/@daniellefenske?source=rss-971f1d4484c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ENnkkuywqo3PbGSlocoJjQ.jpeg</url>
            <title>Stories by Danielle Fenske on Medium</title>
            <link>https://medium.com/@daniellefenske?source=rss-971f1d4484c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:33:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daniellefenske/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[PagerDuty + Slack + Azure Integration]]></title>
            <link>https://medium.com/payscale-tech/pagerduty-slack-azure-integration-2444d668c4fa?source=rss-971f1d4484c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2444d668c4fa</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[pagerduty]]></category>
            <category><![CDATA[alerts]]></category>
            <dc:creator><![CDATA[Danielle Fenske]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 19:37:26 GMT</pubDate>
            <atom:updated>2020-02-18T19:37:26.645Z</atom:updated>
            <content:encoded><![CDATA[<h4>An illustrated walk through of how to correctly set up the integration between these three services.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*gWPfYJcOwKwMh9BV" /><figcaption>Photo Credit: <a href="https://unsplash.com/photos/okvqMfl78YE">unsplash.com</a></figcaption></figure><p>Our tech ecosystem involves <strong>PagerDuty </strong>for alerting, <strong>Slack </strong>for communicating, and <strong>Azure </strong>for logs. We wanted to integrate all of these so we could have clear, transparent alerting for our various apps that we host in Azure.</p><p>We thought we had this integration all set up, but we were observing a strange anomaly. Slack would not notify us if the Azure alert had been triggered. It would only notify us when the alert had been acknowledged, resolved, etc. Furthermore when we tried to view the specific alert in PagerDuty, the whole site would freeze or crash.</p><p>We finally figured out the cause of these issues: <strong>the large JSON payload associated with the alert from Azure.</strong></p><blockquote><strong>note</strong>: this occurs only with Azure Alerts that are configured using the “<strong>Log Search</strong>” Signal Type.</blockquote><p>To restate the problems we were seeing:</p><ul><li>Slack would not notify us of Triggered alerts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*KIQo2tIh7jSgC5Em-DB3Vg.png" /><figcaption>Problem 1: Slack didn’t notify us of a Triggered PagerDuty alert</figcaption></figure><ul><li>The PagerDuty app would crash regularly while trying to view the alerts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*ppO-278Neuo57h5_xHZHkw.png" /><figcaption>Problem 2: The PagerDuty site would crash when viewing the specific alert, due to the large JSON payload</figcaption></figure><p>To resolve these issues, I found that we needed to configure a Custom JSON payload for our Azure Webhooks, which are used by PagerDuty. To do that, I went into the configuration for our Azure alerts.</p><h3>Azure Configuration</h3><p>As you can see below, our PagerDuty Webhook was already set up, and the condition is a <strong>Custom Log Search.</strong> This following steps are only required if the alert is a Custom Log Search type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ts0o6qF55GDa-YbeYNieXQ.png" /><figcaption>Step 1: Configuring the Azure Log Search Alert to use a custom JSON Payload for the <strong>Webhook</strong></figcaption></figure><p>Then to actually customize the JSON payload, I checked the box labeled “Include custom JSON payload for webhook”. To specify the JSON output, I referred to the Azure <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-log-webhook">documentation</a> on how to use predefined variables in the text of the JSON. You can use variables such as #searchresultcount to include details in the text about this specific alert.</p><p>To ensure that my custom JSON looked correct, I clicked the “View Sample Webhook Payload” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*N7QYjSlNPql2tEEMKtFv1Q.png" /><figcaption>You can use predefined variables from Azure to configure the custom JSON payload (<a href="https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-log-webhook">documentation</a>)</figcaption></figure><p>After configuring my alert in Azure, I tested my alert in Slack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*lT3wXhMZ43-4R0v7R7_YZw.png" /><figcaption>Problem 3: My Slack notification was missing a description, because it couldn’t be parsed from the JSON</figcaption></figure><p>But wait… there’s a new problem ! The summary is missing from the Slack alert.</p><h3>PagerDuty Configuration</h3><p>To configure the summary of an alert in Slack, I had to go into PagerDuty to configure my service to read from the correct JSON fields. So I went to the Event Rules tab of my service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*8lHXpkexOvwI6KtiaJRwXQ.png" /><figcaption>The Event Rules tab is where you can configure the correct fields to use in the Slack alert</figcaption></figure><p>Inside the Event Rules, I configured a new rule with the following criteria:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYVkew_MS7rESaWndGptKQ.png" /><figcaption>You need to configure an Event Rule to extract the right details from the custom JSON payload</figcaption></figure><p>In the following screenshots, I show more detail on what values need to be configured to populate the Slack alert’s summary. I needed to create a rule that fired only if the text field of Custom Details existed. (text should be replaced with whatever field in the JSON object you want to extract Summary from).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*ccb68zwar7crMh0pVogvzQ.png" /><figcaption>Step 1 for configuring the Event Rule</figcaption></figure><p>Then I clicked “Do these things” and went to the Advanced tab. I checked the box “Add or replace the summary field” and filled it in as shown below. This specifies that the alert should replace the Summary field with the custom field named text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F45yCezvjP2tygfHb7bKTQ.png" /><figcaption>Step 2 for configuring the Event Rule</figcaption></figure><p>I then tested my alert one more time — success! The alert shows up as Triggered in Slack, with the summary that I configured in Azure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*QS_FlJhy6KwGI6lJk7uA6A.png" /><figcaption>The Triggered alert showed up in Slack, with a detailed error message from the Custom JSON payload.</figcaption></figure><p><strong>One last thing:</strong> if you don’t see the Event Rules tab in your PagerDuty Service configuration, you may need to edit the service so that it can create alerts AND incidents. The Event Rule tab will not show up if the service is configured differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*w9tR73KBmNtLm1k9VWdY6A.png" /><figcaption><strong>Note: </strong>If you don’t have your service configured this way, the Event Rules tab won’t show up</figcaption></figure><p>Hopefully this can help anyone facing a similar issue to correctly configure their alerts. <strong>Happy configuring!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2444d668c4fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/payscale-tech/pagerduty-slack-azure-integration-2444d668c4fa">PagerDuty + Slack + Azure Integration</a> was originally published in <a href="https://medium.com/payscale-tech">PayScale Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Network Timeouts and CPU Limitations in Azure Kubernetes Service]]></title>
            <link>https://medium.com/payscale-tech/network-timeouts-and-cpu-limitations-in-azure-kubernetes-service-178789ebe41?source=rss-971f1d4484c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/178789ebe41</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Danielle Fenske]]></dc:creator>
            <pubDate>Tue, 03 Sep 2019 17:45:28 GMT</pubDate>
            <atom:updated>2019-09-03T17:45:28.057Z</atom:updated>
            <content:encoded><![CDATA[<h4>How under-provisioned applications behave, and the kinds of errors that are caused by limited CPU</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*0gZBK45R6CcI-6IZ" /><figcaption>Image Credit: <a href="https://unsplash.com/photos/KYxXMTpTzek">Unsplash</a></figcaption></figure><h4>Intro</h4><p>We have been plagued by a mysterious issue in our production environment for many weeks now — and now that we have solved the issue, we wanted to document the solution for anyone else out there that is struggling with a similar problem.</p><h4>Application Details</h4><p>We built a <a href="https://nextjs.org/learn/basics/getting-started">Next.js</a> application running on a custom Express server in Docker on Azure Kubernetes Service. Our application relies heavily on data that is fetched from an API. The API runs on an Azure Web Application and returns large (~100KB) JSON blobs. Our app is running behind <a href="https://azure.microsoft.com/en-us/services/application-gateway/">Azure Application Gateway</a>.</p><h4>How the issue manifested</h4><p>We were puzzled by the combination of issues we saw — at each level of the pipeline, we were seeing different problems.</p><ul><li>After the app had been spun up, as it got more and more traffic, we would start to see lots of network timeouts while fetching data from the API.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BX931Ug7_yJuZHaIUT4LoA.png" /><figcaption>Lots of network timeouts while calling the API (seen in an Azure Log Analytics query)</figcaption></figure><ul><li>The network timeouts caused the <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/">readiness probe</a> for our pods in AKS to constantly fail due to timing out. AKS would take those pods out of rotation, causing the other pods to be overloaded with more traffic. This caused a cascading failure to all our pods, so out of all our pods, about half of them were unhealthy at any given time, and they just kept cycling from healthy to unhealthy.</li><li>Increase in 5XX errors in the Azure Application Gateway</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDCStDL8OGEcw6D1AuNLGg.png" /><figcaption>Spike in failed requests in Azure Application Gateway</figcaption></figure><ul><li>Decline in requests to the application itself</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JC0tmWcLajMQQOrwhSErtg.png" /><figcaption>Decline in total requests that were making it to the application (seen in an Azure Log Analytics query)</figcaption></figure><ul><li>No errors or high response time observed in the API logs</li></ul><h4>What we tried</h4><p>At first we thought that the <a href="https://nodejs.org/uk/docs/guides/dont-block-the-event-loop/">event loop was being blocked</a>. We realized we were using console.log, which is synchronous and <a href="https://expressjs.com/en/advanced/best-practice-performance.html">not suitable for a production environment</a>. We replaced console.log with <a href="https://www.npmjs.com/package/winston">Winston</a>, an asynchronous logging framework. For a few days, we thought that this solved the problem.</p><p>When we did another deployment, everything started to crash again. This time we tried increasing the number of pods — all the way up to 64. This did not help, and instead we now had 32 pods unhealthy at any given time…</p><p>We created a <a href="https://medium.com/payscale-tech/load-testing-your-website-by-replaying-cloudfront-logs-eb81cbaf27ea">load tester</a> that replays Cloudfront logs on a specified domain, so we were able to reproduce the issue locally. We tried many different performance optimizations and tried commenting out code, bit by bit, while running the load tester, but nothing seemed to prevent the network timeouts.</p><p>We noticed that CPU usage was high and spiky while load testing, so we tried to increase the <a href="https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/">CPU requests</a> per pod. There are two CPU values you need to configure in your YAML file when provisioning an application on AKS: one is requests and one is limits. These names may sound vague but they are just the lower and upper bounds of how much CPU you want each pod to use.</p><p>So we started with this configuration:</p><pre>resources:</pre><pre>  requests:</pre><pre>    cpu: .5</pre><pre>    memory: 1Gi</pre><pre>  limits:</pre><pre>    cpu: 2</pre><pre>    memory: 2Gi</pre><p>This means we want at least half a CPU for each pod and we want each pod to take up no more than 2 CPUs. When we tried scaling out from 8 pods to 64, this meant that we were requesting 0.5 * 64 = 32 CPUs from the cluster.</p><p>Then we wanted to try bumping the CPU request up to 1 CPU. When we tried this with 64 pods, we got an error saying “Insufficient CPU”, meaning we were requesting more CPU than the cluster had available.</p><p>This led us to increase the number of nodes in our cluster from 7 to 15. We were then able to deploy our application with CPU requests = 1, and CPU limits = 2, since we now had enough resources available in the cluster for this configuration. This solved our problem! It allowed us to even reduce the number of pods back to 8 and the app stayed healthy.</p><h4>Solution (and Explanation)</h4><p>Solution: Increase the number of nodes in your AKS cluster.</p><p>Explanation: Scaling our number of nodes in our AKS cluster up to 15 allowed each pod to get enough CPU for it to function smoothly. One question I had was “why did it struggle before, even when we said each pod could take up to 2 CPU for itself?” We realized that before we increased the number of nodes, we had lots of pods that said “I can go up to 2 CPUs if I need”, but we didn’t have 2 * number of pods CPU available to give out. So each pod was never able to get close to that upper limit of CPU allocated for itself, since there just weren’t enough resources to be provisioned for each pod.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=178789ebe41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/payscale-tech/network-timeouts-and-cpu-limitations-in-azure-kubernetes-service-178789ebe41">Network Timeouts and CPU Limitations in Azure Kubernetes Service</a> was originally published in <a href="https://medium.com/payscale-tech">PayScale Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Testing your Website by Replaying Cloudfront Logs]]></title>
            <link>https://medium.com/payscale-tech/load-testing-your-website-by-replaying-cloudfront-logs-eb81cbaf27ea?source=rss-971f1d4484c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb81cbaf27ea</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[cloudfront]]></category>
            <dc:creator><![CDATA[Danielle Fenske]]></dc:creator>
            <pubDate>Tue, 06 Aug 2019 23:26:56 GMT</pubDate>
            <atom:updated>2019-08-06T23:26:56.730Z</atom:updated>
            <content:encoded><![CDATA[<h3>Replay AWS CloudFront Logs to Load Test Your Website</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*_KXJnDUH3LoaSz-j" /><figcaption>Photo Credit: <a href="https://unsplash.com/photos/lsJsaERGu4c">Unsplash</a></figcaption></figure><h4>Motivation</h4><p>We have a <a href="https://nextjs.org/">NextJS </a>application that runs on a <a href="https://www.docker.com/">Docker </a>container in <a href="https://azure.microsoft.com/en-us/services/kubernetes-service/">Azure Kubernetes Service</a> (AKS). And we ran into a problem: things would be running fine in all environments, right up until we actually deployed to production. Then we would see strange errors, intermittent 504s, and other odd behavior. We were wondering then… how can we catch these performance issues and other obscure bugs before the code reaches the production environment?</p><h4>Idea</h4><p>We wanted a way to mimic the amount of traffic we’re getting to production in our dev environments. We could just hit a few different URLs over and over again… but that wouldn’t really be representative of what is actually going on in production. Then we thought — what if we could just pull a set of the requests to our production site and replay them against our site in the dev environment?</p><h4>Solution</h4><p>The way I went about doing this was simple once we had a vague idea of what we wanted. I wrote two Node scripts that do the following:</p><h4>Script #1: Pull an hour’s worth of CloudFront logs from S3</h4><p>The first script is named download-cloudfront-logs.js. It accepts parameters that specify where in AWS to find the logs you want to use. It also accepts a timestamp which specifies the specific hour for which you want to download the logs.</p><p>To run the download-cloudfront-logs.js script, I run this command:</p><pre>node ./download-cloudfront-logs.js --timestamp 2019–08–05–01 --bucketName &lt;the-bucket-with-the-logs&gt; --s3folder &lt;the-folder-in-the-bucket&gt; --cloudfrontId &lt;the-cloudfront-distribution-id&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*0Eg7l4TDy4fpqT-bHPgZyQ.png" /><figcaption>The output from running ./download-cloudfront-logs.js</figcaption></figure><h4>Script #2: Replay the logs against a different URL</h4><p>Replay those logs against a given URL (the dev environment) at the same interval that the requests were originally made.</p><p>The script that executes the requests displays in the console a color coded list of status codes that it received from our app. If we see any red lines (5xx status codes), that’s an instant clue that we have a problem in our app.</p><p>To run the load-test.js script, I run this command:</p><pre>node ./load-test.js --maxPings 100 --urlHost <a href="https://www.payscale.com/">https://www.&lt;dev-environment-url&gt;.com</a> --prefix ‘/research/’</pre><p>which is saying “replay just the first 100 requests against our dev environment, and only replay the requests that begin with ‘/research/.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7-Q7tWIP_nF8iAgHyEGCA.png" /><figcaption>The CloudFront logs are read into memory, sorted in order of timestamp, and then replayed at the correct intervals</figcaption></figure><h4>Other Uses for this Script</h4><p>We also have started using this script to just look for bugs in our local environment when we are writing new code. I can run this script against my local environment and watch the application logs and look for exceptions being thrown. I have found cases where I forgot to define a variable or forgot to add a null check, which only occurred in special situations and which I wouldn’t have been able to catch if I hadn’t thought to check a specific URL.</p><h4>Github Repo</h4><p><a href="https://github.com/payscale/load-test-script">payscale/load-test-script</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb81cbaf27ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/payscale-tech/load-testing-your-website-by-replaying-cloudfront-logs-eb81cbaf27ea">Load Testing your Website by Replaying Cloudfront Logs</a> was originally published in <a href="https://medium.com/payscale-tech">PayScale Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to React Hooks]]></title>
            <link>https://medium.com/payscale-tech/introduction-to-react-hooks-29ef97547862?source=rss-971f1d4484c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/29ef97547862</guid>
            <category><![CDATA[react-16]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Danielle Fenske]]></dc:creator>
            <pubDate>Fri, 19 Jul 2019 18:50:35 GMT</pubDate>
            <atom:updated>2019-07-19T18:54:12.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0IR0e4YRL7km2tngBe8eg.jpeg" /></figure><h3>Why do we need Hooks?</h3><p>How many times have you written a simple functional React component, only to realize you need to store state, and therefore you must convert it to a class component? You have to change the component declaration, add a constructor, and use the lifecycle methods.</p><p>React Hooks provide you the option of leaving the component functional, while still being able to keep track of state. They are very powerful, but require a bit of a paradigm shift to get used to. In this blog post, I will show examples of components that use React Hooks, and compare them with an equivalent component built using the “old way”. Hopefully this will help you understand why React Hooks are useful and allow you to start using them in your own code.</p><h3>Hook #1: useState</h3><p>useState allows you to add state to your functional components. The syntax is a little funky, but once you know what each parameter stands for, it is easy to pick up.</p><p>A simple example:</p><pre>const [value, setValue] = useState(null);</pre><p>Which means:</p><pre>const [&lt;variable name&gt;, &lt;name of handler for that variable&gt;] = useState(&lt;initial value&gt;);</pre><h4>Class Component (23 lines)</h4><p>Here, we have a very simple example. It displays an input, and below the input, displays “Hello” + the value of the input. Every time we type in the input, the handleChange function is called which updates state, and the whole component is re-rendered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfd5dadfb9bf181d90b28baf032079ad/href">https://medium.com/media/cfd5dadfb9bf181d90b28baf032079ad/href</a></iframe><h4>Functional Component with React Hooks (10 lines)</h4><p>In the React Hooks version of the component, we see that we define our state value (name), the handler (setName), and the initial value for name (‘’), all on one line. We can then reference these in the component below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b682e0fee9d0b6184e21eae92310e27/href">https://medium.com/media/2b682e0fee9d0b6184e21eae92310e27/href</a></iframe><h4>Hook #2: useEffect</h4><p>useEffect takes the place of some lifecycle methods on class components; the React team describes it as a combination between componentDidMount, componentDidUpdate, and componentWillUnmount. We can utilize useEffect to trigger side effects.</p><p>useEffect takes two parameters:</p><ol><li>The first is the function that will be run when the effect is triggered</li><li>The second is an optional list of dependencies. The effect will only run if one of the dependencies in the list changes. If the list of dependencies is left empty ([]), then the effect will only be run once, when the component mounts.</li></ol><p>A simple example:</p><pre>useEffect(async () =&gt; {<br>    // Fetch some data when name changes<br>    const result = await fetch(`/getPerson/${name}`);</pre><pre>    // Do something with the result<br>    setPerson(result);<br>}, [name]);</pre><p>Or in generic terms:</p><pre>useEffect(&lt;function to call&gt;, [&lt;list of dependencies&gt;]);</pre><p>When trying to think of useEffect in relation to the lifecycle methods, you can consider it this way (this list came from the slides associated with <a href="https://code.react-advanced.smooth-code.com/">this hooks tutorial</a>).</p><ul><li>Mount: Run effect</li><li>Update: Clean effect, Run effect</li><li>Unmount: Clean effect</li></ul><p>The clean effect stage is where you can do some clean up if you need to — eg. if you added an eventListener with the effect, in the cleanup, you would want to remove that eventListener.</p><p>The way to add a clean-up stage in the useEffect syntax is by adding a return statement that returns a function. (The following code snippet came from the slides from <a href="https://code.react-advanced.smooth-code.com/">this React hooks tutorial</a>).</p><pre>function ClickSpy() {<br>  useEffect(() =&gt; {<br>    function handleClick() {<br>      alert(&#39;clicked&#39;)<br>    }<br>    document.addEventListener(&#39;click&#39;, handleClick)<br>    // The function return by the effect is the clean up<br>    return () =&gt; {<br>      document.removeEventListener(&#39;click&#39;, handleClick)<br>    }<br>  })</pre><pre>  return null<br>}</pre><h4>Class Component (38 lines)</h4><p>This class uses componentDidMount to fetch some data from Reddit. The response is then rendered once the fetch has returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d31a8a585dcd4e79adcd0ebc9db6cc78/href">https://medium.com/media/d31a8a585dcd4e79adcd0ebc9db6cc78/href</a></iframe><h4>Functional Component with React Hooks (28 lines)</h4><p>In the functional version, we use useState to store loading and redditResult, and we use useEffect with no dependencies to run the fetch on the first mount of the component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f0fc4fb4ebd55594095997714a7c705/href">https://medium.com/media/2f0fc4fb4ebd55594095997714a7c705/href</a></iframe><h3>Hook #3: useRef</h3><p>Although it’s not typically recommended, sometimes you need to access the DOM directly in React. One good example is modals — to open and close them it is helpful to just be able to access the DOM to manipulate them. To do this, you need to use refs.</p><h4>Class Component (37 lines)</h4><p>We used to be limited to only using refs in class components. The way to use them was to create one using createRef(), assign it as a field on the component instance, and then refer to it throughout the component this way: this.imgRef. In this sample, we have a button that, when clicked, will randomly choose one of the four kitten images and replace the image tag’s src attribute with the new URL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e5aa7a9e87070893b6b514ce4b2a91c/href">https://medium.com/media/4e5aa7a9e87070893b6b514ce4b2a91c/href</a></iframe><h4>Functional Component with React Hooks (30 lines)</h4><p>With the new useRef hook, we can have a ref inside of a functional component. We create a reference first with useRef(defaultValue), use that reference in the &lt;img&gt; tag, and then we can manipulate that DOM element using the imgRef we created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4278d17027cd881e657948f2202662b6/href">https://medium.com/media/4278d17027cd881e657948f2202662b6/href</a></iframe><h3>Hook #4: useContext</h3><p>The Context API is a tool that was introduced in React v16.3. It is useful for setting global settings for an app, like a theme or a configuration value. It is an easy way to allow all components to access a value, without having to pass it as a prop through each level of the component hierarchy.</p><p>React Hooks added to this useful tool by creating the useContext hook.</p><h4>Old Way: Providers and Consumers (26 lines)</h4><p>To use the Context API, you must create a context with React.createContext(defaultValue). This instantiates a context, with a default value. In the old way, to make the value of Context available to components, you needed to use Providers and Consumers to wrap React components. In the parent component, you would wrap the child in a &lt;Provider&gt; component, and then in the child component, you wrap a component in the &lt;Consumer&gt; to make the value of Context available. To use the value, you use the render props format.</p><p>In the example below, we want to use the Context to store the color theme for our component, using the same input and text components that we saw in our first example. If we render the &lt;App&gt; component, we explicitly set the context’s value to ‘red’, so the colors will be red. However, if we just render &lt;MyComponent&gt; to the page, we have not passed in a value to the context, so it will use the default, ‘blue’ (try this out in Codepen using the link below the snippet and see for yourself).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5532c26d8c3b8afed310d9985d40473a/href">https://medium.com/media/5532c26d8c3b8afed310d9985d40473a/href</a></iframe><h4>React Hooks (22 lines)</h4><p>With hooks, you will still instantiate the context with React.createContext(). The difference here is that instead of having to wrap your child component with the Consumer to make the context’s value available, we can just use React.useContext(&lt;contextName&gt;) to get the value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cd7dd033acb0e6bd3a09949823c8dc3/href">https://medium.com/media/1cd7dd033acb0e6bd3a09949823c8dc3/href</a></iframe><h3>Conclusion</h3><p>We have covered 4 of the basic React hooks: useState, useEffect, useRef, and useContext. Some other hooks we did not cover are useReducer, useCallback, and useMemo. These hooks are more complex — a basic description of what each one does is:</p><ul><li>useReducer: a more complex version of setState, which lets you configure multiple different action types for different scenarios.</li><li>useMemo: this stands for memoize — a way of caching results or values, so that if you input the same parameters into a function twice, instead of redo-ing the calculation the second time, the function will just returned the result from the first time.</li><li>useCallback: Similar to useMemo, but used for memoizing a callback function instead of a value.</li></ul><p>Some other things to note before you go out into the world and start using React Hooks everywhere</p><ul><li>Hooks must be called in the <strong>same order</strong> every time — you cannot use them inside if statements or conditionals. The React documentation explains: “That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls”. There is an <a href="https://www.npmjs.com/package/eslint-plugin-react-hooks">eslint-plugin</a> to help you make sure you’re sticking to this rule.</li><li>State is <strong>not merged</strong> when using useState. The new state overwrites the old state — this is important if you have an object in state and you’re just trying to set one property. You need to do the merge yourself.</li><li>It is recommended to use one useState per piece of state stored. Don’t try to store all state in one object with one useState declared. It gets messy.</li><li>Same goes for useEffect — use one useEffect statement per side effect you are controlling.</li><li>You can <a href="https://reactjs.org/docs/hooks-custom.html">write your own hooks too!</a></li></ul><h3>Resources</h3><ul><li>My CodePen Collection of all the above code snippets: <a href="https://codepen.io/collection/nwqdpg/">https://codepen.io/collection/nwqdpg/</a></li><li>Hooks at a Glance: <a href="https://reactjs.org/docs/hooks-overview.html">https://reactjs.org/docs/hooks-overview.html</a></li><li>Hooks API Reference: <a href="https://reactjs.org/docs/hooks-reference.html">https://reactjs.org/docs/hooks-reference.html</a></li><li>Great React Hooks Tutorial: <a href="https://code.react-advanced.smooth-code.com/">https://code.react-advanced.smooth-code.com</a></li><li>Github repository for a great Pluralsight course on React Hooks: <a href="https://github.com/pkellner/pluralsight-course-using-react-hooks">https://github.com/pkellner/pluralsight-course-using-react-hooks</a></li><li><a href="https://www.npmjs.com/package/eslint-plugin-react-hooks">eslint-plugin-react-hooks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29ef97547862" width="1" height="1" alt=""><hr><p><a href="https://medium.com/payscale-tech/introduction-to-react-hooks-29ef97547862">Introduction to React Hooks</a> was originally published in <a href="https://medium.com/payscale-tech">PayScale Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Prerendering: Next.js + Docker + Azure]]></title>
            <link>https://medium.com/payscale-tech/react-prerendering-next-js-docker-azure-b3236f8ec80e?source=rss-971f1d4484c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3236f8ec80e</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Danielle Fenske]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 16:58:42 GMT</pubDate>
            <atom:updated>2019-04-11T16:58:42.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyZjZ3p-7Cwc0hKesqcWAQ.jpeg" /><figcaption>credit: unsplash</figcaption></figure><p><strong>Intro</strong></p><p>We started with a simple goal that had multiple possible solutions. Our goal:</p><blockquote>Improve SEO by pre-rendering webpages, while still utilizing the JavaScript framework we like: React.</blockquote><p>The application we focused on is the <a href="https://www.payscale.com/cost-of-living-calculator">Cost of Living site</a>. The code currently lives in a legacy repo, and we wanted to pull it out of that repo, modernize the design and improve SEO.</p><p>When we started thinking about this problem, we first thought of <a href="https://www.npmjs.com/package/aspnet-prerendering">ASP.NET Pre-rendering</a>, an NPM package that works with C# and React. We implemented a solution using this method, but after many issues and even more correspondence with AWS and Azure support, we pivoted. The next option: <a href="https://nextjs.org/learn/">NextJS</a>. This is a Node-based framework, which means we need to use <a href="https://www.docker.com/why-docker">Docker</a> so that we can easily deploy it to <a href="https://portal.azure.com/">Azure</a>. In this post, we describe the steps we took to reach our final solution, as well as many of the gotchas we encountered.</p><p><strong>NextJS</strong></p><p><a href="https://nextjs.org/learn/">NextJS</a> claims out-of-the-box server-side rendering, as well as fast page loads using code splitting and simple and flexible configuration. NextJS is also being used by many companies today, including <a href="https://www.npmjs.com/">NPM</a>, <a href="https://www.ticketmaster.com/">TicketMaster</a>, <a href="https://success.docker.com/">Docker</a>, and apparently <a href="https://www.eltonjohn.com/">Elton John</a> ¯\_(ツ)_/¯.</p><p>NextJS is a node-based framework that allows us to set up a React app with automatic server-side rendering. The basic structure of a NextJS app is the following:</p><pre>next-app<br>│ node_modules/<br>│ pages/<br>└─── _document.js<br>│ homepage.js<br>| anotherPage.js<br>│ styles/<br>└─── index.scss<br>│ next.config.js<br>│ package.json<br>│ server.js</pre><p><strong>/pages</strong></p><p>A key component to making this solution a reality is getInitialProps. Inside each page, you can add Page.getInitialProps() and inside that function, you can fetch all the data you need to be pre-rendered. The data is fetched server side, before the component is rendered, and this is how SSR works in NextJS.</p><p><strong>/next.config.js</strong></p><p>The next.config.js file serves a similar function as webpack.config.js in other React apps. It abstracts most of the configuration and allows you to add just the configuration you need for special use cases. One of the configurations we specify is we import the @zeit/next-sass module to utilize Sass within your NextJS app. We also specify an assetPrefix so that all static files that normally live in .next/ will be looked for in a CDN instead.</p><p><strong>Gotcha #1: Build IDs on Two Servers Don’t Match</strong></p><p>In our next.config.js file, we also specify a BuildID and configure a chunk hashing. This is to solve a problem we ran into, where we build our project on the TeamCity build machine so we can upload the built files to our CDN, <em>as well as</em> building it inside the Docker image. The problem we encountered was that when building in two different places, the build IDs and the chunk hashes used in some file names were different. This meant our Docker image was looking for a specific file named chunk-1234.js (for example), while the CDN files only had a file named chunk-5678.js. This resulted in 403s and missing code from our deployed website. With the configuration we included, we were able to ensure the build IDs and chunk hashes matched between builds.</p><pre>module.exports = withSass({<br>  useFileSystemPublicRoutes: false,<br>  assetPrefix: isProd ? settings.cdn : ‘’,<br>  generateBuildId: async () =&gt; {<br>    return ‘app’<br>  },<br>  webpack(config, options) {<br>    config.output.filename = ({chunk}) =&gt; {<br>    // Use `[name]-[id].js` in production<br>    if (!options.dev<br>      &amp;&amp; (chunk.name === CLIENT_STATIC_FILES_RUNTIME_MAIN<br>      || chunk.name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK)) <br>      {<br>        return chunk.name.replace(/\.js$/, ‘-[id].js’)<br>      }<br>   return ‘[name]’<br>};</pre><pre>config.output.chunkFilename = options.isServer<br>  ? `${options.dev ? ‘[name]’ : ‘[name].[id]’}.js`<br>  : `static/chunks/${options.dev ? ‘[name]’ : ‘[name].[id]’}.js`;<br>    return config;<br>  }<br>});</pre><p><strong>/server.js</strong></p><p>server.js sets up the Express routing for the app. We also initialize Azure Application Insights in this file so that we can track requests in Azure.</p><p><strong>Gotcha #2 — Exposing a Client Secret</strong></p><p>Most of our API calls to the Cost of Living Service were made in the getInitialProps for each page, which happens on the server side. However, one special case requires us to make API calls client-side: a Cost of Living Calculator allows users to enter two cities and a salary and dynamically see a comparison between those two cities. So as the user interacts with the page, we have to make multiple calls to the API in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rS7-V0X6RWF7SYCYjyd9yg.png" /></figure><p>This poses a problem, since we use secret-based authentication. If we make client-side authentication calls, we risk exposing our secret in the browser. So we needed a way to make these client-side calls become server-side calls.</p><p>To fix this problem, we created a proxy route to handle these requests. We call this proxy endpoint from the calculator client-side, but then the actual authentication can be done server-side. This way, all our API calls are made server-side and we don’t have any security risks. To set up this route, we include this line in our server.js file:</p><pre>server.get(‘/api/compareCities/:toCity/:fromCity’, async (req, res) =&gt; {<br>  await api.CompareCities(req.params.toCity, req.params.fromCity)<br>  .then(data =&gt; {<br>    res.json(data);<br>  });<br>});</pre><p><strong>Performance Tweaks</strong></p><p>At first, when we deployed our app, we had a <a href="https://developers.google.com/web/tools/lighthouse/">Lighthouse</a> performance score of nearly 0. To improve the performance, we added the following:</p><p>* server.use(compression()); to our server.js file, which compresses the output files from the build.</p><p>* setAssetPrefix to our next.config.js to serve static files from a CDN.</p><p>* We made sure we were setting the NODE_ENV to production during the Docker image build.</p><p>These tweaks increased our Lighthouse score from under 10 to in the 80s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*SGPXpKG6OLHxseT2SH9WqQ.png" /></figure><p><strong>Gotcha #3–500 Errors and the Magic of web.config</strong></p><p>We had to add a web.config file to be able to deploy our app to Azure. The web.config file directs the web app to where to look for the application code. Without this, the app returns a 500 error.</p><pre>&lt;! — Indicates that the server.js file is a node.js site to be handled by the iisnode module --&gt;</pre><pre>&lt;add name=”iisnode” path=”/.next/static/runtime/main.js” verb=”*” modules=”iisnode”/&gt;</pre><p><strong>Docker</strong></p><p>The next step in the process was to figure out how and where to deploy our NextJS app. After quickly trying and failing to deploy a simple Node app to a basic Azure web app, we realized the necessity of Docker. Docker works well with Node apps. We created a simple Dockerfile which just directs Docker to install packages using yarn and then runs yarn start. We got that to run locally. Now to deploy it to the cloud.</p><p><strong>Azure Containers</strong></p><p>Our team has mostly worked with Azure web apps and we thought it would be cool to still be able to utilize the ease of Azure management and App Insights to manage our app. With a little digging, we found a thing called <a href="https://docs.microsoft.com/en-us/azure/app-service/containers/quickstart-nodejs">Azure App Services for Containers</a>. This service is like a normal App Service but with a way to configure a container for the app service to look at to get its source code. The Azure portal has a great UI for managing this, as well as a display of the Docker logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4CIFBvOl9Qk5a0PV_czug.png" /></figure><p><strong>Gotcha #4 — Linux must be separate</strong></p><p>When trying to create the app services in Azure, we ran into limitations for where you’re allowed to create them. We quickly found what was limiting us: quoted from the Azure Docs:</p><pre>You cannot create Web App for Containers in an App Service plan already hosting non-Linux Web Apps. There is a current limitation in regards to not mixing Windows and Linux apps in the same resource group as well.</pre><p>We easily side-stepped this problem by creating our own resource groups and app service plans, separate from non-Linux apps.</p><p><strong>TeamCity + Octopus setup</strong></p><p><em>TeamCity</em></p><p>Finally, it is time to set up the deployment process. We’ve got the build setup from Docker, we’ve got the app services initialized, and now we just need to set up the flow from BitBucket to the cloud. This step took lots of iterating, as we tried to optimize performance and solve issues we ran into.</p><p>The TeamCity build configuration we settled on includes the following steps:</p><p>1. Determine a version number for the build that can be saved and used in multiple steps (eg. 2018.12.18.11.23). This is used as the image tag when we push our image to Docker.</p><p>2. Update a config file (appsettings.json) with TeamCity parameters, based on the environment. This includes settings like the Identity endpoint and secret.</p><p>3. Run yarn and yarn build</p><p>4. Copy the compiled, static Next files to S3, so that we can serve them from our CDN</p><p>5. Build and push the Docker image to DockerHub</p><p>6. Create an Octopus release</p><p>This step is where we ran into the mismatched Build IDs between steps 3 and 5.</p><p><em>Octopus</em></p><p>The Octopus deploy consists of a PowerShell script that just configures our Azure Web App to look at the Docker image that we just created in our TeamCity build. We pass the ImageTag from TeamCity to the Octopus deploy, and then just set the Azure Web app to point to that specific tag. We also restart the web app and run a warm-up step, for good measure.</p><p><strong>Conclusion</strong></p><p>This blog post aimed to detail the steps that we took and the problems we ran into during our attempts to create a React-based app that is also server-side rendered. Hopefully you can now use it as a reference when you need to do something similar, and avoid some of the problems we listed here.</p><p><strong>Resources</strong></p><p>* <a href="https://nextjs.org/docs">NextJS Docs</a></p><p>* <a href="https://docs.docker.com/">Docker Docs</a></p><p>* <a href="https://docs.microsoft.com/en-us/azure/app-service/containers/quickstart-nodejs">Azure App Service for Containers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3236f8ec80e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/payscale-tech/react-prerendering-next-js-docker-azure-b3236f8ec80e">React Prerendering: Next.js + Docker + Azure</a> was originally published in <a href="https://medium.com/payscale-tech">PayScale Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>