<?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 Damon Aw on Medium]]></title>
        <description><![CDATA[Stories by Damon Aw on Medium]]></description>
        <link>https://medium.com/@daemonsy?source=rss-406555305928------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MVyJWBP3jkKy7Bid.jpeg</url>
            <title>Stories by Damon Aw on Medium</title>
            <link>https://medium.com/@daemonsy?source=rss-406555305928------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:45:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daemonsy/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[Working with Background Pages on Chrome extensions? This hack will change your life.]]></title>
            <link>https://medium.com/damon-aw/working-with-background-pages-on-chrome-extensions-this-hack-will-change-your-life-b6df8a29d86?source=rss-406555305928------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6df8a29d86</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <dc:creator><![CDATA[Damon Aw]]></dc:creator>
            <pubDate>Fri, 20 Apr 2018 22:01:00 GMT</pubDate>
            <atom:updated>2018-04-21T18:32:42.912Z</atom:updated>
            <content:encoded><![CDATA[<p>Now I got your attention, you can buy my … Just kidding :)</p><p>This is a short post on opening Background Pages on your main browser window. The tip is nothing revolutionary but I bet there must be folks new to Chrome extensions development facing the same pain as me.</p><p>Recently I’ve been working on a <a href="https://chrome.google.com/webstore/detail/jira/odofgglajlcgbjcbbifcehfhbalgeacl">Chrome extension</a> that makes it easy to jump into Jira issues or search for them using the Omnibox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*254u-1cwYe8fij3_hSr_VA.png" /><figcaption>What the extension does</figcaption></figure><p>I already have a workflow that builds any code change into the unpacked folder that gets picked up. That works really well for the Pop Up. Most of the code to operate the Omnibox is in the background script and inspecting it is really annoying.</p><p>The painful approach goes like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*jKrSFGASk4NhW6WyxbiwvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHMRt7EwCDIjsbfnAmGd4w.png" /><figcaption>Using Manage Extensions is my own sin. It’s my quick jump to the extension page.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTIs4sTiPEu9X3_tgUxnfA.png" /><figcaption>Yay now we have a separate window for console debugging the Background Page. It’s really annoying.</figcaption></figure><h3>What if I pasted that URL in the console window into my browser window?</h3><p>It turns out that the chrome extension URL opens the background page!</p><pre>chrome-extension://&lt;extension-id&gt;/background.html</pre><p>This assumes that you named your background page as background.html in the manifest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOrGWd9QnJLnCdzVaQZm8Q.png" /><figcaption>A Background Page opened in a main browser window with attached Inspector</figcaption></figure><p>Now we can drive the Omnibox and debug it the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oHbG3lLIV9w0xENQikLOQ.png" /><figcaption>Background Page in a main browser window. It’s just a page!</figcaption></figure><p>I can refresh, pin and bookmark this page too. I feel like a URL hackerz 😎.</p><h4>Since it’s a HTML page, can we write to it?</h4><p>The answer is YES!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pTRGvG6djfWfn-8fF-iYw.png" /><figcaption>Background page with Omnibox activated</figcaption></figure><p>I can imagine a build process where we can write useful messages to the window directly in development. This code can be stripped out when building for distribution.</p><h4>One more thing…</h4><p>You can inspect other views too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2iCRTtROjFWfu5nPmOlRQ.png" /><figcaption>Popup page opened in the main browser window</figcaption></figure><p>I really hate clicking on the Pop Up to trigger it on every change. I wonder if this will open up workflows for live reloading. Going to explore that next.</p><p>My extension’s code is at <a href="https://github.com/daemonsy/jira">https://github.com/daemonsy/jira</a> if anyone’s interested.</p><p>That’s all folks, hope this was helpful :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6df8a29d86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/damon-aw/working-with-background-pages-on-chrome-extensions-this-hack-will-change-your-life-b6df8a29d86">Working with Background Pages on Chrome extensions? This hack will change your life.</a> was originally published in <a href="https://medium.com/damon-aw">Damon Aw</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[There is a tide in the affairs of men.]]></title>
            <link>https://medium.com/@daemonsy/there-is-a-tide-in-the-affairs-of-men-64fc5c80039c?source=rss-406555305928------2</link>
            <guid isPermaLink="false">https://medium.com/p/64fc5c80039c</guid>
            <dc:creator><![CDATA[Damon Aw]]></dc:creator>
            <pubDate>Sat, 13 Aug 2016 00:06:13 GMT</pubDate>
            <atom:updated>2016-08-13T00:06:13.073Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a tide in the affairs of men.</p><p>Which, taken at the flood, leads on to fortune;</p><p>Omitted, all the voyage of their life</p><p>Is bound in shallows and in miseries.</p><p>On such a full sea are we now afloat,</p><p>And we must take the current when it serves,</p><p>Or lose our ventures. — Brutus</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64fc5c80039c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using NGINX on Heroku to Serve Single Page Apps and Avoid CORS]]></title>
            <link>https://medium.com/alphasights-engineering-blog/using-nginx-on-heroku-to-serve-single-page-apps-and-avoid-cors-5d013b171a45?source=rss-406555305928------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d013b171a45</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <dc:creator><![CDATA[Damon Aw]]></dc:creator>
            <pubDate>Tue, 03 May 2016 04:39:35 GMT</pubDate>
            <atom:updated>2016-05-05T17:46:33.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EB4BYyaNlVZkFRGAb3qUVQ.png" /></figure><p>I published an article recently <a href="https://m.alphasights.com/killing-cors-preflight-requests-on-a-react-spa-1f9b04aa5730">Killing CORS Preflight Requests on a React SPA</a> which demonstrated some ways to prevent browsers from sending CORs preflight requests that slows down your app with almost no benefit.</p><p>That article was part 1 of a two part exploration of removing preflight requests, which explained how to make requests simple (no infrastructure involved) and this follow up details using a NGINX reverse proxy to route API calls through the same domain and avoid CORS altogether.</p><h3>Why Proxy at all?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*j-ogswCmesI1f-80u1ibuQ.png" /></figure><p>My initial desire in using <a href="https://m.alphasights.com/killing-cors-preflight-requests-on-a-react-spa-1f9b04aa5730">simple requests</a> was to keep things simple (see what I did) and avoid adding infrastructure. As our app evolved, more of the stack on Relay-GraphQL that sends every request using POST. Mentioned previously, the only way to make a POST request simple is to cheat on <em>Content-Type </em>by setting it to “text/plain” even though the content is actually JSON.</p><p>Even if we’re willing to do the hack, it seems like a losing battle where there’s only one way to keep a request classified as simple and a myriad of ways to end up with a preflight request. Also, putting the token in the URL is inherently “leakier” as they show up in logs and error reporting services (<strong><em>/endpoint?token=secret)</em></strong>.</p><p><strong>Other benefits:</strong></p><ul><li>Simpler to work with, feels like a server to server request</li><li>Works perfectly with any third party API calls you make from the client, regardless of whether they support CORS</li></ul><p>Overall, I believe proxying is the solution that will go the distance after trying both.</p><p>The search for a reverse proxy solution led me to find an awesome <a href="https://github.com/heroku/heroku-buildpack-static">static buildpack</a> for Heroku. This post ended up to be mostly about killing the proverbial two birds, using it to serve your single page app and also getting rid of CORS.</p><p>If you’re serving a single page app on Heroku and have CORS issues, I hope this is a useful guide. If you’re hosted somewhere else, skip to the NGINX config portion to see how simple it is to avoid CORS.</p><p><em>Learned from Hackernews feedback on my other post to express the scope of the article earlier so not to waste readers’ time, thank you for that.</em></p><h3>Getting NGINX on your Heroku App</h3><p>First, we have to get NGINX installed on your dynos as part of the build process. If you’re using Heroku to serve a static app, there’s usually a lot of memory to spare given the limit of 512mb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXtcXb0xGlaCape4EvAa8g.png" /><figcaption>Well, we have memory to spare :)</figcaption></figure><p>We should strive for a setup where the proxy configuration is expressed in the project’s repository (e.g. a proxy.json file) to have full transparency into how the proxy works and to make maintenance easier for future developers.</p><p>The initial idea was to shop for a reliable custom buildpack that installs NGINX during the deployment and sets up <strong><em>proxy_pass</em></strong> via a config file in the app. However, a team mate (thanks <a href="https://medium.com/u/f469b0664903">Tor</a>!) pointed me to Heroku’s <a href="https://github.com/heroku/heroku-buildpack-static">static buildpack</a> during a water cooler chat and it elegantly solves both the CORS problem and serving our single page app.</p><p><strong>Advantages over custom NGINX buildpack:</strong></p><ul><li>A nice high level config that avoids having to directly mess with NGINX</li><li>Serves your single page app’s <strong><em>index</em></strong> page with support for clean urls and HTML5 routing</li><li>Serves your static assets (JS, CSS, images) and you can add headers to each of them for caching and cross origin headers for CDNs</li><li>Gzip and Heroku logging setup by default</li></ul><p>A <strong>major caveat</strong> is that it’s clearly stated to be an “experimental OSS project”, but we tested it in production for about a month now with no issues.</p><p>Thanks to this nifty buildpack, we could remove Express from our setup and our memory usage actually went down :)</p><p>Here’s a sample of our <strong><em>static.json</em></strong> to showcase some of the offered features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86d134bd32a752e05dd4cb346d145df3/href">https://medium.com/media/86d134bd32a752e05dd4cb346d145df3/href</a></iframe><h4>Let’s start with sending assets to the root folder</h4><p>This is where you expose the publicly viewable files of your app, commonly named <strong><em>dist</em></strong> on many projects.</p><p>There are two typical ways you can preprocess and build a static bundle on Heroku. You can build locally (e.g. using Webpack / gulp) and check in your <strong><em>dist</em></strong> folder or do it on push, using npm’s postinstall call. I much prefer the latter since it allows the team to maintain one machine config when building our production bundles. You can read more about the post install recommendations on this <a href="https://devcenter.heroku.com/articles/node-best-practices#hook-things-up">Heroku guide</a>.</p><p>Our project’s postinstall:</p><pre>“postinstall”: “webpack --config ./webpack.config.js”</pre><p>The above command builds our productions and dumps all of them in the <strong>dist</strong> folder, including:</p><ul><li>index.html (our static app)</li><li>bundle-[hash].js</li><li>styles-[hash].css</li><li>pictures and webfonts</li></ul><h4>Routes for HTML5 PushState</h4><p>If you’re using clean HTML5 routing, this allows you to redirect all routes to your root page and the client side router can take over.</p><p>The buildpack does not cause a redirect if you have a file matching the route, hence <strong>/**</strong> does not match <strong>/styles.css </strong>making it super easy to setup.</p><h4>Setting up the CORS proxy</h4><p>Finally, we’re getting to this. If you namespaced your API to something like <strong><em>/api</em></strong>, this is really easy. In the proxies section, each key defines a Location<strong><em> </em></strong>rule on NGINX.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef11339a8b95212773cd5b65a70220a/href">https://medium.com/media/cef11339a8b95212773cd5b65a70220a/href</a></iframe><p>From our example config, by redirecting “/api/”, visiting <strong><em>/api/v1/candidates.json </em></strong>redirects to <strong><em>backend.example.com/api/v1/candidates.json</em></strong>.</p><p>That’s it, CORS problem solved. My apologies if that was underwhelming to you :P</p><h4>Cache Headers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/262c9f83e8ae7ee71323059337662ecb/href">https://medium.com/media/262c9f83e8ae7ee71323059337662ecb/href</a></iframe><p>Bonus benefit of using the buildpack — You can instruct it to return cache headers for CSS and JS assets. Please only do so if you fingerprinted them for cache busting.</p><p>If you use a CDN, there’s a high chance you need to whitelist your distribution as an allowed origin because it will hit your app for the asset if it’s not cached yet. For example, AWS’s Cloudfront has a custom origin mode that does just that.</p><h4>HTTPS only please</h4><p>I recommend setting <strong>https_only</strong> to true, just a friendly reminder :)</p><h3>Putting everything together</h3><p>Once you have the configuration up, I suggest forking your production app and testing the deployment process before moving forward. It’s quite easy to get a blank screen when messing with the buildpack configuration.</p><p><strong>Find out the current buildpack configuration:</strong></p><pre>-&gt; heroku buildpacks --app frontend-app</pre><pre>=== frontend-app Buildpack URLs<br>1. heroku/nodejs</pre><p><strong>Add the static buildpack to the LAST index</strong></p><pre>-&gt; heroku buildpacks:add --index 2 <a href="https://github.com/heroku/heroku-buildpack-static.git">https://github.com/heroku/heroku-buildpack-static.git</a> --app frontend-app</pre><pre>Buildpack set. Next release on frontend-app will use:<br>  1. heroku/nodejs  <br>  2. <a href="https://github.com/heroku/heroku-buildpack-static.git">https://github.com/heroku/heroku-buildpack-static.git</a></pre><p>Now, you’re ready to delete away the Procfile and let the buildpack use NGINX to serve the app. If you did it correctly, the Heroku dashboard should show something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuIZUdaKbuwBsDhd51FJFg.png" /><figcaption>default web process for the Heroku static buildpack</figcaption></figure><h3>Woah magic… That’s it?</h3><p>Wait, this seems way too simple. No Procfile, how does that work?</p><p>In essence, all the buildpack does is assume that you’re building static assets and storing them into a <strong><em>dist</em></strong> folder and telling NGINXto serve this folder, kind of like Rails’ public folder or the <strong><em>/var/www </em></strong>folder. It comes with a few bonus web best practice features like enforcing https, headers and gzipping by default which I think that makes it a complete solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*RWN4kMu3yfVXaMW7AIoBUg.png" /><figcaption>The buildchain after pushing to Heroku</figcaption></figure><p>We have to add the static buildpack last so it boots NGINX to serve requests just like the diagram above. This means that your standard buildchain (be it Ruby or NodeJS) can work as normal, compiling and sending the static assets into the root folder.</p><h3>Digging into the Config and Proxy Pass</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf08c7050fc2fc39f8df1f70c824b7d4/href">https://medium.com/media/cf08c7050fc2fc39f8df1f70c824b7d4/href</a></iframe><p>Remember that proxies section in static.json? Each item eventually translates to a <strong><em>proxy_pass</em></strong> directive and as of publication, this is exactly how much code there is on the config.</p><p>I like the simplicity but this might not be enough for you. For example, it does not forward headers so it’s not easy to track the performance of requests. Fear not, there are people using the buildpack and actively sending pull requests.</p><p><a href="https://github.com/heroku/heroku-buildpack-static/pull/33/files">Send typical proxy headers by ankon · Pull Request #33 · heroku/heroku-buildpack-static</a></p><h3>Conclusions</h3><p>Thank you for reading this! I hope this illustrated the benefits of using avoiding CORS with an NGINX reverse proxy and the benefits of using the static buildpack.</p><p>After putting this into production, the team managed to get rid of Express and a bunch of middleware to achieve the same functionality. I also trust NGINX to be equally performant if not much more.</p><p>If you’re trying any of the recommendations in this guide, post a response and let me know how it went.</p><p><em>If you enjoyed the article and have a keen interest in working on modern stacks utilizing Rails, React and Ember, we are </em><a href="https://engineering.alphasights.com/#positions"><em>hiring</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d013b171a45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alphasights-engineering-blog/using-nginx-on-heroku-to-serve-single-page-apps-and-avoid-cors-5d013b171a45">Using NGINX on Heroku to Serve Single Page Apps and Avoid CORS</a> was originally published in <a href="https://medium.com/alphasights-engineering-blog">AlphaSights Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Killing CORS Preflight Requests on a React SPA]]></title>
            <link>https://medium.com/alphasights-engineering-blog/killing-cors-preflight-requests-on-a-react-spa-1f9b04aa5730?source=rss-406555305928------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f9b04aa5730</guid>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[relayjs]]></category>
            <dc:creator><![CDATA[Damon Aw]]></dc:creator>
            <pubDate>Mon, 04 Apr 2016 12:43:12 GMT</pubDate>
            <atom:updated>2016-05-03T17:15:51.386Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Update: Since publishing this post, the team continued adding Relay-GraphQL features into our app and came to the conclusion using a reverse proxy t0 avoid CORS altogether. A follow up has been <a href="https://m.alphasights.com/using-nginx-on-heroku-to-serve-single-page-apps-and-avoid-cors-5d013b171a45">posted here</a> about setting up NGINX and serving a single page app painlessly on Heroku.</blockquote><blockquote>A practical issue we are uncomfortable with is that tokens also sometimes get leaked by error reporting or logging services. Thanks for all the feedback on Hackernews, I didn’t even know there was a thread on it until it was too late.</blockquote><p>AlphaSights’ recruitment platform evolved from a Rails application into a classic SPA app.</p><p>The Rails app serves as a RESTful API backend while the frontend app is built on React/Flux (with some Relay). Here’s a bad visualization of how the setup looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*UoF7XDjSiU7FPDVwZGYYfw.png" /></figure><p>The two app setup allowed us to iterate on the client and the backend independently. Express is used on the frontend app to serve cache headers and do HTML5 routing.</p><p>When the team launched the app, we got a lot of praise from users for its speed and UI snappiness compared to the previous Rails app.</p><p>If this feels “so 2015” to you, we <strong>did</strong> start building the app in early 2015 and went down the centralized RESTful API route.</p><h4>CORS, the dirty word</h4><p>Whenever a teammate mentions “seems like a CORS issue”, it strikes fear into the deepest reaches of my soul.</p><p>With this setup, we had to deal with making CORS requests from app.example.com to api.example.com in one of the two ways:</p><p>1. Find a way to proxy requests so that there’s no CORS<br>2. API serves CORS headers for app.example.com</p><p>We chose 2 to reduce the complexity of dealing with forwarding and proxies. Serving headers is easy thanks to the <strong>rack-cors</strong> gem. In normal requests, the headers look like this:</p><pre>Access-Control-Allow-Credentials:true<br>Access-Control-Allow-Methods:POST, GET<br>Access-Control-Allow-Origin:<a href="http://localhost:3000/">http://localhost:3000</a><br>Access-Control-Expose-Headers:<br>Access-Control-Max-Age:1728000<br></pre><h4>What are Preflight Requests</h4><p>The one thing that came with CORs were preflight requests. When I first saw them appearing in the web inspector, it confused me greatly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxgkpYl0jitA6oYqDK34JA.png" /><figcaption>Preflight OPTIONS requests in the Network tab of Web Inspector</figcaption></figure><p>Preflight requests are made when requests are not “simple”.</p><blockquote>“preflighted” requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. Source: <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">MDN</a></blockquote><p>After more reading, I believe the preflight request is a “security by awareness” measure. Examples:</p><p>1. The browser makes an <strong><em>OPTIONS</em></strong> request is sent to a server without any CORS awareness. This will <strong>fail</strong> and protect the server from potentially executing a forged cross-domain <strong><em>DELETE</em></strong> request.</p><p>2. The browser does not make an <em>OPTIONS</em> request, the server with awareness can potentially not allow the request. Web frameworks don’t do this because in lieu of better security measures, such as CSRF or using sessionless authentication.</p><p>A good <a href="https://stackoverflow.com/questions/15381105/cors-what-is-the-motivation-behind-introducing-preflight-requests">SO answer</a> explains this in detail.</p><p>It is also unfortunate that preflight requests are incompatible with one of its bigger use case — Sending cross site JSON POST/PATCH requests because it sets the <strong><em>Content-Type</em></strong> to <em>application/json</em>.</p><h4>Fighting Preflight requests, the latency multiplier</h4><p>This didn’t really bother the team originally because the requests add little overhead and there were a myriad of higher value issues to tackle.</p><p>Months later, I found the app to be a little slow and looked at the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCXF2YTtdZqHrmSMHYQGjw.png" /><figcaption>Preflight requests taking longer than 200ms!?!?</figcaption></figure><p>“Holy smokes! That’s a whole lot of latency, adding almost a second to the data loading for no real reason.”</p><p><strong>Why didn’t I notice this before?</strong> =&gt; I am in between relocation and is currently working out of Singapore, which has a geographical latency to Heroku’s Virginia data centers. This means that users in our Hong Kong and London offices are probably facing significant amount of latency, a big #fail for me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*Zoxflz2SpGOBUrt7t8EsXg.jpeg" /><figcaption>Well if you’re using the app at the datacenter :)</figcaption></figure><p>This is a good lesson, request latencies across long distances do become significant. In our case, since each CORs request makes a preflight check, it doubles this significant latency without adding any value. Well, time to really figure this out.</p><h4><strong>Cache requests, the low hanging fruit</strong></h4><p>Preflight requests can be cached by the browser if we remember to serve the <em>Access-Control-Max-Age</em> header. Make sure this is included in your response headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LMpubZGg3DxPINBhAVa3g.png" /><figcaption>Max Age caching</figcaption></figure><p><strong>But…</strong> Most browsers don’t allow you to cache the <em>OPTIONS</em> request for this long. For example, Webkit allows a maximum of 600 seconds.</p><pre>static const auto maxPreflightCacheTimeout = std::chrono::seconds(600); <br><a href="https://github.com/WebKit/webkit/blob/master/Source/WebCore/loader/CrossOriginPreflightResultCache.cpp#L41">source code</a></pre><p>This makes caching much less useful because the cache will be cold most of the time. Boo.</p><h4><strong>Simple Requests, the holy grail</strong></h4><p>After reading a <a href="http://www.soasta.com/blog/options-web-performance-with-single-page-applications">great blog post</a> and MDN’s CORS <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">docs</a> I realized there are circumstances where the browser <strong>does not</strong> make a preflight request, if conditions are met:</p><p>- Only uses <em>GET</em>, <em>POST</em>, <em>HEAD</em> methods<br>- Doesn’t set any manual headers other than those set by the browser and these headers:<br> — Accept<br> — Accept-Language<br> — Content-Language<br> — Content-Type<br>- For Content-Type, the only allowed values:<br> — application/x-www-form-urlencoded<br> — multipart/form-data<br> — text/plain</p><p>Wow, my first thought was “headers are messy and this is so restrictive”. As a lazy developer, I’ve shied away from dealing with headers, relying on abstractions provided by libraries and frameworks. In reality, it was easier than I imagined. Given a request header that our app’s GET api call generates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjNm2_DuqB7_neu-VyBMmA.png" /></figure><p>We can see that the request is not simple because of the custom <strong><em>Authorization</em></strong> header and a <strong><em>Content-Type</em></strong> that set to an unacceptable value.</p><h4><strong>We don’t need Content-Type for GETs</strong></h4><p>I took a dive into the api wrapper over Superagent we made to issue the GET requests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66c6cf44968ee6564a6940a91e6cdd4d/href">https://medium.com/media/66c6cf44968ee6564a6940a91e6cdd4d/href</a></iframe><p>GET requests don’t have a <em>body</em> and hence does not need to specify a <strong><em>Content-Type</em></strong>. Removing the <strong><em>.type()</em></strong> call removed the header.</p><h4><strong>Moving Authorization to the query string</strong></h4><p>The app uses session-less authentication powered by <strong>Doorkeeper</strong> gem and the <strong><em>Authorization</em></strong> header specifies the secret used to identify the user after logging in.</p><p>In order to remove the header, we have to move the token to the query string.</p><p><strong>What did you just say????</strong></p><p>In terms of security, all API calls should be using https and there is little difference in putting the token in headers or as part of the query string. Do beware that the token should be filtered in the logs. In our setup, we used what doorkeeper expects, <em>bearer_token</em> and this gets filtered out by Rails when logging requests (guessing it’s Doorkeeper’s handy work).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76aoIUIUjOxONBM2c9Gmcw.png" /></figure><p>We also have to note that the GET urls are now replayable, since the authentication information is contained in it. Most normal users won’t inspect the console and copy urls to paste around, but a good caveat emptor for developers.</p><h4><strong>Taking profit on GET requests</strong></h4><p>Phew, we got through all that, now the request headers are simple and no more <em>OPTIONS</em> requests are made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utHQL5jiw43J4PnTUaSzgg.png" /><figcaption>No more preflight requests</figcaption></figure><p>If you have a typical web app that’s <em>GET</em> heavy, this should already be a significant win and we can stop here.</p><h4>But we’re using Relay…</h4><p>Relay uses <em>POST</em> requests to send queries to our GraphQL endpoint. I believe Relay chose <em>POST</em> because the queries are long for <em>GET</em> requests, seeing that a typical query on our page url serialized is around 1900 characters and the url’s limit is around 2083 characters.</p><h4>Taking it to the extreme — Don’t do this at home</h4><p>In order to make Relay’s request simple, we have to set the default <em>application/json</em> content-type in the <em>POST</em> request to something else. Two possible strategies:</p><p><strong>1st Attempt — Send JSON but set Content-Type to <em>text/plain</em></strong><br>Since we know the API request to <em>/graph</em> from Relay is always in JSON, hence we can tell Relay to set the headers to <em>text/plain</em> and qualifying as a simple request.</p><p>Next, we instruct the backend to change the <em>Content-Type</em> to <em>application/json</em> before reaching Rails’ params parsing layer, the greatest scam is done :)</p><p>This deception was a big hack to implement because it goes against the behaviors of both libraries. For example, Relay uses <em>fetch</em> under the hood and it wants to set the <strong><em>Content-Type</em></strong> conveniently for you based on the data.</p><p><strong>2nd Attempt — Send data as formData instead, qualifying as a simple request</strong></p><p>Relay’s default network layer has this code to <a href="https://github.com/facebook/relay/blob/d4c38604ac02dd9b527ab984168930a4eb14fa9b/src/network-layer/default/RelayDefaultNetworkLayer.js#L147">send queries using fetch</a>.</p><p>Pseudo coding it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5781049753b20bc7b1782a9d9b35ab19/href">https://medium.com/media/5781049753b20bc7b1782a9d9b35ab19/href</a></iframe><p>We could alter it to produce <em>formData</em> instead:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0e34bcd84da966486400c6f75d44f96/href">https://medium.com/media/c0e34bcd84da966486400c6f75d44f96/href</a></iframe><p>This causes fetch to use <em>form/multipart</em> that qualifies as a simple request.</p><p>The params <em>query</em> was a string, so it’s the same as before on Rails. However, <em>variables</em> is now stringified JSON and manual parsing it back to JSON is required on the Rails backend.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0178ffec6e745df372d16794be407200/href">https://medium.com/media/0178ffec6e745df372d16794be407200/href</a></iframe><p>This works and Relay’s POST request does not do preflight anymore. I’m not sure if the cost is worth it and <strong>did not </strong>ship this to production.</p><h3>Conclusion</h3><p>IF you have CORS preflight requests and latency significant users:</p><p>1. Use the preflight cache<br>2. Make sure GET requests are simple</p><p>For my own app, fixing the GET requests was a significant win though we still have latency with the Relay features (10% of the app currently).</p><p>After going down the rabbit hole, I think it’s easier and straightforward to fight CORS with reverse proxy such as using nginx to forward requests to your API server. i.e. <em>app.example.com/api</em> proxies requests to <em>api.example.com</em>. We’re hosted on Heroku which makes it less trivial to do this, but will explore this as Relay / GraphQL takes over more of the data loading from RESTful endpoints.</p><p>Thanks for reading this! I hope it helped, even if the conclusion is “preflight requests are too troublesome, I’m going proxy” :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f9b04aa5730" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alphasights-engineering-blog/killing-cors-preflight-requests-on-a-react-spa-1f9b04aa5730">Killing CORS Preflight Requests on a React SPA</a> was originally published in <a href="https://medium.com/alphasights-engineering-blog">AlphaSights Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>