<?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 Nicola Molinari on Medium]]></title>
        <description><![CDATA[Stories by Nicola Molinari on Medium]]></description>
        <link>https://medium.com/@emmenko?source=rss-bfc7be47900d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vgqicOiU1Tj1-64OY4AKmw.jpeg</url>
            <title>Stories by Nicola Molinari on Medium</title>
            <link>https://medium.com/@emmenko?source=rss-bfc7be47900d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 09:24:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emmenko/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[Scaling our Frontend architecture with our team's growth]]></title>
            <link>https://medium.com/commercetools-tech/scaling-our-frontend-architecture-with-our-teams-growth-9ecd36abcece?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ecd36abcece</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[team-productivity]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Tue, 26 Jul 2022 14:07:04 GMT</pubDate>
            <atom:updated>2022-07-26T14:07:04.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Looking up at a spiral staircase with many light bulbs hanging in the middle." src="https://cdn-images-1.medium.com/max/1024/0*EbdBMsKC_HD-Qc5_" /><figcaption>Photo by <a href="https://unsplash.com/@santesson89?utm_source=medium&amp;utm_medium=referral">Andrea De Santis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Over the last several years the commercetools team and product witnessed an exponential growth that required organisational changes as well as a strong technical foundation to accompany the current and future growth plans.</p><p>The <a href="https://commercetools.com/features/business-tooling">Merchant Center</a>, which is our main web application for administrating the project data in our <a href="https://commercetools.com/features/commerce">Composable Commerce APIs</a>, was no exception to that growth.</p><p>When we started developing the Merchant Center application we were a small team of frontend developers and designers. We had our own repository, our own process, our own deployment pipeline, etc.</p><p>The Merchant Center was a Single-Page Application using React.js and we developed most of the UI components on our own, following our design guidelines.</p><p>Eventually the team and requirements started growing to the point where working as one team, in one codebase, was not feasible anymore.</p><h3>How can we scale up our technology together with our teams?</h3><p>Some of the organizational changes in the company were related to the structure of the teams, more specifically to having <a href="https://techblog.commercetools.com/vertical-teams-and-collective-thinking-4d4943112588">vertical teams</a>. A vertical team is an independent team that focuses and owns a specific domain of the company’s product(s) and consists of different roles required to work on that domain. Most of the time teams have the following roles: Product Manager, Engineering Manager, Designer, Frontend Engineer, Backend Engineer, Agile Coach.</p><p>For the Merchant Center frontend application it meant that multiple teams (specifically the Frontend Engineers of those teams) will contribute to the development following their own requirements and processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*drKNVfxNXSzE_ZGB" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>So how can multiple contributors work on the same codebase without stepping on each other’s toes? Who decides when to deploy? What about merge conflicts?</em></p><p>Obviously our repository setup, our development and deployment processes, our tooling, all of that needed to be changed as well to align with the structural changes of the teams.</p><p>At the same time, our enterprise users and customers were showing interest in being able to customise parts of the Merchant Center to tailor some of their specific business requirements.</p><p>With similarities between internal and external requirements we saw a chance of addressing both problems with one solution.<br>This is the story of how <a href="https://docs.commercetools.com/custom-applications">Custom Applications</a> came to be.</p><h3>Introducing Custom Applications</h3><p>With our basic requirements around teams and customisability we started envisioning the future of the Merchant Center and more generically of frontend development.</p><p>We identified the following points:</p><ul><li>Teams should develop and own independent parts of the Merchant Center.</li><li>Teams should deploy and release parts of the the Merchant Center without deployment dependencies.</li><li>Teams should focus on building user features by using the same set of shared development tools.</li><li>Teams should focus on implementing consistent and usable user interfaces by using the same set of shared UI components and by following the same UX guidelines.</li><li>Our external users and customers should be able to do all of the above.</li></ul><p>One thing was clear: we needed to split up the Merchant Center application into multiple little ones.</p><p><em>Wait, isn’t all of this what </em><a href="https://micro-frontends.org/"><em>Micro Frontends architecture</em></a><em> is about?<br></em>Yes, conceptually very similar but also not, as there are different ways to implement it.</p><p>In a nutshell, the idea is to have different parts of the application developed and deployed independently while the end-user consumes and interacts with the application as if it was one.</p><p>This split fits also with the organizational changes to vertical teams, where a team owns one or more parts of the application. For example, our Product and Catalog Management team works on the products and categories applications while the Checkout team works on orders and customers.</p><p>Each application is developed and hosted independently and on production there is a routing component that sits in front of every application and determines which application should be rendered using the following URL scheme:</p><pre>https://mc.&lt;domain&gt;.com/:projectKey/:entryPointUriPath</pre><p>The projectKey identifies the Project of the user while the entryPointUriPath identifies the application to be served.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m65nghJ8GbzMFC3DtXzIkg.png" /><figcaption>Showing the routing component to serve a specific application.</figcaption></figure><p>To ensure an overall consistency across the different applications, there are common parts that must be used by every application. For example, the main application layout and the basic rendering logic are implemented as a shared component that each application must use. We call it the &lt;ApplicationShell&gt; .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBz9UC_32y1Plp_C7Z17xA.png" /><figcaption>The &lt;ApplicationShell&gt; implements the general application layout.</figcaption></figure><h3>Planning the work</h3><p>After identifying the long term vision of our frontend infrastructure we needed to execute the plan. At the same time all the technical and structural changes had to be performed in a backwards compatible way to avoid disrupting the existing application.</p><h4>Going monorepo</h4><p>As a first chunk of work, we started splitting up the codebase into multiple packages and created a proper <a href="https://en.wikipedia.org/wiki/Monorepo">monorepo</a>. This required also to move many of the UI components and utilities used across the applications into shared packages within the same monorepo.</p><p>Naturally, our CI/CD pipeline also needed to be adjusted and, after many iterations, we ended up with a complex but effective multi-pipeline workflow to test, build and deploy each application independently.</p><h4>Sharing tools and components</h4><p>The second phase of the plan was focused on enabling this kind of development to external users. To do so we needed to do two main things:</p><ul><li>Open source many of our UI components to develop the applications.</li><li>Open source the tooling to develop, test and build the applications.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*13QUWwtRInHR0N5u" /><figcaption>Photo by <a href="https://unsplash.com/es/@hnhmarketing?utm_source=medium&amp;utm_medium=referral">Hunter Haley</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Why open sourcing?</em></p><p>For one thing, we wanted our users to have easy access to the same tools and components that we were using internally but also to establish a common place around developing Merchant Center applications and encourage contributions.</p><p>And so we created two public repositories: <a href="https://github.com/commercetools/ui-kit">UI Kit</a> and <a href="https://github.com/commercetools/merchant-center-application-kit">Application Kit</a>.</p><p>The UI Kit is the place where we develop our design system and implement all basic UI components such as buttons, inputs, notifications, table, etc. All these components are the building blocks for developing the UI in the Merchant Center.</p><p>The Application Kit includes all the tooling for developing, testing and building applications.</p><p>All these packages are then published to the NPM registry and can be consumed by anyone. Obviously we use all of them internally as well.</p><p>With the second phase reaching a mature point, it was time to officially enable the development of these UI applications to external users.<br><strong>This product feature is known as Custom Applications.</strong></p><blockquote>A Custom Application is a set of UI tools and components to extend the existing functionality of the commercetools APIs and the Merchant Center.<br>Merchants can implement specific business requirements in a Custom Application and use it in their Merchant Center Projects by configuring and installing Custom Applications into their commercetools Organizations.<br>A Custom Application is developed and managed by merchants.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9i3GNqfI94OsN0AeW1Mrhg.png" /><figcaption>High-level overview of using Custom Applications.</figcaption></figure><p>To allow users to integrate their Custom Applications into the Merchant Center we had to build a bunch of other things like <a href="https://docs.commercetools.com/merchant-center/managing-custom-applications">storing the configuration of Custom Applications via a dedicated UI workflow</a>. A user will then develop and host a Custom Application to a hosting service of their choice and provide the URL link in the configuration that points to the hosted application.</p><p>The Merchant Center routing service (as mentioned before) ensures that the matching application is served correctly, no matter if it’s an application developed within commercetools or by external users.</p><p>Custom Applications evolved a lot over the years but the main vision remained the same: <strong>to empower teams to independently contribute to the Merchant Center and to focus on delivering customer value</strong>.</p><h3>Looking back</h3><p>Scaling our frontend ecosystem with our multiple internal teams (and external users) was definitely a lot of work but a necessary effort to ensure that teams remain productive and focus on what’s important within their business domain. Similarly, external users can do the same and focus on building and delivering custom solutions tailored to their business requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4n8A5KWFOpuG1TFS" /><figcaption>Photo by <a href="https://unsplash.com/@christopher__burns?utm_source=medium&amp;utm_medium=referral">Christopher Burns</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Eating_your_own_dog_food">Dogfooding</a> the tools and components that our customers use allows us to constantly keep working and improving them, even though at times the process might seem a bit cumbersome. However, with proper automation tools and processes things usually go smooth. In addition to that, we also plan and release features and changes carefully and well tested as both our internal teams and external users would be affected the same way.</p><p>As for our teams, the flexibility of working on different parts of the Merchant Center independently is a great benefit. Not only that but all the tools and UI components that we provide allow them to focus on delivering useful and usable features fast. For example, by using our UI Kit components library there is less to no need to implement custom CSS styles.</p><p>However, it’s not all sunshine and roses. Working with this kind of setup, especially in a monorepo, has it’s own pitfalls and downsides as well.</p><p>For instance, an ever growing monorepo comes with its own inherited issues. More packages and dependencies to maintain, more teams working on it, more development activity, more CI load.</p><p>Updating dependencies can be at times frustrating as there is a larger surface area where things could suddenly fail, in particular to the parts of the codebase without a regular maintenance.</p><p>On the other hand, introducing new tools, new libraries or updates to existing ones can be as challenging or even impossible due to the fact that the entire codebase is affected and so are the teams. For example, trying out the latest React version in one application would likely cause version conflicts and weird errors in the other applications.</p><p>Another important point to consider is about ownership of the parts of the codebase in the monorepo. For example, applications are easily assigned to teams as owners but for other parts is not always clear who the owner is.</p><p><em>When implementing a shared component used between multiple applications, who owns it?</em></p><p>Ownership is important in terms of maintenance and helps also with reviewing contributions and changes to that code.</p><h3>Conclusion</h3><p>Scaling the frontend architecture with your teams does indeed require technical and organizational changes and you need to find a balance about the setup, the tooling and the team’s processes.</p><p>Using a monorepo has many benefits and for us it was and still is a valuable setup for many of our teams and projects. It also helps with consistency and to easily share and keep things up-to-date.</p><p>However, as the organization and codebase grow, there might be issues and limitations to tackle in order to find that balance. For us it meant to invest in things like improving our CI/CD pipeline, having better automation tools, improving our integration and acceptance tests, but also to define clear ownership, to have cross-team collaborations via the Front-Line Dev and the Frontend Chapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xm-ZKeCDX8Yd3DcL" /><figcaption>Photo by <a href="https://unsplash.com/@mphotographym?utm_source=medium&amp;utm_medium=referral">Moritz Mentges</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We are also looking at other ways to facilitate that growth and collaboration between teams. For instance, we are currently evaluating and trying “<em>breaking up</em>” our main monorepo to allow teams to have more focused spaces to work on without some of the limitations of a monorepo mentioned before.</p><p>On the other hand, this forces us to invest more into tooling and sharing parts of the stack that is required across repositories.</p><p>At the end of the day, <strong>find the balance </strong>to what works best for your structure and teams and <strong>invest in tooling and processes</strong> to help you with that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ecd36abcece" width="1" height="1" alt=""><hr><p><a href="https://medium.com/commercetools-tech/scaling-our-frontend-architecture-with-our-teams-growth-9ecd36abcece">Scaling our Frontend architecture with our team&#39;s growth</a> was originally published in <a href="https://medium.com/commercetools-tech">commercetools tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing JavaScript applications with confidence]]></title>
            <link>https://medium.com/commercetools-tech/testing-javascript-applications-with-confidence-ff539c4a25f2?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff539c4a25f2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[confidence]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Thu, 29 Oct 2020 16:01:22 GMT</pubDate>
            <atom:updated>2020-10-29T16:01:22.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z2f9qmfArnbGesge" /><figcaption>Photo by <a href="https://unsplash.com/@muzammilo?utm_source=medium&amp;utm_medium=referral">Muzammil Soorma</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is undeniable that a lot has changed in the last few years in the world of JavaScript. This should not come as a surprise. We are particularly excited to see a lot of progress in the way we write and think about testing in the JavaScript ecosystem.</p><p>If we take a small step back, about 3–4 years ago the landscape was already promising. Test runners like <a href="https://jestjs.io/">Jest</a> were already quite popular, providing a good Developer Experience, and testing React components was pretty much dictated by <a href="https://enzymejs.github.io/enzyme/">Enzyme</a>.</p><p>We at <a href="https://commercetools.com/">commercetools</a> were pretty thrilled about the tooling we had at our disposal and we tried to establish some best practices in our team on how to write good unit tests. We wrote about it in this article: <a href="https://techblog.commercetools.com/testing-in-react-best-practices-tips-and-tricks-577bb98845cd">Testing in React: best practices, tips and tricks</a>.</p><p>However, if I reread this now, my reaction would be to disapprove most of what the article is preaching. Yes really, as this just shows how much things have changed since then.</p><p>Luckily they have changed for the better! Let’s have a look at what exactly has changed.</p><h3>Testing mentality</h3><p>We mentioned before that we had good testing tools at our disposal. What we believe was lacking was the fundamental mentality on how we should approach writing and thinking about testing.</p><p>Thanks to the community effort, and to the teachings of <a href="https://kentcdodds.com/">Kent C. Dodds</a>, the way we test JavaScript applications has radically changed.</p><blockquote>The more your tests resemble the way your software is used, the more confidence they can give you.</blockquote><p>The key takeaway with this, is how we think about what needs to be tested. Traditionally the majority of us (we assume) wrote tests that also tested most of the internals, for example, of UI components, leading to frustration and problems when having to refactor code, as both the implementation and the tests had to be changed. After all, one of the main reasons to write tests is to be able to change to the implementation in the future with confidence.</p><p>As a result, tests should only be concerned about <strong>what the end-user sees and can interact with</strong>. Therefore, tests are agnostic of the implementation details, allowing much more confident refactoring as only the implementation needs to be changed, not the end result and thus the tests.</p><p>To help follow this mentality and enforce best practices, the <a href="https://testing-library.com/docs/intro">DOM Testing Library &amp; Co.</a> were born.</p><p>If you wish to know more about this topics, check out the following resources:</p><ul><li><a href="https://kentcdodds.com/blog/introducing-the-react-testing-library">https://kentcdodds.com/blog/introducing-the-react-testing-library</a></li><li><a href="https://testingjavascript.com/">https://testingjavascript.com/</a></li><li><a href="https://kentcdodds.com/testing/">https://kentcdodds.com/testing/</a></li></ul><p>For us at <a href="https://commercetools.com/">commercetools</a> this helped a lot to rethink and re-evaluate how we want to write tests. Most importantly we have seen the following benefits:</p><ul><li>We have much more <strong>confidence</strong> when refactoring existing code or implementing new features, as we can rely on stable tests.</li><li>We don’t write tests for each component but instead more at the application level, giving us more depth coverage of what is being tested. This implicitly helps us to also test things like routing.</li><li>The DOM Testing Library promotes writing and testing <strong>accessible components</strong>.</li></ul><h3>Data fetching and mocking</h3><p>Jest already provides a good mocking system. However, it leaves a lot of room for testing data fetching in components.</p><p>We at <a href="https://commercetools.com/">commercetools</a> primarily use GraphQL and Apollo, especially in our frontend applications.<br>Apollo has a <a href="https://www.apollographql.com/docs/react/development-testing/testing/#mockedprovider">Mocked Provider</a> component that can be used to mock the GraphQL queries. This is extremely useful when testing things at the application level and in turn plays very well with the DOM Testing Library approach.</p><p>Still, mocking the GraphQL queries with the Apollo <a href="https://www.apollographql.com/docs/react/development-testing/testing/#mockedprovider">Mocked Provider</a> has shown its own downsides. One reason being that matching requests can get quite verbose and different scenarios can be hard to distinguish, like having partial data, or different HTTP status codes. This is partly due to the nature of not being able to mock close enough to the network level, as it relies on Apollo itself.</p><p>We can also argue that using the Apollo mocks requires to know the implementation details of the requests, which ideally is not what we should be aiming for (as mentioned before).</p><p>Therefore, a better option would be to mock directly at the network level and thus removing the need for Apollo to dictate the mocking behavior. Using libraries such as <a href="https://www.npmjs.com/package/xhr-mock">xhr-mock</a> we can intercept requests and handle them according to predefined matching rules. For example for GraphQL requests we can match GraphQL queries by their operation name. Apollo also offers tools to automatically create mock data based on the GraphQL schema.</p><p>This approach is more inline with the mentality of testing how the application behaves rather than how the application is implemented.</p><h4>Mock Service Worker</h4><p>Luckily, to make it easier to mock requests at the network level, there is a new library called <a href="https://mswjs.io/">Mock Service Worker</a> (MSW).</p><blockquote>By bringing the ability of Service Workers to capture requests for the purpose of caching, Mock Service Worker enables API mocking on the highest level of the network communication chain. It is the closest thing to a mocking server without having to create one.</blockquote><p>We at <a href="https://commercetools.com/">commercetools</a> have been looking and trying out this library in the past months and so far we have been extremely happy with it.<br>We have found that the test setup to mock the network requests is much simpler then, for example, using Apollo mocks. It also works for both GraphQL and REST requests, so the same mocking approach can be used for both. Lastly, MSW can be used in both the browser and a Node.js environment, removing the need to know and use different libraries.</p><p>Migrating to use MSW was also pretty much seamless as all we had to do was replace the requests mock setup and the tests kept working as before.</p><p>Furthermore, besides some of the nice features of MSW, the core idea of MSW follows the same testing principles that we discussed before: <a href="https://mswjs.io/docs/recipes/request-assertions">test how the application behaves rather than how it’s built</a>.</p><blockquote>Instead of asserting that a request was made, or had the correct data, test how your application reacted to that request.</blockquote><p>However, we can still perform validations of incoming requests by <a href="https://mswjs.io/docs/recipes/request-assertions#include-failure-scenarios">sending an error response</a>.</p><p>We can only recommend checking it out and giving it a try.</p><h4>Test data</h4><p>Another important aspect of testing is about the underlying test data. Oftentimes you end up writing the same “fake” data in a bunch of tests, maybe also omitting certain fields because they are not used in that specific test scenario. Plus, the data might not even cover real world scenarios, thus making most tests almost meaningless.</p><p>This process is very verbose and error prone and we at <a href="https://commercetools.com/">commercetools</a> have bumped into these issues more and more in the past years. With the increasing number of APIs in our platform, having to maintain tests in such a way is not scalable at all.</p><p>So we decided to tackle this issue and started an initiative to have <strong>generated test data</strong>.<br>In short, the idea is that every entity in our platform APIs is defined as a test data model. A model contains all the available fields for that entity, most of which are generated as random values using the <a href="https://www.npmjs.com/package/faker">faker</a> library.<br>We also have a concept called transformer where we can derive a different representation of the base model, for example for a GraphQL-like or REST-like shape.</p><p>Combining this with the testing tools like DOM Testing Library and MSW results in a very powerful combo which makes the tests setup simpler allowing us to focus more on what matters: writing reliable tests with confidence.</p><h3>Conclusion</h3><p>The approach you take on testing your application is crucial and most importantly the tests should <strong>help you and your team to have the right level of confidence</strong> rather than getting in the way.</p><p>At <a href="https://commercetools.com/">commercetools</a> we are very happy with how we continuously look to improve our testing approach, as it has proven useful a lot of times and has helped us be more productive and yes, more confident. Having a good level of confidence is what also enables us to do things like continuous deployments (deployment train).</p><p>If most of this sounds new to you, we really recommend that you start rethinking how you can approach testing your application and UI components, and choose the tools suggested to help you write resilient and meaningful tests.<br>Most importantly, you don’t have to rewrite everything at once. For example, we recommend rewriting the tests from scratch based on the existing test scenarios and remove all the previous tests related to that functionality, rather than trying to rewrite the previous tests.</p><p>For instance, we still have parts of our codebase that use the “legacy testing approach” and that causes trouble from time to time. Whenever we have a chance to, we write the tests for that part of functionality as new tests and remove the previous test files.</p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff539c4a25f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/commercetools-tech/testing-javascript-applications-with-confidence-ff539c4a25f2">Testing JavaScript applications with confidence</a> was originally published in <a href="https://medium.com/commercetools-tech">commercetools tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adopting Changesets for release and changelog automation]]></title>
            <link>https://medium.com/commercetools-tech/adopting-changesets-for-release-and-changelog-automation-cbdc36bbdc10?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbdc36bbdc10</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[release-notes]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[changelog]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Wed, 27 May 2020 11:24:47 GMT</pubDate>
            <atom:updated>2020-05-27T11:24:47.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eoU1-I9h9bl0SWG5" /><figcaption>Photo by <a href="https://unsplash.com/@austinchan?utm_source=medium&amp;utm_medium=referral">Austin Chan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When working on Open Source Software (OSS), documentation is a crucial part of the project. It helps to ease adoption by providing in-depth descriptions on how to get started, how to use advanced functionalities, to communicate best practices with examples, and so on.</p><p>However, documentation does not end with an initial release. It continuously evolves during the life-cycle of the project. New versions can contain new features, bug fixes, improvements, or even breaking changes. All of that needs to be documented and communicated properly.</p><h3>How can we communicate changes to the users?</h3><p>Traditionally, people expect to find this information in a file called CHANGELOG.md, or in <a href="https://help.github.com/en/github/administering-a-repository/about-releases">GitHub Releases</a>.</p><p>A release can include different things: links to commits or Pull Requests related to the new version, contextual information and code examples, emojis, and so on. At the end of the day, it’s just Markdown and it&#39;s up to the maintainers of the project to provide necessary and useful information.</p><p>Certain parts of the release notes often require manual content and review, while other parts can be automated.</p><h3>Automating all the things</h3><p>Ideally, the release notes for your project should have some kind of consistency. This is where tools and automation can come in to help.</p><p>This becomes very useful particularly in large projects, or in monorepositories (or monorepos for short) with a lot of packages.</p><p>For instance, the release process including generating release notes can be automated and seamlessly integrated into your Continuous Integration (CI) system. Some popular examples include <a href="https://github.com/semantic-release/semantic-release">Semantic Releases</a>, <a href="https://github.com/lerna/lerna">Lerna</a> with <a href="https://github.com/lerna/lerna-changelog">Lerna Changelog</a>, and many other community projects.</p><p>These automation tools can provide by default a lot of context about the release, such as references to Pull Requests, commit messages, list of contributors, etc.</p><h3>Release Notes in a Monorepos</h3><p>At <a href="https://github.com/commercetools/">commercetools</a>, we have a bunch of open source monorepositories and as such, we needed a way to make the process simple and effective for all the contributors.</p><p>So far we’ve been using <a href="https://github.com/lerna/lerna">Lerna</a> and <a href="https://github.com/lerna/lerna-changelog">Lerna Changelog</a>. The tools work great and they are very helpful to manage and release multiple packages within the same repository.</p><p>However, certain steps have to be taken during the release process to ensure that the release notes are properly documented.</p><p>For instance, merged Pull Requests that should be included in the release notes must have a label assigned to them. This allows <a href="https://github.com/lerna/lerna-changelog">Lerna Changelog</a> to reference the Pull Request and group it appropriately in the generated release notes.</p><p>After running the changelog command, we need to manually add the output to the CHANGELOG.md file and in GitHub Releases. We don’t want to have this step fully automated, as sometimes we need to provide more contextual information — which requires manual writing.</p><p>While it’s very helpful and nice, the publication of release notes isn’t fully automated and relies on the user knowing what to do.</p><p>This could be a bit of an issue for contributors who aren’t very familiar with the release process or are afraid to mess things up, so they end up getting discouraged from doing it.</p><h3>Using Changesets</h3><p>Recently I’ve been looking into another interesting project called <a href="https://github.com/atlassian/changesets">Changesets</a>. It’s described as:</p><blockquote>A way to manage your versioning and changelogs with a focus on monorepos</blockquote><p>It takes a bit of a different approach and it’s designed to work within a monorepository, which is very important for us.</p><p>There is a nice <a href="https://github.com/atlassian/changesets/blob/master/docs/detailed-explanation.md">documentation page</a> about the motivation and design principles behind the project. I recommend to go check it out.</p><p>What I like about the project is that you <strong>document the changes as you develop them.</strong> Those changes then dictate which packages will eventually be released. Additionally, each package gets its own CHANGELOG.md file, which is also nice and helpful when searching for changes of a specific package.</p><h4>Automation Bots</h4><p>Using the changesets command-line interface (CLI) on its own is still not super useful. However, combine it with the <a href="https://github.com/apps/changeset-bot">Changesets GitHub App</a> and the <a href="https://github.com/changesets/action">Changesets GitHub Action</a>, and suddenly you have a powerful killer feature.</p><p>The new workflow roughly looks like this:</p><ul><li>You open a Pull Request and include a changeset file with a proper documentation of the changes and the desired semantic version bump (<em>major, minor, patch</em>).</li><li>Merging the Pull Request does not trigger any release, instead a new Pull Request named Version Packages is created by the <a href="https://github.com/changesets/action">Changeset GitHub Action</a> and includes the release plan. The release plan bumps the versions of all packages and dependent packages affected by the changeset files present in the repository, as well as the updated CHANGELOG.md files in each package.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TL08rOAelPc5bFpLfb-eVg.png" /></figure><ul><li>When it’s time to trigger a release, you simply merge the Version Packages Pull Request. The <a href="https://github.com/changesets/action">Changesets GitHub Action</a> takes care of doing the actual release, by publishing the packages to NPM, creating the git tags and the GitHub Release notes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bywUoE-VCmzVuMLWFhK1bQ.png" /></figure><blockquote>The steps mentioned above assume that you have installed the <a href="https://github.com/apps/changeset-bot">Changesets GitHub App</a> and configured the <a href="https://github.com/changesets/action">Changesets GitHub Action</a>.</blockquote><h3>Conclusion</h3><p>The <a href="https://github.com/atlassian/changesets">Changesets</a> project gets many points right, compared to how we previously worked with versioning and release notes, and it fits perfectly with the monorepository workflow that we have. It also simplifies the process of releasing and documenting version changes significantly, making that much more accessible to contributors of our projects.</p><p>We can only recommend to try it out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbdc36bbdc10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/commercetools-tech/adopting-changesets-for-release-and-changelog-automation-cbdc36bbdc10">Adopting Changesets for release and changelog automation</a> was originally published in <a href="https://medium.com/commercetools-tech">commercetools tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Patching Lobotomized Owl selector for Emotion SSR]]></title>
            <link>https://emmenko.medium.com/patching-lobotomized-owl-selector-for-emotion-ssr-5a582a3c424c?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a582a3c424c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[gatsby]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 09:34:59 GMT</pubDate>
            <atom:updated>2021-01-07T10:49:56.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FY_WpxkuLSubQZ-S" /><figcaption>Photo by <a href="https://unsplash.com/@quinoal?utm_source=medium&amp;utm_medium=referral">Quino Al</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I’ve been working on a <a href="https://github.com/commercetools/commercetools-docs-kit">Gatsby theme website</a> to enable teams at <a href="https://techblog.commercetools.com/">commercetools</a> to write documentation for different parts of the product. The Gatsby theme uses some of our <a href="https://github.com/commercetools/ui-kit">UI-Kit</a> Design System elements and UI components, some of which are used for layout purposes. We call them <strong>Spacings</strong> components and they all use a pretty interesting CSS selector: the <a href="https://alistapart.com/article/axiomatic-css-and-lobotomized-owls/">Lobotomized Owl</a> selector.</p><pre>&gt; * + * {}</pre><p>A (ex)colleague of mine <a href="https://medium.com/hackernoon/margin-or-padding-f5252562313">introduced this to me some years ago</a> and since then I’ve been using it wherever I can. It just <strong>makes things way easier</strong> to style<strong>.</strong></p><p>Our UI components, and the Gatsby theme, use the <a href="https://emotion.sh/">Emotion</a> CSS-in-JS library for styling purposes. It’s a wonderful library to work with and we’ve been quite happy with it so far.</p><h3>Undesired style effects</h3><p>At some point during the development of the website, we bumped into an issue in production mode: most of the elements on the page were “moving” after the page was loaded. At first it appeared that we were experiencing the infamous <strong>FOUC</strong> (Flash Of Unstyled Content).</p><p>Upon further investigation, it was clear that the issue was caused by how Emotion deals with SSR (Server-Side Rendering) in relation to the Lobotomized Owl selector. Unfortunately, this is a known issue for Emotion, see <a href="https://github.com/emotion-js/emotion/issues/1178">GitHub issue about this topic</a>.</p><p>To be able to find a viable solution, we need to understand the problem at hand first.</p><h4>How Emotion SSR works</h4><p>Emotion comes with <a href="https://emotion.sh/docs/ssr">support for SSR</a>, which is necessary for tools like Gatsby to be able to generate static pages. The browser renders the static HTML markup first, then Gatsby client side JavaScript kicks in and hydrates the page which is then managed by JavaScript and React.</p><blockquote>Server side rendering in Emotion 10 has two approaches, each with their own trade-offs. The default approach works with streaming and requires no additional configuration, but does not work with nth child or similar selectors. It’s strongly recommended that you use the default approach unless you need nth child or similar selectors.</blockquote><p>The static page contains inline &lt;style&gt; elements injected by Emotion, next to each HTML element that requires those styles. When the page is loaded and hydrated, Emotion moves all those inline &lt;style&gt; elements to the &lt;head&gt; of the document. This is what makes the elements “move” after the page is hydrated.</p><p>The reason is simple: elements that implement the Lobotomized Owl selector might have undesired &lt;style&gt; elements as children, because of Emotion SSR. This disrupts the CSS selector to count a wrong element in the adjacent siblings. For example, elements applying a margin-top to each children besides the first one will possibly result in the first element having the margin as well, only to be removed once the injected &lt;style&gt; elements get moved away.</p><pre>&lt;div class=&quot;css-161caka e1gnsc3u4&quot;&gt;<br>  <strong>&lt;style data-emotion-css&quot;&quot;&gt;.css-1yzfhzg{font-size:3rem}&lt;/style&gt;</strong><br>  &lt;h1 class=&quot;css-1yzfhzg&quot;&gt;Hello World&lt;/h1&gt;<br>  &lt;div&gt;How are we doing?&lt;/div&gt;<br>&lt;/div&gt;</pre><p>In the example above, the &lt;h1&gt; element gets the margin-top as long as the &lt;style&gt; element stays there.</p><h3>Approaching the solution</h3><p>Ideally the &lt;style&gt; elements injected by Emotion should not be there and interfere with the CSS selectors. This is a conscious choice by the Emotion team and therefore we need to find a different solution.</p><p>The problem with the Lobotomized Owl selector in this scenario is that it uses the <strong>adjacent sibling combinator</strong> +.</p><blockquote>The <strong>adjacent sibling combinator</strong> (+) separates two selectors and matches the second element only if it <em>immediately</em> follows the first element, and both are children of the same parent element.</blockquote><p>In other words, the Lobotomized Owl selector picks all the sibling elements except the first one, because it does not have any sibling element before that.</p><h4>Excluding the style element</h4><p>What we need is a CSS selector that <strong>excludes</strong> the style element from the results, thus keeping the correct styles as they were intended to.</p><p>To exclude something from a selector we can use the :not pseudo-class and apply it to the style element: :not(style).</p><p>Ideally the selector should read: <em>select all sibling elements that follow another element, except if the element is a </em><em>style element</em>.</p><p>Possible combinations of the new selector are:</p><pre>&gt; *:<strong>not(style)</strong> + * {}<br>&gt; * + *<strong>:not(style)</strong> {}<br>&gt; *<strong>:not(style)</strong> + *<strong>:not(style)</strong> {}</pre><p>Which one works? The answer: <strong>none</strong> of them. 😱</p><p>Each selector has a scenario where it does not work as it should (see Codesandbox below).</p><h4>Understanding the general sibling combinator</h4><p>How can we solve this problem? After a bit of research I came across another combinator: the <strong>general sibling combinator</strong>.</p><blockquote>The <strong>general sibling combinator</strong> (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element.</blockquote><p>If we modify the Lobotomized Owl selector with this combinator and try to exclude the style element, we have:</p><pre>&gt; *:not(style) <strong>~</strong> * {}<br>&gt; * <strong>~</strong> *:not(style) {}<br>&gt; *:not(style) <strong>~</strong> *:not(style) {}</pre><p>Does it work now? <strong>Yes</strong>, it does! 🙌</p><p>In the Codesandbox below you can see a comparison of the results of using both combinators with different scenarios. The two green selectors on the rigth side are the winners of our experiment, which successfully apply the styles to the elements regardless of the position of the &lt;style&gt; element.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F8jjlm&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F8jjlm&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F8jjlm%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/67c53b61cf706961d5f1240e9d857c53/href">https://medium.com/media/67c53b61cf706961d5f1240e9d857c53/href</a></iframe><h3>Patching Emotion SSR in Gatsby</h3><p>How can we make this work in our Gatsby website? One approach is to directly patch the CSS selectors but it’s kind of error prone and not ideal.</p><p>A less nicer but effective approach is to patch the generated static HTML and CSS. To do so, we need to follow the <a href="https://emotion.sh/docs/ssr#advanced-approach">advanced approach</a> described in the Emotion docs. Then we can patch the Lobotomized Owl selectors by doing a search-replace on the HTML and CSS strings, before passing them to Gatsby.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83b79b9414c78d7a837898988a02706e/href">https://medium.com/media/83b79b9414c78d7a837898988a02706e/href</a></iframe><h3>Conclusion</h3><p>While this solution seems to work, I wish there is a more robust approach to deal with this issue. Maybe <a href="https://github.com/emotion-js/emotion/issues/1606">Emotion v11</a> will reserve some positive surprises.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a582a3c424c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prisma Horizontal Scaling: a practical guide ]]></title>
            <link>https://medium.com/commercetools-tech/prisma-horizontal-scaling-a-practical-guide-3a05833d4fc3?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a05833d4fc3</guid>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 15:30:00 GMT</pubDate>
            <atom:updated>2018-10-23T15:30:00.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7rp_KZIgMFyirYh_" /><figcaption>“green frame photography” by <a href="https://unsplash.com/@gabrielediwald?utm_source=medium&amp;utm_medium=referral">Gabriele Diwald</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re reading this, you probably heard about <a href="https://www.prisma.io/">Prisma</a>. If not, you will find some references about it at the end of this article.</p><blockquote>Prisma is a performant <strong>open-source GraphQL ORM-like*</strong> layer doing the heavy lifting in your GraphQL server. Prisma is the glue between your GraphQL API and database.</blockquote><p>Assuming that you are now familiar with Prisma and are eager to use it, you are quickly confronted with a question: “<em>Should I be hosting my own Prisma cluster or use the managed version Prisma Cloud?</em>”.</p><p>We also faced this question and the answer depends on your company and project’s needs. We needed to use our own database while wanting to have full control over the deployment in our already existing Kubernetes cluster. Given this context we wanted to share our experience on the <strong>self-hosting part</strong> and <strong>how we manage it</strong> here at commercetools.</p><h3>Motivation</h3><p>When you get started with Prisma you want to run things locally first. Given that you have Docker installed, you run a docker-compose file that will spin up a database (e.g. Postgres) and the Prisma service from the <a href="https://hub.docker.com/r/prismagraphql/prisma/">official Docker image</a>. That’s it!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e82a436d87ecb4d86647fd61fbc1e27/href">https://medium.com/media/9e82a436d87ecb4d86647fd61fbc1e27/href</a></iframe><p>However, running in a <strong>production environment</strong> is a whole different story, as you need to ensure a <strong>scalable and available system</strong>.</p><p>There is a <a href="https://github.com/prisma/prisma/issues/2850">GitHub Issue</a> that describes the struggles with the setup for <strong>Horizontal Scaling</strong>. I bumped into this issue myself and, with some help from the lovely Prisma devs, managed to make it work. Other people are still confused though and are apparently still struggling with a proper setup. In retrospect, many of these aspects are not very clear at the beginning, hence the confusion. However, the documentation and tutorials are being constantly improved and hopefully things will be easier to grasp in the future.</p><p>With that in mind, I’d like to illustrate how we run a <strong>production</strong> Prisma setup in our Kubernetes cluster and what parts you need to pay attention to.</p><h4>Why writing an article?</h4><p>There are several resources out there that focus on the same thing: there is a <a href="https://github.com/helm/charts/pull/6483">Helm Chart for Prisma</a>, there is a <a href="https://www.prisma.io/tutorials/deploy-prisma-to-kubernetes-ct13/">tutorial for running Prisma on Kubernetes</a> and some others. Somehow though, they still lack of a proper way of scaling horizontally as also <a href="https://github.com/prisma/prisma/issues/3266">reported by one of the core developers of Prisma</a>. I’ve also <a href="https://github.com/prisma/prisma/issues/2850#issuecomment-413031270">been asked to provide some sort of template</a> to run Prisma on Kubernetes.</p><p>I believe that <strong>having a single way of setting things up is not enough</strong> and makes things more complicated. More specifically, a production Prisma setup includes several components and the different variations and combination of those components is what makes it complicated to cover all possible cases. On top you might also have cloud vendors specific configurations.</p><p>Therefore, I decided to write an article instead about how we at commercetools chose to do it to better fit within our infrastructure. Hopefully this will help other people making the correct choices given their setup and requirements.</p><h3>The Prisma cluster</h3><p>When we talk about “cluster”, we usually refer to a group of similar components that work together as a single unit in a distributed way. This is what allows things like <strong>High Availability </strong>(HA). When we run a service like Prisma on Kubernetes, we want to run it with at least a <strong>replica</strong> of 2 instances to ensure some sort of availability and to be able to scale up if necessary.</p><p>The Prisma service itself is a <strong>stateful</strong> application and is composed of the following elements:</p><ul><li>the Prisma API: a server running on a JVM that exposes a GraphQL API plus a Management API (<em>more of that later</em>)</li><li>the DB connector: traditionally for a relational database (MySQL, PostgreSQL) but other DB types are and will be supported as well</li><li>the cache layer: holds a cache of the GraphQL schema to reduce latency on query execution</li><li>the webhook/subscription layer: handles GraphQL subcriptions and webhooks</li></ul><p>As you can imagine, all those different parts need to efficiently work when the Prisma service is replicated over multiple instances.</p><h3>Our setup: requirements</h3><p>At commercetools, we run most of our services on GCP. We also live and work with a decentralized DevOps culture across our teams, meaning that besides the main Operations Team, each team is empowered and responsible of managing their own services.</p><p>In particular, managing a Database with HA is not something you wish to be doing on your own. Luckily, most of the big cloud providers (Google, AWS, etc) offer several managed services that you are more than happy to pay for.</p><p>In our case, we ended up with the following setup on Kubernetes:</p><ul><li>own Helm chart to deploy and scale the services</li><li>managed Google Cloud SQL (Postgres) as the database</li><li><a href="https://github.com/helm/charts/tree/master/stable/rabbitmq">official Helm chart for RabbitMQ</a> as a dependency of our own Helm chart</li><li>Google KMS to encrypt/decrypt our secret values</li></ul><p>The RabbitMQ component is essential for HA as <a href="https://github.com/prisma/prisma/issues/2850#issuecomment-409990506">explained in this comment</a>. In our case, we were only interested in maintaining a synced cache layer and therefore opted for a simple Kubernetes installation of RabbitMQ managed by Helm. Depending on your requirements, you might opt for other solutions to ensure your RabbitMQ service is robust and scalable.</p><blockquote>NOTE: there is an <a href="https://github.com/prisma/prisma/issues/2867">open Issue</a> about supporting other types of PubSub systems besides RabbitMQ, so different options might be available in the future.</blockquote><h3>Caveat: the Prisma Management API</h3><p>Once we settled on those initial requirements, we started implementing our own Helm chart. There is <strong>one very important thing</strong> to consider though: the <strong>Prisma Management API</strong>.</p><p>This is a special API endpoint that the Prisma server and Prisma CLI use to perform administrative tasks, such as deploying schema changes etc. However, <a href="https://github.com/prisma/prisma/issues/2850#issuecomment-409868271">only one instance of the Prisma service is allowed to run with this API enabled</a>. You do so by setting enableManagementApi: true in the PRISMA_CONFIG environment variable. When the Prisma service starts, it will try to get a lock, claiming to have the Management API enabled.</p><pre>Obtaining exclusive agent lock...<br>Obtaining exclusive agent lock... Successful.</pre><p>This means that, across all the instances of the Prisma service, <strong>only one is supposed to work with the Management API enabled</strong>. This makes the setup a bit more complicated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tr-kpNg0hy5AbIBMnZSMg@2x.png" /><figcaption>Overview of the components installed in the Kubernetes cluster, specifically the Prisma Pod with the Management API.</figcaption></figure><h3>Caveat: the PRISMA_CONFIG</h3><p>Another small caveat is the PRISMA_CONFIG environment variable. This variable contains both sensitive and non-sensitive information which makes it a bit tricky to deal with. For instance, you want to ensure that sensitive information is kept encrypted and at the same time the normal configuration is easily accessible and reusable.</p><p>In our case, as you will see later on, we decided to encrypt the entire PRISMA_CONFIG for security reasons (as you should do) and simply duplicate it into two Secrets to differentiate them from the enableManagementApi option. Hopefully the Prisma team will improve this in the future to make it simpler to manage.</p><h3>Our Prisma Helm Chart</h3><p>With the caveats and considerations described in the previous sections, we can now look at the Helm chart itself. The main peculiarity of the chart is that it contains two sets of Deployments and Secrets:</p><ul><li>one that <strong>does not have the Management API enabled</strong> and can be <strong>scaled up with multiple replicas</strong>. Those multiple instances are load balanced by a Service which can be exposed by an Ingress (depending on the requirements).</li><li>one that <strong>has the Management API enabled</strong> and has a <strong>fixed replica of </strong><strong>1</strong>. This Kubernetes resource consists only of a Deployment, no Service or Ingress attached to it.</li></ul><h4>Chart folder structure</h4><p>The chart contains the following files, which we are going to look into.</p><pre>k8s/prisma/<br>├── Chart.yaml<br>├── README.md<br>├── charts<br>│   └── rabbitmq-2.1.1.tgz<br>├── requirements.lock<br>├── requirements.yaml<br>├── templates<br>│   ├── deployment-management.yaml<br>│   ├── deployment.yaml<br>│   ├── secret-management.yaml<br>│   ├── secret.yaml<br>│   └── service.yaml<br>├── secrets.enc<br>├── secrets.yaml<br>└── values.yaml</pre><h4>RabbitMQ chart dependency</h4><p>To install the chart dependency, define a requirements.yaml and follow the Helm instructions to install it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/402cb79210036a3f0c8145e89ddba4d0/href">https://medium.com/media/402cb79210036a3f0c8145e89ddba4d0/href</a></iframe><p>The configuration for the RabbitMQ chart can be provided within the main values.yaml as long as it’s grouped by a key with the same name as the dependency chart rabbitmq. Sensitive information should be as always encrypted (in our case we define them in a secrets.yaml which gets encrypted with Google KMS).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3233c56be7639d668b24ac83101ab8c/href">https://medium.com/media/d3233c56be7639d668b24ac83101ab8c/href</a></iframe><h4>Secret resources</h4><p>As mentioned before, we use two sets of Secrets. Notice that, besides the names, the only difference is the enableManagementApi value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7974afc382b34a6f4f172c72eb5fcdfa/href">https://medium.com/media/7974afc382b34a6f4f172c72eb5fcdfa/href</a></iframe><h4>Deployment resources</h4><p>Similarly, Deployments are also defined twice.</p><blockquote>NOTE: the Docker image for Prisma production is called prismagraphql/prisma-prod, which is different from prismagraphql/prisma! (<a href="https://github.com/prisma/prisma/issues/2850#issuecomment-410209662">source</a>)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63dbaee5d535a4affb75b70dc0fa4610/href">https://medium.com/media/63dbaee5d535a4affb75b70dc0fa4610/href</a></iframe><h4>Service resource</h4><p>The only thing to note here is that it points to the “normal” Deployment, not the management one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7f70e0252877dd8b3a132f64a06f980/href">https://medium.com/media/b7f70e0252877dd8b3a132f64a06f980/href</a></iframe><h4>Installing the chart</h4><p>Simply run the helm install command:</p><pre>$ helm upgrade \<br>  --install \<br>  --wait \<br>  --namespace $NAMESPACE \<br>  -f k8s/prisma/values.yaml \<br>  -f k8s/prisma/secrets.yaml \<br>  $HELM_RELEASE_NAME k8s/prisma</pre><p>And you should eventually see something like this:</p><pre>$ kubectl get pods<br>NAME                                 READY     STATUS<br>prisma-rabbitmq-0                    1/1       Running<br>prisma-rabbitmq-1                    1/1       Running<br>prisma-6cf659ccc9-8dgg4              2/2       Running<br>prisma-6cf659ccc9-m5fdk              2/2       Running<br>prisma-management-5bb959bbb5-qdbth   2/2       Running<br><br>$ kubectl get svc<br>NAME              TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)<br>prisma-rabbitmq   ClusterIP   10.35.244.85    &lt;none&gt;        4369/TCP,5672/TCP,25672/TCP,15672/TCP   73d<br>prisma            ClusterIP   10.35.254.183   &lt;none&gt;        80/TCP</pre><h3>Using the Prisma Management API</h3><p>Just for the sake of completeness, when you want to deploy e.g. a schema change, you would need to connect to the prisma-management-xxx-xx pod</p><pre>$ kubectl port-forward prisma-management-5bb959bbb5-qdbth 4467:4466</pre><p>and execute the prisma deploy command.</p><pre>$ prisma deploy -e .env</pre><p>In our case, the .env contains the following variables:</p><pre>PRISMA_API_URL=http://localhost:4467/my-service/staging<br>PRISMA_API_SECRET=xxx<br>PRISMA_MANAGEMENT_API_SECRET=xxx</pre><h3>Conclusion</h3><p>Even though this guide is tailored to our setup at commercetools (e.g. Google CloudSQL), I hope it provides some useful information about getting a Prisma service up and running for production. I’m sure in the future there will be more generic solutions that might “just work” out-of-the-box. Even then, it might not cover all use cases and might not work for you. In that case, I hope this article to remain useful and to inspire you in setting up the different parts of a self-hosted Prisma cluster in detail.</p><p>With that said, Prisma is great and you should definitely check it out and contribute back to its community.</p><h3>References</h3><ul><li>Prisma (<a href="https://www.prisma.io/">Official Website</a>)</li><li>Prisma (<a href="https://www.prisma.io/blog/">Blog</a>)</li><li>Prisma Horizontal Scaling (<a href="https://github.com/prisma/prisma/issues/2850">GitHub Issue</a>)</li><li>Prisma Bindings (<a href="https://www.howtographql.com/graphql-js/4-adding-a-database/">HowToGraphql</a>, <a href="https://www.prisma.io/features/bindings/">Official Website</a>)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a05833d4fc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/commercetools-tech/prisma-horizontal-scaling-a-practical-guide-3a05833d4fc3">Prisma Horizontal Scaling: a practical guide 📘</a> was originally published in <a href="https://medium.com/commercetools-tech">commercetools tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes DNS and TLS automation ]]></title>
            <link>https://medium.com/commercetools-tech/kubernetes-dns-and-tls-automation-c3ce0919ff1d?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3ce0919ff1d</guid>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[tls]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Fri, 06 Jul 2018 14:39:47 GMT</pubDate>
            <atom:updated>2018-07-06T14:39:47.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9-sGwGO31OBPcud2" /><figcaption>Photo by <a href="https://unsplash.com/@jbcreate_?utm_source=medium&amp;utm_medium=referral">Joseph Barrientos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>NOTE: this article assumes that you have some basic knowledge with </em><a href="https://kubernetes.io/"><em>Kubernetes</em></a><em>, DNS providers and TLS certificates.</em></p><p>In the recent years, the DevOps community grew a lot and created new tools and ways to accomplish cumbersome tasks like managing DNS records or issuance of TLS (<em>previously SSL</em>) certificates. Nowadays, doing infrastructure work is like coding, thanks to tools such as <a href="https://www.terraform.io/">Terraform</a>, <a href="https://www.chef.io/">Chef</a>, <a href="https://serverless.com/">Serverless</a>, etc.</p><p>However, even with those tools, managing domains still requires a certain amount of boilerplate and management effort because it still remains a <em>static</em> configuration. What we want though, is something more <em>dynamic</em> that is easy to use and to manage.</p><h3>Going declarative</h3><p>How nice would it be to simply <strong>tell what you want</strong> to have and let the system care about <strong>how is done</strong>?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FE87jjnSCANThe%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fnight-thursday-ritual-E87jjnSCANThe&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FE87jjnSCANThe%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="184" frameborder="0" scrolling="no"><a href="https://medium.com/media/79e8cdb06dcae2eb7e0212a2fbcda4a4/href">https://medium.com/media/79e8cdb06dcae2eb7e0212a2fbcda4a4/href</a></iframe><p>With Kubernetes, we use yaml files to describe the resources that we would like to have installed/deployed. The yaml syntax is traditionally very <strong>declarative</strong> and easy to read, therefore a perfect match to what we are aiming to achieve.</p><p>So how does this relate to “managing domains”?</p><p>Well, we can <strong>declare</strong> what domain we want to be created and that we want a valid TLS certificate for that. In Kubernetes world, we can do that by using <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/">annotations</a>, to allow other services to hook into the created resources through the Kubernetes API.</p><p>This approach brings certain advantages:</p><ul><li>✂️ almost zero management hassle (<em>= happier Engineers</em> 🎉)</li><li>📜 declarative configuration</li><li>🚒 automatic renewal of expiring TLS certificates (<em>e.g. </em><a href="https://letsencrypt.org/2015/11/09/why-90-days.html"><em>Let’s Encrypt issues certificates with short lifetime of 90 days</em></a><em>, which means improved security</em>)</li></ul><h3>Use case: branch deployments</h3><p>To demonstrate how we can implement that and what we need to set up, we can imagine to <em>deploy branches</em>. This is a common use case when you are developing features that should be reviewed and tested by developers and non-developers.</p><p>PS: if you look around, there are already awesome solutions out there to deploy a branch after opening a PR and that integrate very well with e.g. GitHub. On top of my head, I’d really recommend <a href="https://www.netlify.com/">Netlify</a> and <a href="https://zeit.co/blog/now-for-github">Now</a>. If that’s good enough for your use-case, go ahead and use one of those! (or both) 😉</p><blockquote>Spoiler: the article will explore things from a “branch deployment” point of view. However, the final result can be used for any kind of application.</blockquote><h4>Requirements for branch deployments</h4><p>Our requirements are quite simple:</p><ul><li>opt-in to deploy a branch after opening a PR (to reduce the number of used resources)</li><li>use the same tools and setup of our staging/production environment</li><li>have a unique “user-friendly” URL (e.g. pr-1234.example.com)</li><li>the URL must run on HTTPS</li></ul><p>The first two points are covered by the CI setup. For example, on CircleCI you can use an “approval” step to trigger the deployment whenever you want to.</p><p>The challenge we are facing is about the last two points: having to <strong>dynamically manage a DNS domain</strong> and <strong>issue valid TLS certificates</strong> for running on HTTPS.</p><p>To solve those problems, we’re going to look at two specific tools that integrate very well with Kubernetes:</p><ul><li><a href="https://github.com/kubernetes-incubator/external-dns">external-dns</a> to manage DNS resources with DNS providers</li><li><a href="https://github.com/jetstack/cert-manager">cert-manager</a> to manage TLS certificates with Certificate authorities</li></ul><h3>External DNS</h3><p>This tool works like a bridge between your Kubernetes resources and your existing DNS providers (<em>Google CloudDNS, AWS Route 53, etc.</em>). It will use the Kubernetes API to retrieve metadata from Kubernetes resource <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/">annotations</a> and perform actions based on that, such as create or delete a DNS record.</p><p><em>NOTE: we are going to install this tool in a Kubernetes namespace called </em><em>external-dns using the related </em><a href="https://github.com/kubernetes/charts/tree/master/stable/external-dns"><em>helm chart</em></a><em>.</em></p><p>At commercetools we use Google Cloud, therefore we’re going to look at the integration with the <a href="https://cloud.google.com/dns/docs/"><strong>Google CloudDNS</strong></a>.</p><h4>Create a DNS zone</h4><p>The first thing to do is to create a DNS zone where all the DNS entries will be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfIKEYe2fpp9Mw2Q7Md8bg.png" /><figcaption>Google CloudDNS basic setup for example.com</figcaption></figure><h4>Create a service account</h4><p>Once you have the DNS zone set up, you need to define credentials to access your CloudDNS. For that we need to create a <em>service account </em>with the role roles/dns.admin.</p><p>Then, we need to generate a <strong>private key</strong> for that service account.</p><pre>$ gcloud iam service-accounts keys create \<br>    ~/key.json \<br>    --iam-account external-dns@&lt;project-key&gt;.iam.gserviceaccount.com</pre><h4>Create a Kubernetes secret</h4><p>The private key of the service account should be stored in a Kubernetes <strong>secret</strong>, which can be safely referenced by the external-dns service.</p><pre>$ kubectl create secret generic external-dns-credentials \<br>    --from-file=key.json \<br>    --namespace external-dns</pre><h4>Install the external DNS chart</h4><p>The last step is to install the helm chart.</p><pre>$ helm upgrade \<br>  --install external-dns \<br>  --namespace external-dns \<br>  -f external-dns-values.yaml \<br>  stable/external-dns</pre><p>Where the external-dns-values.yaml contains the following configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70d1027bd75c5f42a2fa3576f9bae997/href">https://medium.com/media/70d1027bd75c5f42a2fa3576f9bae997/href</a></iframe><p>That’s it, the service now runs in the cluster and will start looking into Kubernetes metadata annotations to check which DNS entries it needs to create. 🎉</p><h4>Referencing a DNS entry from an Ingress resource</h4><p>With the external-dns running in the cluster, we can manage DNS entries within the Ingress of the service that you want to deploy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6475d10e66da5a4c90fb098517f12d51/href">https://medium.com/media/6475d10e66da5a4c90fb098517f12d51/href</a></iframe><p>In the example above, a new DNS entry foobar.example.com will be created in Google CloudDNS. When the Ingress resource will be deleted, external-dns will take care of removing the DNS entry.</p><h3>Cert manager</h3><p>This tool works also like a bridge between your Kubernetes resources and TLS certificate issuers (<em>e.g. Let’s Encrypt</em>). It will use the Kubernetes API to retrieve metadata from Kubernetes resource <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/">annotations</a> and performs actions based on that, such as provisioning and validating TLS certificates for a given domain and automatically renewing expiring certificates.</p><p><em>NOTE: we are going to install this tool in a Kubernetes namespace called </em><em>cert-manager using the related </em><a href="https://github.com/kubernetes/charts/tree/master/stable/cert-manager"><em>helm chart</em></a><em>.</em></p><p>At commercetools we use decided to use <strong>Let’s Encrypt</strong>, therefore we’re going to look at the integration with their service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*idmXXdGC-GZ-4NL-1-L1jg.png" /><figcaption>High level overview of the cert-manager integration with Let’s Encrypt (<a href="https://cert-manager.readthedocs.io/en/latest/index.html">source</a>)</figcaption></figure><h4>Certificate Authority Authorization (CAA record)</h4><p>Since Let’s Encrypt will be going to issue certificates for a domain, <a href="https://letsencrypt.org/docs/caa/">it needs to be authorized to do so</a>. Therefore, we need to define a CAA record in our CloudDNS to trust Let’s Encrypt (<em>this assumes that you already have set up a DNS zone</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MvobW-uODo9euFn9514Tg.png" /><figcaption>CAA record to authorize Let’s Encrypt</figcaption></figure><p>Note that you can optionally specify an email with iodef where you want to get error reports about the certificates.</p><h4>Create a service account</h4><p>The cert-manager needs to access the DNS zone as well in order to perform a so called ACME DNS-01 challenge (<em>more on that later</em>). Therefore, we need to create a new <em>service account</em> with the role roles/dns.admin.</p><p>Then, we need to generate a <strong>private key</strong> for that service account.</p><pre>$ gcloud iam service-accounts keys create \<br>    ~/key.json \<br>    --iam-account cert-manager@&lt;project-key&gt;.iam.gserviceaccount.com</pre><h4>Create a Kubernetes secret</h4><p>The private key of the service account should be stored in a Kubernetes <strong>secret</strong>, which can be safely referenced by the external-dns service.</p><pre>$ kubectl create secret generic cert-manager-credentials \<br>    --from-file=key.json \<br>    --namespace cert-manager</pre><h4>Install the cert manager chart</h4><p>We can now proceed on installing the helm chart.</p><pre>$ helm upgrade \<br>  --install cert-manager \<br>  --namespace cert-manager \<br>  -f cert-manager-values.yaml \<br>  stable/cert-manager</pre><p>Where the cert-manager-values.yaml contains the following configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c9f3d9e7d31904b6ab016934df2e5ca/href">https://medium.com/media/5c9f3d9e7d31904b6ab016934df2e5ca/href</a></iframe><p>Now the chart is installed but it’s not enough, as we still need to configure the actual “issuer”.</p><h4>Configure the issuer</h4><p>This is the crucial piece of the puzzle. An Issuer or ClusterIssuer represents a certificate authority from which signed x509 certificates can be obtained.</p><p>The difference between an Issuer and a ClusterIssuer is that the first only works within a cluster namespace whereas the latter works across all namespaces. Depending on the setup of your cluster, you can choose the one or the other.</p><p>In our case, we went with a ClusterIssuer to be able to use the issuer across our namespaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/937364127b90d8a712dd46dbdd1c27da/href">https://medium.com/media/937364127b90d8a712dd46dbdd1c27da/href</a></iframe><p>Let’s break down a couple of things here:</p><ul><li>we define the ClusterIssuer resource kind to use the ACME protocol</li><li>the ACME server points to Let’s Encrypt production API, however there is also a <a href="https://letsencrypt.org/docs/staging-environment/">staging environment</a> that you can use for testing</li><li>the privateKeySecretRef is managed by cert-manager to store the private tls.key of the issuer account (account registration is done automatically, you simply need to define a valid email address)</li><li>the dns01 configuration contains a list of providers that can be used to solve DNS challenges. A challenge is like a procedure of proving the ownership of the domain between the CA and the DNS provider</li><li>the provider google-clouddns references the service account secret that we created beforehand</li></ul><h4>Referencing a TLS entry from an Ingress resource</h4><p>With the cert-manager now up and running in the cluster, we can manage TLS certificates within the Ingress of the service that you want to deploy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eab137068c44f1baf15776ec69b1a9d8/href">https://medium.com/media/eab137068c44f1baf15776ec69b1a9d8/href</a></iframe><p>In the example above, a new Certificate for the hostname foobar.example.com will be created by Let’s Encrypt and stored within the namespace of the Ingress.</p><p>Note that it takes some minutes for the certificate to be issued and available.</p><h3>Final setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*5LzxNNfzDY_g0gzexIRDIg@2x.png" /><figcaption>Overview of the Kubernetes cluster setup between the different components and the cloud services</figcaption></figure><h3>Conclusions</h3><p>Managing DNS and TLS does not have to be hard and painful. More importantly it should be very easy for every developer to do so, not only for the DevOps team. Using a combination of those tools we were able to abstract away all the management hassles of DNS and TLS and focus on getting our application (for branch deployments) up and running with a declarative configuration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3ce0919ff1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/commercetools-tech/kubernetes-dns-and-tls-automation-c3ce0919ff1d">Kubernetes DNS and TLS automation 🚀</a> was originally published in <a href="https://medium.com/commercetools-tech">commercetools tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Security for Single Page Applications: great impact with little effort]]></title>
            <link>https://medium.com/commercetools-tech/web-security-for-single-page-applications-great-impact-with-little-effort-a7a506cec20b?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7a506cec20b</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[xss-attack]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Wed, 18 Apr 2018 07:52:25 GMT</pubDate>
            <atom:updated>2018-05-03T09:34:38.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UafAdhlpIQCEdBir." /><figcaption>Photo by <a href="https://unsplash.com/@shotbyjamespond?utm_source=medium&amp;utm_medium=referral">James Pond</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As the web keeps growing, so do the challenges that we need to undertake in order to maintain a high level of trust and security for our Web Applications. Recently browser vendors have been implementing great new features based on the <a href="https://www.w3.org/">W3C</a> specs to provide better and more advanced tools to allow us, developers, to keep up with those challenges.</p><p>In this article, we are going to look at some of those tools and show you how much you can achieve with minimal effort. If you’re familiar with the <a href="https://en.wikipedia.org/wiki/Pareto_principle">Pareto principle</a> (also known as the <em>80/20</em> rule), that’s exactly what I’m talking about.</p><p><em>NOTE: even though this article is focusing on the aspects from the perspective of a JavaScript Single Page Application, many of the tools and concepts can be applied to any Website or Web Application.</em></p><h3>Table of Content</h3><p>The article covers the following sections. If you are already familiar with some of those topics, feel free to “jump” to the section of your interest.</p><ul><li><em>Common vulnerabilities</em></li><li><em>Protecting against XSS</em></li><li><em>Security Headers (CSP &amp; SRI, HSTS, HPKP)</em></li><li><em>Securing sensitive information</em></li><li><em>Protecting agains CSRF</em></li><li><em>CORS</em></li><li><em>Conclusions &amp; References</em></li></ul><h3>Common vulnerabilities</h3><p>When we think about Web Security, probably the first thing that comes to mind is <a href="https://en.wikipedia.org/wiki/HTTPS">HTTPS</a>, which is a protocol that describes and ensures that the data exchanged over the connection is securely encrypted.</p><p>But is that enough? Unfortunately, it’s not.</p><p>Two of the most common vulnerabilities for Web Applications are <a href="https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting">XSS</a> and <a href="https://developer.mozilla.org/en-US/docs/Glossary/CSRF">CSRF</a> (I assume that you have a vague understanding of them, otherwise there are some useful references at the end of the article).</p><p>When we talk about vulnerabilities and attacks from malicious parties, it’s all about <strong>data</strong>, more specifically <strong>sensitive data</strong>, and how we keep it <strong>protected</strong>. This can be anything like a session token, a user email, etc. The browser offers different ways to store and exchange data, each one comes with pros and cons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLTQic89XjgHmoAzVJRPCQ.png" /><figcaption>General overview of storing sensitive data with the related vulnerabilities.</figcaption></figure><p>Here at <a href="https://commercetools.com/">commercetools</a> my team and I are working on a Web Application called “Merchant Center”. From a technical point of view, it’s a JavaScript Single Page Application that runs on the browser and connects to a proxy API in order to consume different services within our platform. When implementing a Single Page Application, it’s common practice to store an authorization token in window.localStorage so that it can be retrieved when sending an API request.</p><p>Unfortunately window.localStorage was never designed to be secure. Any piece of JavaScript <strong>can read and write from/to it</strong>, which opens up an XSS vulnerability attack (like a “malicious” script that reads from window.localStorage and sends data to an external “malicious” server).</p><p>In the last weeks, we’ve been digging more into this security topic and made some simple changes to raise our security defenses to a higher level. Today we want to share this experience with you, hoping that you will feel more comfortable in understanding and implementing security measures with just a few steps.</p><h3>Protecting against XSS</h3><p>In a JavaScript application, an <a href="https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting">XSS</a> (<em>Cross-Site Scripting</em>) attack is one the most malicious attacks. Fortunately, browsers offer and implement several features to help prevent those vulnerabilities.</p><p>First, we’re going to look at some <strong>Security Headers</strong>.</p><p>A security header is “just” an <a href="https://developer.mozilla.org/en-US/docs/Glossary/Response_header">HTTP Response Header</a> specifically designed for security purposes. There are a few of them which are worth mentioning.</p><h3>Content Security Policy (CSP)</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy">CSP</a> header describes a series of directives (or rules) to instruct the browser to allow or block resources to be loaded and executed.</p><pre>Content-Security-Policy: default-src &#39;self&#39;; …directives</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNkrgWOi4lmPSrG7ei82EQ.png" /><figcaption>Overview of the most important directives for CSP.</figcaption></figure><p>I would argue that this is one of the most important Security Headers to use. However, it can be quite challenging to properly set it up. Let’s have a look at how you can get started with it and implement a basic CSP.</p><p><strong>1) Start with a default template</strong></p><pre>Content-Security-Policy:<br> default-src &#39;none&#39;;<br> script-src &#39;self&#39;;<br> connect-src &#39;self&#39;;<br> img-src &#39;self&#39;;<br> style-src &#39;self&#39;;</pre><p><strong>2) Use </strong>-Report-Only <strong>mode</strong> so that the policy is active but the browser does not block anything, instead it will send violation reports to the provided URI</p><pre>Content-Security-Policy<strong>-Report-Only</strong>:<br> default-src &#39;none&#39;;<br> script-src &#39;self&#39;;<br> connect-src &#39;self&#39;;<br> img-src &#39;self&#39;;<br> style-src &#39;self&#39;;<br><strong> report-uri: https://sentry.io/xxx/csp-report;</strong></pre><p><strong>3) Inspect policy violations</strong> (within the reporting tools of your choice, for example we use <a href="https://sentry.io/">Sentry</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-_gHVvX38RqgP5ImYyauw.png" /><figcaption>An example of a policy violation report from Sentry.</figcaption></figure><p><strong>4) Update the policy to white-list the domains and resources that you trust</strong></p><pre>Content-Security-Policy<strong>-Report-Only</strong>:<br> default-src &#39;none&#39;;<br> script-src &#39;self&#39;;<br> connect-src &#39;self&#39; <strong>https://www.google-analytics.com</strong>;<br> img-src &#39;self&#39;;<br> style-src &#39;self&#39;;<br> <strong>report-uri: https://sentry.io/xxx/csp-report;</strong></pre><p><strong>5) Repeat steps 3 and 4 until you covered all the minimal rules to make your application work.</strong> To further help this process, 3rd party services like Intercom <a href="https://docs.intercom.com/configure-intercom-for-your-product-or-site/staying-secure/using-intercom-with-content-security-policy">provide a list of directives to white-list all their resources</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1TZcHxWqmBpf2%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Floop-bun-1TZcHxWqmBpf2&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1TZcHxWqmBpf2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="546" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c30406c00bcbe952e82f6480f1fb2d1/href">https://medium.com/media/2c30406c00bcbe952e82f6480f1fb2d1/href</a></iframe><p><strong>6) Enforce the policy</strong> (replace Content-Security-Policy-Report-Only with Content-Security-Policy)</p><pre><strong>Content-Security-Policy</strong>:<br> default-src &#39;none&#39;;<br> script-src &#39;self&#39; <strong>&#39;unsafe-inline&#39; &#39;unsafe-eval&#39;</strong>;<br> connect-src &#39;self&#39; <strong>https://www.google-analytics.com</strong>;<br> img-src &#39;self&#39;;<br> style-src &#39;self&#39;;<br> <strong>report-uri: https://sentry.io/xxx/csp-report</strong>;</pre><p>Once you have your base policy enabled you can start tweaking it. One thing I would like to focus on is related to the script-src directive.</p><p>As you might have noticed, I used unsafe-inline and unsafe-eval which basically allows <strong>any kind of injected script to be executed</strong>. This might seem acceptable, depending on the type of application, but <strong>we can do better</strong>. In fact, I strongly recommend trying to get rid of those.</p><h4>Safe inline scripts</h4><p>Let’s look at a common example: Google Tag Manager. To set it up, you need to put an inline script in your HTML page.</p><pre>&lt;script&gt;<br> dataLayer = [{ &#39;gtm.start&#39;: new Date().getTime() }];<br>&lt;/script&gt;</pre><p>Of course, you can decide to put it into a JS file, load the file instead and white-list the URI where the file lives (at the cost of an additional network request). However, for the sake of the example let’s assume we want it as an <strong>inline script</strong>.</p><p>In order to white-list that inline script, we simply need to <strong>hash it</strong>.</p><pre>&gt; require(&#39;crypto&#39;)<br> .createHash(&#39;sha256&#39;)<br> .update(&quot;dataLayer=[{&#39;gtm.start&#39;:new Date().getTime()}];&quot;)<br> .digest(&#39;base64&#39;);<br><strong>&#39;gNc6N+b7YhV0rkQNN7PDbQXK1JJ70pky2rQYS6w0czM=&#39;</strong></pre><p>The CSP supports 3 types of hash algorithms: <strong>sha256</strong>, <strong>sha384</strong>, <strong>sha512</strong>.<br>Once you have the hash, you can white-list it in your CSP.</p><pre><strong>Content-Security-Policy</strong>:<br> default-src &#39;none&#39;;<br> script-src &#39;self&#39; <strong>&#39;unsafe-eval&#39; &#39;sha256-gNc6N+b7YhV0rkQNN7PDbQXK1JJ70pky2rQYS6w0czM=&#39;</strong>;<br> connect-src &#39;self&#39; <strong>https://www.google-analytics.com</strong>;<br> img-src &#39;self&#39;;<br> style-src &#39;self&#39;;<br> <strong>report-uri: https://sentry.io/xxx/csp-report</strong>;</pre><p>That’s it, simple as that.</p><p>NOTE that <strong>the hash is static</strong> and can be hard-coded in your CSP. If the inline script changes, you obviously need to update the hash (the browser will “remind you” of that 😉 because it simply won’t execute the script). In rare cases, you might need to dynamically generate the hash on each request, based e.g. on some environment variables. If you have control over the HTTP server you can still do that, otherwise, you need to find a different solution.</p><p><strong>UPDATE:</strong> As an alternative of the “sha-hash”, you can also use a cryptographic “nonce-hash”. The difference is that the “nonce-hash” is uniquely generated by the server on each request and does not need to hash the script content. This is useful for more traditional Web Applications where there might be a lot of inline scripts on different pages and hashing each one of them becomes complex and tedious.</p><p>Using a “sha-hash” will allow to be more strict in which inline scripts are allowed. Using a “nonce-hash” will provide more flexibility to allow any kind of inline script rendered by the server and prevent unknown script injection.</p><h4>Safe eval 😈</h4><p>Well, that’s fairly easy: do not use eval 😇</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Do_not_ever_use_eval!">Seriously, it’s really discouraged!</a></p><p>Furthermore, inspect your 3rd party dependencies and look for the usage of eval() or Function. If you find any, open an issue at the related library to address the problem.</p><h4>Browser support</h4><p>There are <a href="https://caniuse.com/#search=csp">different versions</a> of the CSP spec, the current one being version 2.0 with the upcoming 3.0 (still in draft). <strong>All major browser vendors support most of the features</strong>, with the exception of IE (it only supports 1.0 with the sandbox directive, nothing else 🙃).</p><p>What happens when a browser does not support a directive? Nothing, really. The unsupported directives will simply be ignored. This is a good thing for us developers because we just need to maintain one policy. On the other hand, if such an “old” browser is used, the user will simply not benefit from the security features.</p><h3>Subresource Integrity (SRI)</h3><p>We just looked at the Content Security Policy as a way to white-list resources that we trust to be loaded and executed.<br>Some of those resources might come from a <a href="https://developer.mozilla.org/en-US/docs/Glossary/CDN">CDN</a>. We might trust the CDN domain or URI but <strong>can the files be fully trusted</strong>? 🤔</p><p>If an attacker is able to modify the e.g. jquery.min.js file content that is stored on a CDN, our application will still load and trust the file but it doesn’t know that the content changed and that it might contain malicious code.</p><p>In order to prevent that, we can use another important security feature: <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity">Subresource Integrity</a>.</p><p>Using SRI enables browsers to verify that files they fetch (for example, from a CDN) are delivered without unexpected manipulation.</p><p>Again, this is also pretty simple to implement. We <strong>hash the file</strong> and <strong>reference</strong> the hash in the script file.</p><pre>&lt;script src=<a href="https://cdnjs.../3.3.1/jquery.min.js">&quot;https://cdnjs.../3.3.1/jquery.min.js&quot;</a><br> <strong>integrity=&quot;sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=&quot;</strong><br> <strong>crossorigin=&quot;anonymous&quot;</strong>&gt;&lt;/script&gt;</pre><p>Then we enable the require-sri-for script directive in our CSP.</p><pre><strong>Content-Security-Policy</strong>:<br> default-src &#39;none&#39;;<br> script-src &#39;self&#39; <strong>&#39;unsafe-eval&#39; &#39;sha256-gNc6N+b7YhV0rkQNN7PDbQXK1JJ70pky2rQYS6w0czM=&#39;</strong>;<br> connect-src &#39;self&#39; <strong>https://www.google-analytics.com</strong>;<br> img-src &#39;self&#39;;<br> style-src &#39;self&#39;;<br> <strong>report-uri: </strong><a href="https://sentry.io/xxx/csp-report;"><strong>https://sentry.io/xxx/csp-report</strong>;</a><br><strong> require-sri-for script;</strong></pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FMCZ39lz83o5lC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FMCZ39lz83o5lC&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeTNraGp2Mzg3anJueWVjZmYyMTBiOGFic3Mwcm9mYnA5YXdqNTBrOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FMCZ39lz83o5lC%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="232" frameborder="0" scrolling="no"><a href="https://medium.com/media/92e601ed4657b337fc12c85ad91ab348/href">https://medium.com/media/92e601ed4657b337fc12c85ad91ab348/href</a></iframe><p>Content Security Policy is a <strong>powerful feature</strong>. It gives us a lot of options and flexibility to instruct the browser to understand the context of our application or website and take necessary actions. In other words, it allows you to control pretty much everything that’s going on in the browser (scripts, fonts, images, network requests, etc).</p><p>In this article we just looked at some of the features of CSP. However, there is much more to it and I recommend to follow the reference links to dig deeper.</p><p>What else can we do?</p><h3>HTTP Strict Transport Security (HSTS)</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security">HTTP Strict Transport Security</a> is another HTTP response header that tells the browser that it should only allow HTTPS requests on all subsequent requests. Enforcing this header highly reduces possible <a href="https://developer.mozilla.org/en-US/docs/Glossary/MITM">MiTM</a> attacks.</p><pre>Strict-Transport-Security: max-age=31536000</pre><p>If you want to know more about it, I really recommend <a href="https://scotthelme.co.uk/hsts-the-missing-link-in-tls/">reading this article</a> from the well-known Security Researcher, <a href="https://medium.com/u/ad99d83a2484">Scott Helme</a>.</p><h3>HTTP Public Key Pinning (HPKP)</h3><p>This one is more of a “nice-to-have” header. It’s a very powerful one but quite delicate to handle at the same time. You probably want to look at this only in cases where you need a <strong>high level of security</strong>, such as a bank website.</p><p>So what is it? It stands for <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning">HTTP Public Key Pinning</a> and has the ability to instruct the browser to verify a set of given cryptographic public keys against the requesting website. Enforcing this header also highly reduces possible <a href="https://developer.mozilla.org/en-US/docs/Glossary/MITM">MiTM</a> attacks with forged certificates.</p><pre>Public-Key-Pins: pin-sha256=”XXX” max-age=5184000</pre><p>However, there are some important trade-offs to be aware of before using this. Again, you can <a href="https://scotthelme.co.uk/im-giving-up-on-hpkp/">read more about this in this article</a> from the well-known Security Researcher, <a href="https://medium.com/u/ad99d83a2484">Scott Helme</a>.</p><h3>Securing sensitive information</h3><p>As we saw in the previous sections, Security Headers do not take much effort to implement and offer a built-in high level of protection from the browser. However, in the case that an attacker still manages to bypass those security protections, our sensitive data might still be at risk.</p><p>What else can we do to store that data more securely? The answer is: use <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies">HTTP Cookies</a>, specifically in Secure and HttpOnly mode.</p><pre>Set-Cookie: Expires=Wed, 21 Oct 2015 07:28:00 GMT; <strong>Secure; HttpOnly</strong></pre><p>The Secure flag ensures that the browser sends the cookie only over a HTTP connection.</p><p>The HttpOnly flag prevents any JavaScript code to read from it.</p><p>Simple as that…or is it? 🤔 Well, using HTTP Cookies opens up another vulnerability, namely CSRF.</p><h3>Protecting against CSRF</h3><p>A <a href="https://developer.mozilla.org/en-US/docs/Glossary/CSRF">CSRF</a> attack (<em>Cross-Site Request Forgery</em>, also pronounced as “<em>sea-surf</em>” or “csurf”) has been around longer than <a href="https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting">XSS</a> and traditionally applies to normal Web Applications (using server-side rendering and forms). It’s the ability to perform unwanted actions on an authenticated user’s behalf</p><p>To understand how we can prevent this within a Single Page Application, we need to look at CORS first.</p><h3>CORS</h3><p>CORS stands for <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing</a> and it outlines a policy that defends against one origin from “stealing” another origin’s data.</p><p>This is a common thing to encounter if you develop a JavaScript application that makes network requests to other origins. In order for the request to “succeed”, the second origin server needs to consent the request via the Access-Control-Allow-Origin header in the response.</p><p>When does a request need the consent from the server?</p><p>Well, it depends whether <strong>the browser is forced to check</strong> if the CORS protocol is understood by the server or not. The check is performed via a “<strong>preflight</strong>” request with the HTTP OPTIONS method. The check logic is determined by the “kind” of the request: <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests">Simple</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests">Non-Simple</a>.</p><p>A simple request is a request that does <strong>NOT</strong> trigger a “CORS-Preflight” and it must fulfill the following requirements:</p><ul><li>Method: GET, HEAD, POST</li><li>Headers: Accept, Accept-Language, Content-Type(*), …</li><li>Content-Type(*) values: application/x-www-form-urlencoded, multipart/form-data, text/plain</li></ul><p>Simple requests allow CSRF attacks in case the affected origin performs authenticated requests using credentials stored as e.g. HTTP Cookie or Basic Authentication.</p><p><strong>So how can we protect from CSRF attacks?</strong> We use Non-Simple requests!</p><p>A non-simple request is a request that <strong>TRIGGERS</strong> a “CORS-Preflight”. As opposed to a simple request, it fulfills other requirements:</p><ul><li>Method: PUT, DELETE, OPTIONS</li><li>Headers: <em>same as for simple requests, plus any custom header</em> (e.g. X-Something)</li><li>Content-Type values: all other values that are not included in simple requests (e.g. application/json)</li></ul><p>As you might have noticed, requests to a JSON API will send the Content-Type: application/json header, making it a Non-Simple request.</p><p>JSON APIs are automatically protected against CSRF attacks, given that the API enforces Content-Type: application/json.</p><h3>Conclusions</h3><p>Securing your Web Application is <strong>NOT</strong> hard and it takes only a few steps to produce a big impact.</p><blockquote>I think it’s important that every developer, especially those working with the browser, is aware of the possible security threats and understands how to minimize the risk of an attack.</blockquote><p>I hope this article gave you good insights on the steps you can take to further secure your website, or at least to increase your knowledge level in case you were already familiar with those topics.</p><p>Nevertheless, I strongly <strong>recommend to read and inform yourself more about security</strong>, as it’s a very broad subject. Below there are some useful and interesting links that you can start with.</p><h3>References</h3><p>In general, I really recommend following and reading articles from the well-known Security Researcher, <a href="https://medium.com/u/ad99d83a2484">Scott Helme</a> (<a href="https://scotthelme.co.uk/">https://scotthelme.co.uk/</a>).</p><p>In particular:</p><ul><li><strong>Modern Web Security Standard</strong> (<em>by </em><a href="https://medium.com/u/ad99d83a2484"><em>Scott Helme</em></a>)<br><a href="https://www.youtube.com/watch?v=j-0Bj40juMI">https://www.youtube.com/watch?v=j-0Bj40juMI</a></li><li><strong>Protect site from Cryptojacking CSP + SRI</strong> (<em>by </em><a href="https://medium.com/u/ad99d83a2484"><em>Scott Helme</em></a>)<br><a href="https://scotthelme.co.uk/protect-site-from-cryptojacking-csp-sri/">https://scotthelme.co.uk/protect-site-from-cryptojacking-csp-sri/</a></li><li><strong>Migrating from HTTP to HTTPS. Ease the pain with CSP and HSTS</strong> (<em>by </em><a href="https://medium.com/u/ad99d83a2484"><em>Scott Helme</em></a>)<br><a href="https://scotthelme.co.uk/migrating-from-http-to-https-ease-the-pain-with-csp-and-hsts/">https://scotthelme.co.uk/migrating-from-http-to-https-ease-the-pain-with-csp-and-hsts/</a></li><li><strong>Authoritative guide to CORS for REST APIs</strong> (<em>by Derric Gilling</em>)<br><a href="https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/">https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/</a></li><li><strong>Understanding CORS</strong> (<em>by </em><a href="https://medium.com/u/a5f578f5b81a">Bartosz Szczeciński</a>)<br><a href="https://medium.com/@baphemot/understanding-cors-18ad6b478e2b">https://medium.com/@baphemot/understanding-cors-18ad6b478e2b</a></li><li><strong>Content Security Policy with Sentry</strong> (<em>by </em><a href="https://medium.com/u/c59fa51dcfb"><em>Geller Bedoya</em></a>)<br><a href="https://medium.com/sourceclear/content-security-policy-with-sentry-efb04f336f59">https://medium.com/sourceclear/content-security-policy-with-sentry-efb04f336f59</a></li><li><strong>Tools for setting up security headers</strong><br><a href="https://report-uri.com/home/tools">https://report-uri.com/home/tools</a><br><a href="https://securityheaders.io/">https://securityheaders.io</a></li><li><strong>I’m harvesting credit card numbers and passwords from your site. Here’s how.</strong> (<em>by </em><a href="https://medium.com/u/f735d3b0f2f3"><em>David Gilbertson</em></a>)<br>(Part 1) <a href="https://hackernoon.com/im-harvesting-credit-card-numbers-and-passwords-from-your-site-here-s-how-9a8cb347c5b5">https://hackernoon.com/im-harvesting-credit-card-numbers-and-passwords-from-your-site-here-s-how-9a8cb347c5b5</a><br>(Part 2) <a href="https://hackernoon.com/part-2-how-to-stop-me-harvesting-credit-card-numbers-and-passwords-from-your-site-844f739659b9">https://hackernoon.com/part-2-how-to-stop-me-harvesting-credit-card-numbers-and-passwords-from-your-site-844f739659b9</a></li></ul><p>And last but not least, I recommend watching this funny and very informative talk from <a href="https://medium.com/u/fca129c29b73">Dominik Kundel</a> from the last JSConf 2018 in Iceland. Enjoy 😎</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fc6mqdsfWdmE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dc6mqdsfWdmE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fc6mqdsfWdmE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bffda8ae9ad66ea73a2a5561507c5363/href">https://medium.com/media/bffda8ae9ad66ea73a2a5561507c5363/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7a506cec20b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/commercetools-tech/web-security-for-single-page-applications-great-impact-with-little-effort-a7a506cec20b">Web Security for Single Page Applications: great impact with little effort</a> was originally published in <a href="https://medium.com/commercetools-tech">commercetools tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Takeaways from CSS, JS, React and GraphQL Europe conferences]]></title>
            <link>https://medium.com/commercetools-tech/10-takeaways-from-css-js-react-and-graphql-europe-conferences-d1974d922bdf?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1974d922bdf</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[community]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Tue, 30 May 2017 12:06:34 GMT</pubDate>
            <atom:updated>2017-06-02T10:36:37.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niOJs162rPEMy-ZiG6MINA.jpeg" /></figure><p>In the last couple of weeks, we had the privilege to take part in 4 amazing conferences: <a href="http://2017.cssconf.eu/">CSS Conf EU</a>, <a href="http://2017.jsconf.eu/">JS Conf EU</a>, <a href="https://www.react-europe.org/">React Europe</a> and <a href="https://graphql-europe.org/">GraphQL Europe</a>.</p><p>It’s been quite a long journey and an amazing experience in many different ways. In this post we would like to share our thoughts and our takeaways.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlCn-XCASn98%3Fstart%3D25%26feature%3Doembed%26start%3D25&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlCn-XCASn98&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlCn-XCASn98%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8fc146d2252e112cd20e6058542739e/href">https://medium.com/media/e8fc146d2252e112cd20e6058542739e/href</a></iframe><p>Out of the three conferences, <strong>CSS/JS Conf</strong> was the largest one. The location was astonishing and boy, such delicious food 🌮🍜. The audience gathered from all over the world, with lots of attendees and speakers travelling all they way from e.g. US and Australia. For many of them this was considered <em>one of the most important conferences of the year</em>. Nonetheless, <strong>React and GraphQL Europe</strong> were as just as good, considering the smaller size and locations.</p><h4>Takeaway #1: Talk to the people around you</h4><p>What struck us the most across all conferences was first and foremost the people. I guess we kind of knew it before, but really: we have such a great community! We had plenty of interesting conversations with many different people, from different countries, with different backgrounds. And everyone was really nice and helpful and keen to share their knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQOcld_ejrgudT6S2fb9mw.jpeg" /></figure><h4>Takeaway #2: Performance optimizations</h4><p>This was kind of a recurring topic across all conferences. Optimizing your website/application, does bring value and a much better experience to users.</p><blockquote>Time is money 💸</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7vUs5yOuv-o%3Fstart%3D25%26feature%3Doembed%26start%3D25&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7vUs5yOuv-o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7vUs5yOuv-o%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceaeda6c2c528590531dae0aae9044a0/href">https://medium.com/media/ceaeda6c2c528590531dae0aae9044a0/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fcc3rdiXl5eY%3Fstart%3D25%26feature%3Doembed%26start%3D25&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dcc3rdiXl5eY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fcc3rdiXl5eY%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/30ed74c6747220ce7135e77efa08a988/href">https://medium.com/media/30ed74c6747220ce7135e77efa08a988/href</a></iframe><h4>Takeaway #3: Code splitting</h4><p>It relates to “performance” as mentioned earlier and it’s an important architectural decision of many applications.</p><blockquote>Rollup is for libraries, Webpack for apps</blockquote><p>(<em>Here’s a very good article about</em> “<a href="https://medium.com/webpack/predictable-long-term-caching-with-webpack-d3eee1d3fa31">Predictable long term caching with Webpack</a>”)</p><h4>Takeaway #4: 80% result with 20% effort</h4><p>Also known as the “<a href="https://en.wikipedia.org/wiki/Pareto_principle">Pareto Principle</a>”, it’s a principle formulating an “80/20 rule” that can be applied to many different fields (science, economics, software, sports, etc.). We can apply this to our everyday job in which we try to focus on delivering e.g. a feature with 20% effort while aiming for an 80% result instead of 100%. Having this in mind will effectively speed up your delivery time.</p><p><em>(video is not up yet)</em></p><h4>Takeaway #5: “Worse is better” (start simple, then iterate)</h4><p>Again, somehow related to the aforementioned, it’s an interesting concept to have in mind when developing e.g. new features, a library, etc.</p><blockquote>Simplicity above all else. Simplicity leads to popularity. Popularity leads to contributors who will fix the missing pieces.</blockquote><p><em>(video is not up yet)</em></p><h4>Takeaway #6: Metrics and monitoring</h4><p>Obviously this is a crucial part of development lifecycle and of a product itself. How do you know if the feature XYZ is used? Do you know which parts of it are used the most? How many people are using it? All those questions are not only important to measure the performance of a feature but also to determine how to evolve your product (e.g. what can be deprecated).</p><p>Those who are using GraphQL with the Apollo Client, can and should try out <a href="http://www.apollodata.com/optics/">Apollo Optics</a>. It is now free for 10.000 requests per month 🎉.</p><h3>Apollo on Twitter</h3><p>We&#39;re excited that our #GraphQL APM tool Optics is now free for 10,000 requests per month! Here&#39;s how to set it up. https://t.co/M4OpXSsAXY</p><p><em>(video is not up yet)</em></p><h4>Takeaway #7: Composition</h4><p>Writing more Higher-Order Components and composing them together can really clean up your code. Just look at this example taken from <a href="https://medium.com/u/ff3f225e7f5c">Nik Graf</a>’s talk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*q6ou18ypnoXGuOW3L4G9bA.png" /><figcaption>Composing Higher-Order Components for maximum code reuse and readability</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqJgff2spvzM%3Fstart%3D25%26feature%3Doembed%26start%3D25&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqJgff2spvzM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqJgff2spvzM%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd73e86d560189aba5fd4f7d5dca003b/href">https://medium.com/media/cd73e86d560189aba5fd4f7d5dca003b/href</a></iframe><h4>Takeaway #8: Separate by encapsulation</h4><p>One of the themes of CSS Conf was <strong>CSS-in-JS</strong> (<em>of course </em>😜). <a href="https://medium.com/u/d7225e72eea">Mark Dalgleish</a> and <a href="https://medium.com/u/59124a41bb46">Glen Maddern</a> gave good tips about how we should separate our concerns with often overseen benefits of <strong>CSS-in-JS</strong>.</p><h3>Michele Bertoli on Twitter</h3><p>A slide so perfect I wish I made it :) From https://t.co/VXvUNsh3wb by @areaweb</p><p>Mark also published a <a href="https://medium.com/seek-blog/a-unified-styling-language-d0c208de2660">blog post version of his talk</a> if you don&#39;t want to wait for the video to be uploaded 👀.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FX_uTCnaRe94%3Fstart%3D10%26feature%3Doembed%26start%3D10&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DX_uTCnaRe94&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FX_uTCnaRe94%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffabc4bd0dcb6327d7fddd8925346731/href">https://medium.com/media/ffabc4bd0dcb6327d7fddd8925346731/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMT4D_DioYC8%3Fstart%3D10%26feature%3Doembed%26start%3D10&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMT4D_DioYC8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMT4D_DioYC8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/76f88cf7a1f535b61c7ec52985f71ac0/href">https://medium.com/media/76f88cf7a1f535b61c7ec52985f71ac0/href</a></iframe><h4>Takeaway #9: WebAssembly implementation in Browser is (just) an MVP</h4><p><a href="https://medium.com/u/d3391efe481a">Lin Clark</a> gave two amazing talks about <a href="http://webassembly.org/"><em>WebAssembly</em></a>. One explaining what it is and how it works:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHktWin_LPf4%3Fstart%3D2%26feature%3Doembed%26start%3D2&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHktWin_LPf4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHktWin_LPf4%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b65087669bbf71c8988bba7153a3558/href">https://medium.com/media/2b65087669bbf71c8988bba7153a3558/href</a></iframe><p>And another one about what it means for React:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3GHJ4cbxsVQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3GHJ4cbxsVQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3GHJ4cbxsVQ%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e57090a800b2cb553a8fe02994b5fd4f/href">https://medium.com/media/e57090a800b2cb553a8fe02994b5fd4f/href</a></iframe><blockquote>WebAssembly it is the future. But it will take us a couple more years to really benefit from it.</blockquote><p>Some things that still need to be implemented in browsers:</p><ul><li>Threads with shared memory, so that JavaScript and WebAssembly can share data and interact with each other</li><li>Direct DOM access for WebAssembly (right now WebAssembly has no DOM access at all)</li><li>Integration with the browser’s GC</li></ul><h4>Takeaway #10: Schema Driven Development</h4><p>This paradigm was mentioned in a couple of talks at <a href="https://graphql-europe.org/">GraphQL Europe</a> and it is successfully used at companies like <a href="https://github.com/">GitHub</a> and <a href="https://www.graph.cool/">Graphcool</a>.</p><p><em>Schema Driven Development</em> means having people that write and consume an API sit together in one room and define the schema for a new feature. This ensures that all client needs are met and that the knowledge is shared across different teams, including frontend, backend, native.</p><p><em>How is this schema defined?</em> Using the <a href="https://www.graph.cool/docs/faq/graphql-sdl-schema-definition-language-kr84dktnp0/">GraphQL IDL</a>.</p><h3>Graphcool on Twitter</h3><p>What is GraphQL IDL? Here is an overview of all the concepts behind the schema definition language. 💡 https://t.co/40mZ0TAHig</p><p><em>Does it require more effort?</em> No, because instead of having all iOS developers sitting in one room and all backend developers sitting in the other room, you have a couple of developers from each group sitting together.</p><p><em>(videos are not up yet)</em></p><h3>Conclusion</h3><p>The conferences were really interesting for a variety of reasons. The most enjoyable part and key for us was to have <em>good discussions with a lot of different people</em> and to come back home with <em>new ideas and inspirations</em>.</p><p>See you all at the next conferences! 🎉</p><h4>Some related articles about the conferences</h4><ul><li><a href="https://medium.freecodecamp.com/what-ive-learned-from-react-europe-2017-c433468890d6">https://medium.freecodecamp.com/what-ive-learned-from-react-europe-2017-c433468890d6</a></li><li><a href="https://hackernoon.com/react-europe-2017-551961487403">https://hackernoon.com/react-europe-2017-551961487403</a></li><li><a href="https://medium.com/@miduga/jsconf-eu-2017-the-awesome-the-bug-and-the-ugly-6d4267701566">https://medium.com/@miduga/jsconf-eu-2017-the-awesome-the-bug-and-the-ugly-6d4267701566</a></li><li><a href="https://medium.com/@kotzendekrabbe/what-an-a-m-a-z-i-n-g-weekend-65ad099453f7">https://medium.com/@kotzendekrabbe/what-an-a-m-a-z-i-n-g-weekend-65ad099453f7</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1974d922bdf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/commercetools-tech/10-takeaways-from-css-js-react-and-graphql-europe-conferences-d1974d922bdf">10 Takeaways from CSS, JS, React and GraphQL Europe conferences</a> was originally published in <a href="https://medium.com/commercetools-tech">commercetools tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in React: best practices, tips and tricks]]></title>
            <link>https://medium.com/commercetools-tech/testing-in-react-best-practices-tips-and-tricks-577bb98845cd?source=rss-bfc7be47900d------2</link>
            <guid isPermaLink="false">https://medium.com/p/577bb98845cd</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Nicola Molinari]]></dc:creator>
            <pubDate>Mon, 20 Mar 2017 17:07:24 GMT</pubDate>
            <atom:updated>2018-05-03T09:22:04.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hyn4PlBars99pFIyFBt9YQ.png" /></figure><p>Working in a UI environment is not that straightforward anymore, especially in the modern era dominated by complex front-end applications. And it’s not always fun.</p><p>With the “arrival” of React, things changed a lot, especially in the way of thinking about UI in terms of components. But what about testing?</p><p>Wait, testing JavaScript? Who does that?</p><p>Well, that might have been the case 10 years ago, nowadays it’s a completely different story. As we all know testing such complex UIs and applications is very crucial. And stop with excuses such as “I had a tight deadline and couldn’t find the time for writing tests”. Writing tests is usually the first thing you should start with, even if you don’t strictly follow TDD.</p><p>Enough with the jibber-jabber, let’s have a look at some tips and best practices we have found to be useful when testing UI / React components. Because at the end, testing should not be a pain or a burden, it’s a necessary piece of software development and you should feel comfortable as well as having fun doing it.</p><h3>The test runner</h3><p>First of all I’m going to use <a href="https://facebook.github.io/jest/">Jest</a> as the test runner. Most of the things described in this article can easily be done with any other test runner, but some of them are possible because of Jest features.</p><blockquote>If you’re not using Jest, we strongly recommend to switch to it. It really steps up in terms of “<strong>T</strong>esting e<strong>X</strong>perience” and it has a lot of awesome powerful features.</blockquote><p>I’m also going to assume that you use <a href="http://airbnb.io/enzyme/">Enzyme</a> as a React test library. I think this speaks for itself.</p><h3>Structuring the test</h3><p>At this point you’re ready to start writing tests. If you do TDD that’s what you do anyway to start with.</p><p>It’s a good practice to “<em>describe</em>” your test steps and assertions, just like you do when you write a check list. It’s good for having a mental picture of what you want to test as well as for preparing the different test setups and simply to have a list to follow. You are going to do that using “<em>describes</em>” and “<em>its</em>” (or whatever the test runner of your choice provides).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d3cacd07ed54d3810d6d92e74535b12/href">https://medium.com/media/7d3cacd07ed54d3810d6d92e74535b12/href</a></iframe><p>That’s good, but we can do a lot better.</p><p>For example, the main describe “<em>Core::Buttons::LinkButton</em>” might be useful to “uniquely” identify this specific test in the test runner output. Fortunately with Jest (and probably with other test runners as well) this is not necessary anymore. Jest groups all tests by their filenames. If a test fails you will then get the “path” to the failed assertion, as well as a lot of useful information. That’s one of the things I love the most about Jest, they really did an amazing job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLc0YaTeFzLNOkAL4V07qw.png" /><figcaption>Jest tells you exactly in which file, test, and line the assertion failed</figcaption></figure><p>As you can see having targeted test assertions is really helpful. It not only makes the test easier to read but also easier to identify the specific assertion.</p><p>So don’t be afraid of <strong>nesting</strong> different “<em>describes</em>” and to split your assertions across multiple “<em>it</em>” blocks.</p><blockquote>We found that is beneficial when each “it” block only contains one assertion. This allows to properly document each test using the “it” block instead of using the assertion message.</blockquote><p>What we also do is to group the main “<em>describes</em>” by some sort of <em>context</em>, which usually looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6692f9265f2ce803a26175c03bb2eb5a/href">https://medium.com/media/6692f9265f2ce803a26175c03bb2eb5a/href</a></iframe><p>In general, you should structure your test steps by nesting them in a way that they are <em>readable</em>. This implies nesting “<em>describes”</em> on many levels. Don’t be afraid of that, it’s perfectly fine to do it, even more so if we consider the point above of having one “<em>it</em>” block per assertion.</p><p>This approach is called RDD (Readme Driven Development).</p><blockquote>“<em>describes</em>” are meant to explain conditions, whereas “<em>its</em>” are meant to explain the expected output.</blockquote><p>Look at this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e55cd6b2e2faab58c5e9ad54e8e9540d/href">https://medium.com/media/e55cd6b2e2faab58c5e9ad54e8e9540d/href</a></iframe><p>It’s very easy to read and to understand what’s going on. It also allows to have specific setups in each nested “<em>describe</em>” (e.g. rendered component props, mocked imports, etc) using “<em>beforeEach</em>”.</p><p>Speaking about “<em>beforeEach”</em>, it becomes really helpful when you are testing different <em>states</em> of your component. Look at this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cc702bdc22577fafb386578253bc26e/href">https://medium.com/media/3cc702bdc22577fafb386578253bc26e/href</a></iframe><h4>Things to remember if you are using Jest</h4><ul><li>prevent order-of-execution errors — be careful not to mix code sitting next to “<em>describes</em>” and “<em>its</em>” with “<em>beforeEach</em>” hooks. Because hooks are async, Jest will execute the synchronous code first instead of the “<em>beforeEach</em>”, as you would expect.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b76f3490cd2949383d6501134db09c5/href">https://medium.com/media/4b76f3490cd2949383d6501134db09c5/href</a></iframe><ul><li>prevent dependent tests — make sure that each “<em>it</em>” block can be run in isolation. The latest Jest version provides also an easy command in “watch” mode to run specific tests within a test suite.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uN-nGD-mMqE0EIiRkBErxQ.png" /></figure><h4>Tip for increase productivity</h4><p>If use use iTerm, you can “cmd + click” on the file path in the stacktrace, in case the test fails, to jump into the file on the specific line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRlgcfXEJGBELjFzGWwIBw.gif" /></figure><p>Go to “Preferences &gt; Profiles &gt; {profile} &gt; Advanced &gt; Semantic History” and provide (in case you are using Atom):</p><pre>/usr/local/bin/atom \1:\2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCrtBICJ__rMSu7X0dNFCQ.png" /></figure><h3>Shallow vs. mount</h3><p>You’ve got your test structure set up. You can now start testing your React component.</p><p>If you are just getting started with testing in React you probably face one dilemma: how to render the component for testing it? Enzyme provides a “<em>shallow</em>” and a “<em>mount</em>” function. Which one should you use?</p><p>This is really easy to answer: <strong>use “<em>shallow</em>”</strong>! 99% of the time it’s what you want. There has to be a damn good reason to use “<em>mount</em>”. You could even see it as a <em>code smell</em>.</p><p>Why should you not use “<em>mount</em>”? Because unit tests should be isolated. When testing a component we only want to test the logic of that specific component and that component only. If you use “<em>mount</em>” you are automatically exposed to the logic of all components in your render tree making it impossible to only test the component in question.<br>Additionally, “<em>mount</em>” requires <a href="https://github.com/tmpvar/jsdom">JSDOM</a> and therefore <strong>slows down your tests </strong>dramatically.</p><p>Even if you want to test a component in its <em>mounted</em> state you don’t need to use “<em>mount</em>”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc63d0c7c9f406685bc51f63bb7880c/href">https://medium.com/media/3fc63d0c7c9f406685bc51f63bb7880c/href</a></iframe><h3>Test data</h3><p>This is more of a <a href="https://medium.com/javascript-scene/looping-over-child-components-in-react-shotgun-episode-3-396de16289cc#.pglyfwdkq"><em>best practice</em></a> we’ve adopted rather than a rule.</p><p>Instead of passing each single prop to the component we are testing, we define a function that <em>creates test props.</em> Then you just <em>spread</em> the props when rendering the test component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e76814f7471ab7073ed953cd3f67b2e/href">https://medium.com/media/7e76814f7471ab7073ed953cd3f67b2e/href</a></iframe><p>This approach allows us to clearly see the common props that the component expects, it keeps the test setup small and is flexible enough to easily add / override those props for special cases.</p><h3>Mocks and spies</h3><p>Writing unit tests means testing something in <strong>isolation</strong>. When we test React components, we test them in isolation using <em>shallow rendering</em>. We are not interested in what sits outside of the component we are testing, therefore we define mocks to abstract away the real implementation.</p><p>Furthermore, you want to check that all your functions passed as props are being called throughout the tests. To do that it’s a good practice to always provide a <em>spy</em> for props that are functions.</p><p>You can do a lot with spies. With Jest when you call “<em>jest.fn()</em>” you can pass an implementation of that function that does / returns whatever you need it to do.</p><p>In the example below, the “<em>fetchData</em>” function provides a callback that is called when the data fetching is done. We can use “<em>jest.fn()”</em> to simulate the success of the data fetching by executing the callback manually. This allows us to test whatever code runs as a result of a successful data fetching (e.g. show a notification, update the state, redirect to another route, etc).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ff6994f3e4acd72eadd173ae0336e79/href">https://medium.com/media/5ff6994f3e4acd72eadd173ae0336e79/href</a></iframe><p>If you don’t use Jest, you should probably use <a href="http://sinonjs.org/">sinon</a> as your spy/mocking library. If you do use Jest, you have all of this out of the box. Additionally, Jest provides a really powerful <a href="https://facebook.github.io/jest/docs/jest-object.html#jestmockmodulename-factory-options">module mocking</a> system built-in.</p><h3>Snapshot testing</h3><p>What about <a href="https://facebook.github.io/jest/docs/snapshot-testing.html#content">snapshot</a> testing? Couldn’t we have simply tested all of the rendered components with a snapshot test? True, but that’s not always what you want. Snapshot testing is great and we should use it but we should do so with care and only when it makes sense.</p><blockquote>With great power comes great responsibility</blockquote><p>In general, I would say that we should be <strong>explicit</strong> on what elements are rendered or what props are passed to those elements — even if it’s a bit verbose. In the example below, we want to make sure that the “<em>Button</em>” is disabled if a certain limit is reached. If we explicitly test for it, we see how the output log helps us understanding the context (“<em>rendering &gt; &lt;Button&gt; &gt; when limit is reached &gt; should disable the &lt;Button&gt;</em>”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*liqxTH3UVtJ2F9bpfJco6w.png" /></figure><p>If we were to test the entire component solely using a <em>snapshot test</em>, it would still fail (given the same circumstances) but you would lose the context related to the failing test (“<em>rendering &gt; outputs correct tree</em>”). You don’t know anymore <strong>why</strong> the “<em>Button</em>” should be disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGebPFCDgdR98aDC6mJRsw.png" /></figure><p>Nevertheless, in many simple test scenarios, it’s more than enough to just use snapshot testing. Snapshot testing is great when you want to <em>validate</em> the structure of something like a component or an object. Even better is to use them in combination with normal test cases: you get the benefits of snapshot testing as well as the fine-grained control of targeted assertions.</p><h4>When solely using snapshot testing, you…</h4><ul><li>lose the ability of doing TDD — well, you can’t have a snapshot of something that doesn’t exist yet</li><li>lose the ability of doing RDD — the test file no longer describes what is important to be rendered in the component</li><li>don’t know what the actual output “should be”, you only know what it “was” before.</li></ul><h3>Advanced test cases</h3><h4>React elements as props</h4><p>There are cases when the component your are testing renders a component that has a prop in the shape of a React element or a function that returns one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec1be3cdade5f9200dbca96af2b540c0/href">https://medium.com/media/ec1be3cdade5f9200dbca96af2b540c0/href</a></iframe><p>So how would you test those props? In the example above, the component renders “<em>Table</em>” or “<em>Button</em>”, but because of shallow rendering everything beyond that won’t get rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vM7UfP2wd-PrM36pl0WqPw.png" /><figcaption>Output of “wrapper.debug()”, showing how shallow rendering prevents “Button” and “Table” to render their own elements</figcaption></figure><p>This is how you can solve it — it just requires a bit more configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e7909cfeedbed56d61b5c68384423c/href">https://medium.com/media/d4e7909cfeedbed56d61b5c68384423c/href</a></iframe><p>You simply shallow render it as a normal react component. The same thing applies for the prop being a function, you just pass the arguments based on whatever it is that you want to test.</p><h4>FaC components</h4><p>You probably already heard about this: <em>Function as Child</em> components. If you don’t there are <a href="https://medium.com/merrickchristensen/function-as-child-components-5f3920a9ace9#.20tohm7bo">plenty of articles</a> explaining what this is / does. Or you’ve seen this before but you didn’t know it was called like this.</p><p>Let’s take a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9da76667948e78c442e406c69d83b58/href">https://medium.com/media/f9da76667948e78c442e406c69d83b58/href</a></iframe><p>The “<em>Collapsible</em>” component basically manages the <em>toggle state</em> and returns a “<em>isOpen</em>” boolean flag to indicate the current state as well as a “<em>toggle</em>” function to, you know, update the state.</p><p>Imagine wanting to test a “<em>CollapsiblePanel</em>” component which uses the “<em>Collapsible</em>” component. Since you’re testing the “<em>CollapsiblePanel</em>” component with shallow rendering, the child function of “<em>Collapsible</em>” won’t be executed. How do you test this then?</p><p>This is how you can solve it: extract the child function into a function on the component instance, then test the function directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d864895166a34728c87403333790f056/href">https://medium.com/media/d864895166a34728c87403333790f056/href</a></iframe><p>Now all you have to do is to call the “<em>renderPanel</em>” function directly and test the returned value as a normal React component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12a347d3db8e5a3ca734d84c3c08792e/href">https://medium.com/media/12a347d3db8e5a3ca734d84c3c08792e/href</a></iframe><h3>Conclusion</h3><p>Testing React components is not difficult. If combined with a test runner like Jest it provides a really powerful experience. Furthermore, if you follow some guidelines and have a proper structure, people in your team will write tests more consciously, resulting in higher quality, faster iterations, less bugs and more productivity.</p><p>I hope the tips in this article will help you achieve that and improve your development time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/452dc09d24109ff254446f1754273290/href">https://medium.com/media/452dc09d24109ff254446f1754273290/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=577bb98845cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/commercetools-tech/testing-in-react-best-practices-tips-and-tricks-577bb98845cd">Testing in React: best practices, tips and tricks</a> was originally published in <a href="https://medium.com/commercetools-tech">commercetools tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>