<?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 tzar on Medium]]></title>
        <description><![CDATA[Stories by tzar on Medium]]></description>
        <link>https://medium.com/@tzar?source=rss-90ddf2f59e02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*s5kuyjfMGG8m8hXj6mw0vA.jpeg</url>
            <title>Stories by tzar on Medium</title>
            <link>https://medium.com/@tzar?source=rss-90ddf2f59e02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:42:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tzar/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[Changing from moment to Day.js — how, why and fixing vue-chartjs]]></title>
            <link>https://levelup.gitconnected.com/changing-from-moment-to-day-js-how-why-and-fixing-vue-chartjs-786314ef4697?source=rss-90ddf2f59e02------2</link>
            <guid isPermaLink="false">https://medium.com/p/786314ef4697</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[tzar]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 23:14:18 GMT</pubDate>
            <atom:updated>2021-01-12T23:14:18.426Z</atom:updated>
            <content:encoded><![CDATA[<h3>Changing from moment to Day.js — how, why and fixing vue-chartjs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SUEQG9C-Ac2aPzKAyhmaQ.png" /><figcaption>Photo by <a href="https://unsplash.com/@fabrizioverrecchia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fabrizio Verrecchia</a> on <a href="https://unsplash.com/s/photos/clocks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://momentjs.com/">moment.js</a> is an awesome date/time library that I have used in essentially every project I’ve worked on for the last decade. Sadly, it’s showing its age these days with the creators <a href="https://momentjs.com/docs/#/-project-status/">discouraging its use for new projects and the project being put into maintenance only mode</a>.</p><p>I can understand why — the tooling and structure of JavaScript libraries have evolved rapidly in recent years and older libraries often can’t keep up without making massive, backwards incompatible changes. The web itself has evolved as well — the scourge that was IE has all but vanished and almost everything has slowly become powered by Webkit and its variants instead. There’s a lot of backwards compatibility that simply isn’t needed any more and at some point it becomes more sensible to just rewrite.</p><p>So why should this bother you — and should you bother switching? If you’re trying to cut down on your bundle size, I’d say it’s worth considering as moment is pretty heavy compared to the new generation of lightweight date manipulation libraries. It’s also fairly easy to do even with a complex existing codebase thanks to <a href="https://day.js.org/">Day.js</a> which attempts to keep an <em>almost</em> identical API to moment.js.</p><p>There are really only two things you need to know when swapping between the two — Day.js uses a core + plugin system, so depending on the format strings and features you’re currently using, you’ll need to register the appropriate plugins. For example, I need .weekday() so I register the weekday plugin:</p><pre>import dayjs from &#39;dayjs&#39;<br>import weekday from &#39;dayjs/plugin/weekday&#39;</pre><pre>dayjs.extend(weekday)</pre><p>You may end up with a few of these plugins by the time you’re done! The second thing you need to know is that Day.js objects are immutable — so anything like this:</p><pre>var foo = moment()<br>foo.add(1, &#39;day&#39;)</pre><p>Will instead change to this:</p><pre>var foo = moment()<br>foo = foo.add(1, &#39;day&#39;)</pre><p>Once you have the right plugins registered and you’re used to immutable objects, it’s essentially identical. A few find and replaces and you can give yourself a pat on the back! Unless you’re using Chart.js or vue-chartjs anyway, in which case…</p><h4>Forcing Chart.js to use Day.js as well</h4><p>So where does vue-chartjs come in? As it turns out, Chart.js actually bundles moment.js by default, and of course vue-chartjs uses Chart.js as well. So we need to do the following:</p><ul><li>Tell Chart.js to stop bundling moment.js</li><li>Add a date/time adapter so that Chart.js uses Day.js instead</li><li>Make sure that we do the above <strong>without interfering with code splitting</strong></li></ul><p>That last part can be a little tricky but is crucial — after all, we started this process looking for a way to reduce our bundles! If you simply import dayjs and Chart.js in your entry file and start messing with plugins and adapters, the code splitting system isn’t going to be able to pull it out into its own chunk any more. This won’t matter much for Day.js as you’re probably going to use it everywhere and it’s pretty small anyway — but Chart.js is another matter entirely.</p><p>The approach that has worked the best for me is to wrap the underlying libraries and pass through exports. So for Day.js I have a file — src/dayjs.js — which looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5b135980b4b8cd294b254b75636f0e9/href">https://medium.com/media/a5b135980b4b8cd294b254b75636f0e9/href</a></iframe><p>It’s very simple — import the library, configure it, then export it again. Now throughout my codebase, instead of import dayjs from &#39;dayjs&#39; I simply import dayjs from &#39;@/dayjs&#39;. This ensures that everywhere gets the same plugins and code can still be split into chunks as needed.</p><p>We also need to wrap vue-chartjs to tell it how to use Day.js instead of moment.js. There are some libraries on npm which claim to do this but I had better luck adapting (hah!) <a href="https://gitlab.com/mmillerbkg/chartjs-adapter-dayjs/-/blob/master/src/index.js">the adapter from here</a> to also use my wrapped Day.js instead. We’ll be wrapping vue-chartjs this time as that’s what we ultimately end up importing (and as such is what the code splitting is going to use):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c75be4cb9ce5a5743baad12f4b7b3e6/href">https://medium.com/media/9c75be4cb9ce5a5743baad12f4b7b3e6/href</a></iframe><p>Finally, we need to stop the default bundling of moment.js into Chart.js. You can do this by updating your webpack config, e.g in vue.config.js:</p><pre>module.exports = {<br>  configureWebpack: {<br>    externals: {<br>      moment: &#39;moment&#39;<br>    }<br>  }<br>}</pre><p>This lets us lie to webpack that moment will already exist on the page externally so it won’t try to import it. Of course, it won’t actually exist, but nothing will use it anyway, so.. mission accomplished?</p><p>Once all this is done — depending on the number of Day.js plugins you use and whether you previously set up rules to remove moment.js locales — you should see an anywhere between a <strong>45–250kB reduction</strong> in the parsed size of your codebase. Not too shabby!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=786314ef4697" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/changing-from-moment-to-day-js-how-why-and-fixing-vue-chartjs-786314ef4697">Changing from moment to Day.js — how, why and fixing vue-chartjs</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to back up Firestore easily and automatically]]></title>
            <link>https://levelup.gitconnected.com/how-to-back-up-firestore-easily-and-automatically-eab6bf0d7e1f?source=rss-90ddf2f59e02------2</link>
            <guid isPermaLink="false">https://medium.com/p/eab6bf0d7e1f</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[backup]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[tzar]]></dc:creator>
            <pubDate>Mon, 24 Aug 2020 11:53:17 GMT</pubDate>
            <atom:updated>2020-12-18T02:14:13.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-m1UO-KNpGnmI-4YXIIoA.png" /></figure><p>Firebase and Firestore provide a great, fully managed platform for developers to quickly prototype and launch their products. Unfortunately, backups seem to be a neglected part of the platform with no easy to use controls to capture periodic snapshots of your database. While you’re unlikely to lose any data due to hardware failure, backups are still critical because of the other source of failures: developers.</p><p>Migrations go wrong, code has bugs. Even if you strive for perfection (and attain it!), will the next person to work on it be so dedicated? You need backups, and as there’s no button to do it in Firestore, we’re just going to have to do it ourselves. Fortunately, it can now be implemented fairly simply by using a combination of Firebase Functions (to initiate and automate the backups) and Google Cloud Storage (to store them).</p><h4>Step 1: Plan your Backup Strategy</h4><p>Before you configure anything, you’re going to need to consider the following:</p><ul><li>How frequently do you want to take your backups? More frequently = more reads &amp; higher data stored = higher cost. Less frequently = higher potential data loss.</li><li>Can you run them on-demand? Given our primary failure mode is developer failure, backing up as a pre-deploy step might be justified.</li><li>How often do you want to delete back ups? For certain industries, you’ll have specific time windows that you’ll need to retain data for, which includes backups. You may also not be allowed to retain data after that window ends, which again includes backups. So there needs to be a way to automatically remove them too.</li><li>Does the GDPR apply? Right to be Forgotten may apply to backups too, which is why I (as did many developers) did a double take when it was first announced and mentally crossed out the EU from my target market in the future. My position on this has since mellowed, but you may not be able to store backups containing identifying information long term if you want to be GDPR compliant unless you have some way to forget personal data from old backups, such as keeping all personal information in a separate database/service with a different configured backup cycle.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*Ij4KT4i8MQ3Uyr2w_AQQGg.png" /><figcaption>It’s a real headache… (Photo courtesy of <a href="https://unsplash.com/photos/sxQz2VfoFBE">Unsplash</a>)</figcaption></figure><p>With that considered, you should now have a retention time and a regulation induced headache. Let’s get to actually implementing the backups.</p><h4>Step 2: A place for our backups to go</h4><p>Create a bucket in Google Cloud Storage. <strong>Note that this bucket MUST be in the same region or multi-region as your Firestore database.</strong></p><ul><li>Go to <a href="https://console.cloud.google.com/storage/browser">Google Cloud Storage</a></li><li>Make sure you have the correct project selected in the topbar!</li><li>Click “Create Bucket”</li><li>Give it a name — I like using a mixture of an obvious description and a not obvious suffix for some bonus security by obscurity</li><li>Choose the same region or multi-region as your Firestore database. For example, the US multi-region.</li><li>Choose a storage class. If you’re only planning on keeping your backups for a couple of months at a time, Nearline is ideal as it has a minimum retention period of only 30 days. Otherwise, Coldline has a 90 day retention period and offers further cost savings.</li><li>For access control, as this bucket will only store backups “Uniform” access control makes the most sense and is the easiest to maintain. We don’t want our backups accessible to anyone other than us and this makes it easy to enforce that.</li><li>Finally, the advanced settings. This is where we set up our retention period — tick “Set a retention policy” and add your desired configuration.</li><li>Click “Create”.</li></ul><p>Assuming your bucket ended up in the same project as your Firebase application, your application’s service account should automatically have permission to read and write from your bucket. You can double check this by opening your bucket in the console, going to the “Permissions” tab and looking for yourproject@appspot.gserviceaccount.com. It should have the “Storage Admin” role.</p><h4>Step 3: Coding our Automated Backups</h4><p>Time to write some code to trigger a backup. The easiest way to accomplish this is to implement a <a href="https://firebase.google.com/docs/functions/">Firebase Function</a> — specifically, a <a href="https://firebase.google.com/docs/functions/schedule-functions">Scheduled Function</a>. I’m assuming that you’ve already used Firebase Functions before and have it set up on your project. If not, <a href="https://firebase.google.com/docs/functions/get-started">do that first</a>.</p><p>We need to make sure that our new function can run data exports by granting our service account yourproject@appspot.gserviceaccount.com the “Cloud Datastore Import Export Admin” role. You can either do this through the Google Cloud Console’s IAM interface or from the command line (replace both instances of yourproject):</p><pre>gcloud projects add-iam-policy-binding yourproject \<br>  --member serviceAccount:yourproject@appspot.gserviceaccount.com \<br>  --role roles/datastore.importExportAdmin</pre><p>In the function we implement, we’re going to use the Firebase Admin SDK (yarn add @google-cloud/firestore to add this to your functions project) to trigger the creation of a backup job. As we’re running this from inside Firebase Functions, we can get most of the project configuration we need from the environment. Just make sure to replace gs://your-bucket-name with your actual bucket name! You can also change the schedule to match your own requirements, I have it set as daily in this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac022189bb687c4479bff4ae95f5bd76/href">https://medium.com/media/ac022189bb687c4479bff4ae95f5bd76/href</a></iframe><p>Once we have this in place, our scheduled backup function will now be deployed with the rest of our application with a simple firebase deploy. It should then happily run according to the schedule you set. To call it manually, we can either use the web UI:</p><ul><li>Go to the Firebase Console for your project and then choose Functions from the sidebar</li><li>Find your function, then click the three dots on the right hand side of the row and select “View in Cloud Scheduler”</li><li>Find your schedule and click “Run Now”</li></ul><p>Or we can use the gcloud CLI (e.g as part of your CI/CD process):</p><ul><li>To get a list of your scheduled functions: gcloud scheduler jobs list</li><li>To run one: gcloud scheduler jobs run your-scheduler-name</li></ul><p>Once your function has run, have a look in the bucket you created earlier. You may need to wait a little while for the backup to complete (gcloud firestore operations list to check on recent operations), but eventually you should see a timestamped folder containing the backup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*TxtvoARFi81iqx5El4L7Eg.png" /><figcaption>A successful backup!</figcaption></figure><h4>Let’s talk about cost</h4><p>Firestore itself has an interesting pricing model. It bills based on reads and writes, total storage &amp; total transferred. But the really expensive part? The reads and writes. They’ve recently added a warning to their documentation that clarifies that reads are definitely charged when exporting data (i.e backing up), but this is something I had to find out the hard way.</p><p>Depending on how much data you’re storing and how frequently you back up, the cost of taking backups may exceed the actual running costs of your application by several orders of magnitude. In my current project, I need to store a great deal of infrequently accessed currency conversion rate data and this means extremely expensive backups.</p><p>Unfortunately, the only way around this at this stage is to either back up less or only selectively back up your data. You can explicitly state in your backup code which collections you want to include by modifying the collectionIds parameter. So if you e.g only want to back up your users and restaurants collections, you’d specify collectionIds: [&#39;users&#39;, &#39;restaurants&#39;] .</p><p>A big gotcha is that nested collections (e.g users/{userId}/posts) also need to be added as well or <strong>they will not back up. </strong>It’s not well documented, but to save you some trial &amp; error <strong>this is how you back up subcollections</strong>:</p><pre>collectionIds: [<br>  // This will back up users/{userId}<br>  &#39;users&#39;,<br>  // This will back up users/{userId}/posts/{postId}<br>  &#39;posts&#39;<br>]</pre><p>For the data that you’ve decided is too expensive to back up, make sure you have a disaster recovery plan for how you’re going to be able to get that data back if something goes wrong.</p><h4>Afterthoughts</h4><p>I hope that at some stage Firebase can improve their backup tooling. At the moment it’s expensive for some common workloads and not user or developer friendly. I would say it’s one of the weaker parts of an otherwise great developer experience. Backups are something you need to have implemented for your service from day zero, so it’s my opinion that every responsible managed DB service should include prominent tools for backup and recovery and at the very least offer a basic, simple to set up automated backup solution. Making backing up your data cost-prohibitive or too technically challenging can lead to a lot of clients shooting themselves in the foot or deciding to risk it and I fear this is what Firestore has done.</p><p>Whether this applies to you or you’re just starting out, hopefully this article has shown you how to put together a robust backup system for your own Firebase application. <a href="https://firebase.google.com/docs/firestore/manage-data/export-import#import_data">And don’t forget to test that your backups work every so often.</a> There are too many horror stories out there of projects who have put together a backup system, and then never actually tried restoring from one until a disaster had already occurred…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab6bf0d7e1f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-back-up-firestore-easily-and-automatically-eab6bf0d7e1f">How to back up Firestore easily and automatically</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common issues pre-rendering your Vue.js app (and how to fix them)]]></title>
            <link>https://levelup.gitconnected.com/common-issues-pre-rendering-your-vue-js-app-and-how-to-fix-them-14e7fe8a5a60?source=rss-90ddf2f59e02------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e7fe8a5a60</guid>
            <category><![CDATA[pre-rendering]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[tzar]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 17:13:07 GMT</pubDate>
            <atom:updated>2020-04-16T17:13:07.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*QSqfYS86ZTuTJ0OhKWBl8g.png" /></figure><p>When you’re trying to get your first paint times down, pre-rendering your application can be an easy way to get an immediate boost. The way it works is quite simple — as a part of your application build process, you emulate a browser and visit the routes in your app that you want to pre-render. They’re allowed to load to an initial ready state, then the current DOM state is saved and that becomes your pre-rendered entrypoint.</p><p>So now when a user visits your website for the first time, they immediately download static HTML which represents your already loaded application — ergo, even though your application hasn’t loaded yet, it looks like it has! Then hopefully, before they can notice, it’s loaded anyway. This may also have some advantages in making your website easily crawled by some search engines.</p><p>With the latest Vue CLI, setting up pre-rendering as a part of your build process is incredibly simple. But after several days of head scratching and debugging, I thought I’d go over a couple of issues and interactions that tripped me up in my own development. Hopefully I can save you some time in the future!</p><h4>Dealing with Duplicate or Dynamically Injected Tags</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQmHyC65eTsrLx_QWCIczA.png" /></figure><p>Sometimes libraries that you include will dynamically insert a &lt;script&gt; or inject an &lt;iframe&gt;. They do this to defer the load, to post relevant tracking information, or to load different resources depending on the client’s configuration. Unfortunately when you’re pre-rendering, your build machine is now the client so everything they add is now garbage. A couple of examples of libraries that do this are <a href="https://firebase.google.com/">Firebase Analytics</a> (which pulls in <a href="https://developers.google.com/gtagjs">gtag.js</a>) and <a href="https://stripe.com/docs">Stripe</a> (which adds a tracking &lt;iframe&gt; with session information already encoded as URL params).</p><p>To fix this, you need to remove the garbage — pre-rendering shouldn’t have removed the original libraries which caused these tags to be added, so those should run again in the pre-rendered version and this time output something useful. This means all we need to do is post-process any pre-rendered outputs to remove the added tags. The recommended library for Vue pre-rendering is <a href="https://github.com/chrisvfritz/prerender-spa-plugin">prerender-spa-plugin</a> and in this library post-processing is handled via the postProcess hook which accepts a single object as an argument. What we need to process is then contained in the .html prop on that argument which we can rewrite and return:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9555010f914f35fc057619c377d1b5d4/href">https://medium.com/media/9555010f914f35fc057619c377d1b5d4/href</a></iframe><p><em>In my example code, I’ve used some simple regular expressions to remove the offending script and iframe tags to keep it simple. A more robust and less error-prone method would probably be to use a DOM manipulation library like </em><a href="https://github.com/cheeriojs/cheerio"><em>cheerio</em></a><em> to handle cutting out these tags.</em></p><p>You can verify that this worked correctly by building your project and manually inspecting the pre-rendered output files for duplicated tags.</p><h4>Async scripts and stylesheets no longer async</h4><p>There are a few different ways to lazily load scripts, and not many ways at all to lazily load stylesheets. One of the common ways is to use JavaScript to do it by manipulating the &lt;script&gt; or &lt;link&gt; tag itself (e.g by swapping the value of the media attribute) to take it out of the critical path and load a bit later in the process. After the previous issue, you can probably see what’s going to go wrong here. The tags will immediately transform themselves, so all of your async magic is now gone due to the pre-rendering.</p><p>The solution to this is the same as the previous issue — you’ll need to manually post-process your generated HTML to convert your &lt;script&gt; and &lt;link&gt; tags back into their lazy loaded equivalent. The actual code to do this will depend on what scripts and css you have set up and the method you’re using to defer their load. For example, you might be doing critical path CSS inlining with a library like <a href="https://github.com/GoogleChromeLabs/critters">critters</a> and lazy loading CSS like this:</p><pre>&lt;link rel=&quot;preload&quot; onload=&quot;this.rel=&#39;stylesheet&#39;&quot;&gt;</pre><p>After your page is pre-rendered, you’ll just be left with a &lt;link rel=&quot;stylesheet&quot;. To fix it, you’ll need to convert it back to rel=&quot;preload&quot; in postProcess.</p><h4>You get a flash of the wrong pre-render before your page loads</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*EqzGs5LnjJZ3wBubcgPgUw.gif" /><figcaption>Combining pre-rendering with service worker SPA rules can lead to some unusual results</figcaption></figure><p>Now this is the big one that took some tracking down, and the culprit is your service worker. The configuration for your service worker most likely includes a fallback match-all rule which will load /index.html. This means that if a user has your service worker installed, when they visit a route that you have pre-rendered, <strong>they will actually be served a pre-rendered version of the index page</strong>! So they’ll get a flash of the wrong page before your app kicks in and loads the right page. Definitely not what you want.</p><p>You’ll need to adjust a couple of areas of config to get the right behavior. First, you’ll need to adjust the list of routes you’re pre-rendering — expand it to include as many parts of your application as possible to reduce the number of areas handled by the fallback rule.</p><p>Next you need to make some adjustments to your service-worker.js. You’ll need to find the default redirect, which will look something like workbox.routing.registerNavigationRoute(&#39;/index.html&#39;) and add a blacklist which is an array of regular expressions. For example, if you have /foo pre-rendered, you’d want:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c8cafb14b67d452fa607c71a53699c5/href">https://medium.com/media/5c8cafb14b67d452fa607c71a53699c5/href</a></iframe><p>This will then exclude /index.html from being served when the user visits /foo.</p><p><strong><em>Note: </em></strong><em>If you don’t have a </em><em>service-worker.js and are rather confused, it might be that your workbox config is using “generateSW” mode where the entire service worker file is generated. I haven’t tried this mode as I need extra service worker features — if it does have the issue described, you may need to switch to “InjectManifest” mode to solve it.</em></p><h3>To conclude…</h3><p>Pre-rendering definitely complicates your build process a bit and introduces a whole new source of bugs which can be challenging to figure out. But once it’s all up and running, the extra speed on that first paint is really noticeable, so it’s well worth investing the time. The above issues can be tricky to diagnose, but once you know about them they are quite simple to solve. Hopefully I’ve saved you some time in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e7fe8a5a60" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/common-issues-pre-rendering-your-vue-js-app-and-how-to-fix-them-14e7fe8a5a60">Common issues pre-rendering your Vue.js app (and how to fix them)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing vendor.js by asynchronously loading large libraries]]></title>
            <link>https://levelup.gitconnected.com/optimizing-vendor-js-by-asynchronously-loading-large-libraries-5b5432d7015f?source=rss-90ddf2f59e02------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b5432d7015f</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[tzar]]></dc:creator>
            <pubDate>Tue, 07 Apr 2020 03:20:04 GMT</pubDate>
            <atom:updated>2020-04-07T03:20:04.148Z</atom:updated>
            <content:encoded><![CDATA[<p>So you’ve built something awesome, everything is working beautifully; but you’ve taken a look at your vendor.js and boot times and they’re not pretty. There’s a whole host of common wisdom on how to solve this problem — splitting your routes and your code into chunks automatically, writing your imports so that you import only what you need from larger libraries thanks to tree shaking, using smaller libraries. But nevertheless, sometimes you can’t avoid needing a larger library and pulling that data in can have a significant impact on your time to first load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZLVv5fDvzw-uxqEAWpoLQ.png" /><figcaption>This one library is bigger than vendor.js, but I definitely need it.</figcaption></figure><p>For example on my most recent project, I wanted to be able to offer customers the ability to import and export from XLSX files. Even the smallest libraries for these actions are still rather large to say the least, and I definitely didn’t want them weighing down the load for everyone who isn’t using that functionality! I already had the wonderful webpack <a href="https://webpack.js.org/plugins/split-chunks-plugin/">SplitChunksPlugin</a> set up which could automatically split out these libraries so they theoretically didn’t impact other pages, only the routes on which they were used. But they were still being preloaded in for every user which was impacting my performance figures thanks to the network overhead and JS parsing overhead. So how do we optimise for this case?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*QZtrzONjeEkOLEwAcVvkyA.png" /><figcaption>Laziness? No. Efficiency.</figcaption></figure><p>The answer is to manually lazy load heavier parts of your vendor JS just in time, which in a modern webpack + ES6 environment is very simple by using the import function. I prefer to wrap this in a JS service file for a few reasons:</p><ul><li>It provides a single place to provide annotations for the webpack pre-processor.</li><li>It can simplify your code when you only need one part of a library (like import { Foo } from &#39;bar&#39; ) by only exporting the part of the library that you need.</li><li>It provides a consistent interface with your other import statements in the files that use this service.</li><li>It makes it very easy to manually preload by calling your service exactly when you anticipate that you might need it.</li></ul><p>There are a few key advantages to handling this yourself rather than relying on automatic code splitting. You can decide exactly when you need it, so you don’t pull in data for your users un-necessarily. Your app will probably boot faster, if loading and parsing your large library is deferred until it is actually needed. Critically, it gives you a way to hook into the load process itself and provide UI feedback to the user so they don’t feel like your app is “slow”, by dealing with the promise-based interface yourself.</p><p>I’m assuming that you already have a modern frontend development environment with webpack set up. The first thing you’ll need is a service to wrap your target library, in my example the wonderful (but heavy!) <a href="https://www.npmjs.com/package/xlsx">xlsx</a>. At its simplest, this service doesn’t need to do much — it just needs to keep a reference to a single promise returned by an import call and return it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/962aa74b1c30540055eba70eec4557e8/href">https://medium.com/media/962aa74b1c30540055eba70eec4557e8/href</a></iframe><p><strong>Important Note: </strong>If you already have webpack’s prefetch plugin set up in your project, you will also need to ensure that it excludes your file from preloading when compiling the project! For Vue.js where it is enabled by default, you can customise this in your vue config like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/597224ce5cb5eb6b8ccc690069f6c31d/href">https://medium.com/media/597224ce5cb5eb6b8ccc690069f6c31d/href</a></iframe><p>For other frameworks, you’ll be looking for wherever PrefetchPlugin is configured.</p><p>Now that you’ve got your service file and webpack configured, instead of your typical import xlsx from &#39;xlsx&#39;, you would now import xlsx from &#39;./async-xlsx&#39;. You can then call your service to preload (e.g as part of the component lifecycle that likely needs it) and await the result to use it. In my import workflow, I have an import view which preloads the service on mount ( xlsx()) and a callback function that only runs once the user selects a file to import from:</p><pre>xlsx().then(parser =&gt; parser.read(...))</pre><p>The import callback once entered also starts a view state with a loading spinner, so everything in the UI is snappy and responsive should there be a delay in loading the library to continue the import process.</p><p>The other case I want to talk about is the import { Foo } from &#39;bar&#39; case — where you need just a small part of the library. When you use import this way, unfortunately you will end up loading in the full library. You can make it cleaner for your calling code by either handling it in the service:</p><pre>asyncFoo = import(&#39;bar&#39;).then(bar =&gt; bar.Foo)</pre><p>Or if you do need a couple of things from the library, it might be cleaner to handle it in your application code by using destructuring on the result of your service:</p><pre>asyncBar().then(({Foo}) =&gt; ... )</pre><p>Anyway, that’s all I have for this short tip. Once you do it the first time, it’s not too much extra effort over automatic splitting, and it definitely does improve the performance and responsiveness of your application by precisely deferring when you actually need to download and parse these larger libraries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b5432d7015f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/optimizing-vendor-js-by-asynchronously-loading-large-libraries-5b5432d7015f">Optimizing vendor.js by asynchronously loading large libraries</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Stateless, Dynamic HTML Embeds]]></title>
            <link>https://medium.com/swlh/how-to-implement-stateless-dynamic-html-embeds-da8200724a35?source=rss-90ddf2f59e02------2</link>
            <guid isPermaLink="false">https://medium.com/p/da8200724a35</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[tzar]]></dc:creator>
            <pubDate>Mon, 09 Mar 2020 03:56:18 GMT</pubDate>
            <atom:updated>2020-03-10T17:47:15.100Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been building a net worth tracker (<a href="https://nutworth.app/">nutworth.app</a>) and one of the features that I really wanted to build in was a sharing widget, similar to a YouTube embed code for example. In my use-case, users would configure various features of their charts, what data they want included, colours etc. They would then be given an embed code which could be added to a blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*48_Z-rLBTw7JH70rKTICEg.png" /><figcaption>Annotated example YouTube embed code</figcaption></figure><p>Typically, you’d do this by saving the parameters of what you wanted to share in some database and passing any other minimal state through URL parameters in the embed code. Looking at the YouTube embed code above, we have two main items of state which are passed through to YouTube to decide what to display — the Video ID (a database reference to load a state from) and a Start Time (directly passed, not saved anywhere on YouTube’s side).</p><p>There are a few issues with this approach that made it not suitable for me. First, the embed widgets I offered needed to be essentially static and not update even if the source material changed, and with all the different customisation options I offered there could be essentially an infinite number generated per account. This translates to either an embed code management interface which wouldn’t fit with my “simple” product, or potentially infinite database clutter where every embed code generated writes a relatively large document to a special collection.</p><p>The second issue is speed. I’m using Firestore as my primary database which has been great to develop against. The issue is that this is a relatively large package to download and has a bit of lag on the initial connection open. Having slow load times on embedded widgets is not really an option if you want anyone to use them! So either I would need to introduce a second data store (and the extra ongoing complexity and cost that entails) or I would need to spend a significant amount of time optimising that initial boot time and put the widget subsystem on its own dedicated pared down app (also complexity and ongoing maintenance overhead).</p><p>Instead, I decided to take a fully stateless approach — that is to say, the data to be displayed in the widget forms part of the embed code in some intermediate form. I built my widget around an iframe tag, similar to a YouTube embed. This simplifies development of the widget as there is no chance of your widget code clashing with any CSS or JS running on the embedding website.</p><p>As I mentioned, the typical way to implement data transfer to an embedded iframe is by passing data through the URL parameters, but this doesn’t work out that great when you’re talking about charts which can contain a significant amount of data. URL string limits are inconsistent at best, and eventually you’ll run into issues. Not to mention serialising complex data to a URL is ugly and space-consuming.</p><p>Thankfully, there’s a better way to do it with excellent cross-browser support by using Window.postMessage. The trick here is to have two tags in your embed code — one is your typical iframe, with an ID to make it easy to reference. The second is a small snippet of javascript which posts the desired state to the iframe once it loads. Here’s an example embed code from <a href="https://nutworth.app/">nutworth.app</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df80b18a01829a9cc2fc8baf1a4f3875/href">https://medium.com/media/df80b18a01829a9cc2fc8baf1a4f3875/href</a></iframe><p>As you can see, it’s relatively simple — the iframe onload calls a function, which we define in a script tag adjacent to the iframe. This function (which has a timestamp and a namespace so it won’t clash with the host page) does nothing more than send a javascript object into the iframe via postMessage. The actual data structure is down to your imagination — I included a version (1) and a message type (“chart”) so that I can implement and upgrade different types of widgets in the future as needed, while maintaining compatibility with the old embed codes.</p><p>So that handles sending the data to your widget, now how do we fetch it and render it? We need to listen to the event and then pass it through to our render function somehow. As the event is going to be sent to your iframe quite early, I found the most elegant way to handle this is with a “service” type file which immediately returns a promise. Once data is received, the promise then resolves with that data. This way, you don’t really have timing issues with your rendering code and receiving the data. Here’s how you would do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37a7883c7b7130109de2a0618c4e7f0/href">https://medium.com/media/a37a7883c7b7130109de2a0618c4e7f0/href</a></iframe><p>In your embed page, you’d then import this service and wait for data. I put up a spinner while waiting for data as well so that there is immediate visual feedback while everything loads into place:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/377587fe24400de135e04ccd2360b870/href">https://medium.com/media/377587fe24400de135e04ccd2360b870/href</a></iframe><p>As no database hit is necessary, this loads quickly and is relatively easy to optimise if needed. There’s not really anything to cache outside of your typical asset delivery CDN. Once you have the basic skeleton down as above, it’s also very easy to work with and pass whatever data you wish.</p><p>There are of course a few disadvantages to this approach. First, as your embed state is in plain text, the person embedding it can very easily modify it. In my use-case, this doesn’t really matter — it’s more of a feature than a bug. But if this was a major issue, it would be possible to protect the embed code with a cryptographic signature like <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">SigV4</a>.</p><p>Another issue is that being fully stateless, you really don’t have any good way to update or migrate the transferred state in the embed code later. This is why good embed versioning practice and building out a robust data structure to transfer your data initially are essential for this approach, or you may have some headaches to deal with years later.</p><p>Finally, having the state be part of the embed code means that if a user tries to break out of the iframe and put it in its own dedicated tab, there’s nothing you can actually display any more as there is no state. It’s possible to pick up the fact that there’s nothing to display with a timer and at least show an error page, but this is probably the biggest annoyance with using this method to embed data.</p><p>Nevertheless, for my usecase it has worked great and definitely simplified the overall embedding subsystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*v5lIIDpP1aMVp_Sb.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da8200724a35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-implement-stateless-dynamic-html-embeds-da8200724a35">How to Implement Stateless, Dynamic HTML Embeds</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reddit Ads Suck]]></title>
            <link>https://medium.com/@tzar/reddit-ads-suck-fb617cfa44c9?source=rss-90ddf2f59e02------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb617cfa44c9</guid>
            <category><![CDATA[reddit]]></category>
            <category><![CDATA[advertising]]></category>
            <category><![CDATA[startup-lessons]]></category>
            <dc:creator><![CDATA[tzar]]></dc:creator>
            <pubDate>Sat, 07 Mar 2020 09:09:23 GMT</pubDate>
            <atom:updated>2021-01-28T02:11:33.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTt-lRWfsPw9OZfrx2UW6A.jpeg" /><figcaption>The reddit ads user experience (Image: <a href="http://www.efile.com/">efile</a>)</figcaption></figure><p>I’ve been building out web applications for over a decade now, but usually it’s been as part of a team of people. Now that I’ve set out entirely on my own, when it came time to launch <a href="https://nutworth.app/">nutworth.app</a> I had to jump in the deep end and manage my own SEO and advertising. As an avid redditor building a product which matched my own interests on reddit, my natural thought was “Hey! Reddit ads exist, why not use those?”. Lots of people in precise categories, who are like me.. Surely nothing can go wrong?</p><p>Some research later, the internet had painted a pretty bleak view of the efficacy of Reddit ads due to the general hatred of sponsored content there. But these were generally marketing types saying this — as an actual redditor who to some extent shared that hatred, I figured it was still worth a shot. I wouldn’t fall into the same traps, I’d be open and honest about who I was and what I was offering. So, to the ads section of reddit I went!</p><p>Unfortunately, this was the start of my problems. If I went through ad registration with my current user, I would have to add a bunch of extra personal information (fine), but — importantly — my ads would all run under my personal username rather than using my brand name. This was definitely not ideal as I wanted to keep my personal and business affairs separated as a matter of best practice. So that meant a new reddit account to change the name and have a proper profile picture. Annoying, but somewhat understandable. I registered a new account.</p><p>Then I actually got to start creating ads. There was no real introduction to the ad system, just a white screen with three categories — campaigns, ad groups and ads. After some trial and error, here is my attempt at explaining these:</p><ul><li><strong>Campaigns</strong>: Where you decide if you want to pay per view or per click. Why is this a campaign level setting? I have no idea.</li><li><strong>Ad Groups:</strong> Where you decide which geographical regions, interests and subreddits you want to target. You can also pick device types and time of day. Your ad budget is set per ad-group rather than per campaign, which is very annoying. Additionally, you’re not able to target subreddits below a certain size, which was extremely annoying as a lot of my potential customers are in niche-size subreddits.</li><li><strong>Ads:</strong> Where you put together the actual ads you want to serve. Title, imagery, etc. Pretty straightforward except for the fact that reddit has both old and new interfaces, which means you now have five different layouts to design for in the new interface plus the old one.</li></ul><p>These things are organised as a tree, so you can’t share ad groups between campaigns etc. Several of the settings feel like they’re on the wrong entity — like ad budget being on who you’re targeting rather than the campaign itself. Perhaps this helps with more advanced use-cases, but for mine this just resulted in a lot of duplication and awkwardness when trying to set up e.g a mixture of pay per click and pay per view with no ability to share the ad budget between the two. It was also very un-intuitive trying to find the edit buttons when I wanted to go back and fix a mistake I’d made — they’re hidden behind three dots on each row and I only discovered them by accident a day later than I needed them.</p><p>Anyway, I struggled through these issues, duplicating and archiving content until finally I had three ads phrased differently and ready to go for my experiment. Now I just needed to wait for them to be approved and we should be good to go, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*jFcEluLyLBTu6lyLlYDi2g.png" /><figcaption>Wrong.</figcaption></figure><p>Wrong. All of my ads were denied with a message saying that I needed to do physical ID verification with their helpdesk. If this was the case, why the hell wasn’t this part of the initial sign up form? Why on earth is this part of individual ad verification? You’re sent off to a scammy looking not actually reddit domain — reddithelp — to fill in a generic support form where almost nothing in the form matches what you need to actually provide, which is scanned documents. Some googling later to make sure this was common, I begrudgingly did this. Time to wait again (and sleep).</p><p>In the morning, my ads had thankfully all been approved. Great success! Now to watch them run and grow my app. Wonderful! Except, they didn’t seem to be running, they didn’t seem to be doing anything at all. Well, I thought, I’m probably just getting outbid. Unwilling to bid more, I resolved to wait.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*NtOEuFHzMfuiiliNtgvLNw.png" /><figcaption>This is not what you want to see</figcaption></figure><p>A few days later, my pay per view ads had been running but the result wasn’t pretty. 0.072% click through rate, or about $5 per click. No signups. Shit. Everything I’d read had said that Google Ads was the priciest option out there on the market, and Reddit Ads were several times cheaper. Maybe my ads just sucked? But I was also running very similar ads on Google using their Smart Campaign feature, which were running at around $1 per click with a nearly 13% click through rate. Clearly this wasn’t working. I turned it off.</p><p>Perhaps this was just a pitfall of pay per view ads though. I upped the bid on my pay per click ads, hopeful to at least get some useful data out of them. But they wouldn’t run. I’m probably being significantly outbid, but I refuse to bid higher than I would to just run Google Ads targeted at people searching for exactly what I’m trying to provide. I attributed not being able to get my ads shown to not being able to target the exact communities that I want to — instead I have to target larger ones, which are probably also being targeted more broadly by more companies with deeper wallets than mine.</p><p>Eventually, some did run and I got click-through rates of 0.3–0.6% and a cost per click of $0.55–0.65. Still no conversions, but at least it was cheaper than Google Ads — the problem was just that I was bid constrained rather than constrained by my daily budget. I simply couldn’t show enough ads at this price point. I think they mostly ran in the night-time for the country I was targeting as well, so presumably when no-one else wanted a slot.</p><p>So, I tried retargeting. Maybe if I broadened my audience I would have better luck. I found some other kind of related subreddits. Added them to my Ad Group. Bam, <strong>now all my ads were pending approval again, and the old versions wouldn’t continue to run while this happened</strong>. What I thought was a small adjustment now meant more waiting on a manual process and no ads at all. I guess any adjustment you want to perform should be done by creating an entirely new campaign and ad group if you don’t want this downtime (more duplication, joy). I wish there had been a warning that this would happen on the edit screen.</p><p>So in the end, my experience with Reddit Ads could be summarised like this. Terrible sign up and on-boarding process (with dodgy extra verification step), bad experience for new users, ads that are generally more expensive than Google Search ads, way too many formats that ads will display in to design for. Fighting an interface and tree model to get the mixture of ad modes I wanted, terrible click through rates and zero sign ups. Lots of long gaps while I waited for manual approval. Other fun bonus annoyances like now having to switch between multiple reddit accounts in order to view my ad stats and big delays on spend data coming into the ad platform.</p><p>I’ll probably leave my pay per click ads running for a while on a lower bid, to pick up the occasional click and see if anything comes of it. I would definitely not recommend doing pay per view on reddit ever if you value your money. At any rate, for now I think I’ll focus my efforts elsewhere. Reddit Ads is just frustrating, time consuming and ultimately not cost effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb617cfa44c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>