<?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 sakulstra on Medium]]></title>
        <description><![CDATA[Stories by sakulstra on Medium]]></description>
        <link>https://medium.com/@sakulstra?source=rss-66486a3abe8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b7jSyzz6MNwh2Pjr3tqmWA.jpeg</url>
            <title>Stories by sakulstra on Medium</title>
            <link>https://medium.com/@sakulstra?source=rss-66486a3abe8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:32:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sakulstra/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[The new aave ui]]></title>
            <link>https://sakulstra.medium.com/the-new-aave-ui-791f1d248c2a?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/791f1d248c2a</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 15:52:18 GMT</pubDate>
            <atom:updated>2022-03-18T16:09:03.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EP7JHTb0yk_M_uqj" /><figcaption>Photo by <a href="https://unsplash.com/@cnbrightskies?utm_source=medium&amp;utm_medium=referral">Carlos Nunez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A peek under the hood</h4><p><em>In this article I want to give a deep dive into the new </em><a href="https://github.com/aave/interface"><em>aave interface</em></a><em>, the architectural decisions taken and discuss the general problems of decentralized websites and interfaces. If you’re new to aave v3 please check out the </em><a href="https://aave.mirror.xyz/2TnHYHQRnNhSG56Y4CcssulFArSVqrFbmAdYfU7Kxp0"><em>release post</em></a><em> where you can read all about the v3 protocol improvements and new features.</em></p><h4>Why a new interface?</h4><p>The aave-ui was originally created for aave protocol V1 and continuously improved by the community and core developers to satisfy new needs(e.g. V2, staking, new governance,etc). As a result, the current codebase is dated and has frankensteined a bit over time making it hard to follow and understand the code. That said it also contains gained knowledge, workarounds and special case handling from over 2 years of development. Doing a “complete rewrite” is almost never a good idea. While <a href="http://app.aave.com/">the new interface</a> looks and feels very different to the <a href="http://classic.aave.com/">classic ui</a> some compromises have been made to be able to maintain some chunks of the original ui and transaction logic.</p><p>On the other hand the rewrite allowed us to resolve some long outstanding issues. Let’s jump into them one by one and see if/how well we managed to resolve them. They are not in any particular order so just skip the boring parts.</p><h4><strong>Governance</strong></h4><p>Governance in the classic aave-ui — in my eyes — has always been a bit suboptimal and it has only gotten worse with each created proposal. While it was functional the ui didn’t scale well with the governance process.</p><p><strong>Data source:</strong> In aave-ui you always have the choice between “<em>light mode</em>” and “<em>normal mode</em>”. Light mode fetches all data from rpc, whereas normal mode utilizes subgraphs for certain things to reduce rpc load and improve ui performance. To understand why this is problematic in governance one has to understand how subgraphs work and how the governance works: With the subgraph we can index events and store blockchain data when, and only when, an event occurs. In governance though some things don’t emit an event as they are not related to a transaction. <br>So let’s assume a proposal is created(event emitted), voted on(events emitted) — when the voting time has passed nothing happens onchain and therefore no event will be emitted. As long as no-one interacts with the proposal the subgraph will store it as active although it isn’t.</p><p>The classic ui, “solves” this issue by trying to correctly calculate current state based on potentially wrong state stored on the subgraph. The new ui “solves” this issue by ditching the subgraph. The app will now always use what was formerly known as “<em>light mode</em>”. We didn’t want to sacrifice on performance though so we jumped through some hoops to improve on that front as well:</p><p><strong>Performance:</strong> In aave-ui light mode the governance will fetch all existing proposals via rpc &amp; all related ipfs files via public ipfs gateways. This is problematic as it causes quite some load on -<br>a) the client<br>b) the rpc<br>c) the ipfs gateway.<br>This is especially problematic as these calls increase linear with each new proposal and will be kicked off per user. Also there’s no way to partially load an ipfs file, so the client has to download all proposals blobs(including description, discussion, etc) just to eventually render a list of titles.</p><p>To solve this issue we built a <a href="https://github.com/aave/next-ui/tree/master/src/static-build">build cache</a> which will hold all governance ipfs files and the current chain state of each proposal at build time. The necessary parts of the cache will then be statically inlined into the page. The page will only fetch updates by querying the diff based on the current state. As proposals are now prerendered on the server side we can now add proposal specific meta tags for rich embedding.</p><p><a href="https://app.aave.com/governance/proposal/61/">Aave - Aave Starknet - Phase I</a></p><p><strong>Styles</strong></p><p>The classic aave-ui is using scss and styled-jsx with theme variables located in the aave-ui-kit subrepo. The issues with this setup are that:</p><ul><li>the theme variables come from an aave-ui-kit subrepo which forced ui forks to fork ui-kit as well breaking the contribution loop</li><li>it’s really hard to follow where styles come from when just reading through a <a href="https://github.com/aave/aave-ui/blob/master/src/components/AddATokenButton/index.tsx#L46">component</a></li><li>everything was custom build and there was no consistent typography or similar so it was hard to maintain by the community</li></ul><p>The new aave-ui relies on <a href="https://mui.com/">mui</a> which utilizes <a href="https://emotion.sh/docs/theming">emotion</a> for theming. Most of the new styling is now done on the theme level, so forks can simply change the theme.tsx to alter the global app styles*. All components are well tested and documented in the <a href="https://mui.com/components/buttons/">mui docs</a> which decreases the learning barrier for community contributions.</p><p>*We still have to see how good this works out as all forks that I’m aware of are based on the “classic” aave-ui. We’re definitely looking forward to removing roadblocks not yet considered.</p><h4><strong>I18n</strong></h4><p>The classic aave ui hosts messages in dedicated <a href="https://github.com/aave/aave-ui/blob/master/src/components/AMPLWarning/messages.ts">message</a> files and then references them via imports in the code. This is nice for type-safety and component translation isolation. But sadly, the packages to achieve this were no longer maintained and for new contributors it was hard to find* the “correct” files as text search would develiver them the messages file, not the corresponding ui file. We would have loved to use <a href="https://nextjs.org/docs/advanced-features/i18n-routing">next.js native i18n solutions</a>, but it’s not compatible with next export which is used on ipfs deployments. Therefore we went with a solution based on <a href="https://lingui.js.org/">linguiJS</a> which seems to be decent &amp; well maintained.</p><p>We also added crowdin to our build pipelines to make language maintenance &amp; language addition more seamless for non developers.</p><p>*Another thing making it hard to find files is the common, but annoying usage of index files, making file search essentially useless. So this is something we got rid off as well.</p><h4><strong>Token icons</strong></h4><p>The most common contribution to the aave-ui are token additions like <a href="https://app.aave.com/#/governance/63-QmU4MH1mps19vXJzWeV555T6yhqX2sqSceaN1fkkxgFDe1">most recently ENS</a>. For a token to be added to the ui nothing has to be done as it’s all retrieved from the blockchain so it will happen automatically. The token icon is not on-chain though so it has to manually be added or the interface will look trashy. In the classic ui this is done by creating a PR at aave-ui-kit adding the token symbol as svg and another svg for the a-token variant of that icon. Once that’s reviewed and merged another pr has to be made at the aave-ui to bump the ui-kit version accordingly.</p><p>As this was quite cumbersome in the new ui you only have to drop the svg into the public folder and <a href="https://github.com/aave/next-ui/blob/master/CONTRIBUTING.md#token-addition">that’s it</a>*. The new ui generates a-Token icons on the client only when needed. Also the token icons are no longer eagerly loaded and embedded into the main bundle reducing initial load.</p><p>*While this is sufficient for most tokens, you can still manipulate the name and similar <a href="https://github.com/aave/interface/blob/master/src/ui-config/reservePatches.ts">here</a>— this is especially useful for generic pool tokens which have a generic symbol(like G-UNI). For pool tokens the ui requires the symbol to be snake cased. If the token doesn’t follow that standard you can also rewrite the symbol.</p><h4><strong>Ipfs routing</strong></h4><p>For a React SPA to properly work you usually need some sort of server-side routing via nginx or similar. To work around that issue the classic aave ui relies on react-routers hash router which moves all routes behind a # anchor.</p><p>This kind of <a href="https://bafybeigpceacyjyzl2zsuzaibji7aymkmvtdyvvtgtlc3c7rvxbk54wx2u.ipfs.cf-ipfs.com/#/markets">works</a>, but <a href="https://bafybeigpceacyjyzl2zsuzaibji7aymkmvtdyvvtgtlc3c7rvxbk54wx2u.ipfs.cf-ipfs.com/markets">breaks</a> links without the # . With the nextjs file based router &amp; static export, we managed to go back to pre-ipfs routes as each route is it’s own file and entry point.</p><h4>Shareability</h4><p>In the current aave-ui some urls are not actually sharable. When a link is shared with another user to to checkout the <a href="https://classic.aave.com/#/reserve-overview/0x385eeac5cb85a38a9a07a70c73e0a3271cfb54a7-0x385eeac5cb85a38a9a07a70c73e0a3271cfb54a70xd05e3e715d945b59290df0ae8ef85c1bdb684744">GHST</a> token on polygon, chances are good the user will be presented with the market landing page and a different market is selected, causing the reserve to not be found. The app now persists the market in the query parameters, so<a href="https://app.aave.com/reserve-overview/?underlyingAsset=0x385eeac5cb85a38a9a07a70c73e0a3271cfb54a7&amp;marketName=proto_polygon"> v2 GHOST</a> will actually lead the user to v2 GHOST and <a href="https://app.aave.com/reserve-overview/?underlyingAsset=0x385eeac5cb85a38a9a07a70c73e0a3271cfb54a7&amp;marketName=proto_polygon_v3">v3 GHOST</a> will lead to v3 GHOST.</p><h4>Dx speed</h4><p>The classic aave-ui takes more than a minute for me to just boot up locally and when changing code it usually takes quite some time until it is present on the ui. There’s not a single reason for this, but more a mixture of various things (scss + postcss, custom babel, wp4, …). The new ui uses vanilla next.js with wp5 and hmr making it almost instant. We sadly had to opt out of the even faster swc option due to the dependency on babel-macro which is not yet supported.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FVHHxxFAeLaYzS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fhacking-kung-fury-hackerman-VHHxxFAeLaYzS&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZW1ubXlqNGJiZXVpMDJlOGUwd2RqbHZtOG5tazRjN3F0bGxsYmxkeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FVHHxxFAeLaYzS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/baf369dc089c793b87f3e2dedf80c928/href">https://medium.com/media/baf369dc089c793b87f3e2dedf80c928/href</a></iframe><h4>Build time</h4><p>The classic aave-ui takes around 10 minutes to build &amp; deploy. The new interface takes around 50% less time while at the same time building more than 60 static pages for governance which the classic ui doesn’t. There’s probably still some room to improve though(e.g. swc once macro is supported).</p><h4>Bundle size</h4><p>This point in my eyes is the most interesting &amp; also saddest point. The classic aave-ui has an initial js bundle load of 2.2MB. The goal was to come close to 400kb, but this was not achieved. In the end we’re at around 480kb for the main bundle but around 560kb with the page &amp; framework bundle. One reason for the bundle-size getting out of hand was the lack of monitoring. In the new aave interface there’s a ci step running on each commit comparing bundle size with master to add transparency to dependency updates &amp; feature additions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F241M8mwa4d8LDjQsga%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fthebreakerupperers-over-relationship-241M8mwa4d8LDjQsga&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2F241M8mwa4d8LDjQsga%2Fgiphy.gif%3Fcid%3D790b76117b3b93977371c9c20af102657761149faa9d83ba%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/445904468e5d3bffbe5f1eec77febbdc/href">https://medium.com/media/445904468e5d3bffbe5f1eec77febbdc/href</a></iframe><p>Some will say that React was the wrong choice when aiming for a good bundle size and they are correct. React was chosen because it allowed us to reuse some of the classic ui; also because the ecosystem is huge and the people involved being more comfortable with it. <br>We would be happy to review a PR which switches to From React to Preact or review an alternative ui being built on svelte or something similar. That said, React is not the(only) reason for the immense bundle size — a huge part of that is caused by the broader “web3” ecosystem. We started opening issues/PRs at certain dependencies for much needed changes, but eventually we dropped some wallet integrations where we didn’t think we’re expected to see improvements in the near future.<br>Eventually a big issue that remained is the <em>n</em> different libraries for handling big numbers and the <em>m</em> different versions of these libraries requested by each wallet integration. Sadly the bundle still includes 10 different copies of bn.js (bignumber handling is around ~20–25% of total bundle size :/). On the bright side, the governance pages might drop <a href="https://github.com/jonschlinkert/gray-matter/pull/137">a few kb</a> in the near future.</p><p><em>I hope you enjoyed reading this ❤ <br>If you feel you can make things better don’t hesitate to create an issue or pr on github. Even if you don’t feel like it — give it a go! </em>🏗<em> 💪 🌈 !</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=791f1d248c2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going serverless]]></title>
            <link>https://sakulstra.medium.com/going-serverless-4fa99915524e?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fa99915524e</guid>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 13:57:57 GMT</pubDate>
            <atom:updated>2020-11-30T18:04:15.703Z</atom:updated>
            <content:encoded><![CDATA[<h4>vercel + next — things i learned on the way</h4><p><em>If you’re hoping for a Vercel/Next.js bash that’s the wrong post for it. I’m pretty much ❤in it. Coming from more monolithic architecture I faced a few problems though from which some I didn’t expect. In the post I tried to collect all the issues I faced over the last few months and the solutions I used to work around them.</em></p><h3>Database</h3><h4>MongoDb connection delay</h4><p>In a monolithic app db connection time is neglect able as you’ll never notice it. It happens once t startup and then you’ll just reuse the pool. On serverless connecting to MongoDb for me was relatively slow(&gt;1s) and a re-connection might happen on every call. Locally/In a monolith the connection creation is a lot faster for me which might be due to better collocation of database and app server — you got little control over that on vercel I guess.</p><p>While I didn’t find a 100% solution for this issue, atlas <a href="https://docs.atlas.mongodb.com/best-practices-connecting-to-aws-lambda/#example">provides some docs</a> about increasing the chance of connection reuse on lambdas which makes <strong>frequently used</strong> api endpoints faster. This only works for frequently used api endpoints though, as for the ones only called e.g. every 2 minutes there will never be a cache hit.</p><h4>MongDb connection pools</h4><p>Another problem, probably more specific to mongodb is connection pooling. In mongodb a client instance opens up a connection pool, holding a certain amount of connections which is then shared for the mongo-client. On serverless though, sharing the connection between lambdas is not possible as each lambda runs in it’s own isolated environment. Each mongdb server has a connection maximum, which for mongdb atlas is 500 for the shared servers.<br>At a certain point I hit that limit as for working around the connection delay issue I didn’t close the connections automatically so stale connections + new connections where just to much for my db instance.</p><p>I worked around that issue in two ways:<br>1. I realized that some of the very minimal api endpoints i created could be combined as I always needed their data in combination anyways.<br>2. The default connection pool size is 5, but for most apis I didn’t run more than one or two queries/mutations and they usually run sequentially so there was no pointin a lot of connections so I could decrease the <strong>poolSize</strong> without any noticeable drawback.</p><h3>Data fetching</h3><h4>Loading global config from an api</h4><p><em>Disclaimer: This might be a not so common usecase<br></em>I built some sort of website generator which gets injected with a remote config at build time. Therefore I wanted to load the config in _app getStaticProps and inject it into all pages. <a href="https://github.com/vercel/next.js/issues/12434">Sadly that feature does not exist yet</a>.</p><p>I worked around this issue, but 1) fetching the config as a build step 2) serializing it as json and caching it in the file system 3) import it where needed</p><h4>GetStaticPaths &gt; GetStaticProps</h4><p>GetStaticPaths &amp; GetStaticProps are incredible handy utilities to generate masses of static pages. Sadly there’s no built in way to share non route related data between the two. With a growing size of data this resulted in a quite unnecessary increase of build time as usually the workflow is sth like:<br>- GetStaticPaths fetches a list of x<br>- GetStaticProps fetches a single x</p><p>This seems to be a <a href="https://github.com/vercel/next.js/discussions/11272#discussion-519">relatively common problem</a> and I worked around it by writing the cache to a file system json.</p><h3>Build</h3><h4>Size budgets</h4><p>Coming from non-nextjs applications, you might be familiar with bundlesize/size-limit et al for monitoring you frontend bundle/page size-budgets. Nextjs does some clever things for bundle size chunking making it hard to <a href="https://github.com/vercel/next.js/issues/10383">reason about bundle size</a> for a certain page.</p><p>As this wasn’t the biggest priority for now, I went the easy route by just having a budget for a selection of chunks. As vercel/next are incorporating a lot of dev/ops things right into the system I could imagine that at some point this is just a page level config feature you can opt in to.</p><h3>Different behavior on dev vs prod</h3><p>This is by far the most frustrating issue I ran into multiple times in various situations. The issue comes down to nextjs trying to hide the complexity from serverless, but in the end you might face parts of it eventually.<br>When running next dev you can essentially do what you want and where you want to, because after all — it’s a node app you’re running on your system.<br>When running things on prod though your pages will run in their own lambdas coming will all the up/downsides of these environments.</p><h4>Chromium</h4><p>While chromium works on build, it will simply not work inside the deployed functions. That’s not only true for api routes, but also for getStaticProps revalidate so while your build in which you use chromium inside getStaticProps might work — within the re-validation things might fail.</p><p>I created workarounds for not using chromium where I did, but later found <a href="https://github.com/vercel/now-examples/pull/207/files#diff-896ea04d45c9095779edd447cc607412181ed4e88eb1ab8c492c23efac6c326bR1">this issue</a>, which might solve things as well.</p><h4>File system</h4><p>Coming from non vm-like/stateful environments you might be used to caching things in memory or on the file system to speed up api responses. While in memory might work to some degree (like with the mongo connection trick), file system caches and similar most definitely wont.</p><p>Moved my cache to the database instead — a more clever way would probably been redis or similar, but i wanted to keep the tech stack small so it seemed more reasonable to just reuse the db i already got.</p><h3>Inherent complexity from serverless</h3><p>Not sure if vercel/next could do anything about these issues as these are more general problems you might face at serverless.</p><h4>cron-jobs</h4><p>The whole serverless structure is event based at it’s core. There’s nothing like long-running or reoccurring jobs build in. Having this in mind I had to learn that <strong>most things</strong> I did with long running jobs or cronjobs can be done in an event based fashion. Still I always ended up needing cron jobs for <strong>some things</strong>. This is the case whenever I wanted to trigger some event not immediately in response to another event, but e.g. with a 15 minute delay. The same issue arises when you want to do something which is just “not event based”, like e.g. sending a notification email once a week.</p><p>Vercel recently added <a href="https://vercel.com/docs/solutions/cron-jobs">some docs</a> for this and there is a <a href="https://github.com/quirrel-dev/quirrel">community project</a> targeting this in a more dx friendly way.<br>I started of using google cloud scheduler, but found it to expensive (10ct per job/month) for using it essentially as ping service. Also it was unnecessary hard to integrate in my dev/code setup. Eventually I ended up spinning up a long running app-engine app running <a href="https://github.com/agenda/agenda">agenda</a> which I deployed alongside my nextjs app.</p><h4>realtime data/subscriptions¹</h4><p>This punches essentially in the same hole than the previous point. Lambdas are nice for simple function execution, but as they are short running &amp; stateless they are not suited for e.g. keeping websockets open for features that might require realtime updates(e.g. notifications or chat).</p><p>I started solving this by experimenting with <a href="https://www.mongodb.com/realm">mongodb realm</a> and <a href="https://firebase.google.com/docs/database">firebase realtime database</a>, with the goal to just move away the realtime things from the next api to the client. In the end I — quite ironically — just used polling which simplified my client code quite a bit. I realized that in my case no-one cared about real-time and a polling delay of a few seconds just makes that requirement go away.</p><p>¹This seems to generally be a bigger problem than I expected as a lot of these “just deploy your app” kind of cloud service providers don’t support websockets (at least default app engine &amp; cloud run don’t).</p><h4>3rd party events</h4><p>Parts of my data doesn’t come from my own services, but are provided by a 3th party which doesn’t allow setting up a callback hook, but only over websocket/polling. So I was facing the same issue as with cronjobs, this time I couldn’t offload the effort to the client/polling as I needed to first process that data in the database.</p><p>While there are SAAS which essentially allow you to transform websocket events to api callbacks, I didn’t want to use yet another 3rd party service, so I just added a service which polls events on my app-engine server and writes them to the db.</p><p>I hope this article provided you with some workarounds for issues you might face. My overall learning from these serverless experiments was that “going full serverless” might be an unrealistic/undesirable goal. While it’s certainly possible to archive, it comes to the price of a Frankenstein architecture stitching x services together just to solve problems that wouldn’t be problems otherwise.</p><p>I’m overall happy with the setup I ended up with (although I’m not sure if i’d take mongodb as a db again):<br>- a serverless next.js core serving the frontend &amp; isolated api endpoints<br>- a server application doing the more complex/stateful tasks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fa99915524e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating google cloud-build]]></title>
            <link>https://sakulstra.medium.com/experimenting-with-google-cloud-build-af41ffc54082?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/af41ffc54082</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-build]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Sat, 28 Jul 2018 12:52:54 GMT</pubDate>
            <atom:updated>2018-07-30T17:16:17.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgaPmVdOZTqnOhn8-NgtwQ.jpeg" /></figure><p><em>When using CIs for things like testing/linting/building you usually use either a Jenkins server or one of the various CIaaS providers. Both are reasonable choices, Jenkins gives you the opportunity to do whatever you want. Services like travis-ci (i’m not affiliated, replace travis with whatever CI you usually use) give you the possibility to focus on product development and not care about the ci setup at all. The thing that bugs me about CI service providers is that they are usually pretty expensive and require you to use an even more expensive plan when doing slightly advanced stuff. So if you want to end up cheap you might invest some time to roll your own jenkins and utilize e.g. preemptive gce instances to save some money. There’s a new competitor joining the party: </em><strong><em>google cloud-build</em></strong><em>. Let’s take a closer look!</em></p><h3>The differences</h3><p><em>Disclaimer: I haven’t used cloud-build a lot. There might some critical features missing which are available on other CI PaaS. I basically evaluated the use for a project I’m currently working on — which does not do a lot of advanced stuff. So the comparison comes down to pricing for small/mid-size projects.</em></p><h4>Pricing</h4><p>All CI providers I know (please let me know if there are others) have a very static pricing model, meaning that you pay a fixed amount of money at the beginning of a month, no matter how much you’ll actually use it. Let’s see what that means for a small project:</p><p>On <a href="https://travis-ci.com/plans">Travis-Ci</a> you pay 69$ a month without any concurrent build at the smallest tier.</p><p>On <a href="https://codeship.com/pricing/basic?hsCtaTracking=35b2d6a6-6c9c-49c0-b222-671b3a4e32d5%7Ce359ef0b-8218-48af-8100-dea7a6269a96">Codeship</a> you pay 49$ a month without any concurrent build on the smallest tier.</p><p>On <a href="https://cloud.google.com/cloud-build/">Google Cloud-Build</a> you get 120 build minutes free per day. Naively calculating this means you still have to pay ~135€¹ a month if you utilize it 24/7 for a whole month. Beeing realistic, you only need it during working hours and even than for a mid sized team it won’t be utilized all the time. So a still pretty naive calculation with 8 working hours per day and 22 working days per month would end up at ~26$² a month. Even if ignoring the two free hours per day this is a lot cheaper than the other CIs.</p><p>¹ 0,0034 * 60 * (24–2) * 30<br>² 0,0034 * 60 * (8–2) * 22</p><h4>Concurrency</h4><p>Now comes the fun part: In most node projects i worked on you need at least some concurrency. Let’s take a node/react project as an example. In your “every-pr” build pipeline you’re likely to install the packages, lint the code, unit test the code, build some artifacts and perhaps even do some visual regression testing. Assuming every testing step takes around two minutes your pr check now takes 8 minutes. You don’t want to wait for the ci, so you might wonder how much of a pricing difference it makes to run lint/unit test/creating artifacts/visual regression in parallel. When starting to use CD this get’s a bigger issue as the application-build step usually takes some time and locks the ci build container for a while.</p><p>We don’t want to run more tests or anything — we just want to run things <strong>faster</strong>. On google-cloud-build you can just run 10 concurrent builds, without any pricing difference. Actually the docs state that you might run more than 10 builds at a time, but you shouldn’t rely on that behavior.<br>Travis and circle-ci differ in how the pricing model works. On travis ci you pay per concurrency. So when running 4 tests and 1 build, you actually need the small business plan($249) to run them all concurrently. On codeship there’s a difference between build and test parallelisation so you only need a concurrency of 2 to run the 2 builds and tests in parallel (99$). On the other hand if having multiple builds in parallel, but no parallel testing, the calculation is the other way around and circle-ci get’s pretty expensive soon ($399 for 4 concurrent builds). Nothing you have to worry about with google cloud-build — concurrency is just included.</p><h4>The Setup</h4><p>Now we heard enough about why you should at least consider giving google cloud-build a try. All you have to do, to collect some experience on you own is creating a cloudbuild.yaml or docker file and enable the cloud-build (e.g. via github marketplace if you’re hosting your project on github).</p><p>Let’s see how a simple setup with parallel execution in a node project might look like:</p><pre># cloudbuild.yaml</pre><pre><strong>steps</strong>:<br>- <strong>name</strong>: &#39;gcr.io/cloud-builders/npm&#39;<br>  <strong>id</strong>: INSTALL<br>  <strong>args</strong>: [&#39;install&#39;]<br>- <strong>name</strong>: &#39;gcr.io/cloud-builders/npm&#39;<br>  <strong>id</strong>: LINT<br>  <strong>args</strong>: [&#39;run&#39;, &#39;lint&#39;]<br>  <strong>waitFor</strong>:<br>  - INSTALL<br>- <strong>name</strong>: &#39;gcr.io/cloud-builders/npm&#39;<br>  <strong>id</strong>: TEST<br>  <strong>args</strong>: [&#39;run&#39;,&#39;test&#39;]<br>  <strong>waitFor</strong>:<br>  - INSTALL</pre><p>Lint and test will both wait for install to finish and then execute in parallel. One important thing to note here: If one step fails, the ci terminates immediately and does’t try to run the remaining steps. For a more extensive documentation <a href="https://cloud.google.com/cloud-build/docs/">checkout the docs</a> or wait till I got some more time to experiment.</p><p>I hope you enjoyed the read and will give it a try as well. I’m eager to see what this new competition in the continuous world leads to. For now the only disadvantage I could find with cloud-build is the missing 100% free plan for open source projects like offered by most of the other ci providers I worked with in the past.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af41ffc54082" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first experience with Intercom]]></title>
            <link>https://sakulstra.medium.com/intercom-c1f327630f32?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1f327630f32</guid>
            <category><![CDATA[meteor]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[intercom]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Fri, 02 Mar 2018 15:44:22 GMT</pubDate>
            <atom:updated>2018-03-02T16:46:42.548Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Things i wished i knew before</em></h4><p><em>I recently had the pleasure to work with Intercom the first time in my life — and eventually decided to not use it in the end. That said, intercom is a great piece of software. It has a superior support team, fair pricing, a good documentation and is super easy to integrate — it just didn’t fit our requirements, but may fit yours. I started this article because I had a medium tab opened when I started integrating and basically dropped noted here whenever i faced a problem. Now there are enough of them to write an article about.</em></p><h3>Integrating Intercom into a meteor/node app</h3><p>I couldn’t find any up to date packages. There is <a href="https://github.com/versolearning/meteor-intercom">meteor-intercom</a> but it uses underscore and sessions. A lot of people integrate Intercom into their apps so it can not be that complicated, can it?</p><h4>The Server side</h4><p>On the server-side we basically have to do two things for a basic setup*. Calculate a unique hash for the current user and publish it to the client.</p><pre><em>Meteor</em>.publish(&#39;currentUserIntercomData&#39;, <strong>function</strong>() {<br>  <strong>if </strong>(<strong>this</strong>.userId) {<br>    <strong>const </strong>intercomHash = crypto<br>  .createHmac(&#39;sha256&#39;, <strong>new </strong>Buffer(secret, &#39;utf8&#39;))<br>  .update(this.userId)<br>  .digest(&#39;hex&#39;);<br><br>    <strong>if </strong>(intercomHash) <strong>this</strong>.added(&#39;users&#39;, <strong>this</strong>.userId, { intercomHash: intercomHash });<br>  }<br>  <strong>this</strong>.ready();<br>});</pre><p>That’s it! We decided to add some hooks to sync user data, but it doesn’t get much more complicated.</p><p>*actually you don’t have to do this at all and could live without a server-side in case you only want to communicate with anonymous users.</p><h4>The client side</h4><p>For client side integration it’s enough to add the loading script they provide and boot intercom. I ended up creating a small react component which does pretty much Intercom(&#39;boot&#39;) on mount and Intercom(&#39;update&#39;) on route changes (required to make intercom aware of route changes on SPAs).</p><blockquote>We’re done intercom is integrated and we can actually start creating awesome auto messages!</blockquote><h3>The bad parts</h3><p><em>Intercom UI/UX is very thought trough. Everything is super responsive and the things that are possible are designed in a pleasant manner. The mobile app is also pretty neat. I’m personally a huge fan of the A/B testing feature for messages. This article will only tackle the bad parts, not because there are no good parts, but because there exist a lot of positive articles about intercom already and I don’t feel like it’s necessary to cover them again. It’s not meant as an Intercom bash, but as a warning for users who are considering intercom.</em></p><p><em>What’s following is a listing of things which made us not use Intercom. Some of them may have workarounds, but at some points we would have more workarounds than working stuff :)</em></p><h4>Emails/Messages</h4><p>We hoped to get rid of our custom solutions and switch over to Intercom for everything around customer messaging.</p><p>Intercom provides basically 3 types of messages from a developers perspective.<br><strong><em>segment based messages:</em> </strong>messages which automatically get set to a user which matches a certain set of rules and logs out off the application before he leaves the segment.<br><strong><em>event based messages: </em></strong>actually very similar to segment based messages, but having an event selector in the rule set. Events are sent to Intercom via rest or whatever endpoint you use, so you could send an email for users which are <em>female</em> and <em>invited a friend</em>. The <em>gender</em> is synced in the user data, <em>invited a friend</em> would come as event.<br><strong><em>admin initiated messages:</em></strong> this is basically the manual approach like you would do with mailgun — not using any cool intercom features, besides storing the message as conversation with the user.</p><h4>Problems</h4><p>There are basically three fundamental problems we faced when trying to implement our messages.</p><p><strong>rulesets are primitive:</strong> You can only chain all rules with “and” or “or”, nothing in between. This is sufficient for some cases, but insufficient for others. The specific case here was that we wanted to send a message on two different pages. It seems like the only possible way is to either create two messages and accept that some users might get it twice, or create an endless chain of is not conditions for all the other pages.</p><p><strong>the message template system is limited: </strong>basically all you can do is write static text and add variables with fallbacks. When you e.g. want to have different salutation based on gender you have to create two different email templates. A simple if/else is not possible.</p><p><strong>emails are only send once:</strong> In most cases this makes a lot of sense as we don’t want to spam our users. When welcoming a user to your platform you only want to send the message once. In some cases it makes sense to send a message multiple times — e.g every time a user invites a friend we want to write him a thank you mail or similar. This is simply not possible.</p><p>Admin initiated messages to the rescue. The support team frequently suggested to use admin initiated messages as it’s basically the manual way of doing things and allows you to do anything you want. While this is true — you are not restricted by rules/templates, it’s again limited:<br>You can select from two predefined templates which you use to inject your body into. Using your own template isn’t possible.<br>You always have to specify an message author (one of the admins) as Intercom will handle the message as conversation and a conversation needs two partners.</p><h4>Messenger</h4><p>The messenger is basically an iframe which embeds to your page. Sadly the customization options are very limited. Adjusting the width is not possible without workarounds. Also a major bummer was the missing possibility to turn off the gif button. It’s not that I personally don’t like gifs :) but it seems inappropriate for our target group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*f5_IBO1QyAGH-x0DmJToYw.png" /></figure><h4>Maintenance</h4><p>Intercom provides a <strong>test-app</strong> for each Intercom app, so you can test your auto messages before releasing them into the wild. Actually I didn’t expect such a feature and was positively surprised! So whats the problem? There’s no syncing or import/export functionality implemented. So whenever you test some new message or try to optimize it on test app you have to copy paste them over to the <strong>production-app</strong>. We did this with a very small set of messages ~20 and already had a lot of errors, because copy/paste actually means “open another tab and clicking through various menus to set the appropriate flags in a message creation dialog”.</p><h4>Github Integration</h4><p>Intercom allows to create tickets from conversations and automatically updated the state inside the conversation. This feature is actually super cool and I would definitely use it for a project with a public issue repository. The problem is, they don’t generate the tickets via api like ci bots do, but instead use the logged in user itself — meaning we would have to create github accounts for all support staff members and give them full repo access to allow them creating tickets.</p><h4>i18n</h4><p>i18n is a major pain point caused by the points mentioned above (no conditionals in templates). I18n in Intercom is restricted to the app. The auto messages aren’t langauge aware at all. If you want to write a different mail for german and english users you basically have to set it up twice and try to ensure they don’t get both.</p><h4>Disclaimer</h4><p><em>I’m still using Intercom for some stuff. I feel like it’s is especially useful/usable for soft realtime interaction with anonymous users — not necessarily for all about customer messaging.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1f327630f32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Honor the byte]]></title>
            <link>https://medium.com/hackernoon/honor-the-byte-dbd314b3d506?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd314b3d506</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[meteor]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Fri, 03 Nov 2017 19:01:39 GMT</pubDate>
            <atom:updated>2017-11-03T19:01:39.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUBrdwkxy2IYC8vaLg2rvg.png" /></figure><h4>Or: do no harm, write maintainable code</h4><p><em>I currently have the glorious task at work to port a legacy react/jquery/materializecss codebase to react/material-ui.</em></p><p><em>It’s a pain, and quite a big one. When I started this a few weeks ago I didn’t really realize what I was getting into — now I’m more aware then I was before, but I still feel like it will take a while to get this finished.<br>A few days ago, after work, a coworker asked me why I was creating a </em><em>ButtonComponent, which was the inspiration for this story.</em></p><h4>Modularization</h4><p>In university, the lectures targeting code quality all promoted to practice modularization wherever possible. I could see the benefits of this approach, but I’ve never been fully aware of what happens if you start finding excuses for ignoring this basic coding practice. Writing small self contained components/functions has big advantages over writing monolithic `do it all` ones which I want to highlight in the following article.</p><p>The application i’m working on has code duplication all over the place huge React components which only differ by a few words in string templates. 100+ Line functions which only differ by an array selector. Eventually I’m exaggerating but you get the point:</p><blockquote>Should I help fixing this or run?</blockquote><p>Obviously I can’t blame the prior developers —<strong> I’ve done similar things in the past</strong>.<strong> </strong>Projects grow rapidly, get more complex then we think at the beginning and hasty design decisions bite our asses at some point. We suddenly have to hold on to some deadline for potential investors or have to pivot as requirements change dramatically. With a huge amount of pressure we tend to betray our own ideals and start to do (not only) things like code duplication, because we convince ourselves that it’s faster and we can refactor later — even if we know better.</p><p>It’s a legacy meteor application, so testing before 1.3 was a mess to even get started with. Suddenly the node environment changed super fast — to the better — but huge projects like this have a hard time catching up with scoped modules/es6/lodash/app-state/unmaintained-packages and other daily hickups.</p><p>We all know historical grown projects, <em>they almost have to be messy. </em>On the other side of the plate we can see it as a challenge — legacy code often contains interesting solutions for special cases noone would ever have on the radar in first place.</p><h3>Why code duplication is bad</h3><p><em>I don’t know a single person who would argue that code duplication is generally a good thing. Nevertheless I think it’s interesting to look at implications from code duplication we are not necessarily aware of.</em></p><h4>Testability</h4><p>As there is no central definition, testing gets basically <em>impossible</em>. When looking at the testing pyramid you would basically have to skip all the ground levels and start right ahead with integration testing. Using simple UI testing tools like snapshots is unimaginable.</p><h4>Ease of use</h4><p>In most cases you will not have a simple button which always has the exact same classes and properties. In our code base for example, some buttons contain a few extra classes when they are used inline and some contain additional classes for left over jquery selectors.</p><p>The problem with css classes is, that you have to remember them — especially when not following any guideline like BEM or SMACSS . This is not an easy task and instead of remembering them you instead look in the code which classes are used elsewhere. This obviously slows down the process and isn’t a good developer experience at all. It’s not transparent which classes exist for a specific element.</p><p>When instead having a component you can simply define possible properties and map property names to classes. It’s not that hard.</p><h4>Ease of change</h4><p>Code is maintainable when you can make simple changes all the time, without breaking things. Let`s assume I wanted to change something about the button… e.g. handle some onClick ripple issues, or `switch the underlying css framework` — You now have to <strong>find</strong> and change all the places which implement some sort of button — you will most probably miss at least one. With proper component structure it would be a ~one-liner.</p><h4>Courage to change</h4><p>The problem, especially with large, duplicated functions and components is not only that they are <strong><em>large</em></strong> and <strong><em>duplicated</em></strong><em>. </em>The biggest problem is, that noone will have the courage to change things. Not because they don’t want to, but because they fear to break something, without noticing— everyone always only touches the code he/she really <em>has</em> to touch. So mess gets messier and the points mentioned above get worse and worse. It’s hard to escape this spiral once entered, as you have to convince your bosses to stop the train and let you do work which doesn’t necessarily affect the products visible value. There’s no direct <em>ROI</em> on cleanup work, so you have to fight for the time and resources.</p><h4>Code Size</h4><p>Especially in web development code size is a major concern. It actually does matter if your bundle size is 200 or 400kb. So having a couple times</p><pre>React.createElement(Button, { onClick: handleClick })</pre><p>vs</p><pre>React.createElement(&#39;button&#39;, { className: &#39;a lot of different classes&#39;, onClick: handleClick })</pre><p>Will actually have an effect on code-size. Of course this is a super simple example not considering minifications and gzipping, but the advantages get more significant with more complex Components and functions.</p><p><strong>Gzip: </strong>most web servers nowadays support gzip, which basically strips out duplicate strings (<a href="http://www.infinitepartitions.com/art001.html">in depth explanation</a>). This doesn’t invalidate the argument, but makes it less problematic in a lot of cases.</p><p><strong>Prepack: </strong>There’s a pretty cool tool called <a href="https://github.com/facebook/prepack">prepack</a>, developed by facebook, which could also help optimizing functions. Still you shouldn’t use code optimizers as an excuse to write bad code, but instead use them to optimize well shaped code.</p><h4>Compile/Transpile time</h4><p>Javascipt is interpreted, so I don’t need to compile it right? No. Actually you need to compile/transpile it for different targets. This is not only, but especially true for web facing applications. You usually can’t just write modern code and run it in the browser. You will most likely use some sort of build system which translates some language features to a lower level to make it executable by *all/old* browsers. Having non modular duplicated code will most likely increase build time and decrease DX.</p><h3>Conclusion</h3><blockquote>The first time you do something, you just do it. The second time you do<br>something similar, you wince at the duplication, but you do the duplicate<br>thing anyway. The third time you do something similar, you refactor.</blockquote><blockquote><a href="https://www.amazon.com/dp/0201485672/"><em>Martin Fowler et al.</em></a></blockquote><p>Don’t wait till the above statement get’s invalid. Refactor your code as soon as you detect the flaw, <strong>not till you find time to clean up</strong> . Nothing is more important than to keep code clean, maintainable and testable. Every time you postpone a refactor you actively create work, decrease product quality and developer experience.</p><blockquote>When programmers lose the fear of cleaning, they clean! And clean code is easier to understand, easier to change, and easier to extend. Defects become even less likely because the code gets simpler. And the code base steadily improves instead of the normal rotting that our industry has become used to.</blockquote><blockquote>What professional programmer would allow the rotting to continue?</blockquote><blockquote><a href="https://www.amazon.de/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073"><em>The clean coder, Robert C. Martin</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd314b3d506" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/honor-the-byte-dbd314b3d506">Honor the byte</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#1 Apollo + React = ❤]]></title>
            <link>https://medium.com/mvp-space/1-apollo-react-98bc751fd773?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/98bc751fd773</guid>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[meteor]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Thu, 13 Jul 2017 21:56:58 GMT</pubDate>
            <atom:updated>2017-07-13T22:20:15.578Z</atom:updated>
            <content:encoded><![CDATA[<h4>infinite scroll/ load more</h4><p><em>I’m currently working on my first </em><em>pure graphql/apollo + react application and had the glorious task to implement lists which initially loads some items and then load more data when reaching the end of the page or pressing a button. </em><a href="http://dev.apollodata.com/react/pagination.html"><em>The Apollo docs for these kind of things</em></a><em> are really good (like for almost everything I had to do with Apollo yet, they provide useful information an full examples ❤), but i had some problems at first implementing it properly, so I hope to save you some headache with it. The focus here is on the Apollo part.</em></p><h4>Introduction</h4><p>Please take a look at the <a href="http://dev.apollodata.com/react/pagination.html">docs</a> as I won’t explain the different approaches, but I feel like it’s good to know the differences. We’re going for the cursor approach as we don’t want page numbers to click trough. Instead of using infinite-scroll we’re using a load-more button as we currently have a footer and we want it to be reachable (not automatically scrolling away).</p><p>The idea is simple: We somehow have to remember which was the last document we fetched. In order to do that we implement a pretty basic protocol:</p><blockquote><strong>Client</strong>: I need `data`!</blockquote><blockquote><strong>Server</strong>: Here you havethe first x datasets. You should have now everything till cursor .<br><strong>Client</strong>: I need *more* data! You only gave me till cursor</blockquote><p>So basically the only thing we have to do is, sending the last cursor to the client — and when the client wants more he has to provide the last received cursor. That’s it — let’s get to the code.</p><h4>Getting started</h4><p>In our example code we’ll fetch some posts, so let’s start with some typeDefs :).</p><p><strong>A post</strong> consists out of a title, content and a createdAt timestamp.</p><p><strong>A cursor</strong> contains two parts: the last cursor and the nextcursor. Next cursor points at the last fetched entry and helps us to find more from that point. In this applicationlast is only for bookkeeping and highlighting newly fetched stuff on the platform. Both cursors will contain a stringified Date so that we can easiliy query for newer/older.You can omit it and go with a single cursor instead.</p><p><strong>A PostsList</strong> contains an array of Posts and the cursor. We also define a query which accepts a cursor and a limit.</p><pre><strong>export const </strong>typeDef = `<br>  type Cursor {<br>    last: String<br>    next: String<br>  }</pre><pre>  type Post {<br>    _id: String!<br>    title: String!<br>    content: String<br>    createdAt: Date<br>  }<br>  <br>  type PostsList {<br>    cursor: Cursor<br>    posts: [Post]<br>  }</pre><pre>  Queries {<br>    getPosts(cursor: Cursor, limit: Int): PostsList<br>  }<br>`</pre><p>As we have the types now we have to write the server-side Query-resolver for getPost(). The code should hopefully be pretty self explanatory, let’s go trough it anyways: If there is a cursor, we fetch the next limitentries older then the next cursor. If there isn’t we just fetch the first limit entries. We then fetch the last Post in our collection and check if we already fetched that — if we did that we reached the end and there is nothing more to fetch.</p><pre>getAllPosts (_, {cursor, limit = 0}) {<br>  <strong>const </strong>query = {}<br>  <strong>if </strong>(cursor) {<br>    query[&#39;createdAt&#39;] = {$lt: <strong>new </strong>Date(cursor.next)}<br>  }<br>  <strong>const </strong>posts = Posts.find(query, {limit: limit, sort: {createdAt: -1}}).fetch()<br>  <strong>const </strong>last = Posts.findOne(query, {sort: {$natural: 1}})<br>  <strong>return </strong>{<br>    cursor: {<br>      next: (posts.length !== 0 &amp;&amp; last._id !== posts[posts.length - 1]._id &amp;&amp; posts[posts.length - 1].createdAt) || undefined,<br>      last: cursor<br>    },<br>    posts<br>  }</pre><p><strong>edit</strong>: let’s examine next as it may be hard to read with medium line wrapping and missing code highlight. It’s a concatenation of and operators so when one fails undefined will be returned. Undefined props will be omitted and never reach the client. Let’s ripp apart that and:</p><pre>posts.length !== 0 // if we didn&#39;t get any results we don&#39;t want the client to ask another time, so we don&#39;t send a next cursor down</pre><pre>last._id !== posts[posts.length - 1]._id // if the last post we fetched already is the last post in the db, we also don&#39;t want the client to ask again</pre><pre>posts[posts.length - 1].createdAt // if both previous conditionals resulted in true, we want to tell the client that there&#39;s more data on the server, so we pass down createdAt as it acts as a courser in this example</pre><h4>Client</h4><p>The server part is already finished. We only need to use it on the client now :) I love HOCs so let’s do it with a HOC.</p><pre><strong>const </strong>GET_ALL_POSTS = gql`<br>  query getPosts($cursor: String, $limit: Int) {<br>    getPosts(cursor: $cursor, limit: $limit) {<br>      cursor {<br>        last<br>        next<br>      }<br>      posts {<br>        title<br>        content<br>        _id<br>        createdAt<br>      }<br>    }<br>  }<br>`</pre><pre><strong>const </strong>withGetPostsQuery = graphql(GET_POSTS, {<br>  props: ({data: {error, loading, getPosts, fetchMore}, ownProps}) =&gt; {<br>    <strong>return </strong>{<br>      loading,<br>      error,<br>      posts: (getPosts &amp;&amp; getPosts.posts) || [],<br>      isMore: getPosts &amp;&amp; !!getPosts.cursor.next,<br>      loadMore: ({limit}) =&gt; {<br>        <strong>return </strong>fetchMore({<br>          query: GET_POSTS,<br>          variables: {<br>            cursor: getPosts.cursor,<br>            limit: limit || 3<br>          },<br>          updateQuery: (previousResult, {fetchMoreResult}) =&gt; {<br>            <strong>if </strong>(!fetchMoreResult) <strong>return </strong>previousResult<br>            <strong>const </strong>previousPosts = previousResult.getPosts.posts<br>            <strong>const </strong>newPosts = fetchMoreResult.getPosts.posts<br>            <strong>return </strong>{<br>              getAllPosts: {<br>                ...fetchMoreResult.getPosts,<br>                posts: [...previousPosts, ...newPosts],<br>                cursor: fetchMoreResult.getPosts.cursor<br>              }<br>            }<br>          }<br>        })<br>      }<br>    }<br>  },<br>  options: (ownProps) =&gt; ({<br>    variables: {<br>      limit: ownProps.limit<br>    }<br>  })<br>})</pre><pre>const PostsList = ({posts, isMore, loadMore}) =&gt; (<br>  &lt;div&gt;<br>    {posts.map(post =&gt; &lt;PostListItem key={post._id} post={post} /&gt;}<br>    {isMore &amp;&amp; &lt;button onClick={loadMore}&gt;Load more&lt;/button&gt;}         &lt;/div&gt;<br>)</pre><pre>export default withGetPostsQuery(PostsList)</pre><p>We’re done already, but it seems like i still owe you some explanation :)</p><p>The HOC automatically fetches limit docs now and provides a function called loadMore, which will fetch 3 new docs whenever called (you can also pass a limit to loadMore({limit:200}) to fetch a custom amount of docs). In addition to that, the HOC provides a isMore flag which keeps track of the cursor and turns false as soon as there is nothing more to fetch.</p><p>You can now use the component like: &lt;PostsList limit={20} /&gt; and the HOC will fetch the first 20 docs and from then on fetch 3 new docs whenever you click more. When there is no more doc to fetch, the load more button will disappear. When using &lt;PostList /&gt; without providing a limit it will fetch all docs.</p><p><em>I hope you enjoyed the article! Feel free to leave a note in the comments or via twitter. If you want me to write about some specific topic, feel free to send me a topic-suggestion.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98bc751fd773" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mvp-space/1-apollo-react-98bc751fd773">#1 Apollo + React = ❤</a> was originally published in <a href="https://medium.com/mvp-space">MVP Space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js meets firebase and mobx | IV]]></title>
            <link>https://medium.com/mvp-space/next-js-meets-firebase-and-mobx-iv-903b3022d0b4?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/903b3022d0b4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 16:03:08 GMT</pubDate>
            <atom:updated>2017-02-17T16:43:13.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEdCx3K_u8P2jHabAEC-5A.jpeg" /></figure><h4>Episode 4 | protected routes and hosting</h4><p><em>In process of writing the </em><a href="https://blog.mvp-space.com/next-js-meets-firebase-and-mobx-iii-1da7cefa9d25#.uo4m42ugo"><em>next.js meets firebase articles</em></a><em> I got a lot of feedback and a few questions i want to answer in this article.</em></p><ol><li>how to implement protected pages</li><li>how to host next.js applications outside of <a href="https://zeit.co/now"><em>now</em></a></li></ol><h3>Protected pages</h3><p>The concept of protected pages is easy: We do a client side redirect whenever a user tries to access a page which requires a valid authentication state. With the mobx store we defined in a previous article this would already be possible, but we don’t have a way to differentiate between “not logged in” and “the application has just started and firebase hasn’t resolved the user yet”.</p><p>The problem is, that we currently only keep track of our user object — not the authentication state. In order to also track a pending authentication we have to modify our <em>authStateChange</em> listener to keep track of the current state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9196a15aea2cbcb7ca2be23ea9c83693/href">https://medium.com/media/9196a15aea2cbcb7ca2be23ea9c83693/href</a></iframe><p>Whenever authIsPending is false, we know that the authentication is ready and whatever is saved inside user defines if we are logged in or not. We could just use the raw @observable inside our React components now, but I decided to add a @<a href="https://mobx.js.org/refguide/computed-decorator.html">computed</a> value which does the legendary “<em>bang, bang you’re boolean” </em>operation for us :). Keep in mind that computed values are super useful and you can do really cool stuff in there — <strong>as long as you don’t mutate the state.</strong></p><p>Now we can write a simple HOC to perform a redirect dependent on the user state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/051ee69813a7f75178ec31825a745e5f/href">https://medium.com/media/051ee69813a7f75178ec31825a745e5f/href</a></iframe><p>That’s all you have to do! The protectedPageHOC can now be used to wrap whatever page we want and get automatically redirected to /access-denied if we aren’t authenticated.</p><h3>Hosting</h3><h4>Disclaimer</h4><p><a href="https://zeit.co/now"><strong><em>Now</em></strong></a><em> is a pretty neat and not that expensive hosting solution. By hosting things yourself you have the burden to keep your stuff up to date in order to keep your users save. Keep always in mind that hosting is more than deploying the newest build from time to time.</em></p><p>Hosting next.js applications is no different to any other node.js application. You basically have to build and run the application — that’s it. If you want it to stay alive on error you have to wrap it with e.g. <a href="https://www.npmjs.com/package/forever">forever</a>, <a href="https://github.com/Unitech/pm2">pm2</a> or some other solution. If you want to automatically start it after reboot you have to add a init-script for it. You can find good tutorials about these topics all over the web.</p><p>In order to make this a bit more interesting I’ll explain how to host your next.js application on a digitalocean dokku instance with letsencrypt ssl and automatic certificate renewal. Hosting directly via firebase is not possible as we need a server-side — you know, for server-side rendering ;) There’s an ongoing <a href="https://github.com/zeit/next.js/issues/604">discussion</a> about exporting a static bundle — which would allow hosting even on e.g. github, but not using any dynamic SSR any more.</p><p><em>If you prefer to not host on your own dokku server you can also use </em><a href="https://www.heroku.com/"><em>heroku</em></a><em>! It’s the exactly same setup like described below for dokku just without all the dokku related stuff! — so you have to adjust your package.json a bit and you are ready to go.</em></p><h3>Getting started with dokku on digitalocean</h3><p>I’m using the newest available one-click install on the cheapest available instance (512mb + 20gb ssd) available on digital ocean — for about 5$ a month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*IUGOCrzJP5y6JHP91FbSbw.png" /></figure><p>In order to follow this guide you have to create a droplet and make sure to add your ssh-key. Access your instance-ip once and submit the form where you ssh key should automatically be prefilled. Now you have a fully functional dokku instance and your ip shouldn’t be reachable any more!</p><h4><strong>Glossary</strong>:</h4><p><strong>ip|domain</strong>: your dukku servers’ ip address or domain</p><p><strong>app_name</strong>: however you want to name your application inside dokku</p><p><strong>remote_name</strong>: the alias you want to push to</p><h4>Preparing the server</h4><p>The prebuild image is already outdated, so let’s first update and restart:</p><pre>ssh root@&lt;ip|domain&gt;<br>apt-get update &amp;&amp; apt-get upgrade -y &amp;&amp; reboot<br># exit you will get kicked out automatically</pre><p>Install the letsencrypt dokku plugin:</p><pre>ssh root@&lt;ip|domain&gt;  <br>sudo dokku plugin:install https://github.com/dokku/dokku-letsencrypt.git  # install letsencrypt plugin <br>dokku letsencrypt:cron-job --add  # certificate auto renewal  <br>exit</pre><p>Create your dokku app container:</p><pre>ssh dokku@&lt;ip|domain&gt; apps:create &lt;app_name&gt;</pre><p>Add your domain to the dokku app container:</p><pre>dokku domains:add &lt;app_name&gt; &lt;domain&gt;</pre><p>Enable letsencrypt for your dokku app container:</p><pre>ssh dokku@&lt;ip|domain&gt; config:set --no-restart &lt;app_name&gt; DOKKU_LETSENCRYPT_EMAIL=&lt;email&gt;  <br>ssh dokku@&lt;ip|domain&gt; letsencrypt &lt;app_name&gt;</pre><p>Dokku runs install --production so devDependencies won’t get installed. If they are required for building the application (e.g. when using babel plugins) you have to tell dokku to install them explicitly:</p><pre>ssh dokku@&lt;ip|domain&gt; config:set &lt;app_name&gt; NPM_CONFIG_PRODUCTION=false</pre><h4>Preparing the repository</h4><p>Dokku doesn’t run the <em>build</em> command automatically, so you have to add a <em>postinstall</em> script which runs the build. Make sure to be on beta.28 or later — before beta.28 next.js used absolute paths inside the webpack build which lead to problems when starting the application on heroku like services. If you whysoever can’t upgrade to beta.28 you can use a <em>prestart</em> script instead, but you’ll lose the benefit of zero downtime deployments.</p><p>Besides that dokku manages the ports for you, so we have to extend the start script to use an environment variable instead of the static 3000 port.</p><pre>&quot;prestart&quot;: &quot;next build&quot;,<br>&quot;start&quot;: &quot;next start -p $PORT&quot;,</pre><p>Optional: to have a less error prone deploy process you should specify a engine/node version — i’d suggest to use the version using in development:</p><pre>&quot;engines&quot;: {<br>  &quot;node&quot;: &quot;7.x&quot;<br>}</pre><p>Add the dokku container as a git remote to your local git repository:</p><pre>git remote add &lt;remote_name&gt; dokku@&lt;ip|domain&gt;:&lt;app_name&gt;</pre><h4>Deploy</h4><p>Now everything is ready and you can deploy you application by pushing to your dokku git remote:</p><pre>git push &lt;remote_name&gt; master</pre><p>If you face problems running npm install inside the deploy step it may be possible that this is caused by “<em>out of memory</em>” errors. This is due to the memory hungry nature of npm/yarn install . To resolve this you can add some swap to your instance (or of course use a better instance):</p><pre>dd if=/dev/zero of=/swapfile bs=1024 count=1024000<br>sudo chmod 600 /swapfile<br>mkswap /swapfile<br>swapon /swapfile<br>sudo nano /etc/fstab<br>/swapfile   none    swap    sw    0   0</pre><h3>Miscellaneous</h3><p><a href="https://github.com/sakulstra/next.js">Next.js</a> is evolving extremely fast! Make sure to watch in star their repository, there are awesome features merged on a daily basis!</p><p><em>I’ve put a lot of ❤ and effort into this article and i’m happy to iterate over/fix/update it :) If you have any feedback, please let me know in the comments! Also, if you have any topic suggestions for further articles, please drop me a message.</em></p><p><em>As always, you can find the current version of code on github.</em></p><p><a href="https://github.com/sakulstra/firebase-nextjs-mobx/releases/tag/v0.0.4">sakulstra/firebase-nextjs-mobx</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=903b3022d0b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mvp-space/next-js-meets-firebase-and-mobx-iv-903b3022d0b4">Next.js meets firebase and mobx | IV</a> was originally published in <a href="https://medium.com/mvp-space">MVP Space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js meets firebase and mobx | III]]></title>
            <link>https://medium.com/mvp-space/next-js-meets-firebase-and-mobx-iii-1da7cefa9d25?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1da7cefa9d25</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[mobx]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Mon, 06 Feb 2017 16:45:55 GMT</pubDate>
            <atom:updated>2017-02-14T13:01:19.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fp9IbcKf0byLjzzq-VsUwg.jpeg" /><figcaption>Lünersee</figcaption></figure><p>Episode 3 | validation rules and reading/writing data</p><h3>Introduction</h3><p><em>In the </em><a href="https://blog.mvp-space.com/next-js-meets-firebase-and-mobx-ii-f89a6bbe7521#.hny5xkbq0"><em>last two episodes</em></a><em> we created a basic next.js application and authenticated our users via firebase oauth providers. It’s been pretty boring to far as we don’t even have any data in our firebase yet :’( So let’s change this!</em></p><p>Firebase is all client-side — but as we cannot trust users, we must define validation rules on the server to prevent malicious usage. The validation rules are somehow hard to <a href="https://firebase.google.com/docs/database/security/">read and write</a> but firebase provides a tool to write rules in a better understandable language and compile it down to a big json file again. It’s called <a href="https://github.com/firebase/bolt">bolt</a> and in beta like…forever. I’ve been using it a lot and never had a problem so I assume it’s stable enough to recommend it in this article.</p><h3>Defining validation rules</h3><p>So let’s first install firebase-tools and firebase-bolt:</p><pre>npm install -g firebase-bolt # needed for compiling bolt<br>npm install -g firebase-tools # needed for deploying changes</pre><p>And add the required files:</p><pre>// file: firebase.json<br>{<br>  &quot;database&quot;: {<br>    &quot;rules&quot;: &quot;database.rules.bolt&quot;<br>  }<br>}<br>// file: database.rules.bolt -&gt; we&#39;ll refine this later<br>path / {<br>    read() {true}<br>    write() {true}<br>}</pre><p><em>You can also run </em><em>firebase init to run an interactive shell which creates the firebase.json for you. Keep in mind that hosting on firebase won’t work as you don’t have a server side which is required by next.js for SSR.</em></p><p>You should now be able to run firebase deploy and be presented with a prompt to select your default project. Following this, the database should be deployed (with read and write access for everything)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*yQQ118xZ6OMM-WoqTD6Org.png" /></figure><blockquote>So let’s refine our rules!</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/086794acc9a1c906635fdb5652959412/href">https://medium.com/media/086794acc9a1c906635fdb5652959412/href</a></iframe><p>So now we check if the user who attempts to write is authenticated and if his/her uid equals the {userid}he/she wants to write to. We have two rules here as we want the user to be able to read all his/her stored hashes by accessing the ref /hashes/{uid} and to access single hashes via ref /hashes/{uid}/{hashId}.</p><p><em>We could also have archived this without the second rule, but I plan to implement a share feature later on by modifying the rule on </em><em>hashes/{uid} — so this setup seems to be beneficial for future requirements.</em></p><p>This setup is quite neat, but not perfect as users can now store whatever they want in hashes/{uid}/{id}. To prevent this we refine our bolt rules a little more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29aa28a898d432de2af73eb782cba32e/href">https://medium.com/media/29aa28a898d432de2af73eb782cba32e/href</a></iframe><p>We now force every hashes/{uid}/{id} to be from type Hash which consists of 3 properties:</p><p><strong>CurrentTimestamp</strong>: is a number containing the current timestamp in firebase server-time(alias <strong>now</strong>)</p><p><strong>InitialTimestamp</strong>: is a number containing either the current timestamp or whatever was entered before. This looks a lot like javascript with small differences: we pass this as a reference and instead of returning the value, we directly mutate it inside the function.</p><p><strong>text: </strong>is a String similar to what you would expect in every other language</p><p>With the modifications above we can now only store data structures as follows:</p><pre>{<br>   text: &#39;sometext&#39;,<br>   created: 121414141,<br>   modified: 14141444<br>}</pre><p>We don’t have any validations on the text property yet but we’ll do this later as the application evolves — enough of validation for now, let’s get some data stored!</p><h4>A few words on validation</h4><p><em>You should always do server side validation — even if you trust your users, which you of course shouldn’t do! Validation helps you to maintain data consistency even if you have software bugs.</em></p><p><em>Imagine in the example above that we have a bug somewhere which inserts </em><em>{text: sometext} instead of the full blown object. When we now iterate over the list of hashes and want to display </em><em>hash.created, we are faced with awkward errors. With the validation rules described, we protect ourselves from these type of bugs.</em></p><h3>Retrieving and storing data</h3><p>What we want to do now is create a store which subscribes to the users hashes and provides actions for adding new data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29437fce7ac2f1918eef2d035c14805c/href">https://medium.com/media/29437fce7ac2f1918eef2d035c14805c/href</a></iframe><p>We get the instance of auth store and start subscribing to the data via on(&#39;child_added&#39;)listener, which first retrieves all the data and then only newly added data. Sounds good doesn’t it?</p><blockquote>… sort of :)</blockquote><p>This implementation will be highly error prone as this.authStore.user could be undefined — and start()will not be able to start the subscription at all.</p><p>What luck we have, that mobx has a pretty awesome function called autorun to handle this specific case ❤!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1d6b4ccf5b8c21c235c726f8139e3cc/href">https://medium.com/media/e1d6b4ccf5b8c21c235c726f8139e3cc/href</a></iframe><p>The autorun will fire as soon as observable this.authStore.user changes and disposes itself as soon as this.authStore.user is valid. How cool is that?!</p><p><strong>Edit: </strong><a href="https://medium.com/u/de4496bfa1e2"><strong>Michel Weststrate</strong></a><strong> </strong>pointed out that actually provides a function for exactly this case — autorun once and dispose() itself— which I wasn’t aware of: <a href="https://mobx.js.org/refguide/when.html">https://mobx.js.org/refguide/when.html</a></p><p>With when we can rewrite our code above like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4355b670509cd9301279c9143147049/href">https://medium.com/media/f4355b670509cd9301279c9143147049/href</a></iframe><h3>Using and adding data</h3><p>Now we have all our store logic ready, let’s find a place to initialize the store and listeners by triggering start() .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ba5680abfc150708f1e75d2d580ca7d/href">https://medium.com/media/7ba5680abfc150708f1e75d2d580ca7d/href</a></iframe><p>So here we have an input field which triggers a save action onChange .This is not really optimal as every onChange creates a single entry in the database but we’ll stick with it for the sake of simplicity — <em>if you want to know how i solved it in the app checkout the repository attached at the bottom</em>. Besides that, we currently only check for child_added events. We will not notice change or remove events. Another flaw in our current implementation is that we don’t know if our store is empty or just not yet loaded.</p><p>Firebase provides a few listeners to solve these problems. With ref.once(&#39;value&#39;) we can retrieve the complete reference <strong>once</strong>. This function is especially useful to distinguish between loaded and empty states as we can set a state variable e.g. @observable ready which is set in the promise resolve. Whenever the variable is true, we know that the initial data is loaded(even if it’s empty). child_changed and child_removed work similar to child_added the promise resolves to a data object containing the updated/removed entry. We can now use the promise response to update our mobx store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7d34fdb9789aba79cf38b988bd15d7e/href">https://medium.com/media/a7d34fdb9789aba79cf38b988bd15d7e/href</a></iframe><p><em>I’ve put a lot of ❤ and effort into this article and i’m happy to iterate over/fix/update it :) If you have any feedback, please let me know in the comments! Also, if you have some topic suggestions for further articles, please drop me a message.</em></p><p><em>As always, you can find the current version of code via tag v0.0.3 on github.</em></p><p><a href="https://github.com/sakulstra/firebase-nextjs-mobx/releases/tag/v0.0.3">sakulstra/firebase-nextjs-mobx</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1da7cefa9d25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mvp-space/next-js-meets-firebase-and-mobx-iii-1da7cefa9d25">Next.js meets firebase and mobx | III</a> was originally published in <a href="https://medium.com/mvp-space">MVP Space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js meets Firebase and mobx | II]]></title>
            <link>https://medium.com/mvp-space/next-js-meets-firebase-and-mobx-ii-f89a6bbe7521?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89a6bbe7521</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Thu, 02 Feb 2017 14:39:40 GMT</pubDate>
            <atom:updated>2017-02-06T16:56:05.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgL80wp40Z66vGlClhyI3Q.jpeg" /></figure><h4>Episode 2 | Firebase auth</h4><p><em>In the </em><a href="https://blog.mvp-space.com/next-js-meets-firebase-and-mobx-b3ae90d5b879#.7iggc5b7a"><em>previous article </em></a><em>we created a simple app which automatically shows a random welcome message. We only used mobx and next.js and did not yet touch on firebase.</em></p><p><em>In this article we’ll add authentication via firebases’ google oauth provider and track the user state in a mobx store. It’s pretty similar for all the other solutions offered by firebase (facebook, github, twitter, custom)— feel free to ask if you have any problems.</em></p><h3>Creating the auth store</h3><h4>Enable auth providers in firebase</h4><p>Authentication with firebase is extremely simple: by enabling your desired auth providers in the firebase console, you’re basically ready to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*nZfV7y2CdUa7D7_SUQ5eyA.png" /><figcaption>firebase auth console</figcaption></figure><h4>Connect our app</h4><p>All we have to do now is to initialize our app and make sure it’s only initialized once:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4564c8a695fe99361ca0b1941d3a3cb/href">https://medium.com/media/f4564c8a695fe99361ca0b1941d3a3cb/href</a></iframe><p>Now we can basically start authenticating our users:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9278dc9774ed001d2504212dd5b84088/href">https://medium.com/media/9278dc9774ed001d2504212dd5b84088/href</a></iframe><p>That was far too easy!… so let’s wrap authentication into a mobx store and listen for auth state changes instead of resolving the promise. This way we can persistently store the auth state across pages and even page reloads as the authStateChanged listener will fire automatically!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e32dfa14a50393844b6edb898a9d77c/href">https://medium.com/media/8e32dfa14a50393844b6edb898a9d77c/href</a></iframe><p>We created an observable user object where we store user data — now we can just use it everywhere and change our views dependent on the user-state.</p><blockquote>Isn’t this just awesome? ❤</blockquote><p>Now we can basically use the inject pattern like described in the previous article and embed the observable user object somewhere on the page — e.g. an avatar widget which displays the user’s google+ image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d3128b9efadf3b9f179f757546885f7/href">https://medium.com/media/3d3128b9efadf3b9f179f757546885f7/href</a></iframe><h3>Takeaway</h3><p>Using firebase for basic authentication is ridiculously simple — it’s basically a one-liner and even when spicing things up with mobx and next.js-SSR, things don’t get any more complicated.</p><p>You can find the git repository at this state tagged with v.0.0.2.</p><p><a href="https://github.com/sakulstra/firebase-nextjs-mobx/tree/v0.0.2">sakulstra/firebase-nextjs-mobx</a></p><h3>Miscellaneous</h3><p>We didn’t add a linter last time but <strong>as we all know</strong>:</p><blockquote>Linting is important!</blockquote><p>So let’s do it now! With next.js you can use whatever linter you like. For the sake of making things as easy as possible, let’s go with <a href="http://standardjs.com/rules.html">standard.js</a>, which is used by next.js internally. Just install the module via:</p><pre>npm install standard --save-dev</pre><p>Now you can prefix basically every npm script you like withstandard &amp;&amp; and it will lint your code before running! I personally would recommend using <a href="https://www.npmjs.com/package/eslint-config-airbnb">eslint with airbnb</a> instead, as it ships with a lot of good recommendations for react code patterns. I’m especially a huge fan of <a href="https://github.com/evcohen/eslint-plugin-jsx-a11y">jsx-a11y</a> which helps you with accessibility in react applications. The installation is a bit more complicated as it requires a lot more dependencies than standard.js but i’d say it’s worth it. Just follow the guidance on npmjs and you are good to go.</p><p><em>In the </em><a href="https://blog.mvp-space.com/next-js-meets-firebase-and-mobx-iii-1da7cefa9d25#.sorvjglwp"><em>next episode</em></a><em> we will use the firebase database to store user specific data and create some validation rules. Stay tuned and make sure to subscribe ❤</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89a6bbe7521" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mvp-space/next-js-meets-firebase-and-mobx-ii-f89a6bbe7521">Next.js meets Firebase and mobx | II</a> was originally published in <a href="https://medium.com/mvp-space">MVP Space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js meets Firebase and mobx | I]]></title>
            <link>https://medium.com/mvp-space/next-js-meets-firebase-and-mobx-b3ae90d5b879?source=rss-66486a3abe8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3ae90d5b879</guid>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[ssrs]]></category>
            <dc:creator><![CDATA[sakulstra]]></dc:creator>
            <pubDate>Tue, 31 Jan 2017 13:38:09 GMT</pubDate>
            <atom:updated>2017-04-18T15:33:19.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dt-vObmuuIJqTkjy7nzIBA.jpeg" /></figure><h4>Episode 1 | next.js SSR fundamentals</h4><p><em>Just recently I wrote about not using meteor any more as a “one size fits all” solution — not because meteor is bad — but because there’s other cool stuff which will no doubt convince you by giving it a chance. In this short tutorial series we are going to use the next.js shiny thing in combination with firebase as the database layer and mobx as state manager.</em></p><p><em>This is not a next.js, firebase promo tour :) I will certainly find things which are super annoying and I’ll also report them (until now next.js css handling is irritating to use, but they are working on it).</em></p><h3>Vision</h3><p><em>Over the next few articles we’ll recreate </em><a href="https://tagbag.today/"><em>https://tagbag.today</em></a><em>. The app consists of an individual input field which allows you to enter one single word or sentence per day. Originally, this was a </em>hackathon<em> project from a few months ago using create-react-app, mobx and firebase.</em></p><h3>Topic</h3><p><strong>This article will cover the basics of ssr with mobx and next.js and not touch firebase at all </strong>— if this is boring stuff for you, you may enjoy the followup <a href="https://blog.mvp-space.com/next-js-meets-firebase-and-mobx-ii-f89a6bbe7521#.m1pzsiw31">firebase-auth article</a>.</p><h3>Preparation</h3><p>Let’s first initiate a new project and add all the dependencies we need.</p><pre>npm init<br>npm install --save next react react-dom mobx mobx-react firebase<br>npm install --save-dev babel-plugin-transform-decorators-legacy babel-root-import</pre><p>̶U̶s̶i̶n̶g̶ ̶b̶e̶t̶a̶.̶1̶8̶ ̶h̶e̶r̶e̶ ̶a̶s̶ ̶i̶n̶ ̶b̶e̶t̶a̶.̶1̶9̶/̶2̶0̶ ̶i̶s̶ ̶a̶ ̶b̶u̶g̶ ̶w̶i̶t̶h̶ ̶m̶o̶b̶x̶.̶ ̶I̶’̶l̶l̶ ̶u̶p̶d̶a̶t̶e̶ ̶t̶h̶i̶s̶ ̶p̶o̶s̶t̶ ̶a̶s̶ ̶s̶o̶o̶n̶ ̶a̶s̶ ̶t̶h̶e̶ ̶i̶s̶s̶u̶e̶s̶ ̶a̶r̶e̶ ̶r̶e̶s̶o̶l̶v̶e̶d̶.̶ (issue was resolved in beta.26)</p><h4>Babel</h4><p><strong>The babel plugins are optional, </strong>but I included them as they make things more readable.</p><p><strong><em>Decorators</em></strong><em>: I like the </em><a href="https://babeljs.io/docs/plugins/transform-decorators/"><em>decorators pattern</em></a><em> — if you don’t, just use the wrapper functions instead. The </em><a href="https://mobx.js.org/refguide/observer-component.html"><em>mobx documentation</em></a><em> is pretty awesome so you’ll figure out how to refactor the @ decorators :)</em></p><p><strong><em>Root-import</em></strong><em>: I tend to be confused by relative </em><em>../../../ madness — babel-root-import basically allows you to write </em><em>~/ instead (where ~/is the root of your source code).</em></p><p>Next.js automatically parses your .babelrc so let’s add the file containing the plugins.</p><pre>{<br>  &quot;presets&quot;: [<br>    &quot;next/babel&quot;<br>  ],<br>  &quot;plugins&quot;: [<br>    &quot;transform-decorators-legacy&quot;,<br>    &quot;babel-root-import&quot;<br>  ]<br>}</pre><h4>Next</h4><p>Last thing left is to add the next.js scripts in package.json so that we can easily start/build from command line.</p><pre>”scripts”: {<br> “dev”: “next”,<br> “build”: “next build”,<br> “start”: “next start”<br>},</pre><h3>Getting started With SSR</h3><h4>Why</h4><p>Server-side rendering is an important part of almost every js based web-application. There are two main goals we want to archive:</p><ol><li>serve a useful initial DOM, so that e.g. twitter and facebook can display rich snippets of your website.</li><li>performance — there are edge cases in which ssr can also slow you down, but we won’t go into that</li></ol><p>I won’t go into it too deeply as there are already good articles on why and where to use SSR: just to <a href="https://medium.com/@andrewingram/you-might-need-server-side-rendering-99d252597dfa#.t2vfjaogp">name one</a></p><h4>How</h4><p>SSR basically works like this:</p><ol><li>The server initially generates the DOM and sends it down to the client.</li><li>The client renders the DOM.</li><li>The client waits until resources are loaded and javascript is evaluated.</li></ol><p>Just after that, the client generates the initial DOM itself and compares its hash to the servers one. To avoid unnecessary re-renders the server should generate the same DOM as the client. This means that <strong>the first render must be deterministic!</strong></p><h3>Practice</h3><p>To practice we create a react component which displays a friendly but random welcome message from a set of predefined messages.</p><blockquote>e.g “You look awesome today”.</blockquote><p><strong>You probably would never do this in that way. You’d be better of without mobx for this component — or at least with a non-random initial State. This is over engineered on purpose to reach the rough edges.</strong></p><p>Let’s first create a few files.</p><ol><li>A store which selects a random message in it’s constructor.</li><li>An index.js which acts as entry-page on /</li><li>A component which displays the store message</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/191154e7fd118e93115a55adb270b069/href">https://medium.com/media/191154e7fd118e93115a55adb270b069/href</a></iframe><p>If you run this, it will most probably <em>work </em>but throw errors in the client console. This is due to the fact that we use Math.random() to select a random message inside the constructor. When we now render the initial DOM on the server and then do the same on the client, we get different results — you know, because it’s random =&gt; <strong>non-deterministic!</strong></p><blockquote>So how can we solve this?</blockquote><p>We basically have to pass down the server values and use them on the client to initialize our stores utilizing the getInitialProps({req})function. This is only run on the server on initial pageload and on the client whenever we change the route via next.js Link component. To archive the data passing, we can extend the HomePage component by:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0c1f133ae56a3c3f42b9e2c63a490f1/href">https://medium.com/media/a0c1f133ae56a3c3f42b9e2c63a490f1/href</a></iframe><blockquote>Hint: <em>getInitialProps runs only when used inside a /pages component — you can’t use it for deeper nested components!</em></blockquote><p>And rewrite our store a bit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e354844c053a726e728653709ce4076/href">https://medium.com/media/1e354844c053a726e728653709ce4076/href</a></iframe><p>With getInitialProps we can now differ between server and client and pass server data down to the client via props. So when we initialize on the server we still let the store select a random message, but on the client we use this message to initialize the store to ensure that the first render on the client equals the server render. That’s it. You now have a fully functional SSR with next.js and mobx.</p><h3>Take away</h3><p>Next.js wanted to make SSR simple and effortless. <strong>It did</strong>. If you don’t use fancy stuff like global state managers then you don’t have to do something special and you have SSR out of the box. Otherwise you have to keep some things in mind but it’s still more convenient than all the other solutions i tried yet.</p><p>Keep in mind that on next.js and unlike meteor or create-react-app, you don’t have a single entry point. Every page in your pages folder is an entry point which has to generate a valid initial state on its own. This means that when you have some global states in your code — like the one i described above — you have to ensure that <strong>every</strong> page and not only the index.js initializes your states properly.</p><p>If you have a web-app with a lot of pages, you probably want to keep code duplication to a minimum. Therefore, I wrote a little HOC which basically initializes the page and allows me to use es6 classes for pages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b45c02860fa645bd6b03dee8c0f727ec/href">https://medium.com/media/b45c02860fa645bd6b03dee8c0f727ec/href</a></iframe><p>I’ve put a lot of ❤ and effort in this article and i’m happy to iterate over/fix/update it :) If you have any feedback, please let me know in the comments!</p><p><a href="https://github.com/sakulstra/firebase-nextjs-mobx/tree/v0.0.1">sakulstra/firebase-nextjs-mobx</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3ae90d5b879" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mvp-space/next-js-meets-firebase-and-mobx-b3ae90d5b879">Next.js meets Firebase and mobx | I</a> was originally published in <a href="https://medium.com/mvp-space">MVP Space</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>