<?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 JP on Medium]]></title>
        <description><![CDATA[Stories by JP on Medium]]></description>
        <link>https://medium.com/@jperasmus11?source=rss-918505509b7d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CsScg1Yhry-cI0nwPI9IEw.jpeg</url>
            <title>Stories by JP on Medium</title>
            <link>https://medium.com/@jperasmus11?source=rss-918505509b7d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:50:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jperasmus11/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[Using Layer4 to store off-chain data on-chain]]></title>
            <link>https://blog.layer4.app/store-off-chain-data-on-chain-27ac36bb634e?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/27ac36bb634e</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[on-chain-data]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Tue, 07 May 2024 09:18:58 GMT</pubDate>
            <atom:updated>2024-07-09T14:39:48.348Z</atom:updated>
            <content:encoded><![CDATA[<p>We all know data is king. Is it a good or bad king? That depends on whether it is corruptible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8z_9depum3nVSuAU7EF0A.png" /></figure><p>Storing data in a traditional centralized database is susceptible to manipulation and, therefore, corruption. To make your data more trustworthy, you want to store it on a blockchain so that it is permanent, incorruptible and auditable in an unprecedented and transparent way.</p><p>Assuming you agree with the benefits of persisting your off-chain data on-chain, does that mean you now need to become a blockchain expert to reap the benefits? With <a href="https://www.layer4.app/?utm_medium=social&amp;utm_source=medium&amp;utm_campaign=offchain-onchain-data&amp;utm_content=article-link">Layer4</a>, you don’t.</p><h3>When would you not want to store data on-chain?</h3><p>Data on the blockchain is transparent by default. When people talk about the security of data on-chain, they are not referring to the data being private or secure from being accessed. The security of on-chain data lies in the fact that it is provably unaltered. Data can not be changed without leaving a trace, or manipulated without corrupting the whole network.</p><p>Understanding the blockchain’s public nature, it is clear that you do not want to store any sensitive data <strong>unencrypted</strong> on-chain.</p><h3>Possible use cases</h3><p>The use cases for on-chain data are vast. In the financial sector, the accuracy and transparency of records like invoices can be ensured. The tracking of product movements using IoT devices for the supply chain can be enhanced. Other uses include safeguarding legal documents from unauthorized alterations, proving ownership and provenance of intellectual property such as patents, and facilitating detailed audit trails for regulatory compliance and risk management.</p><h3>Before you record data on-chain</h3><p>Make sure you <a href="https://www.layer4.app/register?utm_medium=social&amp;utm_source=medium&amp;utm_campaign=offchain-onchain-data&amp;utm_content=free-account-link">register for a free account</a> on the Layer4 web app.</p><p>Once you have registered, a workspace will be created for you. You are now ready to <a href="https://docs.layer4.app/buckets/create-bucket/">create a bucket</a> for your on-chain records.</p><h3>Record data via the web app</h3><h4>Bucket Creation</h4><p>To record data on-chain, you need to have a <a href="https://ethereum.org/en/smart-contracts/">smart contract</a> running on your desired blockchain network — don’t worry, Layer4 deploys the contract for you. In Layer4, this is done by creating a bucket. Each bucket is associated with a specific type of smart contract. You want to choose the “<strong>Store data on-chain</strong>” custom contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1GbxUHdk99ypZ4G0TThsg.jpeg" /></figure><p>Ensure you create your bucket for the blockchain network you prefer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MN995cLpnYfK6F7WPpGGgQ.jpeg" /><figcaption>Blockchain Network Selector</figcaption></figure><p>Give your bucket a unique name or go with the auto-generated option, and click “Create”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HOPME24By0pXQBuVFaCXiw.jpeg" /></figure><p>Once your smart contract is ready, it will clearly show that it has been deployed. You can now create your first record.</p><h4>Record Creation</h4><p>From the bucket dashboard of your newly created bucket, click the “+” icon button on the “Records” card. You will be greeted with a short form with which you can add your first record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6ISPGyssgAY8Xq1rsCh9A.jpeg" /></figure><p>The only required field is to add the Data you want to record.</p><p>As of May 2024, a limit of 512 bytes exists on the <em>Data</em> payload. It is generally recommended to upload and reference a file in the Data field if you need larger payloads. Whatever you add to this field is what will ultimately be stored on-chain.</p><p>Let’s cover the other available fields briefly.</p><p>Within your bucket, records are organised into Segments. All buckets come with a <strong>default</strong> segment. You can <a href="https://docs.layer4.app/segments/create-segment/">add as many segments</a> as you need for your use case. Segments aren’t stored on-chain and only serve as an organizational aid for your data within Layer4.</p><p>Add up to 10 optional Files to your record. Files are uploaded to the decentralized and globally distributed <a href="https://ipfs.tech/">IPFS</a> network and can be referenced in the Data payload. To reference a file, you add a special placeholder tag that the platform interpolates after the file is uploaded. Reference the URI to the file with the {{fileUri:0}} tag where 0 is the index of the file in the list of files. To insert the file’s unique content hash, you use the {{fileHash:2}} tag. Again, index 2 here refers to the 3rd file in the files list.</p><p>To richly present the data, you can optionally specify the Content Type of the Data payload. For instance, if your payload is JSON data, you can set it to application/json. If you’re unsure, leave it as the default text/plain type.</p><p>Once you’re happy with your form, double-check that you have enough credits to fund the record, and click the “Request” button. From here, Layer4 will take care of getting your data on-chain.</p><h4>Viewing the record</h4><p>A few seconds later, you should see your finalized record in the records<a href="https://docs.layer4.app/logs/view-logs/"> table</a> within the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMbhRGvjR60Si1IeoIMJEA.jpeg" /></figure><p>Click on the icon at the start of the row for your record to view its details. From the details panel, you see exactly what was stored on-chain, plus any relevant blockchain transaction details, files and other metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-xy1dDohCE9i6sPyUpASg.jpeg" /></figure><p>Congrats, you’ve stored your first off-chain data on-chain. That was <em>easy</em>!</p><p>If you are looking to store larger volumes of data on-chain, doing it manually via the form is not ideal. For that, let’s look at creating a record via the REST API instead.</p><h3>Record data via the API</h3><p>If you don’t have a bucket yet, reference the section above to do that first.</p><h4>Create an API key</h4><p>To use the Layer4 API, you need an API key, which you also <a href="https://docs.layer4.app/api-keys/create-api-key/">create in the web app</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCdLl4q9swhM47pmZ3U3JA.jpeg" /></figure><p>From the “API Keys” card on the bucket’s dashboard, click the “+” icon to create a new key. Give your key a name that will help you distinguish it from other keys. A good practice is to name the key based on where it will be used. Ensure the key has the appropriate scopes (read and/or write) for your use case and select when the key should expire.</p><blockquote>We encourage regular rotation of your API keys.</blockquote><p>Make sure you copy and store the provided API key in a safe place. It can’t be retrieved once it has been created. You will have to create a new key when you want to replace it.</p><p>Confirm you’ve backed up the key and finally click the “Create” button.</p><p>You are now ready to start making API requests.</p><h4>Pick your endpoint</h4><p>It is important to know that Layer4 distinguishes between Records and Record Requests. A Record is the actual entry that has settled on the blockchain. A Record Request, on the other hand, is an entity created before it eventually settles as a Record.</p><blockquote>The same applies for Tokens and Token Requests but that is for another article.</blockquote><p>Record Requests will be processed asynchronously in the order received. Use the Record Request endpoints when you can fire and forget the request without needing to wait for the Record to settle on the underlying blockchain. Also, if the order of the events is important for auditability, these endpoints guarantee the order will be preserved. Since these requests are processed sequentially, it will take longer to persist on-chain under high load.</p><p>If you need to wait for the Record response, you should use the synchronousRecords endpoints. When you use the Records endpoints, the order in which requests are made to the platform becomes fully your responsibility. Bear in mind that these synchronous endpoints will naturally be slower to respond since they need to wait for the transactions to be included on the underlying blockchain. Confirmation times differ vastly from network to network.</p><p>With that out of the way, let’s create our first record asynchronously via aRecord Request.</p><p>Please take note of your bucket ID and API key and replace them in the requests below. We will use <a href="https://blog.hubspot.com/website/curl-command">the </a><a href="https://blog.hubspot.com/website/curl-command">cURL command</a> in our examples, since it is the most universal, but feel free to translate this to your programming language’s preferred HTTP library.</p><blockquote>In my case the bucket ID is <strong>demo-data-storage</strong> and the API key is <strong>bk_test_iiDYquj4MKUkjpvq</strong>.</blockquote><pre>curl -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;x-api-key: bk_test_iiDYquj4MKUkjpvq&#39; \<br>  -d &#39;{&quot;segmentId&quot;: &quot;default&quot;, &quot;contentType&quot;: &quot;text/plain&quot;, &quot;data&quot;: &quot;Data recorded via async API endpoint&quot;}&#39; \<br>  -X POST https://www.layer4.app/api/v1/buckets/demo-data-storage/async/records</pre><p>Take note that this is the <strong>/async/</strong> API, so it will return a Record Request entry.</p><p>If everything was successful, your response should look similar to this:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;id&quot;: &quot;663391a0ff10483f4272c849&quot;,<br>    &quot;createdAt&quot;: &quot;2024-05-02T13:14:08.524Z&quot;,<br>    &quot;updatedAt&quot;: &quot;2024-05-02T13:14:08.524Z&quot;,<br>    &quot;type&quot;: &quot;CREATE&quot;,<br>    &quot;status&quot;: &quot;REQUESTED&quot;,<br>    &quot;payload&quot;: {<br>      &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>      &quot;segmentId&quot;: &quot;default&quot;,<br>      &quot;contentType&quot;: &quot;text/plain&quot;,<br>      &quot;data&quot;: &quot;Data recorded via async API endpoint&quot;<br>    },<br>    &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>    &quot;recordId&quot;: null,<br>    &quot;files&quot;: [<br>      <br>    ]<br>  },<br>  &quot;statusCode&quot;: 201,<br>  &quot;success&quot;: true<br>}</pre><p>All Layer4 REST API responses adhere to the following format:</p><pre>{<br>  &quot;data&quot;: {},<br>  &quot;statusCode&quot;: 201,<br>  &quot;success&quot;: true<br>}</pre><ul><li>The data field contains the response data.</li><li>The statusCode field displays the HTTP status code.</li><li>The success field indicates whether the request was successful.</li></ul><p>We can query for this particular Record Request’s status using the following request:</p><pre>curl -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;x-api-key: bk_test_iiDYquj4MKUkjpvq&#39; \<br>  -X GET https://www.layer4.app/api/v1/buckets/demo-data-storage/record-requests/663391a0ff10483f4272c849</pre><p>Because the Record Request has since settled on the underlying network, the status is now CONFIRMED and you can see the recordId in the response.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;id&quot;: &quot;663391a0ff10483f4272c849&quot;,<br>    &quot;createdAt&quot;: &quot;2024-05-02T13:14:08.524Z&quot;,<br>    &quot;updatedAt&quot;: &quot;2024-05-02T13:14:22.319Z&quot;,<br>    &quot;type&quot;: &quot;CREATE&quot;,<br>    &quot;status&quot;: &quot;CONFIRMED&quot;,<br>    &quot;payload&quot;: {<br>      &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>      &quot;segmentId&quot;: &quot;default&quot;,<br>      &quot;contentType&quot;: &quot;text/plain&quot;,<br>      &quot;data&quot;: &quot;Data recorded via async API endpoint&quot;<br>    },<br>    &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>    &quot;recordId&quot;: &quot;yEBODz1gK0ggJyZT&quot;,<br>    &quot;files&quot;: [<br>      <br>    ]<br>  },<br>  &quot;statusCode&quot;: 200,<br>  &quot;success&quot;: true<br>}</pre><p>We can next query for the related Record using the returned recordId:</p><pre>curl -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;x-api-key: bk_test_iiDYquj4MKUkjpvq&#39; \<br>  -X GET https://www.layer4.app/api/v1/buckets/demo-data-storage/records/yEBODz1gK0ggJyZT</pre><p>This request should respond with a JSON object similar to this:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;createdAt&quot;: &quot;2024-05-02T13:14:22.319Z&quot;,<br>    &quot;updatedAt&quot;: &quot;2024-05-02T13:14:22.319Z&quot;,<br>    &quot;segmentId&quot;: &quot;default&quot;,<br>    &quot;chain&quot;: &quot;POLYGON_AMOY&quot;,<br>    &quot;contentType&quot;: &quot;text/plain&quot;,<br>    &quot;recordId&quot;: &quot;yEBODz1gK0ggJyZT&quot;,<br>    &quot;data&quot;: &quot;Data recorded via async API endpoint&quot;,<br>    &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>    &quot;transactionHashes&quot;: [<br>      &quot;0x162fe22c8128d97646323ac9c929fc6d0d53c37457f5d4032f46136bf6981031&quot;<br>    ],<br>    &quot;contractId&quot;: &quot;66337c7cb83f2f2ff1939cb0&quot;,<br>    &quot;files&quot;: []<br>  },<br>  &quot;statusCode&quot;: 200,<br>  &quot;success&quot;: true<br>}</pre><p>We can confirm that this record exists on the blockchain.</p><p>Since I deployed my Data Storage contract to the Polygon Amoy Testnet, we can find the transaction on the Polygon Amoy block explorer using the returned transactionHashes.</p><p><a href="https://amoy.polygonscan.com/tx/0x162fe22c8128d97646323ac9c929fc6d0d53c37457f5d4032f46136bf6981031">Polygon PoS Chain Amoy Transaction Hash (Txhash) Details | PolygonScan</a></p><p>Or, you can now see this same record in the Layer4 web app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16YJQN5t2uAZmSmHxRSuhg.jpeg" /></figure><p>This concludes the full asynchronous flow for creating Records.</p><p>Before we wrap up, let’s quickly look at how you would use the synchronous Records endpoint to create a record.</p><pre>curl -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;x-api-key: bk_test_iiDYquj4MKUkjpvq&#39; \<br>  -d &#39;{&quot;segmentId&quot;: &quot;default&quot;, &quot;contentType&quot;: &quot;text/plain&quot;, &quot;data&quot;: &quot;Data recorded via sync API endpoint&quot;}&#39; \<br>  -X POST https://www.layer4.app/api/v1/buckets/demo-data-storage/records</pre><blockquote>Note that this endpoint does not have the <strong>/async/</strong> path segment.</blockquote><p>This request directly responds with a Record (as opposed to a Record Request) as we would expect.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;createdAt&quot;: &quot;2024-05-02T14:31:02.368Z&quot;,<br>    &quot;updatedAt&quot;: &quot;2024-05-02T14:31:02.368Z&quot;,<br>    &quot;segmentId&quot;: &quot;default&quot;,<br>    &quot;chain&quot;: &quot;POLYGON_AMOY&quot;,<br>    &quot;contentType&quot;: &quot;text/plain&quot;,<br>    &quot;recordId&quot;: &quot;hxFAGd9U92Q0kyZC&quot;,<br>    &quot;data&quot;: &quot;Data recorded via sync API endpoint&quot;,<br>    &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>    &quot;transactionHashes&quot;: [<br>      &quot;0x55afd17a048b036b6000ce6095eaacba21fdadf09d4b76f3d53dda62fce4e215&quot;<br>    ],<br>    &quot;contractId&quot;: &quot;66337c7cb83f2f2ff1939cb0&quot;<br>  },<br>  &quot;statusCode&quot;: 201,<br>  &quot;success&quot;: true<br>}</pre><p>Finally, let’s query for all the Records we’ve created for our bucket.</p><pre>curl -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;x-api-key: bk_test_iiDYquj4MKUkjpvq&#39; \<br>  -X GET https://www.layer4.app/api/v1/buckets/demo-data-storage/records</pre><p>This request responds with the 3 Records we’ve created in this article:</p><ul><li>one directly in the web app</li><li>one using the asynchronous endpoint</li><li>one using the synchronous endpoint</li></ul><pre><br>  &quot;data&quot;: {<br>    &quot;records&quot;: [<br>      {<br>        &quot;createdAt&quot;: &quot;2024-05-02T14:31:02.368Z&quot;,<br>        &quot;updatedAt&quot;: &quot;2024-05-02T14:31:02.368Z&quot;,<br>        &quot;segmentId&quot;: &quot;default&quot;,<br>        &quot;chain&quot;: &quot;POLYGON_AMOY&quot;,<br>        &quot;contentType&quot;: &quot;text/plain&quot;,<br>        &quot;recordId&quot;: &quot;hxFAGd9U92Q0kyZC&quot;,<br>        &quot;data&quot;: &quot;Data recorded via sync API endpoint&quot;,<br>        &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>        &quot;transactionHashes&quot;: [<br>          &quot;0x55afd17a048b036b6000ce6095eaacba21fdadf09d4b76f3d53dda62fce4e215&quot;<br>        ],<br>        &quot;contractId&quot;: &quot;66337c7cb83f2f2ff1939cb0&quot;,<br>        &quot;files&quot;: [<br>          <br>        ]<br>      },<br>      {<br>        &quot;createdAt&quot;: &quot;2024-05-02T13:14:22.319Z&quot;,<br>        &quot;updatedAt&quot;: &quot;2024-05-02T13:14:22.319Z&quot;,<br>        &quot;segmentId&quot;: &quot;default&quot;,<br>        &quot;chain&quot;: &quot;POLYGON_AMOY&quot;,<br>        &quot;contentType&quot;: &quot;text/plain&quot;,<br>        &quot;recordId&quot;: &quot;yEBODz1gK0ggJyZT&quot;,<br>        &quot;data&quot;: &quot;Data recorded via async API endpoint&quot;,<br>        &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>        &quot;transactionHashes&quot;: [<br>          &quot;0x162fe22c8128d97646323ac9c929fc6d0d53c37457f5d4032f46136bf6981031&quot;<br>        ],<br>        &quot;contractId&quot;: &quot;66337c7cb83f2f2ff1939cb0&quot;,<br>        &quot;files&quot;: [<br>          <br>        ]<br>      },<br>      {<br>        &quot;createdAt&quot;: &quot;2024-05-02T11:49:27.766Z&quot;,<br>        &quot;updatedAt&quot;: &quot;2024-05-02T11:49:27.766Z&quot;,<br>        &quot;segmentId&quot;: &quot;default&quot;,<br>        &quot;chain&quot;: &quot;POLYGON_AMOY&quot;,<br>        &quot;contentType&quot;: &quot;text/plain&quot;,<br>        &quot;recordId&quot;: &quot;atevQFy0jtEPExmH&quot;,<br>        &quot;data&quot;: &quot;The logo for the fictional Acme Corporation.\r\nURI: ipfs://bafkreidgw6djetmvs4kq5aui7tibzhkmayznuwor6q5qq3vvol25cwzmjq\r\nContent Hash: bafkreidgw6djetmvs4kq5aui7tibzhkmayznuwor6q5qq3vvol25cwzmjq&quot;,<br>        &quot;bucketId&quot;: &quot;demo-data-storage&quot;,<br>        &quot;transactionHashes&quot;: [<br>          &quot;0x1f4fcfd4b77bc2df1d7e401749bf1fd04603ef438bdf6ecea0e0962b218fb144&quot;<br>        ],<br>        &quot;contractId&quot;: &quot;66337c7cb83f2f2ff1939cb0&quot;,<br>        &quot;files&quot;: [<br>          {<br>            &quot;id&quot;: &quot;66337dc7b83f2f2ff1939cb4&quot;,<br>            &quot;createdAt&quot;: &quot;2024-05-02T11:49:18.822Z&quot;,<br>            &quot;updatedAt&quot;: &quot;2024-05-02T11:49:18.822Z&quot;,<br>            &quot;byteSize&quot;: 20323,<br>            &quot;hash&quot;: &quot;bafkreidgw6djetmvs4kq5aui7tibzhkmayznuwor6q5qq3vvol25cwzmjq&quot;,<br>            &quot;isPublic&quot;: true,<br>            &quot;mimeType&quot;: &quot;image/jpeg&quot;,<br>            &quot;name&quot;: &quot;acme corp logo.jpg&quot;<br>          }<br>        ]<br>      }<br>    ],<br>    &quot;meta&quot;: {<br>      &quot;hasPreviousPage&quot;: false,<br>      &quot;hasNextPage&quot;: false,<br>      &quot;page&quot;: 1,<br>      &quot;limit&quot;: 20,<br>      &quot;itemsCount&quot;: 3,<br>      &quot;totalItemsCount&quot;: 3,<br>      &quot;totalPagesCount&quot;: 1<br>    }<br>  },<br>  &quot;statusCode&quot;: 200,<br>  &quot;success&quot;: true<br>}</pre><p>Notice the meta object field in the response. This endpoint supports pagination.</p><blockquote>See the full API available in the <a href="https://www.layer4.app/api-docs">API documentation</a>.</blockquote><h3>Conclusion</h3><p>We’ve looked at how Layer4 can help you store your off-chain data on-chain for auditability, transparency &amp; immutability. It should be clear now that Layer4 smoothly facilitates this process without becoming a critical dependency you are tied into.</p><p>We look forward to seeing which use cases you have for storing your data on-chain. Reach out to our team via email if you need any assistance: <a href="/service/mailto:team@layer4.app"><strong>team@layer4.app</strong></a></p><p>Follow us to learn more about Layer4 and its part in exciting use cases and developer tutorials.</p><p><a href="https://www.layer4.app/?utm_medium=social&amp;utm_source=medium&amp;utm_campaign=offchain-onchain-data&amp;utm_content=article-footer-link">Website</a> | <a href="https://www.linkedin.com/company/layer4app">LinkedIn</a> | <a href="https://twitter.com/layer4app">X (formerly Twitter)</a> | <a href="https://www.youtube.com/@layer4app">YouTube</a> | <a href="https://discord.com/channels/1175176360260550780/1175176360260550783">Discord</a> | <a href="https://docs.layer4.app/?utm_medium=social&amp;utm_source=medium&amp;utm_campaign=offchain-onchain-data&amp;utm_content=article-footer-link">User Guide</a> | <a href="https://www.layer4.app/api-docs?utm_medium=social&amp;utm_source=medium&amp;utm_campaign=offchain-onchain-data&amp;utm_content=article-footer-link">API Documentation</a> | <a href="/service/mailto:team@layer4.app">Email</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27ac36bb634e" width="1" height="1" alt=""><hr><p><a href="https://blog.layer4.app/store-off-chain-data-on-chain-27ac36bb634e">Using Layer4 to store off-chain data on-chain</a> was originally published in <a href="https://blog.layer4.app/">Layer4</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 80/20 of Flexbox]]></title>
            <link>https://medium.com/@jperasmus11/the-80-20-of-flexbox-8e555195aa71?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e555195aa71</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[flexbox]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 20:16:06 GMT</pubDate>
            <atom:updated>2019-10-20T20:16:06.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IqIsJ2qNj58O-1z_.png" /></figure><p>This article aims to explain the 20% of flexbox that you’ll use 80% of the time.</p><h3>What is Flexbox?</h3><p>Flexbox is a way to describe how elements should be displayed inside another element. The outer element is called the <em>flexbox container</em>, and the inner elements are known as <em>flexbox items</em>.</p><h3>How does it work?</h3><p>A flexbox container is created by adding a display CSS property with a value of flex on it. Any direct child elements inside this container inherently become flex items. A flex item itself could also be a flex container for its child elements, but consider that as a completely isolated flexbox relationship. A flexbox relationship is always a single level deep between a parent element and one or more children.</p><p>After declaring your flexbox container, all flex items will by default be placed horizontally next to one another, starting at the left and stretching to the height of the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FG0VAQTo9NFNQTYA.png" /><figcaption>The default Flexbox layout</figcaption></figure><h3>Flexbox Container properties</h3><p>To dictate whether flex items should be laid out horizontally or vertically, you set the flex-direction property to either row (horizontal default) or column (vertical). There are also reverse &quot;row&quot; and &quot;column&quot; options available that will lay items out horizontally, from right to left ( row-reverse) or vertically from bottom to top ( column-reverse), assuming you use a horizontal left to right writing mode.</p><p>Assuming you use the default flex-direction: row declaration. To specify how items should be placed on the horizontal axis (known as the <em>main axis</em>), think about the justification options you normally have in a rich text editor, i.e. aligned left, aligned right or centered. In flexbox, you use the justify-content property on the container to do the same. The default is justify-content: flex-start that aligns the items at the start of your main axis. Other possible values are flex-end, your best friend center, and lesser-used space-between, space-around and space-evenly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c3qjamm0zrZtIjo0.png" /><figcaption>Justify Content Examples</figcaption></figure><p>To specify how flex items should be placed vertically in the container, on what is known as the cross axis, you use the align-items property. The available values are very similar to what you get for justify-content, with a few exceptions: flex-start, flex-end, center, stretch and baseline. By default flex items will <em>stretch</em> the full height of the container. To place items at the top or bottom along the cross axis, use flex-start or flex-end respectively. Traditionally, it has been quite hard to vertically centre items using only CSS, but with flexbox, you set align-items: center and call it a day. The baseline option is worth knowing about, but you&#39;ll use less often. If you have neighbouring flex items containing different sized text and you want to align them based on the bottom of the text, use baseline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rZ_7nQs6Yk8Q3SLG.png" /><figcaption>Align Items Examples</figcaption></figure><blockquote><em>Have you noticed that we’ve already catered for most layout requirements, and so far we didn’t specify a single CSS property on any flex item? Everything has been on the flex container. Amazing.</em></blockquote><p>With that said, if you need to align items individually, you can set the align-self property on an item. It takes all the available values that the container&#39;s align-items supports.</p><p>It is worth mentioning again that all the examples so far assume a left-to-right writing mode and the default horizontal row flex-direction. When either of these change, the concepts remain the same, only your perspective changes. What I mean is that in a right-to-left writing mode using flex-direction: column-reverse, items will be justified along the main axis from bottom to top, but now aligned along the cross axis from right to left.</p><p>What I’ve found is that it is easier to grasp the fundamentals first using the standard flex-direction: row. After that, you can swap the flexbox axes around in your mind to visualize how reversed columns would work.</p><p>The last flexbox container property worth talking about is flex-wrap. By default flex items will not wrap to a new row when they run out of horizontal space. They rather get very cosy and squash together as far as possible until the CSS layout engine decides that&#39;s enough.</p><p>To tell these items rather wrap to a new row, set flex-wrap: wrap. As I mentioned, the default is flex-wrap: nowrap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1VL5s5v3-d_FQV9r.png" /><figcaption>Flex Wrap Examples</figcaption></figure><p>That wraps up all the container properties that we’re going to talk about. The rest of the properties are all set for individual flex items.</p><h3>Flexbox Item Properties</h3><p>The cosy behaviour of flex items to squash together can be overridden with the flex-shrink property. This property dictates in what proportion an item should shrink inside the container when space becomes scarce. The default is flex-shrink: 1, which means all items shrink equally. If one of the items is set to flex-shrink: 2 while the rest keep a value of 1, this item will shrink twice as fast. It is important to note that the value is a unitless value that represents the shrinkage proportion and not something like 10px or 50%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A9YBlfBJBlDfTx7B.png" /><figcaption>Flex Shrink Example</figcaption></figure><p>In contrast to flex items’ cosy shrink behaviour, they tend to be slightly shy by nature and will not “occupy all spaces” if any free space is available. In more official terms, all flex items have a flex-grow value of 0 set, which restricts it from growing. Just as with flex-shrink, flex-grow is a unitless value that dictates in which proportion an item should grow within a container if any free space is available. It is important to note that if you have two flex items, one with a flex-grow value of 1 and the other of 2, that does not mean the one item will be twice as big as the other. It means, from all the available space (if any), the one will receive two portions and the other, one portion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9YxP5m91233R2QaC.png" /><figcaption>Flex Grow Example</figcaption></figure><p>The final flex item property we’ll cover is flex-basis. You can think of flex-basis as the width of an item along the main axis. This property needs to be set with any of the standard CSS units, for example px, rem, %, vw, etc. The default is flex-basis: auto which means the item takes the width of the content it contains, similar to a display: inline-block element.</p><p>A caveat to this rule is when a width is specified, in which case the width would trump the default flex-basis: auto. Another interesting thing to be aware of is that if you have a min-width specified along with a non-default flex-basis, the min-width will always take precedence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rcSZZ4Ry4ts0n0Wu.png" /><figcaption>Flex Basis Example</figcaption></figure><p>Of course, there is a lot more to flexbox, like shorthand syntax for some of the properties we looked at. Feel free to <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout">dig deeper</a> once you’re comfortable with these.</p><p><em>Originally published at </em><a href="https://jperasmus.me/posts/the-80-20-of-flexbox"><em>https://jperasmus.me</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e555195aa71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quality-first UI Development]]></title>
            <link>https://medium.com/@jperasmus11/quality-first-ui-development-8ff9d1e8c891?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ff9d1e8c891</guid>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Tue, 23 Jul 2019 20:23:11 GMT</pubDate>
            <atom:updated>2019-07-24T12:38:37.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5tk-YnLnjSIIqrgPhJaDeQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kyran12?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kyran Aldworth</a> on <a href="https://unsplash.com/search/photos/focus?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In the same spirit as <a href="https://en.ryte.com/wiki/Mobile_First">mobile-first</a> and <a href="http://offlinefirst.org/">offline-first</a>, I want to write about quality-first.</p><blockquote><em>It merely means: start with quality in mind and don’t make it an afterthought.</em></blockquote><p>If we say we are professional developers, the quality of the systems we produce is our responsibility.</p><p>Does this apply to you? Ask yourself these two questions:</p><ol><li>Does the majority of the work you do revolve around software development? Not <em>coding</em>, but <em>development</em></li><li>Are you paid to do it?</li></ol><p>If you answered “yes” to both these questions, congratulations, you are a professional! 🎉</p><blockquote><em>You can let the imposter syndrome go, you made it!</em></blockquote><p>No one knows everything. Not even close. We’re all still on the journey to master this craft. Everyone started with zero knowledge, zero experience.</p><p>Now that we’ve established that quality is our responsibility let’s talk about it.</p><p>We’re going to look at quality from two perspectives: UX &amp; DX (user experience and developer experience)</p><p>Instead of getting hung up about the correct definitions here, in light of this post, they mean quality from the perspective of the end-user and the developer.</p><p>I would argue that good DX goes a long way in helping to produce good UX. If you don’t agree, let me know on <a href="https://twitter.com/jpunk11">Twitter</a>.</p><h3>UX</h3><p>We all agree UX is essential. If users have a terrible experience, they’ll leave, and without users, what’s the point in what we build?</p><p>To produce a good user experience, we need to understand our users and how they use our products.</p><p>Some questions we need to ask about our users:</p><ul><li>Who are they?</li><li>From where are they?</li><li>Which browsers do they use?</li><li>Do they have any disabilities?</li><li>Are they native English speakers?</li><li>What type of devices are they using?</li><li>How stable are their internet connections?</li><li>What time of day do they typically use the product?</li></ul><p>You get the point. Most of these you probably already think about, but if you’re not, now is an ideal time to start exercising those empathy muscles.</p><h3>DX</h3><p>Developer Experience is focusing on the developers’ quality of life during the development process. A lot of DX comes down to tooling. These tools include the frameworks we choose to use, our IDE’s, browser developer tools, plugins, CI/CD processes and more.</p><p>If you are a team lead, it is your responsibility to set your team up for a win. Make it hard for teammates to produce poor quality by adequately setting up build processes, linting, tests and deployments.</p><h3>Accessibility</h3><p>Accessibility is sometimes a weird subject, and people get very vocal and defensive about it. It doesn’t need to be that way.</p><p>When you hear accessibility, most people think about blind people, but it is about a lot more. It is about real people with real lives and how we, as developers cater to these humans, our users. It is about the web being accessible to as many people as possible. No other platform can do that.</p><p>According to the <a href="https://www.worldbank.org/en/topic/disability">World Bank Group</a>, 1 billion people, or 15% of the world’s population, experiences some form of disability, with more than 100 million of them with a severe disability.</p><p>To put that in perspective: IE11 currently has <a href="https://caniuse.com/usage-table">2.75% global usage</a>, and we’re building websites that work in it. If we care about this small percentage, why would we not cater to the 15% of people with disabilities? I’m not saying that the full 15% of people with disabilities use the web, but the good news is that these users aren’t using IE, that’s for sure. 🤗</p><blockquote><em>We should not charge extra for accessibility. It is part of the quality that we, as professionals, should deliver.</em></blockquote><h4>Some things to consider:</h4><ul><li>Can your app be navigated with only a keyboard?</li><li>Is your app friendly to screen readers used by people with sight impairments?</li><li>Does your app assume users can distinguish options solely based on colour?</li><li>Is there enough contrast between your UI elements (text vs background colours, etc.)?</li><li>Does the user prefer reduced motion?</li><li>Do all your videos provide subtitles?</li></ul><h4>What can we do?</h4><ul><li>Set up tools like ESlint that make us aware of obvious accessibility issues in our code</li><li>Learn proper HTML semantics</li><li>Learn about ARIA</li><li>Use browser and CLI tools to test accessibility issues</li><li>Play with a screen reader</li><li>Test navigating your app using only your keyboard</li><li>Speak up when you notice UX that could be better. Don’t be a developer that only do what is given to you. Use your beautiful brain; you’re a professional, remember.</li></ul><h3>Security</h3><p>We’re not all working for the CIA, but there are some simple principles we can put in place to vastly improve security in our apps.</p><h4>Things to consider</h4><ul><li>Are all your pages served over HTTPS? There isn’t a good reason for your app not to use it anymore. Most hosting providers provide an SSL certificate for free. More than that, many web API’s and features like <a href="https://developers.google.com/web/fundamentals/primers/service-workers/#you_need_https">Service Workers</a> only work for sites served over HTTPS.</li><li>Use HTTP headers like <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security">HSTS</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP">CSP</a> to restrict your site from ever running over plain HTTP or loading any other resources on your page. With something as basic as this, you can almost eliminate most technical security issues.</li><li>Is your app taking any user input? If so, make sure you sanitize everything. A good example is when writing HTML to the DOM using innerHTML. If the HTML string you&#39;re writing is coming from a user, they can effortlessly inject a script into your app. Expect the worst. It is suitable for a developer to be slightly cynical.</li><li>Most of the time, the most significant gap in our security plans, is us, the humans involved. A solid philosophy to follow when it comes to security is the “<a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">principle of least privilege</a>”. It simply means to provide the minimum permissions needed to accomplish a task and nothing more. For instance, if a user should only be able to add a new entry, don’t give them delete permissions. At startups, when iterating quickly, this can be unnecessary red tape for your internal systems, but think about it and make a decision that suits your team the best.</li></ul><h3>Performance</h3><p>Performance is probably one of the most critical aspects of quality software that we can look at, both from a user’s and a developer’s point of view. Numerous studies have reported the financial gains, or losses companies have when seconds are shaven off from their app load times. We should, therefore, <em>optimize for performance</em> as much as we can.</p><p>We can also look at performance from the point of delivery: how long development of a feature takes. In other words, efficiency. Feature development is an area where faster isn’t always better for quality. On the other hand, slower also does not necessarily mean better quality. Tools can help us.</p><p>Let’s face it; we are not good at repetitive tasks. When you’re moving fast, you can not possibly remember to check everything. Set up your tools beforehand to catch apparent mistakes, and when things slip through the cracks, update your tools for the next time. I use the term “tools” very loosely here. These tools can be code linters, unit tests, spell checkers, release checklists, etc.</p><p>I’m personally not someone that would argue that a Computer Science degree is necessary to be a top-class developer. One thing I would say is that everyone should understand <a href="https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/">Big-O notation</a>. I’m not talking about heavy computer science theory, but as a way to think about the code you just wrote and how well it performs. Understand the difference between time complexity versus space complexity. A function can have O(1) time complexity, but be so extremely heavy in terms of space complexity that your user’s device runs out of memory. An O(1) function is useless in that scenario. With this said, Big-O is something to be aware of — if you’re thinking about it, you are already winning.</p><h3>Communication</h3><p>I’m not going to say much about this, because we hear it all the time, communication is essential in most areas of our lives. Instead of quoting another cliché, let’s talk about one or 2 places where communication is important in our day to day jobs as developers:</p><h4>Code Reviews</h4><p>Few communication tools make such a big difference, in the quality that we produce, as code reviews. I want to encourage you to note how you communicate on code reviews. As the person creating a pull request: are you clear about the intent of your code change? Use commit messages, PR descriptions, or before and after screenshots. These things go a long way in giving your reviewers some much-needed context.</p><p>From a reviewers point of view, are you “listening” (paying attention) to the proposed code change? When you give feedback, are you merely nitpicking at a preferred code style or are you aiming to add value? A good thing to keep in mind is the concept of “ <a href="https://www.radicalcandor.com/">Radical Candor</a>”. It boils down to this: speak plainly but from a place of caring about the person and the product. It is healthy to disagree with and question a code implementation, but it is not cool doing that in a mean and condescending way. Luckily everyone at <a href="https://www.goresponsive.com/">Responsive</a> is generally pretty friendly, so this is rarely an issue. 🙂</p><h4>Task Loggers</h4><p>When you write a task description or comment, be a human, think about the person that will be reading it. If that person is not another developer, don’t use all your tech jargon. If you’re writing things and the other person doesn’t understand you, are you communicating?</p><blockquote><em>Always aim for simplicity and clarity.</em></blockquote><h3>Testing</h3><p>I’ll be first to admit that testing is not always the most fun thing to do. No one makes hacker movies about testing; it just isn’t that sexy.</p><p>There are probably as many opinions about the different types of testing as there are developers with right hands, so here’s mine for UI testing:</p><ul><li>Not all types of testing are useful</li><li>TDD does not work well for pure presentational components. It is much easier to add tests after the fact for this.</li><li>Your tests should reflect how a user would interact with the UI as closely as possible — <a href="https://twitter.com/kentcdodds/status/977018512689455106?lang=en">tweet inspiration</a></li><li>Sometimes tests are not worth the time investment</li><li>Sometimes tests will save your bacon</li><li>Unit tests are beneficial for developers and not for stakeholders — stakeholders should not be concerned with code coverage. Developers should write enough unit tests for them to feel confident, rolling out quality code.</li><li>Unit tests work best for pure logic-based functions</li><li>There is a much higher ROI for end-to-end and integration tests than for unit tests. It is better to spend time setting up automated tests to cover the critical journeys in your application than to chase 100% test coverage for your unit tests.</li><li>Tests should run as part of your CI process so that adding code to your main branches requires passing tests.</li><li>Tests should be first-class code in your app and updated alongside the rest of your app code.</li></ul><p>We now know that we want to put quality first, but how do we practically do that? We touched on many useful tools, but I want to take the rest of this post to chat about one particular tool that puts quality front and centre: <a href="https://www.cypress.io/">Cypress.io</a></p><h3>Cypress</h3><p>Cypress.io is an open-source, front-end testing tool, built for the modern web.</p><h4>Why Cypress?</h4><p>Cypress is most often compared to Selenium, but it is fundamentally different based on its architecture. Some of you, I know, have experience with tools like Chimp and Protractor that uses Selenium under the hood. Chimp uses WebDriver, which is Selenium.</p><p>I’ll admit that writing BDD tests on CHEP was probably my least favourite part while I was on the project. Don’t get me wrong, the idea of automated UI tests excited me just as much as any other dev-nerd, but I sat most of the time debugging flakey tests. It just never seemed to do what I wanted. This led to zero confidence in the tool. What is the point in doing it if it doesn’t give us confidence in the app’s quality?</p><p>Where Selenium and other similar tools interact with your application by sending commands from outside the browser, Cypress takes an entirely different approach and works directly within your browser.</p><h4>Why is this great?</h4><p>Cypress can do things that Selenium simply can’t do. Things like mocking out network requests, setting items in local storage, and directly interacting with your app’s state. Selenium can only make educated guesses about your app’s state; Cypress knows intricately what is going on in your app.</p><blockquote><em>No more flake! No more pain!</em></blockquote><h4>Getting started</h4><p>Getting up and running with Cypress is extremely easy, so I won’t be covering it in this post. Install it from NPM and then to run it. Their <a href="https://docs.cypress.io/guides/overview/why-cypress.html#In-a-nutshell">documentation</a> is excellent — I encourage you to take a look.</p><p>The first time you run the cypress open command, it will install Cypress itself and then open the interface. This UI is an Electron app, and like everything else about Cypress, it is 100% written in JavaScript.</p><p>You can run Cypress with the UI Electron app or headless using the cypress run command. The headless option is useful for integrating Cypress into your CI pipeline.</p><h4>Killer Features</h4><ul><li>Time travel</li></ul><p>Realtime reloads</p><ul><li>Debuggability</li></ul><p>Since Cypress runs inside the same browser context as your app, you can easily debug it with familiar tools. Drop a debugger straight in the code or console.log to your heart&#39;s content. Should I mention that since Selenium uses the same debug protocol as the browser developer tools, it is impossible to open the dev tools while it is running? It is crazy how we have been fine with this for so long.</p><p>On top of that, Cypress gives you meaningful error messages.</p><ul><li>Automatic waiting</li><li>Spies, stubs, and clocks</li><li>Network traffic control</li><li>Consistent results</li><li>Screenshots and videos</li></ul><p>I’ve been relatively harsh towards Selenium up until now. It is only fair to say that Selenium is a decent product that served its time well. In the past, before the era of JavaScript frameworks, web apps were a lot simpler. Every user action almost always resulted in a page refresh, which means there was little to no state that needed to be handled by the client. Today’s apps are incredibly complex, and we need new tools to help us make sense of it all. Cypress is such a tool.</p><h3>Some links:</h3><ul><li><a href="https://docs.cypress.io/guides/getting-started/installing-cypress.html">Installation and Setup</a></li><li><a href="https://docs.cypress.io/guides/getting-started/writing-your-first-test.html">Writing tests</a></li><li><a href="https://docs.cypress.io/guides/core-concepts/test-runner.html">Running tests</a></li><li><a href="https://docs.cypress.io/guides/guides/debugging.html">Debugging tests</a></li></ul><p><em>Originally published at </em><a href="https://jperasmus.me/posts/quality-first-ui-development"><em>https://jperasmus.me</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ff9d1e8c891" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Web Developer’s Oath]]></title>
            <link>https://medium.com/hackernoon/the-web-developers-oath-ef145c1ad495?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef145c1ad495</guid>
            <category><![CDATA[software-developers-oath]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-developers-oath]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-developer]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Tue, 18 Sep 2018 21:32:26 GMT</pubDate>
            <atom:updated>2019-05-02T10:29:18.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2qZNV3Ah0uWIXnV_E9VCQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/u26_RbawXyE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/search/photos/promise?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>For the longest time within the medical profession, new physicians have taken the <a href="https://en.wikipedia.org/wiki/Hippocratic_Oath">Hippocratic Oath</a> (or some variation of it) in which they swear to uphold a certain ethical standard. With the great responsibility resting on these individuals, it makes total sense to do this.</p><p>As developers, our actions can sometimes have massive impact on other people’s lives, but yet ethics is not something discussed much in <a href="https://hackernoon.com/tagged/software-development">software development</a> circles.</p><p>What follows is an adaptation of the Hippocratic Oath, but for web developers.</p><blockquote><em>I swear to fulfill, to the best of my ability and judgment, this covenant:</em></blockquote><blockquote><em>I will respect the hard-won scientific gains of those </em><a href="https://hackernoon.com/tagged/developer"><em>developer</em></a><em> giants whose blogs I’ve read, and gladly share such knowledge as is mine with those newbies who are to follow.</em></blockquote><blockquote><em>I will apply, for the benefit of all project stakeholders, all linting rules that are required, avoiding those twin traps of over-engineering and premature optimizations.</em></blockquote><blockquote><em>I will remember that there is art to web development as well as science, and that warmth, sympathy, and continuous learning may outweigh the developer’s current framework preference or build tools.</em></blockquote><blockquote><em>I will not be ashamed to say “I know not,” nor will I fail to create a Stack Overflow question when the skills of another are needed for a project’s successful outcome.</em></blockquote><blockquote><em>I will respect the privacy settings of my end users’ browsers, for their logins to my app are not disclosed to me to insecurely store in plain text. Most especially must I tread with care in matters of code reviews. If it is given me to approve a PR, all thanks. But it may also be within my power to decline the PR; this awesome responsibility must be faced with great humbleness and awareness of my own code under review. Above all, I must encourage diversity.</em></blockquote><blockquote><em>I will remember that I do not style a button, implement an algorithm, but provide a digital experience, whose outcome may affect my users’ family and mental stability. My responsibility includes these related problems, if I am to care adequately for my craft.</em></blockquote><blockquote><em>I will prevent bugs whenever I can, for continuous improvement is preferable to rewrites.</em></blockquote><blockquote><em>I will remember that I remain a member of society, with special obligations to all my fellow nerds, those sound of mind and body as well as those suffering from imposter syndrome.</em></blockquote><blockquote><em>If I do not violate this oath, may I enjoy fast internet and cross-browser consistency, respected while I code and remembered with affection when I become a project manager. May I always develop so as to preserve my end user’s valuable mobile data and may I long experience the joy of coding apps that are accessible as the open web ought to be.</em></blockquote><p>In all seriousness, as a developer, next time you implement a new feature, create a GitHub issue, write a blog post or deliver a meetup talk, consider the impact of your actions on other people. Behind the code, there is a person.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef145c1ad495" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/the-web-developers-oath-ef145c1ad495">The Web Developer’s Oath</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set Firebase security rules for your Flamelink project]]></title>
            <link>https://itnext.io/how-to-set-firebase-security-rules-for-your-flamelink-project-d855e8210198?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d855e8210198</guid>
            <category><![CDATA[flamelink]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Thu, 13 Sep 2018 14:14:15 GMT</pubDate>
            <atom:updated>2018-11-09T06:42:20.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GP0t7I3CXbma7EHrkk08JA.jpeg" /></figure><p>So you are finally ready to take the training wheels off of your Flamelink project and take it live. Before you do that, have you set proper rules on your database? No really, you should!</p><blockquote>If this is the first time you are hearing about Flamelink, a CMS for Firebase, check out our <a href="https://flamelink.io/">website</a> to get started. After linking up your Firebase project to Flamelink head back here to read about securing your content.</blockquote><h4>EDIT: Please note that this article discusses setting security rules for your Firebase Realtime Database and not Cloud Firestore. More info to follow for CF soon.</h4><p>Not too long ago, a new Firebase project shipped in <em>test mode</em>, ie. <em>reads</em> and <em>writes</em> were open to anyone on the real-time database. Since then the good folks at Firebase decided to change that and default to no read or write access in <em>locked mode</em>. This was done because many developers never bothered to tighten security rules for their projects running in production, leaving their databases open to anyone.</p><p>Now, Flamelink cannot work when your DB is in locked mode, because we would not be able to read/write to the DB from your browser. The only way to access your database in locked mode is from a server environment, which will require access via a service account. At Flamelink, we’ve decided against going that route and leave you, the end user, in full control of your project and the level of access you are comfortable in giving us while still sleeping at night. This comes at a cost in terms of the seamless user experience we can offer, and we might provide both options in the future, but I digress.</p><p>To quickly get started with Flamelink we suggest you set the following database rules for the RTDB (real-time database):</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;flamelink&quot;: {<br>      &quot;.read&quot;: &quot;auth != null&quot;,<br>      &quot;.write&quot;: &quot;auth != null&quot;,<br>      &quot;users&quot;: {<br>        &quot;.indexOn&quot;: [&quot;email&quot;, &quot;id&quot;]<br>      }<br>    }<br>  }<br>}</pre><p>In plain English, this reads:</p><blockquote>No access outside the “<strong>flamelink</strong>” namespace BUT read and write access to authenticated users inside the “<strong>flamelink</strong>” namespace.</blockquote><p><em>The user’s index on the “email” and “id” fields are simply for better query performance and not important for this article on access control.</em></p><p>This is fine to quickly get started, but you can imagine it is not production-ready security to allow any authenticated user to write to your database. On the flip side, you might want some of the content to be readable by anyone regardless of whether they are logged in or not — think blog posts on your website, etc. So how can this be improved? Let’s look at a few options.</p><h4>Things to know</h4><p>There are a few things to know about setting security rules for the RTDB:</p><ol><li>Security rules are completely ignored when accessed from a server, they are only applied when accessed by a client — the browser</li><li>If a rule gives read/write access to a parent node any other child nodes further nested in the DB structure will also have access. In other words, you can’t set a rule to <strong>false</strong> if it is already <strong>true</strong> from a rule higher in the DB structure.</li></ol><p>Watch this video for a really good introduction to the RTDB security rules if you are not already familiar:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPUBnlbjZFAI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPUBnlbjZFAI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPUBnlbjZFAI%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/1f412270a92793622d90a7e37c8dbec3/href">https://medium.com/media/1f412270a92793622d90a7e37c8dbec3/href</a></iframe><h4>Read access for your app or website</h4><p>The easiest one is to give read access to anyone for non-sensitive content, so we’ll tackle that first.</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;flamelink&quot;: {<br>      &quot;.read&quot;: &quot;auth != null&quot;,<br>      &quot;.write&quot;: &quot;auth != null&quot;,<br>      &quot;users&quot;: {<br>        &quot;.indexOn&quot;: [&quot;email&quot;]<br>      },<br>      &quot;environments&quot;: {<br>        &quot;$environment&quot;: {<br>          &quot;content&quot;: {<br>            <strong>&quot;nonSensitiveContentType&quot;: {<br>              &quot;.read&quot;: true<br>            }</strong><br>          }<br>          &quot;schemas&quot;: {<br>            <strong>&quot;.read&quot;: true</strong><br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>What you need to notice is the “nonSensitiveContentType” property, which you can replace with your specific content type’s key. This is specific to your data, so take a look in your database. You can do this for as many of the content types as you like. If you want you can make all content readable as well by just setting:</p><pre>&quot;content&quot;: {<br>  <strong>&quot;.read&quot;: true</strong><br>}</pre><p>This is exactly what we’ve done for “schemas” in our example. If you use the official <a href="https://flamelink.github.io/flamelink">Flamelink JavaScript SDK</a>, you will have to give read access to “schemas”, since this is used to determine if fields are valid, relational and some other goodies like caching.</p><p>Another option for read-access for your app users is to still require users to be authenticated, but then use <a href="https://firebase.google.com/docs/auth/web/anonymous-auth">Firebase’s anonymous sign-in</a>. The benefit this would give you is that your DB will only be readable from within your app (or whether you allow authentication for your project) and not via the REST endpoints for instance.</p><h4>Write access for specific users</h4><p>To restrict write access to your DB to only your Flamelink CMS users, you can specify the unique IDs (uid’s) in your rules like this:</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;flamelink&quot;: {<br>      &quot;.read&quot;: &quot;auth != null&quot;,<br>      <strong>&quot;.write&quot;: &quot;auth.uid === &#39;2TnyIXYi3FPeizykrJiLT972Oy53&#39;&quot;,</strong><br>      &quot;users&quot;: {<br>        &quot;.indexOn&quot;: [&quot;email&quot;]<br>      }<br>    }<br>  }<br>}</pre><p>You can find the UID for your users under the “Authentication” section in your <a href="https://console.firebase.google.com/">Firebase console</a>. You can very easily specify multiple UIDs as well:</p><pre>&quot;.write&quot;: &quot;auth.uid === &#39;2TnyIXYi3FPeizykrJiLT972Oy53&#39; || auth.uid === &#39;LOkg1qVvLgTHWPyOkeBgrGaNuHy3&#39;&quot;</pre><p>If you decided to anonymously log in all your app users, you can further restrict writes by checking for the “anonymous” provider:</p><pre>&quot;.write&quot;: &quot;<strong>auth.provider !== &#39;anonymous&#39;</strong>&quot;</pre><h4>Very dynamic rules</h4><p><em>I want to start off, by saying that we do not suggest that you have to do this, but that it is possible. Continue…</em></p><p>In Flamelink, users are assigned to Permission Groups, each with a unique ID. These permission groups map to certain permissions in the app. A permission group could, for instance, be configured to allow only “<strong>view</strong>” access for schemas, but full <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> access for content. We can make use of these permission groups to dynamically restrict access on the database level.</p><p>Bare with me, this might get nasty. We’ll first look at how we can enforce “<strong>view</strong>” permissions on your content types, but the same technique can be used for any of the other CRUD actions.</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;flamelink&quot;: {<br>      &quot;.read&quot;: &quot;auth != null&quot;,<br>      &quot;.write&quot;: &quot;auth != null&quot;,<br>      &quot;environments&quot;: {<br>        &quot;$environment&quot;: {<br>          &quot;content&quot;: {<br>            &quot;$contentType&quot;: {<br>              &quot;$locale&quot;: {<br>                <strong>&quot;.read&quot;: &quot;auth != null &amp;&amp; root.child(&#39;flamelink&#39;).child(&#39;permissions&#39;).child(root.child(&#39;flamelink&#39;).child(&#39;users&#39;).child(auth.uid).child(&#39;permissions&#39;).val() + &#39;&#39;).child(&#39;content&#39;).child($environment).child($contentType).child(&#39;view&#39;).val() === true&quot;</strong><br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Wow! What the heck?! Okay, let’s break that down because the idea is simple, the syntax not so much. I promise it will make sense.</p><p><strong>The idea:</strong> Get the user’s permission group and check if that permission group is set up to allow “view” permissions for the particular content.</p><p><strong>The syntax:</strong> The rule is made up of two parts: getting the permission group ID and then checking the permission configuration for that group.</p><pre>root<br>  .child(&#39;<strong>flamelink</strong>&#39;)<br>  .child(&#39;<strong>users</strong>&#39;)<br>  .child(<strong>auth.uid</strong>)<br>  .child(&#39;<strong>permissions</strong>&#39;)<br>  .val() + &#39;&#39;</pre><p>This code starts at the root of your database and drills down to flamelink.users.&lt;uid&gt;.permissions, where &lt;uid&gt; is the user ID of the user trying to access the DB. The value of this database field is an integer, so we cast it to a string with + &#39;&#39; so that we can use it in the next part of our rule.</p><pre>root<br>  .child(&#39;<strong>flamelink</strong>&#39;)<br>  .child(&#39;<strong>permissions</strong>&#39;)<br>  .child(<strong>&lt;our-previous-query&gt;</strong>)<br>  .child(&#39;<strong>content</strong>&#39;)<br>  .child(<strong>$environment</strong>)<br>  .child(<strong>$contentType</strong>)<br>  .child(&#39;<strong>view</strong>&#39;)<br>  .val() === true</pre><p>Again, we start at the root of the DB and drill down until we get to the actual permission group’s configuration: flamelink.permissions.&lt;user-permission-group&gt;.content.&lt;environment&gt;.&lt;content-type&gt;.view.</p><p>Each permission group configuration consists of the following 4 boolean properties that map to a standard CRUD config:</p><pre>{<br>  <strong>create</strong>: true,<br>  <strong>delete</strong>: false,<br>  <strong>update</strong>: true<strong>,<br>  view</strong>: true<br>}</pre><p>To check for any of the other permissions, simply replace “<strong>view</strong>” with “<strong>update</strong>”, “<strong>delete</strong>” or “<strong>create</strong>”.</p><p>You might have also noticed the auth != null part at the beginning of the rule. That is to ensure we’re still checking that the user is logged in, otherwise, all our hard work would be undone by someone simply not logged in.</p><p>That is it for the &quot;.read&quot; rule. The &quot;.write&quot; rule is similar to our reads, but more complex because we need to also take into account what the user is trying to do to the data to determine whether we should check the <strong>create</strong>, <strong>update</strong> or <strong>delete</strong> config.</p><p>We’re brave developers, so let’s continue.</p><pre>{<br>    &quot;.write&quot;: &quot;<strong>auth !== null</strong> &amp;&amp;<br>    ((<strong>!data.exists()</strong> &amp;&amp;<br>      root<br>        .child(&#39;flamelink&#39;)<br>        .child(&#39;permissions&#39;)<br>        .child(<br>          root<br>            .child(&#39;flamelink&#39;)<br>            .child(&#39;users&#39;)<br>            .child(auth.uid)<br>            .child(&#39;permissions&#39;)<br>            .val() + &#39;&#39;<br>        )<br>        .child(&#39;content&#39;)<br>        .child($environment)<br>        .child($contentType)<br>        .child(&#39;<strong>create</strong>&#39;)<br>        .val() === true) ||<br>      (<strong>!newData.exists()</strong> &amp;&amp;<br>        root<br>          .child(&#39;flamelink&#39;)<br>          .child(&#39;permissions&#39;)<br>          .child(<br>            root<br>              .child(&#39;flamelink&#39;)<br>              .child(&#39;users&#39;)<br>              .child(auth.uid)<br>              .child(&#39;permissions&#39;)<br>              .val() + &#39;&#39;<br>          )<br>          .child(&#39;content&#39;)<br>          .child($environment)<br>          .child($contentType)<br>          .child(&#39;<strong>delete</strong>&#39;)<br>          .val() === true) ||<br>      (<strong>data.exists() &amp;&amp; newData.exists()</strong> &amp;&amp;<br>        root<br>          .child(&#39;flamelink&#39;)<br>          .child(&#39;permissions&#39;)<br>          .child(<br>            root<br>              .child(&#39;flamelink&#39;)<br>              .child(&#39;users&#39;)<br>              .child(auth.uid)<br>              .child(&#39;permissions&#39;)<br>              .val()<br>          )<br>          .child(&#39;content&#39;)<br>          .child($environment)<br>          .child($contentType)<br>          .child(&#39;<strong>update</strong>&#39;)<br>          .val() === true))&quot;<br>  }</pre><p>Now that we’ve ripped off the bandage, what is happening here?</p><p>Apart from the auth != null check for logged in users, there are 3 distinct parts to our rule, each dealing with a different action (create, delete and update).</p><p>For our <strong>create</strong> action we make use of Firebase’s data.exist() method to check if no data currently exist for the particular content. That is how we know someone is trying to add new data.</p><p>For our <strong>delete</strong> action, we use the newData.exists() method to check if new data would not exist. If the user’s action would result in no new data, we know they’re trying to delete something.</p><p>For our last <strong>update</strong> action, we combine the data.exists() and newData.exists() methods to determine that a user is trying to change existing data to something else.</p><p>That was not so bad, was it?</p><p>For a full example of how this can be applied, see this <a href="https://gist.github.com/jperasmus/73741d5d86ad146b56b61f552786c167">gist</a>.</p><p>This approach is not without its limitations. Since Flamelink is an evergreen and always-evolving product, new features are constantly added which could result in new nodes added to the database. If you tie down the database so much that we cannot make the necessary updates to your database structure, you won’t have access to the shiny new features. You can get around this by combining the UID specific rule we looked at earlier with this dynamic setup and ensure that if the user currently logged in is the owner of the project any writes can be made to the database. This would ensure that when new features are rolled out and the owner logged into the project, the necessary DB structure changes are applied.</p><blockquote>With this said, we very rarely make structural changes because of the evergreen nature of the product.</blockquote><h4>Firebase Custom Claims</h4><p>We’ve left the best for last. The most eloquent solution is to use the lesser known feature of Firebase: <a href="https://firebase.google.com/docs/auth/admin/custom-claims">Custom Claims</a>. We would love to ship Flamelink with custom claims out of the box, but customs claims can only be set from a privileged server environment using the Firebase Admin SDK. What that means is that you, the project owner, will have to handle this yourself.</p><p><strong>What are Custom Claims?</strong></p><p>Simply put, custom claims are custom attributes set on user accounts. You can, for instance, set an isAdmin attribute on a user. This is very powerful because it provides the ability to implement various access control strategies, including role-based access control, in Firebase apps. The amazing thing is that these custom attributes can be used in your database’s security rules.</p><p><strong>Some ideas on how we can use them</strong></p><p>Custom claims should only be used for access control and not to store any additional user data. It is best to store additional data in your database.</p><p>When setting your custom claims, you can keep it simple and set an attribute called flamelinkUser on all your Firebase users which should have write access to content. Alternatively, you can set as elaborate claims at you would like, but bare in mind that the custom claims payload should not exceed a limit of a 1000 bytes. It is recommended to keep it as small as possible since these claims are sent along with all network requests and a big payload can have a negative performance impact.</p><p><strong>How to use these custom claims in our security rules?</strong></p><p>Once set, it is extremely easy to check for custom claims in our database security rules. All custom claims are set on the authenticated user’s auth token.</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;flamelink&quot;: {<br>      &quot;.read&quot;: &quot;auth != null&quot;,<br><strong>      &quot;.write&quot;: &quot;auth.token.flamelinkUser === true&quot;</strong><br>    }<br>  }<br>}</pre><p><strong>How to set custom claims for your users?</strong></p><p>The only requirement for setting custom claims is that they are set from a server environment using the Firebase Admin SDK, whether that is with a stand-alone Express server you have running or using <a href="https://firebase.google.com/docs/functions/">Cloud Functions for Firebase</a>, that is up to you. The code looks something like this (example uses JavaScript, but you can use any of the supported server side languages):</p><pre>// import admin SDK<br><strong>const admin = require(&#39;firebase-admin&#39;);</strong></pre><pre>// initialize admin app with any of the supported options<br><strong>admin.initializeApp(/* config here */);</strong></pre><pre>// create your custom claims object (whatever you want)<br><strong>const customClaims = {<br>  flamelinkUser: true<br>};</strong></pre><pre>// set the custom claims object for given UID<br><strong>admin.auth().setCustomUserClaims(user.uid, customClaims)</strong></pre><p>The admin.auth().setCustomUserClaims() method returns a Promise. It is important to note that setting new custom claims overwrite any existing custom claims, so you might want to first retrieve the existing claims and update it before setting it again.</p><h4>Conclusion</h4><p>Hopefully, this gave you an idea of how powerful and flexible Firebase security rules are. I encourage you to read more about these rules in <a href="https://firebase.google.com/docs/database/security/">Firebase’s documentation</a>.</p><p>If you have any other ideas on how we can improve these security rules, please let us know in the comments below or join our <a href="https://flamelink.io/slack">Slack community,</a> we’d love to have you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d855e8210198" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-set-firebase-security-rules-for-your-flamelink-project-d855e8210198">How to set Firebase security rules for your Flamelink project</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful “reduce” use cases]]></title>
            <link>https://itnext.io/useful-reduce-use-cases-91a86ee10bcd?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/91a86ee10bcd</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Tue, 28 Aug 2018 06:44:24 GMT</pubDate>
            <atom:updated>2018-09-11T19:27:03.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ji3NuzK3DyQUmg-NUBUtOQ.jpeg" /></figure><p>I recently saw a tweet from a developer stating that he understands the array reduce function, but can not think of many useful use cases for it. In this post, I’ll aim to give a couple of real-world use cases for reduce.</p><p>The post will assume you are comfortable with JavaScript Promises; if not, I have a very <a href="https://medium.com/@jperasmus11/roll-your-own-async-compose-pipe-functions-658cafe4c46f">simplified primer</a> on them in a previous post that you can check out.</p><h3>Promise chains</h3><p>Promise.all() is very useful to run numerous promises in parallel, but what if the <strong>order</strong> in which your promises should resolve is important? In that case, you need to run them sequentially. The following function will do exactly that.</p><pre>const promiseQueue = (promiseFn, list) =&gt;<br>  list.reduce(<br>    (queue, item) =&gt; queue.then(async result =&gt; {<br>      const itemResult = await promiseFn(item);<br>      return result.concat([itemResult]);<br>    }),<br>    Promise.resolve([])<br>  );</pre><h3>Sum numbers</h3><p>The most taught and classic example of using reduce is to get the total of an array of numbers, so this list won’t be complete without it. It doesn’t need to be an array of numbers though - you can use more complex data structures.</p><pre>const cities = [<br>  {<br>    city: &quot;Chongqing&quot;,<br>    population: 30165500<br>  },<br>  {<br>    city: &quot;Shanghai&quot;,<br>    population: 24183300<br>  },<br>  {<br>    city: &quot;Beijing&quot;,<br>    population: 21707000<br>  },<br>  {<br>    city: &quot;Lagos&quot;,<br>    population: 16060303<br>  },<br>  // ...etc<br>]</pre><pre>const totalPopulation = cities.reduce(<br>  (sum, city) =&gt; sum + city.population,<br>  0<br>);</pre><h3>Filter and Map</h3><p>When you have a data set that needs to be filtered by some criteria and you want to manipulate each remaining item as well, an okay, but slightly naive option would be to first run filter on it and then map over it again essentially doing a lot more looping-over-items than required. A better option would be to use reduce.</p><p>Say for instance you have the results of all the students that wrote a particular paper, but you are only interested in the full names of all the students that had a mark of more than 80 out of a hundred.</p><pre>const studentsData = [<br>  {<br>    firstName: &quot;Albert&quot;,<br>    lastName: &quot;Einstein&quot;,<br>    score: 53<br>  },<br>  {<br>    firstName: &quot;Charles&quot;,<br>    lastName: &quot;Dickens&quot;<br>    score: 84<br>  },<br>  {<br>    firstName: &quot;Marilyn&quot;,<br>    lastName: &quot;vos Savant&quot;,<br>    score: 99<br>  },<br>  // etc.<br>];</pre><pre>const smartestStudents = studentsData.reduce(<br>  (result, student) =&gt; {<br>    // do your filtering<br>    if (student.score &lt;= 80) {<br>      return result;<br>    }</pre><pre>    // do your mapping<br>    result.push(`${student.firstName} ${student.lastName}`);<br>    return result;<br>  },<br>  []<br>);</pre><h3>Array to Object conversion</h3><p>Sometimes you need an object as output from an array and not another array. All other array higher-order functions will <em>always</em> produce an array as output.</p><p>Say for instance you have an array of form fields with their validation constraints and you want an object of constraints where the name of the field is the top level keys in the object.</p><pre>const fields = [<br>  {<br>    type: &#39;text&#39;,<br>    title: &#39;Title&#39;,<br>    name: &#39;title&#39;,<br>    constraints: {<br>      required: {<br>        message: &#39;^Title is required&#39;,<br>        allowEmpty: false<br>      }<br>    },<br>  },<br>  {<br>    type: &#39;text&#39;,<br>    title: &#39;Slug&#39;,<br>    name: &#39;slug&#39;,<br>    constraints: {<br>      required: {<br>        message: &#39;^Slug is required&#39;,<br>        allowEmpty: false<br>      },<br>      format: {<br>        pattern: &#39;[a-z0-9_-]+&#39;,<br>        flags: &#39;i&#39;,<br>        message: &#39;^Can only be a valid slug&#39;<br>      }<br>    },<br>  },<br>  // etc.<br>];</pre><pre>const validationRules = fields.reduce(<br>  (rules, field) =&gt; Object.assign(rules, { [field.name]: field.constraints }),<br>  {}<br>);</pre><p>This would produce something like this:</p><pre>{<br>  title: {<br>    required: {<br>      message: &#39;^Title is required&#39;,<br>      allowEmpty: false<br>    }<br>  },<br>  slug: {<br>    required: {<br>      message: &#39;^Slug is required&#39;,<br>      allowEmpty: false<br>    },<br>    format: {<br>      pattern: &#39;[a-z0-9_-]+&#39;,<br>      flags: &#39;i&#39;,<br>      message: &#39;^Can only be a valid slug&#39;<br>    }<br>  },<br>  // etc.<br>}</pre><p><em>Note: if you care about not mutating data, you might consider using </em><em>Object.assign({}, rules, { [field.name]: field.constraints }) or using the object spread syntax, </em><em>{ ...rules, [field.name]: field.constraints }. I would advise against this. Personally, I’m a firm believer in the value of immutable data, but with pragmatism. In this case, a new object will be created for each iteration which could end up using quite a lot of unnecessary memory in your app.</em></p><h3>Piping or Composing functions</h3><p>Sometimes you have a sequence of functions that you want to be invoked for a specific value. The useful functional programming methods, compose and pipe are perfect for this, but unfortunately, they are not natively part of the JavaScript language (yet!). Not to worry, we can easily write our own:</p><pre>const pipe = (...fns) =&gt; x =&gt; fns.reduce((v, f) =&gt; f(v), x)</pre><p>pipe is a function that takes a list of functions, calling each function in sequence with the output of the previous function used as the input for the next.</p><p>compose is very similar; it just invokes the functions in reverse order, from last to first, so it can be implemented like this:</p><pre>const compose = (...fns) =&gt; x =&gt; fns.reverse().reduce((v, f) =&gt; f(v), x)</pre><p>An example could be calculating the checkout total for an online store:</p><pre>const calculateTotal = pipe(<br>  applyAnySales,<br>  minusStoreCredit,<br>  applyCouponCode,<br>  addTaxes<br>)</pre><pre>const cardValue = 250;</pre><pre>const total = calculateTotal(cardValue)</pre><p><em>If you have any other practical examples of using </em><em>reduce please leave a comment so that I can learn from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91a86ee10bcd" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/useful-reduce-use-cases-91a86ee10bcd">Useful “reduce” use cases</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“forEach” all the things!]]></title>
            <link>https://medium.com/@jperasmus11/foreach-all-the-things-b3c3313473cc?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3c3313473cc</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Fri, 11 May 2018 15:38:51 GMT</pubDate>
            <atom:updated>2018-05-14T06:51:48.767Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclaimer: this is an opinion piece, feel free to disagree.</em></p><p>Having done a good number of code reviews over the past few years and seeing what comes back to bite us vs. what generally works the way we intended, one such issue is knowing when to use forEach. It comes down to asking yourself the right questions.</p><p>On a separate but related point, I would argue that being comfortable with AND knowing when to use forEach, map, filter or reduce, you can tackle any array-related data manipulation problem, so it really pays, as a developer, putting in the effort to get very comfortable with it. Sure there are some other very useful methods, like flatMap, but knowing these four, you can go a long way.</p><p>This post will use JavaScript as an example, but the concept is the same for any language that supports the higher-order array functions: forEach, map, filter and reduce.</p><h4>Who is this post for?</h4><p>Developers that already know to favour forEach over for loops to write more beautiful (declarative!) code, but are perhaps not comfortable with these higher-order array functions. There is a place for a for loop, but more often than not, you should use the more declarative option.</p><h4>“forEach” all the things!</h4><p>The first thing developers start doing when they move from the imperative for loop to more declarative forEach functions, is that they <strong>“forEach all the things”</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*_HepUVzNXC4oo5jGsco_og.jpeg" /></figure><p>This is okay and definitely better than using for loops everywhere, but we can do better.</p><h4>The thinking process</h4><p>Sure you can use a shoe to hang a picture on the wall, but a hammer is a better tool for the job.</p><blockquote>Use the right tool for the job.</blockquote><p>What follows are questions you can ask yourself while coding and trying to decide whether you should use forEach, map, filter or reduce.</p><h4>1. I’ve got an array of things and I want to manipulate each item in some way</h4><p><strong>The wrong way:</strong> use forEach</p><pre>const list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]<br>const newList = []</pre><pre>list.forEach(item =&gt; {<br>  newList.push(item.toUpperCase())<br>})</pre><pre>console.log(newList) // [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]</pre><p><strong>The right way:</strong> use map</p><pre>const list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]</pre><pre>const newList = list.map(item =&gt; item.toUpperCase())</pre><pre>console.log(newList) // [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]</pre><h4>2. I’ve got an array of things and I want to “reduce” it to one thing</h4><p>This one is easy to remember once you are comfortable with it and it works really well for situations like summing totals or reducing a list of objects into a single object. You can think of reduce as compressing a list of inputs into a single output.</p><p><strong>The wrong way:</strong> use forEach</p><pre>let total = 0<br>const list = [1, 2, 3, 4]</pre><pre>list.forEach(item =&gt; {<br>  total = total + item<br>})</pre><pre>console.log(total) // 10</pre><p><strong>The right way:</strong> use reduce</p><pre>const list = [1, 2, 3, 4]</pre><pre>const total = list.reduce((sum, item) =&gt; sum + item, 0)</pre><pre>console.log(total) // 10</pre><p>This example, to sum a few numbers, doesn’t make the pain obvious, but working with more complex data will surface the problem.</p><h4>3. I’ve got an array of things, but I only want a subset of them</h4><p><strong>The wrong way:</strong> use forEach <em>(noticing a pattern here?)</em></p><pre>const list = [1, 2, 3, 4]<br>const evenNumbers = []</pre><pre>list.forEach(item =&gt; {<br>  if (item % 2 === 0) {<br>    evenNumbers.push(item)<br>  }<br>})</pre><pre>console.log(evenNumbers)</pre><p><strong>The right way:</strong> use filter</p><pre>const list = [1, 2, 3, 4]</pre><pre>const evenNumbers = list.filter(item =&gt; item % 2 === 0)</pre><pre>console.log(evenNumbers)</pre><h4>4. I’ve got an array of things and I want to perform an action for each item but I don’t care about a return value</h4><p><strong>The wrong way:</strong> use map, filter or reduce</p><p>Just like it is technically possible to use forEach for everything else, as we saw above, it is possible to use any of the other higher-order functions here, but it would not be the right tool for the job.</p><blockquote>“It is just semantics” is not a thing.</blockquote><pre>const list = [&#39;user1&#39;, &#39;user2&#39;, &#39;user3&#39;]</pre><pre>const newList = list.map(user =&gt; fireAndForgetNetworkRequest(user))</pre><pre>console.log(newList) // [undefined, undefined, undefined]</pre><p><strong>The right way:</strong> use forEach</p><pre>const list = [&#39;user1&#39;, &#39;user2&#39;, &#39;user3&#39;]</pre><pre>list.forEach(user =&gt; fireAndForgetNetworkRequest(user))</pre><pre>// nothing to log</pre><blockquote><strong>Hint</strong>: If you can’t declare your variables with <em>const</em> and you need to use <em>let</em>, you might be using the wrong method.</blockquote><h4>TL;DR;</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*8AOqGSDe1pzNAb1nMrYOTA.png" /></figure><p>If you made it this far, hopefully the post wasn’t too boring. Let me know in the comments if you disagree with anything or if you have some better examples that I haven’t thought of.</p><p><em>Published: 10 May 2018</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3c3313473cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Roll your own async compose & pipe functions]]></title>
            <link>https://itnext.io/roll-your-own-async-compose-pipe-functions-658cafe4c46f?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/658cafe4c46f</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Tue, 19 Sep 2017 05:59:22 GMT</pubDate>
            <atom:updated>2018-09-18T22:31:30.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muSiJcg5NrYQZ0845esMCA.jpeg" /></figure><p>The functional programming inspired functions compose and pipe are awesome, but they only work with synchronous functions. I am going to show you how to write your own functions that will work with both synchronous and asynchronous functions combined, if that’s your type of thing.</p><h3>Cool story bro, just show me the code already!</h3><p>Fine, here you go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ed646ee009458afbc780ccf2e162cd6/href">https://medium.com/media/7ed646ee009458afbc780ccf2e162cd6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebbace6eabc22ad8081729de9c2a9694/href">https://medium.com/media/ebbace6eabc22ad8081729de9c2a9694/href</a></iframe><h4>Right, now what?</h4><p>If you came here just to get a code snippet, there is no shame in that, feel free to add it to your project and go on with your life! Otherwise, if you’re interested in knowing how it works, continue reading.</p><p>It might get a bit hairy but bare with me. If you are familiar with certain parts, just skip ahead.</p><p>These functions require Promises to be available in your application environment, whether that is the browser or server side with Node. If you are developing for the modern web (not including IE), Promises are already supported in most browsers. Back in the real world, you will probably use a <a href="https://github.com/stefanpenner/es6-promise">polyfill</a> or some other third-party library, like <a href="https://www.npmjs.com/package/bluebird">bluebird</a>, that gives you Promise support. Odds are that if you’re reading this you are probably already familiar with Promises, if not, here is a quick primer.</p><h3>Simplified Primer on Promises</h3><p>A Promise is an object that represents an action that will finish at some time in the future. What that means, is that you create your Promise for an asynchronous action, like an AJAX request, and when it finishes, similar to using a success callback, you call its resolve function; if it fails, you call its reject function.</p><p>The Promise object exposes 2 functions that map to the 2 “callback” functions, namely: .then() that will be called when you resolve the promise and .catch() when you reject it.</p><p>There’s loads more to Promises but if you understand that, you’ll be just fine.</p><h3>What’s the deal with compose &amp; pipe?</h3><p>On Medium alone there are numerous articles about the intricacies of compose and pipe which does a great job at explaining it. If you’re too lazy to google it right now and seeing that you are already here, I’ll try and explain: composition is like Lego for grown-ups. It’s a way to build something more complex by using smaller simpler units. In functional programming, compose is the mechanism that composes the smaller units (our functions) into something more complex (you guessed it, another function).</p><p>So, compose takes a list of functions and returns another function that you can call with your data. An example will clear it up:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9e2327e35fc6e057b823f0005724c2d/href">https://medium.com/media/a9e2327e35fc6e057b823f0005724c2d/href</a></iframe><p>To keep things simple, we create 3 basic functions that do simple arithmetics: double, square and plus3. Nothing special here, double takes a value and multiplies it by 2; square takes a value and multiplies it with itself, and finally, plus3 does exactly that — it takes a number and adds 3 to it.</p><p>On line 5, we use our compose method to create a new composedFunction that is build up of our 3 simpler functions. Each time this composedFunction is invoked it will apply these 3 functions to whatever value we pass to it. On line 7, we invoke our composedFunction with the value 2. To visualize what is happening here, picture this:</p><pre>double(square(plus3(2)))</pre><p>That is ugly, but it brings the point across.</p><p>The value 2, is passed into the plus3 function which produces 5. This result becomes the input for our square function, which in turn produces 25. Lastly, we invoke the double function with 25, which then produces 50.</p><p>This is obviously a ridiculously simple example, but the main point is to think of complex problems as the sum of a bunch of smaller problems that you can solve and compose together.</p><p>Now, imagine you have a response from an API call to retrieve a list of products, you want to map over each product and only pluck certain properties like the title, description and let’s say price. Then you also want to filter out all the products that are cheaper than $5 and lastly sort the results alphabetically.</p><p>The old you would write 3 functions: pluckProperties, getCheap and sortByTitle and do something like this:</p><pre>const products = // array of product objects</pre><pre>const result = pluckProperties(sortByTitle(getCheap(products)))</pre><p><strong><em>Bonus Tip:</em></strong><em> always filter first before doing anything else with a dataset, so that you loop through the smallest number of entries.</em></p><p>The new you will use compose to create your reusable getProducts function:</p><pre>const getProducts = compose(pluckProperties, sortByTitle, getCheap);</pre><pre>const products = // array of product objects<br>const result = getProducts(products)</pre><p>Hopefully, you are seeing the beauty in using compose by now. If not, all hope is lost and I can’t help you. Jokes. Keep thinking about it and see where it will help you write cleaner more reusable (read: <strong>better!</strong>) code in your day job.</p><p>We’ll quickly touch pipe as well. It is exactly the same as compose but it applies the functions from left-to-right instead of right-to-left.</p><p>Using pipe, our example will look like this:</p><pre>const getProducts = pipe(getCheap, sortByTitle, pluckProperties);</pre><pre>const products = // array of product objects<br>const result = getProducts(products)</pre><p>pipe is very useful for writing step by step procedures, like:</p><pre>pipe(logUserIn, displayNotification, redirectToHomepage)(user)</pre><h3>What’s cool about async compose and pipe?</h3><p>Traditionally, compose and pipe only works on synchronous functions that you can pass an input value, it does something with the input and then returns an output. Looking at the above pipe example, you will agree that the logUserIn function will most likely be an asynchronous function because you need some communication with a server/database. This won’t work then. Time to cry in the shower.</p><p>Let’s fix that by using our own improved pipe function:</p><pre>pipe(logUserIn, displayNotification, redirectToHomepage)(user)<br>  .then(() =&gt; {<br>    // The user is logged in<br>    // the login notification has been displayed<br>    // and s/he has been redirected to the homepage<br>  })</pre><p>That’s it, you’re done!</p><h3>Let’s break it down</h3><p>For reference, here is the compose snippet again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ed646ee009458afbc780ccf2e162cd6/href">https://medium.com/media/7ed646ee009458afbc780ccf2e162cd6/href</a></iframe><p>First, we see compose is a function that returns a function (example uses standard JavaScript functions):</p><pre>const compose = function(...functions) {<br>  return function(input) {<br>    // ...<br>  };<br>}</pre><p>It uses the ES2015 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a> to combine all the passed in functions as an array of functions.</p><p>To understand the body of the inner function, it is important that you are comfortable with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=b">reduce</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight">reduceRight</a> array methods that are natively part of JavaScript.</p><p>reduce loops over each item in a given array and apply a function to it, with each function’s result being the input of the next item’s function. Whenever you have a list of something and you want to “reduce” it to a single value, use the reduce or reduceRight methods. These methods take 2 arguments, the first is the function that needs to run for each item in the array and the second is the optional starting value.</p><p>The easiest is to think of it as a SUM() or a TOTAL() method, for example:</p><pre>const numbers = [ 1, 5, 9 ];<br>const total = items.reduce(function(sum, number) {<br>  return sum + number;<br>}, 0);</pre><pre>// total = 15 (1 + 5 + 9)</pre><p>The output of each function is the input of the next. For the first number in the array (1), sum will be 0 as that is the starting value and number will be 1. The second number (5) will take 1 as the value of sum and number will be 5, which produces 6. For the third number (9), sum will, therefore, be 6 and number will be 9, which produces the final output of 15.</p><p>The only difference between the reduce and reduceRight is that reduceRight loops over the items in your array from right-to-left (last-to-first) instead of left-to-right (first-to-last).</p><p>Okay, now that we understand reduce and Promises, let’s put them together to understand the final piece of our compose function.</p><pre>functions.reduceRight(<br>  (chain, func) =&gt; chain.then(func),<br>  Promise.resolve(input)<br>)</pre><p>Instead of looping through an array of numbers as we did in our example, here we loop over an array of functions. Instead of starting with the value 0, here we start with a Promise that immediately resolves to the value we called our composed function with.</p><p>Inside our reduce/accumulator function, instead of building up a sum, we are chaining together Promises that will resolve in sequence. To visualize this using our user login example, this is what would be produced:</p><pre>logUserIn(user)<br>  .then(displayNotification)<br>  .then(redirectToHomepage)<br>  .then(result =&gt; `Do whatever we want with the ${result}`)</pre><h3>Wrapping up</h3><p>Hope you found this useful and if you want to include these functions in your project, either copy-paste it in or grab it from NPM:</p><ul><li><a href="https://www.npmjs.com/package/compose-then">https://www.npmjs.com/package/compose-then</a></li><li><a href="https://www.npmjs.com/package/fp-pipe-then">https://www.npmjs.com/package/fp-pipe-then</a></li></ul><p><em>If you have better ideas or something cool to share, please let me know; would love to learn from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=658cafe4c46f" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/roll-your-own-async-compose-pipe-functions-658cafe4c46f">Roll your own async compose &amp; pipe functions</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain sharding on the modern web]]></title>
            <link>https://medium.com/@jperasmus11/domain-sharding-on-the-modern-web-dc97df4f6a90?source=rss-918505509b7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc97df4f6a90</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[browsers]]></category>
            <dc:creator><![CDATA[JP]]></dc:creator>
            <pubDate>Thu, 07 Sep 2017 18:57:23 GMT</pubDate>
            <atom:updated>2017-09-14T09:46:19.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57Rx8QY-2M4v4bW0UvwvfA.jpeg" /></figure><blockquote><strong>TL;DR;</strong><br>You probably don’t need it. If possible, implement a service worker to cache front-end assets and serve up your app from a HTTP/2 supported server, but you probably don’t need that either.</blockquote><p>Recently I’ve been tasked to implement domain sharding on one of <a href="https://www.goresponsive.com/">our</a> client’s web apps following recommendations from a well-known technical consultancy company. Domain sharding is something I’ve implemented a few times before, but not recently, so I wanted to research the subject again. This is the conclusion I came to.</p><h3><strong>What is it?</strong></h3><p>Domain sharding is the official name for a technique used by web developers to load resources from multiple domains/subdomains in an attempt to overcome a browser’s limit on the number of concurrent requests it can make, and therefore improving load performance. The premise of this is that browsers can only make a set limit of parallel requests per hostname, as suggested in the original HTTP/1.1 specification (last updated in 1992). At first glance, this sounds great — make all the things performant!</p><h4>Number of concurrent requests per browser</h4><p>Like all things web, finding a standard for the number of concurrent requests browsers support, is no straight forward task.</p><p>For older browsers, like IE6/7, this limit was 2 requests per hostname, but with more modern browsers the limit ranges with an average of around 6. Another interesting limit is that browsers have a total limit of concurrent connections regardless of the number of different hostnames used. This can be a major reason against domain sharding, if you consider that some browsers only support 10–17 requests max in any case.</p><p>These limits were decided on and implemented by browser vendors with much thought and experimentation to reduce the load on servers and find the optimum amount for most sites. Browser vendors cannot possibly be expected to implement a generic solution for all types of specific use cases. You as the developer would know best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*a9x9kS_1CWiE38vXYjFO0A.png" /><figcaption>Info taken from <a href="http://www.browserscope.org/?category=network&amp;v=top">Browserscope</a>.</figcaption></figure><h4>When is it useful?</h4><p>The main advantage of using domain sharding is to allow blocked assets to be downloaded faster than when they get queued and downloaded sequentially. Most CDN’s as well as awesome services like <a href="http://cloudinary.com/blog/reduce_site_load_time_with_multiple_cdn_sub_domains">Cloudinary</a>, support multiple concurrent calls, so they are geared for domain sharding. It is generally most useful for image-heavy dynamic sites (think product catalogue on e-commerce website), where these images are frequently updated and a large number of them can exist on a single page. For a long time, it has been considered a best practice for these types of sites. Is this still relevant today? Let’s continue…</p><h4>I want to implement domain sharding; how many subdomains should I use?</h4><p>In 2007, when domain sharding was still highly recommended, Yahoo did an <a href="https://yuiblog.com/blog/2007/04/11/performance-research-part-4/">experiment</a> and found that the optimum amount of subdomains were between 2 and 4, with anything more than 4 actually degrading the performance. One of the reasons for this is that each additional host requires new DNS lookups which could add 100–200ms+ to each call depending on where the DNS servers were located in relation to the user. If you are serving users globally, I would not use more than 2 subdomains.</p><h4>SPDY &amp; HTTP/2</h4><p>In 2015, the <a href="https://www.ietf.org/">Internet Engineering Task Force (IETF)</a> released the second major version of the HTTP protocol, not surprisingly called HTTP/2. As a precursor to HTTP/2, Google wanted to scratch their own itch for a better protocol with reduced load latency and started developing the <a href="https://developers.google.com/speed/spdy/">SPDY</a> (pronounced Speedy) protocol. This set the stage for HTTP/2.</p><p>It allows for sending multiple requests for data over a single TCP connection along with a number of other benefits, including fewer header data over the wire and keeping connections open for longer, making them a lot faster without the handshake overhead. It also requires that your site is served over HTTPS.</p><p>HTTP/2 is not perfect, mostly because it needs to be backwards compatible with HTTP/1.1, but is a welcoming step in the right direction for the web. Read more it <a href="https://www.upwork.com/hiring/development/the-http2-protocol-its-pros-cons-and-how-to-start-using-it/">here</a> and <a href="https://developers.google.com/web/fundamentals/performance/http2/">here</a>.</p><h4>Things to consider before implementing domain sharding</h4><p>Domain sharding is very use-case specific and not a good solution for all sites. The technique is also a bit outdated now and had its glory days around 2009–2013 and before that when browsers had a much smaller limit of concurrent calls. If you are supporting only A-grade browsers for your site then concurrent requests are a much smaller problem.</p><p>The most important thing to consider, in my opinion, is the browsers your site or web app needs to support. If you need to support older versions of IE (&lt;IE10) I would not rule out scrapping domain sharding as a possible performance improvement.</p><p>Domain sharding is not as useful for sites with mostly static assets that do not change often, because they will get cached in the browser’s cache. The user will still feel the impact on the first load. You will get further by pushing down less Javascript, CSS and other assets to your users by making use of techniques like code-splitting, but that is a topic for another post.</p><p>It’s also important to ensure that domain sharding isn’t done randomly and assets should consistently be loaded from the same sub-domain. This is to ensure that browser caching can be better utilized, which will always be much faster than any amount of parallel downloads. E.g.: if you load an image from <strong>sub1.example.com</strong> then make sure that the image always gets loaded from <strong>sub1.example.com</strong> and not sometimes from <strong>sub2.example.com</strong>. Loading the image from different domains will actually worsen your page load performance.</p><p>Investigate where in your web app or site you are actually running into assets which are being queued because of the browser’s concurrent call limitation. It might not actually be a problem. Then, first try to reduce the number of assets before deciding on using domain sharding.</p><p>If you are using a server supporting SPDY or HTTP/2 then domain sharding will most likely also hurt performance.</p><h3>Final words &amp; recommendation</h3><p>My recommendation would be to implement a service worker and cache all front-end assets on the device’s filesystem. This is by far the quickest method of getting assets loaded.</p><blockquote>The fastest network request is no network request.</blockquote><p>If it’s not possible to implement a service worker because of browser support (hint: <a href="https://jakearchibald.github.io/isserviceworkerready/">browser support is not bad</a>) or you really want to use domain sharding, then my recommendation would be to add one additional subdomain (for front-end assets served from a CDN). This ensures that the assets are always loaded from the same host. If you have an API then that can be served from another domain.</p><p>First try and optimize the number of requests being made so you don’t have unnecessary calls blocking other more important calls. Additionally, look at implementing HTTP/2 support on your server.</p><p><em>If you agree or disagree with anything I’ve written please let me know; I’m always interested in learning from others.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc97df4f6a90" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>