<?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 Thomas Wang on Medium]]></title>
        <description><![CDATA[Stories by Thomas Wang on Medium]]></description>
        <link>https://medium.com/@xgwang?source=rss-ed034bfb4c86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uG8ZN7kQpdFpfzpj5Qbz3A.jpeg</url>
            <title>Stories by Thomas Wang on Medium</title>
            <link>https://medium.com/@xgwang?source=rss-ed034bfb4c86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:00:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xgwang/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[How Airtable Manages Flaky Tests in a Large-Scale Monorepo]]></title>
            <link>https://medium.com/airtable-eng/how-airtable-manages-flaky-tests-in-a-large-scale-monorepo-5fe09922e90c?source=rss-ed034bfb4c86------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fe09922e90c</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Thomas Wang]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 02:07:14 GMT</pubDate>
            <atom:updated>2023-01-12T02:07:14.653Z</atom:updated>
            <content:encoded><![CDATA[<p>By: Airtable’s Developer Effectiveness and Quality Engineering Teams</p><p>Airtable serves critical use cases for large enterprise customers. Our customers depend on Airtable to be reliable in order to power their businesses. In order to deliver our customers a high-quality product, Airtable’s engineering team writes tens of thousands of tests, including unit tests, integration tests, and end-to-end tests. There are far too many tests for developers to run them all locally, so we leverage Continuous Integration (CI) infrastructure to run all of the tests whenever an engineer submits a pull request. We also use a merge queue to prevent regressions from landing in the main branch.</p><p>But in addition to maintaining a high-quality product, our developer infrastructure also needs to ensure high developer velocity, because our customers also expect us to continue delivering new features that will enable them to leverage our Connected Apps Platform for new use cases. One of the ways that we move fast is by putting almost all of our code into a single, large-scale monorepo. There are lots of benefits to our monorepo, but one of the drawbacks is that flaky tests slow down the entire development team. Flaky tests are those which can both pass and fail without any code changes. <strong>We’ve developed an approach to flaky tests that unblocks engineers while also ensuring we close the loop on finding and fixing regressions.</strong></p><p>Some engineering organizations hold a firm commitment to ensuring that every single test is deterministic. While we agree that deterministic tests are of higher quality, we also take a pragmatic approach and accept that this is a hard property to guarantee, especially in a large-scale monorepo like the one that Airtable is maintained in. We see value in end-to-end integration tests, including those that depend on timing, because they exercise more of the actual code that will run in production (as opposed to only mocks or fake implementations, for example).</p><h3>Enable developer velocity while keeping tests reliable</h3><p>Developers rely on CI to understand code change correctness. There are two requirements for CI to enable developer velocity:</p><ol><li>CI result needs to be <strong>correct</strong>: flaky test failure erodes confidence in the test suite.</li><li>CI needs to be <strong>fast</strong>: waiting for a long-running build breaks the flow.</li></ol><p>On the infrastructure level, we’ve done several things to reduce test flakiness:</p><ol><li>Each test file runs in the same docker container, and different tests that run in parallel are isolated from each other.</li><li>CI leverages each test’s historical CPU utilization to allocate CPU cores to a docker container to make sure a test does not start to become flaky because of CPU throttling. CI is also able to run builds faster by effectively utilizing the host machine to run tests in parallel.</li></ol><p>Given that we accept that tests can be flaky, we take some very basic steps to maintain a good trade-off between detecting regressions and enabling developer velocity:</p><ol><li>CI retries test failures up to 3 attempts (subject to an overall timeout) in order to mitigate the impact of flaky tests on developer velocity.</li><li>We maintain a policy to quarantine any tests that meet a threshold for being too flaky. While we still run quarantined tests (so that we may monitor their reliability over time), they do not impact the result of the build. The quarantine policy is necessary to keep every developer’s builds unaffected by known flaky tests while the test owner is working on a fix.</li></ol><p>The Developer Effectiveness team has been responsible for keeping the main branch healthy by quarantining flaky tests. We’ve built tools and processes to help with managing flaky tests. In the next sections, we’ll discuss how we evolved our system and processes to manage flaky tests as we grow.</p><h3>Run periodic builds to detect flaky tests</h3><p>To quarantine flaky tests, we first need a better way to detect which tests have failed in an unreliable way, instead of relying on developers to report flakiness when their pull requests fail.</p><p>We set up a continuous build pipeline off the main branch to detect flaky tests. This pipeline runs the full test suite and reports any test retries and failures to an analytics platform. We build daily reports that highlight the flakiest tests over a recent period of time. We then quarantine the tests by submitting code changes and merging them into the main branch (later sections discuss how we eventually automated this process). Each test file in our monorepo codebase has an owner team, we have tooling support to tag the owners to triage and fix the test reliability issues.</p><h3>Confirm tests are flaky with stress tests</h3><p>While tracking test reliability over time can help us detect flaky tests, we have noticed that test reliability can change quickly. The most common reason is due to code changes (for example, new race conditions, or fixes for them). Another reason could be due to a temporary issue with a test dependency. When making decisions about whether or not to quarantine a test, it is not practical to wait for additional data from more full periodic builds.</p><p>To facilitate this, we have built the ability to stress test a test case, in which we will run the same test in our CI infrastructure hundreds of times and report the overall pass/fail rate. We use stress tests in our quarantine policy. If a test case fails too many attempts in a stress test (our threshold right now is 5%), we quarantine it. Developers can also trigger stress tests on their own feature branch to see if their code changes make a test more reliable.</p><h3>Automate the process</h3><p>The quarantine tooling described above worked for a while, but required a developer to write a pull request to add or remove a test from the quarantine. This manual step led to two undesirable outcomes:</p><ol><li>Our overall build reliability suffered due to delays from when our analytics detected a test was flaky and when a person took action to quarantine a test.</li><li>Tests languished in the quarantine list, even after they became more reliable.</li></ol><p>Once we had confidence in our quarantine policies, we automated the process of adding and removing tests from the quarantine list:</p><figure><img alt="How a test is transitioned between different states" src="https://cdn-images-1.medium.com/max/1024/1*0pTtUFvhthiCBNXug40hAg.png" /></figure><ol><li>Whenever a test fails on the main branch build, the automation system triggers a stress test for that test case.</li><li>If there are too many failures in the stress test, the automation system adds the test case to the quarantine list.</li><li>Every CI build loads the latest quarantine list on start, and suppresses the failures if the testcase is in the quarantine list. The quarantine list contains the git commit hash when a test starts to fail, and which git commit it is fixed on, so CI would not suppress failure incorrectly. CI still reports the pre-quarantine test result of the build to the automation system.</li><li>The automation system keeps monitoring the reliability of quarantined tests in the main branch build and removes the test case from the quarantine list if there are sufficient numbers of builds without that test failing. We used <a href="https://reliabilityanalyticstoolkit.appspot.com/acceptance_test_sampling">acceptance test statistical analysis</a> to calculate the number of required passing builds to un-quarantine the test.</li></ol><figure><img alt="Flaky tests failures within the quarantine range do not impact feature branches" src="https://cdn-images-1.medium.com/max/1024/1*_c0SCkoAdPYt1GRu2wVoTg.png" /></figure><h3>Hold test owners accountable for fixing flaky tests</h3><p>It is not enough to just quarantine the flaky test, the test needs to be fixed by the owner so we can keep high test coverage. We’ve observed that once developers are notified about the flaky test failure, everyone is very responsive in root causing and fixing the issues.</p><p>A key strength of Airtable is the ability to share data across the organization in a very flexible manner. We sync the quarantine list to an Airtable base and build <a href="https://www.airtable.com/product/interface-designer">Interfaces</a> so that teams can easily visualize the quarantine list, and how it has changed over time.</p><figure><img alt="An Airtable Interface we built to visualize the list of quarantined tests" src="https://cdn-images-1.medium.com/max/1024/1*6oqSovym5eJ7bRsjBGHBkA.png" /></figure><p>We use <a href="https://www.airtable.com/product/automations">Automations</a> to periodically publish a digest of quarantined tests to the Slack channels of each team that owned a test that was in the quarantine list. These notifications bring teams to the interfaces which contain all the information they need to debug why their test is flaky, and how to stress test their fixes with the aforementioned stress test tooling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XlkC2FjTMC12Np60DbwQQ@2x.png" /></figure><p>This is one of <a href="https://blog.airtable.com/how-quality-engineers-use-airtable-to-test-airtable/">many ways</a> that we internally use Airtable to drive our own workflows to effectively connect many teams working towards the same goal.</p><h3>Our results</h3><p>Since enabling this automation, we have seen around 50% of all the passed builds include at least 1 quarantined test failure (which would have been retried and potentially fail the build). We’ve eliminated the need for manual intervention to manually quarantine flaky tests, which means the newly introduced flaky tests are now quarantined within an hour instead of more than a day. At the same time, the developer perceived build failures due to flaky test has dropped from roughly 5% (with manual oncall responses) down to less than 2%. The new quarantine approach also has the advantage of preserving the actual failure reasons instead of skipping the test execution, so developers can investigate much more easily. We’ve also seen good engagement from engineers to act on their flaky tests, thanks to our Airtable Interfaces and Automations to publish digests to Slack.</p><h3>Future work</h3><p>The system has been working great for us since its launch. That said, it’s still not perfect, we plan to improve the user experience and efficiency in the near future:</p><ol><li>Faster stress test so that the system can determine test status more quickly.</li><li>Test attempt failure reporting can happen in real-time to improve the time-to-quarantine.</li><li>Better culprit finding support and root cause analysis to help developers fixing the issues.</li><li>IDE integration to highlight flaky tests.</li><li>Generate insights of frequently quarantined tests to facilitate in the code reviews tooling.</li><li>Being able to differentiate new errors in the same test, e.g., by using error stacktraces.</li></ol><h3>Conclusions</h3><p>Flaky tests are unavoidable in a large monorepo codebase. We’ve found quarantining flaky tests is an effective approach to enable developer velocity while keeping the codebase healthy. Managing quarantined tests requires insights from the data and tooling to automate the entire process, sharing the data with owner teams can help connect everyone to the shared goal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fe09922e90c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airtable-eng/how-airtable-manages-flaky-tests-in-a-large-scale-monorepo-5fe09922e90c">How Airtable Manages Flaky Tests in a Large-Scale Monorepo</a> was originally published in <a href="https://medium.com/airtable-eng">The Airtable Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You May Not Know Beacon]]></title>
            <link>https://xgwang.medium.com/you-may-not-know-beacon-98c3f64e7ea3?source=rss-ed034bfb4c86------2</link>
            <guid isPermaLink="false">https://medium.com/p/98c3f64e7ea3</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Thomas Wang]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 06:18:17 GMT</pubDate>
            <atom:updated>2021-01-20T06:18:17.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4URtjvNLhtXVv44M3JqgQg.jpeg" /></figure><h3>TL;DR</h3><ul><li>navigator.sendBeacon should be used with visibilitychange and beforeunload events, otherwise you&#39;ll lose data</li><li>navigator.sendBeacon has in-flight data limit and other constraints</li><li>Use Beacon API with proper fallback to reliably beacon data to server</li></ul><h3>What is Beacon</h3><p>From <a href="https://www.w3.org/TR/beacon/">W3C spec Beacon</a>, Beacon is:</p><blockquote><em>an interface that web developers can use to schedule asynchronous and non-blocking delivery of data that minimizes resource contention with other time-critical operations, while ensuring that such requests are still processed and delivered to destination.</em></blockquote><p>The <em>delivery of data</em> is just an abstract way of saying the browser makes an HTTP request that sends back data to the server. The reason for another API that does HTTP when we already have <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a>, is to address a typical challenge web developers have.</p><p>There are some HTTP requests from the browser that don’t need to read or even wait for the server response, usually event tracking, status update, and analytics data. The characteristics of these type of requests are:</p><ul><li>No need to access HTTP response — send and forget</li><li>Lightweight — should not impact the user experience or taking too much network bandwidth</li><li>Happen in the background without user interaction</li><li>Need to <strong>reliably send when closing the page</strong> AKA, page unload</li></ul><p>Keeping these in mind, the above description of the goals of Beacon API would make more sense.</p><p>The explicit goals of the Beacon API are to provide a minimal interface to web developers to specify the data and endpoint, then let the browser coalesces the requests.</p><p>Because Beacons do not provide response access in a fire-and-forget way and coalesced by the browser, the browser guarantees to initiate these data delivery requests before page is closed/unloaded, and outlive the page lifecycle.</p><h3>How to Use</h3><p>You can use beacon via navigator.sendBeacon(). A minimal example is given from the W3C spec:</p><pre>&lt;html&gt;<br>&lt;script&gt;<br>  // emit non-blocking beacon to record client-side event<br>  function reportEvent(event) {<br>    var data = JSON.stringify({<br>      event: event,<br>      time: performance.now()<br>    });<br>    navigator.sendBeacon(&#39;/collector&#39;, data);<br>  }</pre><pre>  // emit non-blocking beacon with session analytics as the page<br>  // transitions to background state (Page Visibility API)<br>  document.addEventListener(&#39;visibilitychange&#39;, function() {<br>    if (document.visiblityState === &#39;hidden&#39;) {<br>      var sessionData = buildSessionReport();<br>      navigator.sendBeacon(&#39;/collector&#39;, sessionData);<br>    }<br>  });<br>&lt;/script&gt;</pre><pre>&lt;body&gt;<br> &lt;a href=&#39;http://www.w3.org/&#39; onclick=&#39;reportEvent(this)&#39;&gt;<br> &lt;button onclick=&quot;reportEvent(&#39;some event&#39;)&quot;&gt;Click me&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>MDN has the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">complete API documentation</a>, go take a look!</p><h3>Alternatives</h3><p>People have used alternative ways to do what Beacon API meant to do.<br> By using XMLHttpRequest or fetch, you can POST data periodically in the background, and it&#39;s totally fine not to read the response.</p><p>Another way is to create an img element and leverages the fact it makes a GET request to server:</p><pre>const img = new Image();<br>img.src = `https://mysite.com?${JSON.stringify(data)}`;</pre><p>The problem is when the user closes the page, the last request is skilled and there’s no way to recover. In other words, a significant amount of your analytics data is lost and causes data distortion.</p><p>To avoid the closing page problem, a solution is to create a sync XHR on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event">beforeunload</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event">unload</a> events, this is very bad for user experience as it blocks the page unloading - imagine your customers have to wait a noticeable amount of time to close the browser tab.</p><p>In fact, beforeunload and unload are explicitly said to be legacy API and should be avoided. See <a href="https://developers.google.com/web/updates/2018/07/page-lifecycle-api#legacy-lifecycle-apis-to-avoid">Page Lifecycle API &gt; Legacy lifecycle APIs to avoid</a>.</p><h3>The Confusion</h3><p>It seems easy, a simpler API that does the work reliably. However, people have had issues in production and not seeing the data being beaconed back as expected. <a href="https://volument.com/blog/sendbeacon-is-broken">Beacon API is broken</a> post described their experiment setup and the results suggest Beacon API is not working as expected.</p><p>Reading through the comments section, the problem becomes clear that Beacon itself never had any issues, it is when to call the API.</p><p>MDN added you should use sendBeacon with visibilitychagne, not unload or beforeunload, after the comment discussions from the <a href="https://volument.com/blog/sendbeacon-is-broken">above post</a>:</p><blockquote><em>The </em><em>navigator.sendBeacon() method </em><a href="https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous"><em>asynchronously</em></a><em> sends a small amount of data over </em><a href="https://developer.mozilla.org/en-US/docs/Glossary/HTTP"><em>HTTP</em></a><em> to a web server. It’s intended to be used in combination with the </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event"><em>visibilitychange</em></a><em> event (but not with the </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event"><em>unload</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event"><em>beforeunload</em></a><em> events).</em></blockquote><p>Other than blocking the page unloading, the two events unload and beforeunload are not reliably fired by the browser as you would expect.</p><p><a href="https://www.igvita.com/2015/11/20/dont-lose-user-and-app-state-use-page-visibility/">Don’t lose user and app state, use Page Visibility</a> summarizes:</p><ul><li>beforeunload is of limited value as it only fires on desktop navigation.</li><li>unload does not fire on mobile and desktop Safari.</li></ul><p>Therefore, on all mobile browsers, if you use sendBeacon on beforeunlaod:</p><pre>document.addEventListener(&#39;beforeunload&#39;, navigatior.senBeacon(url, data));</pre><p>The callback function which sends the data is never triggered on mobile when the user swipes away or switches app.</p><p>To fix it, you should use visibilitychange event and beforeunload together.</p><p>A <em>less wrong</em> example looks like:</p><pre>document.addEventListener(&#39;visibilitychange&#39;, () =&gt; {<br>  if (getState() === &#39;hidden&#39;) {<br>    flushData(&#39;hidden&#39;);<br>  }<br>});<br>window.addEventListener(&#39;beforeunload&#39;, () =&gt; {<br>  flushData(&#39;beforeunload&#39;);<br>});</pre><p>Wait? Didn’t we just say we should not use beforeunload? Firing on beforeunload is still necessary because Safari bug: <a href="https://bugs.webkit.org/show_bug.cgi?id=151234">visibilitychange:hidden doesn&#39;t fire during page navigations</a> which is still active as Safari Version 14.0.2 (16610.3.7.1.9).</p><p>In practice, you also need to think about what to do with the fact that some clients not firing beforeunload and some not firing visibilitychange:hidden and potentially events you fired between last hidden and page unload, etc.</p><p>If you want to play with API and events by yourself and confirm, I’ve put up a demo at <a href="https://github.com/xg-wang/how-to-beacon/">https://github.com/xg-wang/how-to-beacon/</a>. Notice this is not for production, read more below.</p><h3>More on sendBeacon</h3><h3>Data size limit</h3><p>The spec (<a href="https://www.w3.org/TR/beacon/#sec-sendBeacon-method">3.1 sendBeacon Method</a>) said:</p><blockquote><em>The user agent MUST restrict the maximum data size to ensure that beacon requests are able to complete quickly and in a timely manner.</em></blockquote><p>The <em>restrict</em> is intentionally vague here because the actual implementation is allowed to be different for different browser vendors.</p><p>An important thing to notice is the <em>maximum data size</em> is for in-flight data that the browser has not scheduled to sent. In other words, if a call to navigator.sendBeacon() returns false because exceeding the limit quota, trying to call navigator.sendBeacon() immediately after will not help.</p><p>When navigator.sendBeacon() returns false, a useful pattern is to fallback to fetch without the keepalive flag (more on that later), or xhr without the sync flag. The drawback is you lose the ability to deliver on page unload, but at least during normal sessions the data is not lost.</p><p>If you want to know the actual limit number — it’s 64KB (<a href="https://github.com/w3c/beacon/issues/38">w3c/beacon issue</a>, <a href="https://github.com/web-platform-tests/wpt/pull/4024">wpt PR</a>). However, you should not take that as a guarantee!</p><h3>Delivery is not immediate</h3><p>Unlike other network API, sendBeacon can be scheduled and coalesced by the browser. You can certainly contain timestamp data in the beacon payload, but the HTTP request time can be delayed.</p><h3>It may throw error, be sure to catch</h3><p>If the url parsing has error, sendBeacon will throw TypeError.</p><p>Another case is you can’t pass reference without binding navigator:</p><pre>// ❌<br>let s = navigator.sendBeacon;<br>s(&#39;/track&#39;, &#39;data&#39;);</pre><pre>// ✅<br>s = navigator.sendBeacon.bind(navigator);<br>s(&#39;/track&#39;, &#39;data&#39;);</pre><ul><li>FireFox: Uncaught TypeError: &#39;sendBeacon&#39; called on an object that does not implement interface Navigator.</li><li>Safari: TypeError: Can only call Navigator.sendBeacon on instances of Navigator</li><li>Chrome: TypeError: Illegal invocation</li></ul><h3>Server is encouraged to return 204 No Content</h3><p>From: <a href="https://www.w3.org/TR/beacon/#sec-sendBeacon-method">https://www.w3.org/TR/beacon/#sec-sendBeacon-method</a></p><blockquote><em>Note<br> Beacon API does not provide a response callback. The server is encouraged to omit returning a response body for such requests (e.g. respond with 204 No Content).</em></blockquote><h3>Fetch keepalive</h3><p>Beacon API uses Fetch keepalive under the hood, which is defined in the spec.</p><pre>fetch(&#39;/track&#39;, {<br>  method: &#39;POST&#39;,<br>  body: getData(),<br>  keepalive: true,<br>});<br>// Same as 👇<br>navigator.sendBeacon(&#39;/track&#39;, getData());</pre><p>This means they share the same data limitation, remember we discussed when falling back to fetch you don&#39;t need to add keepalive?</p><p>But unfortunately keepalive has limited browser support, while sendBeacon is available on all modern browsers.</p><ul><li><a href="https://caniuse.com/mdn-api_request_keepalive">https://caniuse.com/mdn-api_request_keepalive</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zcHnKCkQ6nVhcxuL.png" /></figure><ul><li><a href="https://caniuse.com/beacon">https://caniuse.com/beacon</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5iW46yX-iXxZuwTK.png" /></figure><h3>Send Blob data</h3><p>The second data param sent with sendBeacon is <a href="https://fetch.spec.whatwg.org/#bodyinit">BodyInit</a>, which means you can use Blob to create the data.</p><pre>const obj = { hello: &#39;world&#39; };<br>const blob = new Blob([JSON.stringify(obj, null, 2)], {<br>  type: &#39;application/json&#39;,<br>});<br>navigator.sendBeacon(&#39;/track&#39;, blob);</pre><p>When creating a application/json type request, it is no longer a simple request, and will trigger CORS preflight request. See <a href="https://xgwang.me/posts/a-practical-guide-to-cors/">A practical guide to CORS</a> if you&#39;re not familiar with CORS.</p><h3>Cannot use with compression API</h3><p>There’s a new API you can use to compress data on client side: <a href="https://github.com/wicg/compression/blob/master/explainer.md#deflate-compress-an-arraybuffer">compression</a></p><p>But it won’t work with sendBeacon or Fetch keepalive, fetch will throw error when the keepalive request has stream body.</p><h3>Service Worker</h3><p>The service worker can operate async after the original document closes. (<a href="https://twitter.com/wanderview/status/1234126801049444352">Tweeter thread</a>)</p><p>Ideally, you can put all the existing data processing logic and beaconing to a service worker, to execute code <a href="https://web.dev/off-main-thread/">off the main thread</a>.</p><h3>End word</h3><p>Beacon is a simple API, but there are complexities coming from the heart of UI engineering. Use it with caution and always check your data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c3f64e7ea3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A practical guide to CORS]]></title>
            <link>https://xgwang.medium.com/a-practical-guide-to-cors-51e8fd329a1f?source=rss-ed034bfb4c86------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e8fd329a1f</guid>
            <category><![CDATA[koajs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Thomas Wang]]></dc:creator>
            <pubDate>Wed, 11 Oct 2017 05:34:28 GMT</pubDate>
            <atom:updated>2018-08-08T04:00:07.858Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide for things you need to know about enabling <a href="https://www.w3.org/TR/cors/">Cross-Origin Resource Sharing (CORS)</a>.</p><h3>Why we need CORS</h3><p>Web pages are under the restrictions of same-origin policy, which means scripts contained in a web page cannot access data in another page with different <em>origin</em>. For example, http://www.example.com:81/dir/other.html cannot be accessed by http://www.example.com/dir/page.html because the port is different. You can find more detailed explanations on <a href="https://en.wikipedia.org/wiki/Same-origin_policy#Origin_determination_rules">wiki</a>.</p><p>However, there are some cases we want to enable cross-origin resource sharing.</p><ul><li>Resources you would like to be loaded from separate domains like images, CSS and script files.</li><li>You would like to provide a public API to be consumed by any client, or clients specified by a whitelist.</li><li>When developing, your frontend web app is running on a different port from your backend server.</li></ul><h3>Demo setup</h3><p>So let’s get started. I’ve prepared a simple <a href="http://koajs.com/">KOA</a> server to demonstrate the idea. You can find the demo on <a href="https://github.com/xg-wang/cors-guide">Github</a> and follow the tag for each stage.</p><pre>git clone git@github.com:xg-wang/cors-guide.git<br>cd cors-guide<br>npm i<br>npm start</pre><p>The server runs at <a href="http://localhost:3000/">http://localhost:3000/</a> and frontend runs at <a href="http://localhost:8000/">http://localhost:8000/</a></p><h3>01. CORS fail</h3><p>First we simply retrieve the data through API running on port 3000:</p><pre>fetch(&#39;http://localhost:3000/&#39;)<br>  .then(res =&gt; res.text())<br>  .then(res =&gt; responseElement.innerHTML = res)<br>  .catch(err =&gt; responseElement.innerHTML = err)</pre><p>Click the button to send the request, you could see the returned response：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOlbF3GxzuVx2fGizY6uQA.png" /><figcaption>TypeError: Failed to fetch.</figcaption></figure><p>Now open your dev console, you can find the following error:</p><blockquote><em>Failed to load </em><a href="http://localhost:3000/"><em>http://localhost:3000/</em></a><em>: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘</em><a href="http://localhost:8000/"><em>http://localhost:8000</em></a><em>&#39; is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.</em></blockquote><p>Because our frontend is hosted on port 8000, and server is running on port 3000, the request from browser is restricted by the <strong>same-origin policy</strong>. To fix it, simply add a header to the response in our server code:</p><pre>Access-Control-Allow-Origin: <a href="http://localhost:8000/">http://localhost:8000</a></pre><p>Now click the button again and you should be able to see the response from server!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPVOHXpz59uU4Tzp5n1YJw.png" /><figcaption>Nails it</figcaption></figure><p>Open up the dev server and check the request and response, you can find the Origin: http://localhost:8000 header in the request. This is added by the browser automatically. In the response, we have the header we just added: Access-Control-Allow-Origin: http://localhost:8000. This allows our <a href="http://localhost:8000/">http://localhost:8000</a> to have access to the API endpoint. You may also specify &quot;*&quot; as a wildcard, thereby allowing any origin to access the resource.</p><h3>02. preflight</h3><p>This is not the end of story, let’s try to add some header to our request as &#39;Content-Type&#39;: &#39;application/json&#39;.</p><p>Send the request again and it fails. The console has the following error:</p><blockquote><em>Failed to load </em><a href="http://localhost:3000/"><em>http://localhost:3000/</em></a><em>: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.</em></blockquote><h4>What is a preflighted request/response?</h4><p>Open up the dev tools network tab, the request sent by the browser is not the request we created by JavaScript. It is called a preflighted request and has the following Headers:</p><pre>Request Method: OPTIONS</pre><pre>Access-Control-Request-Headers: content-type</pre><pre>Access-Control-Request-Method: GET</pre><p>Together with the Origin: &lt;origin&gt; header they are all we need for the request. In any access control request, the Origin header is always sent.<br>And Access-Control-Request-Headers might also be a comma separated array.</p><p>These headers are used to tell the server what the following actual CORS request contains. Here we are asking the server to allow the Content-Type header and GET method.</p><p>After the browser receives the legit preflight response, the actual CORS request is sent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*zzdX1swQrC1MnAI69WSQDw.png" /><figcaption>MDN example for preflight request</figcaption></figure><h4>Why there was no preflight request?</h4><p>In the previous section, our request went well and there is no CORS preflight — it is called a ‘Simple Request’. MDN has a comprehensive <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests">description</a> about this. To summarize, a simple request is a GET|HEAD|POST method, and only contains ‘<a href="https://fetch.spec.whatwg.org/#cors-safelisted-request-header">CORS-safelisted request-header</a>’.</p><p>A CORS-safelisted request-header is a header whose name is a byte-case-insensitive match for one of</p><ul><li>Accept</li><li>Accept-Language</li><li>Content-Language</li><li>Content-Type and whose value, once extracted, has a MIME type (ignoring parameters) that is application/x-www-form-urlencoded, multipart/form-data, or text/plain</li></ul><p>or whose name is a byte-case-insensitive match for one of</p><ul><li>DPR</li><li>Downlink</li><li>Save-Data</li><li>Viewport-Width</li><li>Width</li></ul><p>and whose value, once extracted, is not failure.</p><p>By CORS spec, a simple request won’t trigger the preflight request.</p><h4>How to fix it?</h4><p>To grant access to the resource, we need to set corresponding headers in the response for the preflight request.</p><pre>Access-Control-Allow-Origin: http://localhost:8000<br>Access-Control-Allow-Methods: GET<br>Access-Control-Allow-Headers: Content-Type</pre><p>Several things to notice:</p><ul><li>...-Methods and ...-Headers can be comma separated array.</li><li>...-Origin need to be in both preflight response and actual response.</li><li>You can only allow 1 origin, but you can always extract the actual origin from the Origin header and allow it based on your whitelist or simply set a wildcard &quot;*&quot;.</li></ul><p>There are 3 more access control headers you can set:</p><ul><li>Access-Control-Expose-Headers lets a server whitelist headers that browsers are allowed to access.</li><li>Access-Control-Max-Age: &lt;delta-seconds&gt; indicates how long the results of a preflight request can be cached.</li><li>Access-Control-Allow-Credentials will be discussed in next section.</li></ul><h3>03. credentials</h3><p>By default, in cross-site <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch</a> invocations, browsers will not send credentials (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies">HTTP cookies</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication">HTTP Authentication information</a>). But they both have option flag to set. Take Fetch for example, there is a credentials option:</p><blockquote><em>The request credentials you want to use for the request: omit, same-origin, or include. To automatically send cookies for the current domain, this option must be provided. Starting with Chrome 50, this property also takes a FederatedCredential instance or a PasswordCredential instance.</em></blockquote><p>If we add this option and send the request:</p><pre>fetch(&#39;http://localhost:3000/&#39;, {<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>  },<br>  credentials: &#39;include&#39;<br>}).then(res =&gt; res.json())<br>  .then(res =&gt; responseElement.innerHTML = res)<br>  .catch(err =&gt; responseElement.innerHTML = err)</pre><p>The following error will popup in your dev console:</p><blockquote><em>Failed to load </em><a href="http://localhost:3000/"><em>http://localhost:3000/</em></a><em>: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’. Origin ‘</em><a href="http://localhost:8000/"><em>http://localhost:8000</em></a><em>&#39; is therefore not allowed access.</em></blockquote><h4>fix</h4><p>Remember the Access-Control-Allow-Credentials? Set this header in both preflight and request: Access-Control-Allow-Credentials: true. Refresh, send again and it succeeds.</p><p>Some more things to notice:</p><ul><li>For a simple request, response without this header will be rejected.</li><li>Cookie header will be added to the request if credentials flag set.</li><li>Access-Control-Allow-Origin: * fails in this situation, you have to set the allowed origin explicitly.</li><li>It is a good idea to add Vary: Origin response header.</li></ul><blockquote><em>If the server specifies an origin host rather than “*”, then it could also include Origin in the Vary response header to indicate to clients that server responses will differ based on the value of the Origin request header.</em></blockquote><p>A more persuasive reason can be found <a href="https://github.com/rs/cors/issues/10">here</a>.</p><h3>One more thing</h3><p>In the Fetch API, you can set <a href="https://developer.mozilla.org/en-US/docs/Web/API/Request/mode">Request.mode</a></p><blockquote><em>The mode read-only property of the Request interface contains the mode of the request (e.g., cors, no-cors, same-origin, or navigate.) This is used to determine if cross-origin requests lead to valid responses, and which properties of the response are readable.</em></blockquote><p>Set this to ‘cors’ when sending CORS request, more details can be found in the <a href="https://fetch.spec.whatwg.org/#dom-request">spec</a>.</p><h3>Summary</h3><p>In this post we discussed the use cases of CORS and how we can enable it by building a simple API step by step. You can find the full demo on <a href="https://github.com/xg-wang/cors-guide">Github</a>.</p><p>For conclusion, to enable CORS for a general CORS request, you need to add the following headers:</p><p>For preflight request which can be filtered by check method is ‘OPTIONS’:</p><ul><li>Access-Control-Allow-Origin</li><li>Access-Control-Allow-Credentials</li></ul><p>For actual CORS request which is not OPTIONS and has a Access-Control-Request-Method header:</p><ul><li>Access-Control-Allow-Origin</li><li>Access-Control-Allow-Methods</li><li>Access-Control-Allow-Headers</li><li>Access-Control-Allow-Credentials</li><li><em>(Optional)</em> Access-Control-Max-Age</li><li><em>(Optional)</em> Access-Control-Expose-Headers</li></ul><p>Extract origin from Origin header and set it together with Vary: Origin for each response.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e8fd329a1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>