<?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 Ikeh on Medium]]></title>
        <description><![CDATA[Stories by Ikeh on Medium]]></description>
        <link>https://medium.com/@ikehakinyemi?source=rss-ac4a72da674d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S0AAklCl9ndZR3Ir2oRcXQ@2x.jpeg</url>
            <title>Stories by Ikeh on Medium</title>
            <link>https://medium.com/@ikehakinyemi?source=rss-ac4a72da674d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:58:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ikehakinyemi/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[Add RBAC & ABAC to a Webflow App Using PermitIO]]></title>
            <link>https://ikehakinyemi.medium.com/add-rbac-abac-to-a-webflow-app-using-permitio-39926b7cc9a8?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/39926b7cc9a8</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[webflow]]></category>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[abac]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 17:02:06 GMT</pubDate>
            <atom:updated>2025-06-10T17:02:06.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMzV18UCvt9p8MPMXhTBpA.png" /><figcaption>Add RBAC &amp; ABAC to a Webflow App Using PermitIO (AI generated)</figcaption></figure><p>Modern web applications require sophisticated authorization systems that go beyond simple “logged in” or “logged out” states. Whether you’re building a content management system, a collaborative workspace, or an enterprise application, you need to control who can access what resources and perform which actions. This is where authorization comes into play.</p><p>The challenge lies in implementing these authorization systems in Webflow, a no-code platform that doesn’t natively support server-side authorization logic. Traditional approaches require building custom authentication servers and managing complex permission states, often leading to security vulnerabilities or inconsistent authorization enforcement. Webflow’s client-side nature means authorization logic needs careful architecture to prevent tampering while maintaining seamless user experience.</p><p>In this tutorial, you’ll learn how to implement both RBAC and ABAC in a Webflow application using Permit.io, an authorization-as-a-service platform that handles the complexity of permission management. We’ll create an Event Management Dashboard for an organization where different departments organize and manage events. Our application will demonstrate:</p><ul><li><strong>RBAC</strong>: Administrators can manage all events, Organizers can manage department-specific events, and Attendees can only view events</li><li><strong>ABAC</strong>: Users can only edit events they organized or events from their department, with additional time-based restrictions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XdHNSBmUi6lOn6B2.png" /></figure><h3>Prerequisites</h3><p>To follow this tutorial, you’ll need:</p><ul><li>A <a href="https://app.permit.io/signup">Permit IO account</a></li><li>A <a href="https://render.com/">Render account</a> for deployment</li><li>Basic understanding of JavaScript and REST APIs</li><li>A Webflow account with a Basic site plan to work with. Visit the <a href="https://webflow.com/made-in-webflow/website/ikehs-superb-site">Webflow Marketplace</a> to clone a copy of the web application we’ll work with for the rest of the article.</li></ul><h3>Getting Started with Permit IO</h3><p>Before diving into code, we need to set up our authorization platform. Creating a Permit IO account gives you access to their dashboard, where you’ll define your authorization model visually before implementing it in code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*locIhw-n6wMdGPbb.png" /></figure><p>After signing up at Permit IO, create a new project called “Event Management.” This project will house all our authorization configurations. Navigate to the “Projects” page, and click on the “New Project” button. Remember to switch to the Development environment — this is where we’ll set up our entire authorization model before promoting it to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YznzXoQvWw658Zg4.png" /></figure><p>Now, the first step is defining what we’re protecting. In Permit IO, these are called “resources.” For our event management system, we have one primary resource: Events. Navigate to the Policy tab and create an Event resource with these actions: create, read, update, delete, and publish. This gives us fine-grained control over what operations users can perform on events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q2YvW50M1r-QWZF6.png" /></figure><p>Next, we need to establish our roles. Click on the Roles tab and create three roles that reflect our organizational structure: Administrator (full access), Organizer (can manage events in their department), and Attendee (read-only access). These roles form the foundation of our RBAC implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ie2CFfW7M44AMTcq.png" /></figure><p>Now comes the critical part: connecting roles to permissions. In the Policy Editor, you’ll see a matrix where roles meet actions. Check the appropriate boxes — Administrators get all actions on Events, Organizers get create, read, update, publish, while Attendees only get read access. This simple yet powerful configuration is the heart of RBAC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lSk705UCnV2Ig8rf.png" /></figure><h3>Building the Authorization Backend</h3><p>Unlike traditional approaches where we’d build the authorization system from scratch, for this tutorial, we’re starting with a pre-built backend service that’s already been deployed and tested. This approach lets us focus on integrating authorization into your Webflow application rather than spending time building infrastructure.</p><p>The backend service codebase we’ll be using is available on GitHub at <a href="https://github.com/Ikeh-Akinyemi/permit-io-webflow">permitio/webflow-permit-tutorial</a>. This Express.js server acts as a secure bridge between your Webflow frontend and Permit IO’s <a href="https://docs.permit.io/concepts/pdp/overview/">Policy Decision Point (PDP)</a>. By having this intermediary layer, we protect your API keys and ensure authorization checks happen server-side where they can’t be tampered with.</p><p>Here’s what the backend project structure looks like:</p><pre>permit-io-webflow/<br>├── Dockerfile<br>├── index.html<br>├── package.json<br>├── package-lock.json<br>└── src/<br>    └── index.js</pre><p>The beauty of this setup is its simplicity. The index.js file contains all the routes you&#39;ll need for RBAC and ABAC operations:</p><ul><li>/api/auth/sync-user - Registers users with Permit IO</li><li>/api/auth/check-permission - Checks basic role permissions (RBAC)</li><li>/api/auth/assign-role - Assigns roles to users</li><li>/api/auth/check-context-permission - Handles attribute-based checks (ABAC)</li><li>/api/auth/get-user-attributes - Retrieve user attributes for ABAC</li></ul><p>Both the authorization backend and PDP are already deployed and running:</p><ul><li>Backend API: https://permit-io-webflow-1.onrender.com on Render</li><li>PDP Service: The Permit.io team provides a managed Cloud PDP at https://cloudpdp.api.permit.io which is available globally. You can as well deploy your instance using the <a href="https://docs.permit.io/concepts/pdp/overview/#run-a-local-pdp-with-docker">Docker image</a> provided on their website.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vHK7tMUigwQOWjZ9.png" /></figure><p>You can use these endpoints directly for development, or clone the repository to deploy your own instances:</p><pre>git clone https://github.com/Ikeh-Akinyemi/permit-io-webflow.git<br>cd permit-io-webflow</pre><p>If you choose to deploy your own instance, you’ll need to:</p><ol><li>Get your API key from the Permit IO dashboard (Projects → Your Project → Development → Copy API Key)</li><li>Update environment variables:</li></ol><ul><li>PERMIT_API_KEY: Your Permit IO API key</li><li>PDP_URL: URL of your deployed PDP service (if deploying separately)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ltjYvW42NGFqdCsH.png" /></figure><p>The backend uses a standard Express.js setup with the Permit IO SDK integrated. All authentication routes are protected with CORS to ensure they can only be called from your Webflow domain, adding an extra layer of security to your implementation.</p><p>Let me continue with the implementation section, focusing on how we’ll integrate authorization into Webflow using data attributes instead.</p><h3>Implementing Authorization in Webflow</h3><p>Since Webflow operates primarily in the browser, we need a practical approach to implement authorization that works within Webflow’s constraints. We’ll use custom data attributes to mark elements that require permission checks.</p><h4><strong>Setting Up the Authorization Script</strong></h4><p>First, let’s add our authorization script to the Webflow project. Navigate to your site settings on the dashboard, click on the “Custom Code” tab, and add the following script to the “Head Code” section:</p><pre>&lt;script&gt;<br>document.addEventListener(&#39;DOMContentLoaded&#39;, function () {<br>  // References to elements<br>  const signinButton = document.querySelector(&#39;.signin-button&#39;);<br>  const signinButtonContainer = document.querySelector(&#39;.sign_in_container&#39;);<br>  const signinDialog = document.querySelector(&#39;.signin-dialog&#39;);<br>  const formContainer = document.querySelector(&#39;.form-container&#39;);<br>  const emailForm = document.querySelector(&#39;form&#39;);<br>  const successMessage = document.querySelector(&#39;.success-message .s-text&#39;);<br>  const errorMessage = document.querySelector(&#39;.error-message .e-text&#39;);<br>  const roleDeptWrapper = document.querySelector(&#39;.role-dept-wrapper&#39;);<br>  const createEventBtn = document.querySelector(&#39;.create-event-btn&#39;);<br>  const cards = document.querySelector(&#39;.card_x&#39;); // there&#39;s two of this class.<br><br>  // API endpoint<br>  const API_URL = &#39;https://permit-io-webflow-1.onrender.com&#39;;<br>  // Check if user is logged in<br>  const userEmail = sessionStorage.getItem(&#39;user_email&#39;);<br>  if (userEmail) {<br>    showAuthorizedUI(userEmail);<br>  } else {<br>    hideAuthorizedElements();<br>  }<br>&lt;/script&gt;</pre><p>This initial code sets up the basic structure. When the page loads, it checks if a user email exists in session storage. If it does, the user is considered logged in, and we’ll show the appropriate UI elements based on their permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7CmH5aR1chEBcs_h.png" /></figure><h4><strong>Creating the Authentication Flow</strong></h4><p>Next, let’s implement the basic authentication flow. Add a hidden class to all elements within the Webflow project except the header containing the “Sign in” button. Then, set up a dialog containing a form with an email input and a dropdown element with name=”department”. Add options for different departments (Marketing, Sales, Engineering):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2ZlCQgcjBgAr4vZR.png" /></figure><p>To complete the sign in workflow, add the following to your script, right after the previous code:</p><pre>// Show signin dialog when button is clicked<br>signinButton.addEventListener(&#39;click&#39;, function() {<br>  signinDialog.style.display = &#39;block&#39;;<br>});<br><br>// Handle form submission<br>emailForm.addEventListener(&#39;submit&#39;, function(e) {<br>  e.preventDefault();<br>  const emailInput = emailForm.querySelector(&#39;input[type=&quot;email&quot;]&#39;);<br>  const email = emailInput.value.trim();<br>  // Get the selected role from the dropdown<br>  const departmentSelect = emailForm.querySelector(&#39;select&#39;);<br>  const department = departmentSelect.value;<br>  if (!email) {<br>    showError(&#39;Please enter a valid email address&#39;);<br>    return;<br>  }<br>  authenticateUser(email, department);<br>});</pre><p>This code handles the sign-in flow by displaying the dialog when the sign-in button is clicked and processing the form submission.</p><p>Let’s define the authenticateUser function that will communicate with our Permit IO backend:</p><pre>// Authenticate user with Permit IO<br>  async function authenticateUser(email, department) {<br>    try {<br>      // Show loading state<br>      formContainer.classList.add(&#39;loading&#39;);<br>      <br>      // Sync user with Permit IO<br>      const response = await fetch(`${API_URL}/api/auth/sync-user`, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;<br>        },<br>        body: JSON.stringify({ userId: email, email, department })<br>      });<br>      const data = await response.json();<br>      if (data.success) {<br>        // Store user email in session<br>        sessionStorage.setItem(&#39;user_email&#39;, email);<br>        // Show success message<br>        showSuccess(&#39;Authentication successful!&#39;);<br>        // Close dialog after 1 second<br>        setTimeout(() =&gt; {<br>          signinDialog.style.display = &#39;none&#39;;<br>          showAuthorizedUI(email);<br>        }, 300);<br>      } else {<br>        showError(&#39;Authentication failed. Please try again.&#39;);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Authentication error:&#39;, error);<br>      showError(&#39;Authentication failed. Please try again.&#39;);<br>    } finally {<br>      formContainer.classList.remove(&#39;loading&#39;);<br>    }<br>  }</pre><p>This function makes a POST request to our backend to sync the user with Permit IO. If successful, it stores the user’s email in session storage and updates the UI.</p><h4><strong>Managing Authorized UI Elements</strong></h4><p>Now, let’s implement the functions to show and hide UI elements based on the user’s permissions. First, the function to hide elements when no user is logged in:</p><pre>// Hide elements that require authorization<br>  function hideAuthorizedElements() {<br>    // Hide elements with data-permission attribute<br>    document.querySelectorAll(&#39;[data-permission]&#39;).forEach(element =&gt; {<br>      element.style.display = &#39;none&#39;;<br>    });<br>   <br>    // Hide elements<br>    const roleDeptWrapper = document.querySelector(&#39;.role-dept-wrapper&#39;);<br>    if (roleDeptWrapper) {<br>      roleDeptWrapper.classList.add(&#39;hidden&#39;);<br>    }<br>    const createEventBtn = document.querySelector(&#39;.create-event-btn&#39;);<br>    if (createEventBtn) {<br>      createEventBtn.classList.add(&#39;hidden&#39;);<br>    }<br>    const cards = document.querySelectorAll(&#39;.card_x&#39;);<br>    cards.forEach(card =&gt; {<br>      card.classList.add(&#39;hidden&#39;);<br>    });<br>    // Make sure the signin button is visible<br>    signinButton.style.display = &#39;block&#39;;<br>  }</pre><p>Next, the function to show elements based on the user’s permissions:</p><pre>// Show elements based on user permissions<br>  async function showAuthorizedUI(email) {<br>    // Hide signin button and login email<br>    signinButton.style.display = &#39;none&#39;;<br>    signinButtonContainer.textContent = email;<br>    <br>    // Remove hidden class elements<br>    const roleDeptWrapper = document.querySelector(&#39;.role-dept-wrapper&#39;);<br>    if (roleDeptWrapper) {<br>      roleDeptWrapper.classList.remove(&#39;hidden&#39;);<br>    }<br>    const createEventBtn = document.querySelector(&#39;.create-event-btn&#39;);<br>    if (createEventBtn) {<br>      createEventBtn.classList.remove(&#39;hidden&#39;);<br>    }<br>    const cards = document.querySelectorAll(&#39;.card_x&#39;);<br>    cards.forEach(card =&gt; {<br>      card.classList.remove(&#39;hidden&#39;);<br>    });<br>    // Check permissions and show appropriate elements<br>    await checkAndApplyPermissions(email);<br>  }</pre><p>The key to our RBAC implementation is the checkAndApplyPermissions function:</p><pre>// Check user permissions and apply to UI<br>  async function checkAndApplyPermissions(email) {<br>    try {<br>      // Get all elements with permission requirements<br>      const permissionElements = document.querySelectorAll(&#39;[data-permission]&#39;);<br>      <br>      // Check each element&#39;s permission<br>      for (const element of permissionElements) {<br>        const action = element.dataset.permission;<br>        const resource = element.dataset.resource || &#39;Event&#39;;<br>        // Check permission with Permit IO<br>        const response = await fetch(`${API_URL}/api/auth/check-permission`, {<br>          method: &#39;POST&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;<br>          },<br>          body: JSON.stringify({<br>            userId: email,<br>            action: action,<br>            resource: resource<br>          })<br>        });<br>        const data = await response.json();<br>        // Show/hide element based on permission<br>        element.style.display = data.allowed ? &#39;block&#39; : &#39;none&#39;;<br>      }<br>    } catch (error) {<br>      console.error(&#39;Permission check error:&#39;, error);<br>    }<br>  }</pre><p>Finally, add the helper functions for showing success and error messages:</p><pre>// Show success message<br>  function showSuccess(message) {<br>    successMessage.textContent = message;<br>    successMessage.parentElement.style.display = &#39;block&#39;;<br>    errorMessage.parentElement.style.display = &#39;none&#39;;<br>  }<br><br>// Show error message<br>  function showError(message) {<br>    errorMessage.textContent = message;<br>    errorMessage.parentElement.style.display = &#39;block&#39;;<br>    successMessage.parentElement.style.display = &#39;none&#39;;<br>  }<br>}); // End of DOMContentLoaded</pre><h4><strong>Adding Permission Attributes to Webflow Elements</strong></h4><p>Now that our script is ready, we need to mark elements in our Webflow design with data attributes to control their visibility based on user permissions.</p><p>For each element that should be controlled by permissions, add the following data attributes:</p><ol><li>data-permission: The action required (create, read, update, delete, publish)</li><li>data-resource: The resource type (defaults to &quot;Event&quot; if not specified)</li></ol><p>Here’s how to add these attributes in Webflow:</p><ol><li>Select the element you want to restrict</li><li>Click on Settings in the right panel</li><li>Scroll down to the “Custom Attributes” section</li><li>Add a new attribute with the name data-permission and a value like create, update, or delete</li><li>Optionally add another attribute named data-resource with the value Event</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AVgrM0YqBHxLiWKM.png" /></figure><p>For example, to restrict the “Delete Event” button to users with delete permission:</p><ul><li>Select the delete button</li><li>Add custom attribute: data-permission=&quot;delete&quot;</li><li>Add custom attribute: data-resource=&quot;Event&quot;</li></ul><p>Repeat this process for all elements that should be permission-controlled:</p><ul><li>“Create Event” button: data-permission=&quot;create&quot;</li><li>“Edit Event” button: data-permission=&quot;update&quot;</li><li>“Publish Event” button: data-permission=&quot;publish&quot;</li></ul><p>With these attributes in place, our script will automatically handle showing and hiding elements based on the user’s permissions. Here’s what a user with Attendee role will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*41G6FiJ-U-IU3wqQ.png" /></figure><p>Likewise, a user with Administrator role will see all elements as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G_D2WRFQEq5M9TEf.png" /></figure><h3>Implementing ABAC for Department-Based Access</h3><p>Now that we have RBAC working, let’s enhance our authorization with Attribute-Based Access Control (ABAC). ABAC allows for more nuanced permissions based on attributes like department, ownership, or time of day.</p><p>For our Event Management dashboard, we want to implement access control where users can only see events from their department.</p><p><strong>Adding Attributes to Elements in Webflow</strong> First, we need to add department attributes to our event elements. For each event in your Webflow CMS or design:</p><ol><li>Select the event container element</li><li>Add custom attribute: data-department with values like Marketing, Sales, or Engineering</li></ol><p>For example, for a Marketing event:</p><ul><li>Select the event container</li><li>Add custom attribute: data-department=&quot;Marketing&quot;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8IEh6VvDtBQIuPHx.png" /></figure><p>Now modify the department button-like selector below the head section to include data-department for each department:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4e244YIFqxBgrurV.png" /></figure><p>This combination tells our script to check both role-based permissions and attribute-based conditions.</p><h4><strong>Extending Our Script for ABAC</strong></h4><p>Next, let’s enhance our authorization script to handle attribute-based checks. Add the following function to your script, after the checkAndApplyPermissions function:</p><pre>// Check department-based permissions for elements<br>  async function checkAttributeBasedPermissions(email) {<br>    try {<br>      // Get user department from Permit IO<br>      const userResponse = await fetch(`${API_URL}/api/auth/get-user-attributes`, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;<br>        },<br>        body: JSON.stringify({ userId: email })<br>      });<br>     <br>      const userData = await userResponse.json();<br>      const userDepartment = userData.attributes?.department || &#39;&#39;;<br>      // this handles administration.<br>      if (userDepartment == &quot;*&quot;) return.<br>      // Find all elements with data-department attribute<br>      const departmentElements = document.querySelectorAll(&#39;[data-department]&#39;);<br>      // Hide elements that don&#39;t match user&#39;s department<br>      departmentElements.forEach(element =&gt; {<br>        const elementDepartment = element.dataset.department;<br>        if (elementDepartment &amp;&amp; elementDepartment !== userDepartment) {<br>          element.style.display = &#39;none&#39;;<br>        }<br>      });<br>    } catch (error) {<br>      console.error(&#39;ABAC check error:&#39;, error);<br>    }<br>  }</pre><p>This function handles our attribute-based access control by retrieving the user’s department from Permit IO. Then finds all elements marked for ABAC checks, and determine each element’s associated department. It also checks if the user has permission based on these attributes, consequently showing or hiding elements accordingly.</p><p>Now, update the showAuthorizedUI function to include ABAC checks:</p><pre>async function showAuthorizedUI(email) {<br>  ...<br>  // Check attribute-based permissions<br>  await checkAttributeBasedPermissions(email);<br>}</pre><p>With the new ABAC rules, Attendee see only the below UI setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b1Qq9sbyz1kkJlrr.png" /></figure><p>While the Administrator user who has full access across the entire department will see the below UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hoD_7hAlJFBEkBfF.png" /></figure><p><strong>Testing ABAC with Department Permissions</strong> To test the access controls that we have implemented in this Webflow project:</p><ul><li>Create an “admin@example.com” user with attribute set to departmet: &quot;*&quot;</li><li>Create an “attendee@example.com” user with its department set to “Sales”</li><li>Log in with admin email and verify:</li><li>All the UI appeared for the user.</li><li>Create, Delete, and Edit buttons are showing for this user.</li><li>Log in with attendee email and verify:</li><li>This user can only view events from their department with the create, edit, or delete buttons hidden.</li></ul><h3>Conclusion</h3><p>In this tutorial, we’ve successfully implemented a comprehensive authorization system for a Webflow application using Permit IO. By combining RBAC and ABAC, we’ve created a flexible, powerful access control system that can adapt to complex organizational needs.</p><p>The key advantages of our approach include:</p><ul><li><strong>Separation of concerns</strong>: Our authorization logic is maintained in Permit IO, separate from the application UI, making it easier to update and maintain.</li><li><strong>Layered security</strong>: By implementing both RBAC and ABAC, we’ve created multiple security layers that work together to provide precise access control.</li><li><strong>Client-side implementation</strong>: Despite Webflow’s limitations, we’ve built a robust authorization system using client-side JavaScript and data attributes, proving that permission systems are possible in no-code platforms.</li></ul><p>The key advantage of using Permit IO is that it separates authorization logic from your application code, making it easier to manage and update permissions without redeploying your application. As your application grows, you can easily extend this system with new roles, attributes, and policies. You can find the final version of the deployed Webflow project <a href="https://ikehs-superb-site.webflow.io/">here</a>.</p><p>For more advanced use cases, explore Permit IO’s documentation on <a href="https://docs.permit.io/how-to/build-policies/rebac/overview">ReBAC (Relationship-Based Access Control)</a> and <a href="https://docs.permit.io/integrations/gitops/custom_policy">custom policies</a>. You can also join the Permit IO community to discuss authorization patterns and best practices with other developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39926b7cc9a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinventing me]]></title>
            <link>https://ikehakinyemi.medium.com/reinventing-me-b0dd8fcaecaf?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0dd8fcaecaf</guid>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 20:04:44 GMT</pubDate>
            <atom:updated>2024-09-02T20:04:44.437Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately, I been having this depressing urge to reinvent myself. I have this desire to be a particular kind of Software Engineer, and so far I’m not actively doing what will bring me closer to being such Engineer.</p><p>I want to reinvent myself, do more of what I want to do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0dd8fcaecaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nothing]]></title>
            <link>https://ikehakinyemi.medium.com/nothing-30e9f0e22c0b?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e9f0e22c0b</guid>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 18:13:03 GMT</pubDate>
            <atom:updated>2024-09-01T18:26:46.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Absolutely nothing.</p><p>Just scared that I’m not a good person especially to people around me — friends and family. I sense a hint of it occasionally while interacting with my friends.</p><p>I’m so terrible at being a friend (I believe so), but same time I want to be one of the great friends they ever met. But there’s a deep seated fear that if I be my true self, that I will be the worst friend they ever met.</p><p>I fear I have the potential of being a backstabber to them but at same time I feel some sort of great love towards them. The kind of love that would break my heart the way romantic love should break one’s heart.</p><p>I often wonder how they perceive me? How much of my fuck-upped personality (life) do they despise and wish to get rid of?</p><p>I have constantly doubted my ability to even tell when they’re possibly wrong over something that involves me. I always convince myself how it is 90% possible that I might be the one who lacks the intelligence (understanding) of my wrong in the situation. How I’m being the unreasonable one.</p><p>Honestly, I’m even tired of being the kind of person that I am. What am I even? Jesus Christ! I don’t even know. I’m constantly drifting through life. Nothing tangible to offer to people around me. And at same time, I’m a terrible person.</p><p>I withdraw from them so often as a means of holding back the evil in me from manifesting.</p><p>I’m tired of me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e9f0e22c0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless functions in Next.js]]></title>
            <link>https://medium.com/stackanatomy/serverless-functions-in-next-js-a497fd202313?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a497fd202313</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 02:30:10 GMT</pubDate>
            <atom:updated>2023-02-17T00:17:42.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fHyF7pFJPamUC-fgpcJOjg.jpeg" /><figcaption>openreplay image</figcaption></figure><p>In this tutorial, Next.js developers will learn another feature of Next.js — serverless functions. Throughout the article, we’ll discuss Next.js page routes and dynamic routes and later build on the knowledge to learn about Next.js SPA and dynamic API routes.</p><p><a href="https://nextjs.org/">Next.js</a> is a popular JavaScript framework for building server-rendered, single-page applications (SPAs) and static sites. It is built on top of React, a popular library for building user interfaces. It provides tools and features that make it easy to build fast, scalable, and reliable web applications.</p><p>One of its key features is server-side rendering (SSR), which allows you to render your React components on the server and send the resulting HTML to the client. This has several benefits, including improved performance, better SEO, and the ability to render content on the server for users with JavaScript disabled.</p><p>Next.js also includes a variety of other features, such as automatic code splitting, optimized production builds, and support for serverless functions. It is also fully compatible with the latest JavaScript features and has a thriving community of developers and plugins. One of the unique features of Next.js is its support for serverless functions, also known as Lambda functions. These functions allow developers to build scalable and performant applications by offloading specific tasks to the cloud.</p><p>In this article, we will explore how Next.js Lambda functions work and how they can be used in building Single Page Applications (SPAs). We will also cover some prerequisites for using Next.js Lambda functions in your projects.</p><h3>Using Next.js Lambda Functions in Development</h3><p>Next.js provides a simple and powerful way to set up page routing in your SPA. With page routing, you can define specific paths that map to different components or pages in your application. This allows you to create a seamless and intuitive user experience by organizing your content into logical sections.</p><p>To set up page routing in Next.js, you will need to create a Next.js project using the yarn create-next-app command:</p><pre>yarn create-next-app example</pre><p>Inside the pages directory at the root of your project, create files in this directory to correspond to routes in your application. For example, a file called &quot;about.js&quot; in the pages directory will be accessible at the &quot;/about&quot; route.</p><pre>// pages/about.js<br><br>function About() { <br>  return &lt;h1&gt;About Page&lt;/h1&gt;; <br>} <br><br>export default About;</pre><p>You can also create dynamic routes in Next.js by using the [id] parametric pattern in your route. Dynamic routes are an essential feature in Next.js that allow you to create complex, flexible routes for your application. With dynamic routes, you can define a route pattern with a parameter, such as [id].js or [param].js, which can match any route that follows that pattern, like <a href="https://api.example.com/users/$%7Bparam%7D.">https://api.example.com/users/${param}.</a></p><p>For example, you can create a dynamic route in Next.js by creating a page component named [param].js. This component can be accessed via its dynamic route, such as pages/users/[param].js. In this example, [param] could be the page&#39;s id, slug, or pretty URLs. This means that this dynamic route could match any route like /users/1 or /users/xyz.</p><p>Next.js will send the matched path parameter as a query parameter to the page; if there are other query parameters, it will link the matched path parameter with them. For example, if the dynamic route is pages/users/[param].js, and the matched route is /users/xyz, the query object would be {&quot;param&quot;: &quot;xyz&quot;}. If there are additional query parameters, such as ?token=abcdef, the query object would be {&quot;token&quot;: &quot;abcdef&quot;, &quot;param&quot;: &quot;xyz&quot;}.</p><p>To illustrate how to use dynamic routes in Next.js, let’s look at an example. Imagine you have a details component that displays the details of an inventory item to the user whenever they click on an item’s details. To create this component, you would create an inventory folder and, inside it, create a component named [id].js. You can then import the useRouter hook from next/router and use it to access the router object, which contains the query object with the matched path parameter. Here is an example of how you could use this in your component:</p><pre>// pages/inventory/[id].js<br><br>import { useRouter } from &quot;next/router&quot;;<br><br>const Details = async () =&gt; {<br>  const router = useRouter();<br>  const itemId = router.query[&quot;id&quot;];<br><br>  // Retrieve item details by id<br>  const resp = await fetch(`https://api.example.com/inventory/${itemId}`);<br>  const itemDetails = resp.json();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt; {itemDetails.title} &lt;/h1&gt;<br>      &lt;p&gt;{itemDetails.description}&lt;/p&gt;<br>      &lt;p&gt; {itemDetails.price}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default Details;</pre><p>With this code, when a user visits the route /inventory/23456, the dynamic route pages/inventory/[id].js will be matched, and the query object {&quot;id&quot;: &quot;23456&quot;} will be passed to the component. The component will then display the details of the inventory item with an id equal to 23456 to the user.</p><p>With the above sample program, we can see that in addition to creating and serving pages with dynamic routes, Next.js can also create APIs with dynamic routes. This allows you to create flexible, dynamic APIs that handle a wide range of requests and responses.</p><h3>Session Replay for Developers</h3><p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with </em><a href="https://github.com/openreplay/openreplay"><strong><em>OpenReplay</em></strong></a><em> — an open-source session replay suite for developers. It can be </em><strong><em>self-hosted</em></strong><em> in minutes, giving you complete control over your customer data</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*EmPMRAfQTRYz3CnT.png" /></figure><p><em>Happy debugging! </em><a href="https://openreplay.com/"><em>Try using OpenReplay today.</em></a></p><h3>Implementing API Routes with Next.js Lambda Functions</h3><p>API routing with Next.js Serverless Functions allows you to build full-stack applications with backend endpoints using the Next.js framework. This feature, introduced in Next.js v9, enables you to develop full-stack applications that scale effortlessly, as both the frontend and backend are fully implemented with Next.js.</p><p>To create an API route in Next.js, you must place the endpoint files inside the /pages/api folder. Next.js will map these files to the /api/* endpoint. This allows you to create APIs that can be accessed from the frontend of your application.</p><p>To create a Next.js API route, you must export a request handler function as the default export. This function takes two parameters, req and res, which are instances of http.IncomingMessage and http.ServerResponse, respectively. You can use these objects to handle HTTP requests, such as GET, POST, PUT, and DELETE.</p><p>Say you have JSON data that you want to return on one of the endpoints:</p><pre>// data/items.js<br><br>const items = [<br>  {<br>    &quot;id&quot;: 23456,<br>    &quot;Title&quot;: &quot;Item 23456&quot;,<br>    &quot;Description&quot;: &quot;XYZ description&quot;,<br>    &quot;price&quot;: &quot;$999.99&quot;<br>  },<br>  {<br>    &quot;id&quot;: 23457,<br>    &quot;Title&quot;: &quot;Item 23457&quot;,<br>    &quot;Description&quot;: &quot;XYZ description&quot;,<br>    &quot;price&quot;: &quot;$499.99&quot;<br>  },<br>  {<br>    &quot;id&quot;: 23458,<br>    &quot;Title&quot;: &quot;Item 23458&quot;,<br>    &quot;Description&quot;: &quot;XYZ description&quot;,<br>    &quot;price&quot;: &quot;$1499.99&quot;<br>  },<br>];<br><br>export default items;</pre><p>To set up the endpoint, create an inventory.js file inside the /pages/api folder and update it with the following code:</p><pre>// pages/api/inventory.js<br>import items from &quot;../../data/items.js&quot;;<br><br>const handler = (req, res) =&gt; {<br>  switch (req.method) {<br>    case &#39;GET&#39;:<br>      try {<br>        // mock a GET request<br>        res.status(200).json(items);        <br>      } catch(err) {<br>        res.status(404).json({&quot;message&quot;: `error fetching data: ${err}`});<br>      }<br>      break<br>    case &#39;POST&#39;:<br>      try {<br>        // mock a POST request<br>        res.status(200).json({&quot;message&quot;: &quot;successful data write&quot;});        <br>      } catch(err) {<br>        res.status(404).json({&quot;message&quot;: `error writing data: ${err}`});<br>      }<br>      break<br>    default:<br>      // Respond to unrecognized request<br>      res.status(405).end()<br>      break<br>  }<br>}<br><br>export default handler;</pre><p>Next.js API routes also support dynamic routes, which follow the same naming conventions as dynamic page routes. This means you can create dynamic APIs by using brackets in the filename, such as [param].js, which can match any route that follows that pattern.</p><pre>// pages/api/inventory/[id].js<br>import items from &quot;../../../data/items.js&quot;;<br><br>const handler = (req, res) =&gt; {<br>    if (req.method) {<br>      try {<br>        const { id } = req.query;<br>        const item = items.find((item =&gt; item.id === parseInt(id)));<br>        res.status(200).json(item)<br>      } catch(err) {<br>        res.status(404).json({&quot;message&quot;: `error fetching item details: ${err}`})<br>      }<br>    }<br>}<br><br>export default handler;</pre><p>With the above snippet, paths like inventory/23456 will automatically be matched to the dynamic route pages/api/inventory/[id].js. The request handler function will extract the item id using the req.query object. Using this id variable, you will search the items array to find the item with the id, and send it to the client.</p><p>In addition to creating APIs with Next.js, you can also use the framework to create serverless functions. These functions are standalone pieces of code that can be executed on demand without needing a dedicated server. They are useful for handling webhooks, running background jobs, and integrating with external APIs.</p><h3>Conclusion</h3><p>In this article, we have explored how Next.js Lambda functions can be used to build scalable and performant applications. We have seen how to set up page routing and API routes in a Next.js SPA and how to use Next.js Lambda functions to handle dynamic routes and fetch data from APIs.</p><p>By using Next.js Lambda functions, you can offload specific tasks to the cloud and focus on building a high-quality user experience for your users. Whether you are building a simple SPA or a complex full-stack application, Next.js Lambda functions can help you achieve your goals.</p><p>In addition to creating APIs and serverless functions with Next.js, you can also use the framework to build webhooks and integrations with external APIs. This can be done by creating a serverless function that listens for requests from external sources and triggers certain actions within your application. Overall, Next.js API routing and serverless functions provide a powerful and flexible way to build backend application endpoints and serverless functions within the Next.js framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*jYAdxiOn6zFVI0cE.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a497fd202313" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/serverless-functions-in-next-js-a497fd202313">Serverless functions in Next.js</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing Astro and Next for React apps]]></title>
            <link>https://medium.com/stackanatomy/comparing-astro-and-next-for-react-apps-f64e2de97623?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f64e2de97623</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Thu, 19 May 2022 12:15:15 GMT</pubDate>
            <atom:updated>2022-05-19T12:15:15.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*f8U1UoBkoh046y1a4FeswA.jpeg" /></figure><p>When choosing a framework for your web application, it is important to consider the developer experience that they offer. Both Astro and Next.js build on top of React to provide a streamlined development experience. They both have a small learning curve, meaning if you are already familiar with React, you can easily pick them up and get running. However, there is a different experience when building with Astro and Next.js: that’s what we’ll cover in this article.</p><p>This article compares the developer experience between Astro and Next.js in building blazing-fast web applications. In this article, you will learn the basics of Astro and Next.js and a detailed comparison between the two React frameworks. For this article, you should be familiar with the basics of React (as Astro and Next.js are both React frameworks) and how to create components. Before we move into a detailed comparison, it is essential to have background knowledge on Astro and Next.js.</p><h3>What is Astro?</h3><p>Astro is a modern web framework built on top of React and a static site builder with little or no JavaScript for delivering blazing-fast, high-performance websites with a modern developer experience. It lets you build your websites using UI components from your favourite JavaScript UI frameworks like React, Svelte, Vue, etc.</p><p>Astro websites are fully static websites with all the JavaScript code removed. However, when a component (e.g., Image carousels, dark and light mode) requires JavaScript code to run, Astro only loads that component and any required dependencies. The other site components continue to exist as static lightweight HTML. Astro’s <a href="https://docs.astro.build/en/getting-started/">getting started</a> tutorial is excellent for getting started with Astro.</p><h3>What is Next.js?</h3><p>Next.js is an open-source React framework for creating server-rendered React applications with little to no configuration. It provides additional structure and features and handles the React tooling and configuration required for your application.</p><p>Next.js can be used to solve standard application requirements such as routing, data fetching, and integrations. Next.js is built on top of React in a bid to build an easy-to-use development framework to reduce the hassle of creating full-fledged, SSR-friendly web applications and, overall, improve the end-user and <a href="https://blog.logrocket.com/whats-new-in-next-js-10/">developer experience</a>. The Next.js <a href="https://nextjs.org/learn/basics/getting-started">Getting Started guide</a> is a great place to learn about Next.js.</p><h3>Performance</h3><p>Astro was built to create super-fast static sites leveraging the <a href="https://patterns.dev/posts/islands-architecture/">island architecture</a> rather than single-page application architecture. This improves performance, provides a great user experience, and also helps with search engines when trying to rank your site.</p><p>Next.js also supports static builds, but that is not the primary focus. Unlike Astro, Next.js focuses on enabling your React application with additional functionalities such as server-side rendering (SSR). Next.js offers a variety of different fetching methods, i.e., CSR (client-side rendering), SSG (server-side generation), SSR (server-side rendering), and ISR (incremental static regeneration). Whether Astro or Next.js creates a faster web application depends on the use case.</p><p>Next.js is best used for highly dynamic and image-heavy websites like dashboards because of its built-in image optimization. In contrast, Astro is best used for static websites like a portfolio or a personal blog.</p><h3>Hydration</h3><p>Static sites are hydrated first before a user can interact with the page; this reduces performance. The longer the hydration process takes, the more time it’ll take for users to be able to interact with the page.</p><p>Astro solves this problem by loading individual components of a page if and when needed and leaving the rest of the page as static HTML. This is called <a href="https://docs.astro.build/en/core-concepts/partial-hydration/#island-architecture">partial hydration</a>. This process is key to making the Island architecture load faster than the single-page application architecture, as users don’t have to wait for the entire page to load before they can interact with the web page.</p><p>Next.js has <a href="https://piccalil.li/blog/new-year-new-website/#heading-no-client-side-react-code">experimental support</a> for fully static and non-JavaScript websites. However, it doesn’t support hydrating individual components (partial hydration); instead, it loads the entire page in the browser even if the most page content is static.</p><h3>Use cases</h3><ul><li>Simple static website: Although Next.js can be used to build static websites, Astro is more optimal for building static sites (Updates don’t need to reflect real-time) because it adopts the Island architecture and partial hydration.</li><li>Large multi-user sites (published in real-time): Since Server-Side Rendering (SSR) helps cater to different users based on authentication. You need to show unique content to logged-in users on websites like these, and Next.js and Astro will work just fine. Prior to this time (the time of writing), Next.js would have been a better choice, but since the announcement of experimental support for server-side rendering (SSR) in Astro, it can also compete.</li><li>Client-side single application: Both Astro and Next.js are ideal for client-side single-page websites</li></ul><h3>Server-Side Rendering</h3><p>Server-side rendering is a tool for scaling large websites and making them render faster. This basically works because it takes a client-side website and renders it to static HTML and CSS on the server. The HTML is generated in one case at build-time and then reused for each request. This is essential because applications rendered on the server-side are SEO-friendly by default and super faster. After all, server-side rendering web frameworks reduce client load time. Next.js supports server-side rendering, and just recently, Astro announced <a href="https://astro.build/blog/experimental-server-side-rendering/">experimental support</a> for server-side rendering.</p><h3>Ease of use</h3><p>As stated earlier, both frameworks have a small learning curve if you’re already familiar with React. They have very intuitive and informative documentation, and they are both easy to set up.</p><ul><li><strong>Create Astro App</strong> According to Astro’s documentation, create-astro is the fastest, easiest way to start a new Astro project from scratch. Once create-astro starts successfully, it provides a list of three templates to choose from. One of which is a starter template that will allow you to choose any additional framework that you’d like to include in your project. Refer <a href="https://docs.astro.build/en/install/auto/">here</a> for a complete guide on creating a simple Astro application.</li><li><strong>Create Next App</strong> The easiest way to bootstrap a Next.js application is to use the <a href="https://nextjs.org/docs/api-reference/create-next-app">create-next-app</a> command. It is a tool that uses a <a href="https://github.com/vercel/next-learn/tree/master/basics/learn-starter">starter template</a>. Refer <a href="https://nextjs.org/learn/basics/create-nextjs-app/setup">here</a> for a complete guide on creating a simple Next.js project.</li></ul><h3>Code splitting</h3><p><a href="https://developer.mozilla.org/en-US/docs/Glossary/Code_splitting">Code splitting</a> enables you to ship the tiny amount of JavaScript necessary for a route and then lazy loads the rest of the components. Code splitting works by default in Astro and Next.js; they code-split based on page routes. Also, both frameworks have built-in routing for creating new pages.</p><h3>Open Source Session Replay</h3><p><a href="https://github.com/openreplay/openreplay"><em>OpenReplay</em></a><em> is an open-source alternative to FullStory and LogRocket. It gives you full observability by replaying everything your users do on your app and showing how your stack behaves for every issue. OpenReplay is self-hosted for full control over your data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EOblajnT10bjXBRt.png" /></figure><p><em>Happy debugging for modern frontend teams — </em><a href="https://github.com/openreplay/openreplay"><em>start monitoring your web app for free</em></a><em>.</em></p><h3>Key take-aways</h3><p>Next.js supports Static Site Generation (SSG) and Server Side Rendering (SSR), while Astro only supports Static Site Generation (SSG) and Server Side Rendering (SSR).</p><p>Although Astro and Next.js have different functionalities, they still share most things in common like SSR, SSG, easy learning curve, intuitive documentation, and easy setup.</p><p>Both frameworks support hot reloading for a faster development experience as well.</p><p>While Next.js offers lazy loading, Astro supports multiple ways of loading components. This enables composing high-performance, component-driven UIs.</p><p>Also, because Astro automatically removes unnecessary JavaScript and only sends essential JavaScript needed to run your web page, Astro websites load faster than Next.js websites.</p><p>The choice has been relatively easy — Astro if you are building a static website that is super fast and where the content doesn’t often change, and Next.JS for websites with multiple users accessing and editing the content, image-heavy and complicated websites.</p><h3>Conclusion</h3><p>In this blog post, we examined two famous React frameworks: Astro and Next.js. We compared them based on their performance, use cases, developer experience, and similarities. We also covered how to bootstrap a simple project with both frameworks. Both Astro and Next.js offer great functionalities for building scalable web applications, so picking one over another depends on your project.</p><p><em>This article was originally published at </em><a href="https://blog.openreplay.com/comparing-astro-and-next-for-react-apps"><em>blog.openreplay.com</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f64e2de97623" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/comparing-astro-and-next-for-react-apps-f64e2de97623">Comparing Astro and Next for React apps</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Tonic — the component framework]]></title>
            <link>https://medium.com/stackanatomy/introduction-to-tonic-the-component-framework-63e0755e7c1a?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/63e0755e7c1a</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 23:15:31 GMT</pubDate>
            <atom:updated>2022-03-31T23:15:31.734Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Tonic — the component framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*e1KHp1VT_giMI3lKShNgDw.jpeg" /><figcaption>Tonic | blog.openreplay.com</figcaption></figure><p>Frontend development changes frequently as frameworks spring up rapidly. Tonic is an unpopular frontend framework that emerged in the last two years and is great for developing JamStack sites due to its small file size (5KB), making a good choice for websites with great load time. Using libraries to build high-performing web applications has become vitally important, frontend frameworks and libraries have become an important aspect of web development.</p><p>In this article, we’ll discuss Tonic, a component-based framework that allows frontend developers to create incredibly quick and beautiful user interfaces, as well as its properties, capabilities, use cases and its advantages over other component-based frameworks for building JAMstack sites. At the end of this article, readers will have an understanding of what Tonic is, how to use it when styling user interfaces, and also for handling events. This will enable them to build UI components without the use of any additional build tool or complexity. Also, we’ll demo a sample Tonic project on building our first functional component Tonic component.</p><h4><strong>What is Tonic</strong></h4><p><a href="https://tonicframework.dev/">Tonic</a> is a stable and minimal component-based framework that enables frontend developers to build blazing-fast JAMstack sites with amazing UI. It is a server-side rendering by default, it also uses event delegation by default and doesn’t require any build tool. It is a framework that enables you to write async web components.</p><p>Tonic leverages CSS variables to theme components which allow developers to use any CSS framework of their choice. This makes Tonic a design system(for building UI) and a web component framework. It has good examples of components built with Tonic in a <a href="https://github.com/optoolco/components">separate repo</a> available for use.</p><h4><strong>Prerequisites</strong></h4><p>You do not need to have any previous knowledge on Tonic before this article, however, it’s a plus if you are familiar with any component-based framework. You’ll need to be familiar with:</p><ul><li>Basic JavaScript because Tonic is a JavaScript framework</li><li>Basic HTML and CSS.</li></ul><h4><strong>Getting started with Tonic</strong></h4><p>To use Tonic, you have to import it:</p><pre>import Tonic from ‘@socketsupply/tonic’</pre><p>Creating components in Tonic is similar to writing components in other component-based frameworks like React and Vue. To build a component in Tonic, you have to create a class or function. The class must have one method(at least) called <strong>render</strong> which returns a template literal of HTML.</p><pre>class MyGreeting extends Tonic {<br>  render () {<br>    return this.html `<br>      &lt;h1&gt;Hello World&lt;/h1&gt;<br>    `;<br>  }<br>}</pre><p>After creating a component, we need to add the component to Tonic.</p><pre>Tonic.add(MyGreeting)</pre><p>Next, you need to add your JavaScript file to your HTML.</p><pre>&lt;html&gt;<br>  &lt;body&gt;<br>    &lt;my-greeting&gt; &lt;/my-greeting&gt;<br>    &lt;script src=”app.js”&gt;&lt;/script&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Once you have successfully added your JavaScript file to your HTML, then you can use your component anywhere. Please note that custom tags (like <strong>my-greeting</strong>) require a closing tag even if they have no children.</p><h4><strong>Properties</strong></h4><p>If you have used other component-based frameworks like React, you should be familiar with <strong>props.</strong> Props are properties passed from one component to other components via HTML attributes. Props are passed to the component in the same way arguments are passed to a function.</p><p>When you add properties to a component, they appear on <strong>this.props</strong> object. Tonic uses <strong>this.html</strong> to pass complex values to a component.</p><p>The <strong>.reRender()</strong> method is used to manually update a component’s property, this method takes either a function or an object as an argument. The reRender method can also be called directly on a component.</p><pre>this.reRender(props =&gt; ({<br>       …props, <br>       name: ‘John’<br>    }))</pre><h4><strong>Why Tonic</strong></h4><p>There’re many advantages in using Tonic for your JAMstack applications over other popular frameworks like React and Vue.js.</p><p>A key reason why Tonic is ideal for building JAMstack sites is because of its size. It is only 5KB with 350 lines of code which makes your web application load faster. Tonic also doesn’t require any dependencies, build tool or rendering engine installed on the server-side.</p><p>Also, your component names can be viewed in the browser’s DOM of your website which makes it easy to debug production code. You also get the same developer experience as from other modern component-based frameworks.</p><h4><strong>UI styling in Tonic</strong></h4><p>Tonic is a framework that allows frontend developers to create incredibly quick and beautiful user interfaces, it supports multiple approaches for styling components. We’ll go through the three approaches in styling Tonic components:</p><p><strong>Inline styling</strong></p><p>Just like adding CSS inside your HTML, we can add inline styles to any Tonic component we want to render. Tonic provides the `styles()` method that helps you safely inject inline styles to an HTML element.</p><pre>class MyStyle extends Tonic {<br>      styles () {<br>        return {<br>          a: {<br>            color: blue,<br>            fontSize: &#39;30px&#39;<br>          }<br>        }<br>      }<br>      render () {<br>        return this.html`&lt;p styles=&quot;a&quot;&gt;${this.children}&lt;/p&gt;`<br>      }</pre><p><strong>Dynamic stylesheet</strong></p><p>We use the <strong>stylesheet()</strong> method to add a dynamic stylesheet to our component. This way we can change an element dynamically in response to user events.</p><pre>class MyStyle extends Tonic {<br>      stylesheet () {<br>        return `<br>          my-style p {<br>            color: ${this.props.color};<br>          }<br>        `<br>      }<br>      render () {<br>        return this.html`&lt;p&gt;&lt;/p&gt;`<br>      }<br>    }</pre><p>Then in our HTML file:</p><pre>&lt;my-style color=”blue”&gt;Hello World!&lt;my-style&gt;</pre><p><strong>Static styling</strong></p><p>The <strong>static</strong> <strong>stylesheet()</strong> method is used to add a stylesheet to the document only once. The style is fixed and doesn’t change while the application is running, they are not dynamically generated.</p><pre>class MyStyle extends Tonic {<br>      static stylesheet () {<br>        return `<br>          my-style p {<br>            color: red;<br>          }  `<br>      }<br>      render () {<br>        return this.html`&lt;p&gt;&lt;/p&gt;`<br>      }<br>    }</pre><h3>Open Source Session Replay</h3><p><em>Debugging a web application in production may be challenging and time-consuming. </em><a href="https://github.com/openreplay/openreplay"><em>OpenReplay</em></a><em> is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcvihDn16iD3kT4rCGq6Bw.png" /></figure><p><em>Happy debugging, for modern frontend teams — </em><a href="https://github.com/openreplay/openreplay"><em>Start monitoring your web app for free</em></a><em>.</em></p><h4><strong>Tonic’s component state</strong></h4><p>A component can be one of two types. It can be either a <strong>function</strong> component or a <strong>class</strong> component.</p><p><strong>this.state</strong> is a plain-old javascript object whose value is persisted if the component is re-rendered. The state is a built-in object used to store data of the component that is to be rendered. Any component that uses state must have an <strong>id</strong> property.</p><h4><strong>Creating your first component</strong></h4><p>Now let’s build a simple functional Tonic component. This project will be created in code pen. In this project, we will create a button that generates a random number from 1 to 10 whenever we click the button. This short demo will also introduce you to event handling and methods in Tonic.</p><p>First, we need to import Tonic, let’s add the following code in the JavaScript file:</p><pre>import Tonic from “https://cdn.skypack.dev/@socketsupply/tonic&quot;</pre><p>Once we have successfully imported Tonic, then we can go ahead to create our first Tonic component.</p><p>In Tonic, web components require a name with two or more parts. So your class or function name should be <strong>CamelCased </strong>(starting with an uppercase letter). For example, <strong>RandomNumber</strong> becomes <strong>&lt;random-number&gt;&lt;/random-number&gt;</strong>.</p><pre>class RandomNumber extends Tonic {<br>        constructor () {<br>        super();<br>        this.state.counter = 0; <br>      }<br>      click(e) {<br>        const trigger = Tonic.match(e.target, &quot;button&quot;);<br>        this.state.counter = Math.round(Math.random() * 10);<br>        this.reRender();<br>      }<br>      render () {<br>      return this.html `&lt;p&gt;Random Number ${ this.props.name }: &lt;button&gt;${ this.state.counter.toString() }&lt;/p&gt;`<br>      }<br>    }<br>    Tonic.add(RandomNumber)</pre><p>The state object is initialised in the constructor. The constructor is a special method that is called once each time an instance of our component is created. Then we create and set the counter variable to zero.</p><p>The click event as you might have known is used to listen for clicks on the component. This is because we want the random number to be generated only when the button is clicked.</p><p>Tonic prefers the <a href="https://davidwalsh.name/event-delegate">event delegation</a> pattern to attach a <strong>single event listener</strong> rather than using multiple event listeners. Each event handler method will receive an <strong>event</strong> object that contains a <strong>target</strong> property, to target the exact element that was clicked. An event handler can be attached in any component.</p><p>Just like in React, we need a <strong>render</strong> function on the <strong>class</strong> that returns the inherited function <strong>this.html</strong>. This <strong>render</strong> function accepts a template literal containing the HTML element to be rendered. It can also render dynamic values. For example, <strong>name</strong> is a property of the component <strong>&lt;random-number&gt;</strong> with the value of the <strong>name</strong> set to “<strong>generator</strong>”, it is accessed with <strong>this.props.name</strong>.</p><p>Lastly in our JavaScript file, we need to <strong>register</strong> our component with Tonic using <strong>Tonic.add()</strong> method.</p><p>Now we need to add our created component as an HTML element in our HTML file after we have linked our JavaScript file in our HTML. We added an <strong>id</strong> because as stated earlier; any component that uses <strong>state</strong> must have an <strong>id.</strong></p><pre>&lt;body&gt;<br>  &lt;random-number name=&quot;Generator&quot; id=&quot;count&quot;&gt;&lt;/random-number&gt;<br>  &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;</pre><p>That’s it. We have created our first functional Tonic component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kSjakLiy2hDKXMgjjbcQQ.png" /></figure><p>Here’s a link to the code-pen to see exactly how it works: <a href="https://codepen.io/dalu46/pen/ZEvzKoM">https://codepen.io/dalu46/pen/ZEvzKoM</a></p><h4><strong>Conclusion</strong></h4><p>We’ve just scratched the surface of Tonic learning about its properties, event handling, component and a few others. Tonic offers the same developer experience as other component-based frameworks like React, the class approach is similar to writing class components in React. Smaller than other components in size, it makes your site load faster. Building your next static site, consider making use of Tonic to get a feel/experience of what building with it feels like.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63e0755e7c1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/introduction-to-tonic-the-component-framework-63e0755e7c1a">Introduction to Tonic — the component framework</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and deploy JAMstack applications with Cloudflare pages]]></title>
            <link>https://medium.com/stackanatomy/build-and-deploy-jamstack-applications-with-cloudflare-pages-34c3ab541dd0?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/34c3ab541dd0</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-03-03T11:48:38.155Z</atom:updated>
            <content:encoded><![CDATA[<h4>Detailed tutorial on how to put your apps on Cloudfare in 10 minutes or less!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQGh08Zf5ceM51Fq7Of1uQ.jpeg" /></figure><p>Self-hosting web applications is an exciting process but can quickly get time-consuming, costly and tedious as you aim to pay, manage and maintain the servers by yourself. This process isn’t optimal for hosting static sites like your personal portfolio or a blog platform. With several free static hosting web services available, self-hosting has never been easier.</p><p>This article will discuss Cloudflare pages — A JAMstack web hosting platform by Cloudflare for deploying static sites. Cloudflare has, over the years, invested in user-facing web infrastructures that secure <strong>HTTP/HTTPS</strong> requests and <strong>CDN</strong> firewalls, increasing web securities across different protocol connections.</p><p>Cloudflare Pages, as one of the solutions at Cloudflare, is a JAMstack platform designed for frontend developers to foster collaboration amongst themselves and deploy websites seamlessly.</p><p>This tutorial will introduce frontend developers with React experience to build, collaborate and deploy using Cloudflare pages. Nevertheless, the concepts shared here can be extended to other frontend frameworks that are not React.</p><h3>What is Cloudflare pages?</h3><p><a href="https://pages.cloudflare.com/">Cloudflare pages</a> is a static web hosting platform for collaborating, building and deploying JAMstack websites using frameworks like Gatsby, Jekyll, React.js, Next.js and several others. It is effortless and super fast to set up; it takes approximately three minutes to deploy. All you have to do is give it access to your repository and do a little bit of configuration, and automatically it will set up a domain with HTTPS for you.</p><p>PS: If your framework isn’t listed amongst the <a href="https://developers.cloudflare.com/pages/framework-guides">framework guide</a>, or you manage your site without using a static site generator or any framework, you can still deploy your site. Refer to this <a href="https://developers.cloudflare.com/pages/framework-guides/deploy-anything">guide</a>.</p><h3>How Cloudflare pages differ from other JAMstack hosting platforms</h3><p>One of the unique differences Cloudflare pages offers is its dynamic functionality through its integration with Cloudflare <a href="https://workers.cloudflare.com/">workers.</a> Unlike in Netlify, serverless functions are called workers in Cloudflare. The Cloudflare Workers are separate from the pages, which allows you to write or edit your functions with the Cloudflare dashboard. Although functions in Cloudfare is in <strong>beta</strong> at the time of writing, they allow you run server-side code without running a dedicated server. With the help of the workers, you can build full-stack applications.</p><p>Cloudflare pages also provide git integration, which is essential for any website. Instead of manually updating your webpage, unlike in some other JAMstack hosting platforms, you push your code to Github or Gitlab, and your site is automatically updated.</p><p>Cloudflare pages also provide domains that acts as register and have no markup pricing. This means that there is no additional cost to the regular price of domains compared to some other hosting platforms where you pay approximately double the price for the domain.</p><h3>Deploying React app with Cloudflare pages</h3><p>This project is a SPA bootstrapped with React, and just for the sole purpose of this tutorial, so it doesn’t contain any real information. However, to follow along with this tutorial step-by-step, you can clone the project repository. Here’s a link to the repo <a href="https://github.com/Dalu46/Cloudflare-pages">https://github.com/Dalu46/Cloudflare-pages</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*THZnB6xp1YK45Lsi.png" /></figure><p>Visit the above URL, then copy and paste the URL alongside the below git clone command on the terminal.</p><pre>git clone <a href="https://github.com/Dalu46/Cloudflare-pages.git">https://github.com/Dalu46/Cloudflare-pages.git</a></pre><p>After cloning the site, we install dependencies with this line of code</p><pre>npm install</pre><p>Now you have the codebase locally on your machine, you can edit the source code as you choose. Next, we set up a Github repo and push the project to it. This Github repo is what we’d use for deployment on Cloudflare pages. If you don’t have a Github account, you can create one <a href="https://github.com/">here.</a></p><p>Now we have our Github repo ready, let’s create a Cloudflare pages account. Follow the instructions <a href="https://dash.cloudflare.com/sign-up/pages">here</a> to create one<a href="https://dash.cloudflare.com/sign-up/pages">.</a> After a successful set up of a Cloudflare pages account, the dashboard should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oz_rQulThV6i0wnX.png" /></figure><p>The next step is to click on the Create a project button, which will take us to the page to connect our preferred git provider account to Cloudflare pages. And for this tutorial, that&#39;d be Github.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y5QFagHgTGqa9Pok.png" /></figure><p>Next, click on the connect Github button, requiring you to log in to your Github account. Then select the <strong>All repository</strong> and click <strong>install and authorise.</strong> After which we would be directed to this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h22zG1ULfw60NSdk.png" /></figure><p>Now that we have successfully connected our Github account, we need to select the repo we created. You can see the Cloudflare-pages repository was sorted here by the most recently updated. Then we click on Begin setup button, which will take us to the configuration page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AD4kYcy0WIQTLHHq.png" /></figure><p>The project name will be used to generate a subdomain name from the Cloudflare’s pages.dev domain name, which means we are going to have a host name like cloudflare-pages-alh.pages.dev. You can change the project name to anything of your choice. The production branch by default is set to the <strong>main</strong> branch of our repository from Github.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T5t3GlQwJSAjb9yP.png" /></figure><p>Now, for the build settings which we’ll select <strong>create react app</strong> because this is a React application, <strong>and automatically the build command is set to </strong><strong>npm run build </strong>and the build output directory is set to <strong>build.</strong> Once we have these in place, click on the save and deploy button.</p><p>Basically what Cloudflare pages is doing behind the hood is; it would setup a build environment for us and clone our Github repository and then run npm install to install all of our packages, run the build command to build our application and then publish it in approximately three minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9FuUFkLrCNaHWX7X.png" /></figure><p>We have successfully deployed our React app, and Cloudflare pages have also automatically generated a URL for our React app. The main branch is always set to production, so whenever we push or merge changes to our code into the main branch, it will get rebuilt and deployed the changes to our application.</p><p>To see the recent builds of our project, click the <strong>cloudflare-pages</strong> button at the top of the page, and it will direct us to our builds. Refresh the page to see the recent updates as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gtDHCbTx8lVQIplW.png" /></figure><p>Here we see that our production code is built from our default branch, and we also get a new build per a new commit to our repository. This is an automatic deployment, meaning we don’t manually manage it ourselves. Cloudflare pages automatically manage it by listening to changes on our Github repository, automatically making these changes reflect on the deployed site.</p><p>Now, let’s visit the new URL generated by Cloudflare pages. We should see our React SPA app as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t_QsijVe-m-tjWnH.png" /></figure><p>And that’s it, our React app has been deployed successfully.</p><h3>Open Source Session Replay</h3><p>Debugging a web application in production may be challenging and time-consuming. <a href="https://github.com/openreplay/openreplay">OpenReplay</a> is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H_FqSdCI6eckISdB.png" /></figure><p>Happy debugging, for modern frontend teams — <a href="https://github.com/openreplay/openreplay">Start monitoring your web app for free</a>.</p><h3>Adding custom domain</h3><p>Having a custom domain instead of the generated URL is always good. To add a custom domain, we’ll need to navigate to our project dashboard, click on the custom domain link and click on setup the custom domain button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w0-wtK3fX7GXKrWe.png" /></figure><p>Now enter the domain or sub-domain you want to use for the project in the input field provided. You’d have to get a domain name if you do not have one. I’d recommend getting one from <a href="https://www.namecheap.com/">Namecheap</a>.</p><p>While registering your domain name to Cloudflare, you must update name servers. Cloudflare will show you the current nameservers for your domain. You’ll need to log in to your registrar and change your domain name’s nameservers to the ones from Cloudflare, then click on check nameservers. It can take a few hours for your nameservers to propagate. However, if you have already registered your domain to Cloudflare, type the domain name and click <strong>Continue.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1x_6VDYpMQSRsDCO.png" /></figure><p>Now you have to preview the changes, and if you haven’t already, you can configure your DNS to enable HTTPS in your site and then click activate domain. Once this is successful, you’ll see the status reflected on the custom domain tab. This can take up to 48 hours, but most times, it takes lesser time to activate.</p><h3>Conclusion</h3><p>Cloudflare-pages is an awesome platform for self-hosting static sites, which allows you to host static websites from different locations globally without a traditional hosting server. In this article, we deployed a React app using Cloudflare pages. However, as stated earlier: the concepts shared here are applicable to other frameworks that are not React and even other projects that are not frameworks-based like a static HTML page.</p><p><em>Originally published at </em><a href="https://blog.openreplay.com/build-and-deploy-jamstack-applications-with-cloudflare-pages"><em>https://blog.openreplay.com</em></a><em> on February 16, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34c3ab541dd0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/build-and-deploy-jamstack-applications-with-cloudflare-pages-34c3ab541dd0">Build and deploy JAMstack applications with Cloudflare pages</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement Fauna add-on for Netlify applications]]></title>
            <link>https://ikehakinyemi.medium.com/how-to-implement-fauna-add-on-for-netlify-applications-33ba9ae177a5?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ba9ae177a5</guid>
            <category><![CDATA[netlify]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[fauna]]></category>
            <category><![CDATA[faunadb]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 15:52:41 GMT</pubDate>
            <atom:updated>2021-11-30T15:52:41.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InHbW1Xsqny7rup52iQPag.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dsumin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dmitry Sumin</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this tutorial, you learn about the following topics</p><ul><li>Introduction to Fauna and Fauna Add-on For Netlify</li><li>Introduction to FaaS with Fauna and Netlify.</li><li>Build a Notes application with Netlify functions ( Clone the application from GitHub).</li><li>Explain the code and processes involved in setting up Fauna Add-on for the Netlify application built in this tutorial.</li><li>Test our application.</li><li><em>Feel free to navigate through the different sections of the article using the content list provided.</em></li></ul><h3>Fauna add-on for Netlify</h3><p>Serverless computing are services that offer developers an increasingly higher levels of abstraction in the form of serverless offerings. These services are exposed to the developers as APIs that are consumed in applications to reduce or remove the hassle of handling the operational complexity within these applications. Fauna provides a flexible, developer-friendly, transactional database delivered as a serverless, secure and scalable cloud APIs. This means that our database is provided as a “client-serverless” application through serverless APIs. These “<a href="https://fauna.com/client-serverless?utm_source=DevTo&amp;utm_medium=referral&amp;utm_campaign=WritewithFauna_FaunaAddonNetlify_IAkinyemi">client-serverless</a>” applications are written as rich, browser-native clients.</p><p>Fauna Add-on Netlify as an integration makes it easy to use Fauna as the apt database for your Netlify sites and functions. Netlify is a serverless computing company that offers hosting services, and serverless backend services for web applications and static websites. Now with Fauna Add-on Netlify, we can configure and implement a Netlify-specific database, and whilst creating this database, an access token is created and stored in a secured environment variable. Through this means the Fauna Add-on Netlify tool provides us with the basic resources needed to start building Netlify serverless functions that connects to the FaunaDB solely.</p><h3>Introduction to FaaS with Fauna and Netlify</h3><p>The term <strong>FaaS, </strong>also know as “Functions as a Service”, is a category of the clouding computing that allows developers to develop, run and manage application functionalities (microservices) without the hassle of maintaining this infrastructure. The underlying concept is the event-driven computing paradigm wherein application code, or containers, only run in response to events or requests. This means your application executes serverless code in response to events happening within your application.</p><p>With Fauna, it is <a href="https://dashboard.fauna.com/accounts/register?utm_source=DevTo&amp;utm_medium=referral&amp;utm_campaign=WritewithFauna_FaunaAddonNetlify_IAkinyemi">Fauna</a> is a serverless cloud database that offers fast and reliable global access to database via modern APIs, like GraphQL, without sacrificing data consistency. Fauna database can be accessed via HTTPS and there is no cross-database data contamination. Netlify as a serverless platform hosts our serverless applications that communicates with these databases.</p><h3>Build a notes application with Netlify functions</h3><p>Now let’s set up the Notes application using npm and netlify-cli, and as well configure some default settings on the project. With Netlify CLI, we can set up continuous deployment for our project through the terminal, even run development server or deploy our project.</p><p>Before we continue any further, let’s clone the below repository on GitHub into a <strong>Add-on-netlify </strong>folder. This folder would be automatically created while running the git clone command. Then we’ll setup CI/CD on this folder using the Netlify CLI tool.</p><pre>git clone https://github.com/IkehAkinyemi/fauna-add-on-netlify Add-on-netlify</pre><p>Now we’ve created a folder named <strong>Add-on-netlify</strong>, let’s change directory into it:</p><pre>cd Add-on-netlify</pre><p>And inside it we’ll install dependencies that would be used in building our project:</p><pre>npm i netlify-cli -g</pre><pre>npm install faunadb</pre><p>This above command would install the Netlify CLI globally on our local system, and installs JavaScript Driver for FaunaDB. We’ll use the JavaScript Driver to make HTTPS requests to our database to perform the CRUD operations on it. Netlify CLI would help us setup our Netlify application without using the Netlify UI. All the configuring and hosting would be done through the terminal.</p><h3>Setting up Fauna add-on for the Netlify application</h3><p>Let’s setup and configure Netlify for our project by running the below commands, while providing the right response to the questions needed by netlify-cli to configure our project:</p><pre>netlify init</pre><pre>What would you like to do? Create &amp; configure a new site</pre><pre>? Team: Ikeh_Chukwuka_Favour&#39;s team</pre><pre>Choose a unique site name (e.g. the-great-IkehAkinyemi-site.netlify.app) or leave it blank for a random name. You can update the site name later.</pre><pre>? Site name (optional): faunadb-add-on-netlify</pre><pre>Site Created</pre><pre>Site ID:   3d3b27bd-3f93-4968-acae-81ff45c69980</pre><pre>? Your build command (hugo build/yarn run build/etc): yarn run build</pre><pre>? Directory to deploy (blank for current dir): dist</pre><pre>? Netlify functions folder: netlify</pre><pre>Adding deploy key to repository...</pre><pre>Deploy key added!</pre><pre>Creating Netlify GitHub Notification Hooks...</pre><pre>Netlify Notification Hooks configured!</pre><pre>Success! Netlify CI/CD Configured!</pre><pre>This site is now configured to automatically deploy from github branches &amp; pull requests</pre><p>With the above success message, we have successfully linked this project to the Netlify. And at the same time setup CI/CD on the repository, <a href="https://github.com/IkehAkinyemi/fauna-add-on-netlify.">https://github.com/IkehAkinyemi/fauna-add-on-netlify.</a> This means that any update we push to this repository reflects on the deployed application on Netlify.</p><p>Next, let create and add “fauna” to our deployed application as a <strong>add-on.</strong></p><pre>netlify addons:create fauna</pre><pre># Add-on &quot;fauna&quot; created for faunadb-add-on-netlify</pre><p>Now let’s authenticate the<strong> Add-on</strong>, this way we’re actually setting up the database using the Fauna website that the command will open on our browser.</p><pre>netlify addons:auth fauna</pre><p>The above command would either open a sign up page on the Fauna website, or login page if you already have an account or the page to rename the default name given to your database if already logged in. Here, we’ll use the default name, 3d3b27bd-3f93–4968-acae-81ff45c69980, and import it into our account. After this, we now have full access to interact with this database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*25efodbp1_vtb6AE.png" /></figure><p>Once imported, click on the database and navigate to the <strong>Security </strong>page through the sidebar to see the set of keys automatically generated for us. These keys are hidden and not accessible to anyone. The keys are stored in a private environment variables and the Netlify UI never displays them.</p><h3>Configuring Fauna</h3><p>We going to test our application to make sure everything is properly working. Before we continue, let’s navigate to the Collection page and <a href="https://dashboard.fauna.com/accounts/register?utm_source=DevTo&amp;utm_medium=referral&amp;utm_campaign=WritewithFauna_FaunaAddonNetlify_IAkinyemi">create a Collection</a> named <strong>notes.</strong> Click on the <strong>NEW COLLECTION </strong>button to create a collection as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w5cEPhBnBgHhBHVN.png" /></figure><p>After we have successfully created our new collection, we can now go back to our project and run a local development server using the netlify-cli tool.</p><pre>netlify dev</pre><pre>◈ Netlify Dev ◈</pre><pre>◈ Injected addon env var: FAUNADB_ADMIN_SECRET</pre><pre>◈ Injected addon env var: FAUNADB_SERVER_SECRET</pre><pre>◈ Injected addon env var: FAUNADB_CLIENT_SECRET</pre><pre>◈ Ignored general context env var: LANG (defined in process)</pre><pre>◈ Ignored general context env var: LANGUAGE (defined in process)</pre><pre>◈ No app server detected. Using simple static server</pre><pre>◈ Running static server from &quot;Notes backend/dist&quot;</pre><pre>◈ Loaded function create.</pre><pre>◈ Loaded function delete.</pre><pre>◈ Loaded function jokes.</pre><pre>◈ Loaded function read.</pre><pre>◈ Loaded function update.</pre><pre>◈ Functions server is listening on 36151</pre><pre>◈ Static server listening to 34503</pre><pre>┌──────────────────────────────────────────────────┐</pre><pre>│                                                  │</pre><pre>│   ◈ Server now ready on http://localhost:42375   │</pre><pre>│                                                  │</pre><pre>└──────────────────────────────────────────────────┘</pre><p>From the above output, we can see that the FAUNADB_ADMIN_SECRET, FAUNADB_SERVER_SECRET and the FAUNADB_CLIENT_SECRET as <strong>Injected addon env var. </strong>This means that Netlify is managing and providing us with this environment variables from a hidden source within our application. This provides security against hacks or security breaches within our applications. Also, from the output above, we have four serverless CRUD operations defined within our project. These serverless functions can be found in the /serverless directory.</p><h3>Testing our Application</h3><p>Now let open the url, <a href="http://localhost:42375/">http://localhost:42375/</a> in the browser. This is the local development port where the frontend of our project is hosted at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X2tpxg-zY7eBe5wM.png" /></figure><p>Next let’s click on the Create Note button which makes a fetch request to the serverless function, create, to create a Document on the database. Navigate back to the Fauna database page to confirm this action as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9uDpLFzc-stSbXVU.png" /></figure><p>The data provided to this fetch request to create the <strong>Document</strong> can be found within the /dist/js/main.js file.</p><p>Next action is to create a new index. Navigate to the <em>Indexes</em> page to create an index. Searching documents in Fauna can be done by using indexes, specifically by matching inputs against an index’s terms field. Click on the NEW INDEX button to create an index. Once in create index screen, fill out the form: selecting the collection we’ve created previously, then giving a name to our index. In this tutorial, we will name ours <strong>all_notes</strong>. We can now save our index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I8Q_Wovhkgjg1wAF.png" /></figure><p>Next, click on the Read All Notes button to get the <strong>Documents </strong>created on the database. Check the terminal for the response as we used the console.log function to output the response there.</p><pre>Request from ::1: GET /.netlify/functions/read</pre><pre>[<br>  {<br>    ref: Ref(Collection(&quot;notes&quot;), &quot;123&quot;),<br>    ts: 1632442835420000,<br>    data: { name: &#39;Todo-list&#39;, desc: &quot;Patrick&#39;s mother&quot; }<br>  }<br>]</pre><pre>Response with status 200 in 864 ms.</pre><p>Next, we insert a new document. You can find this document in <a href="https://github.com/IkehAkinyemi/fauna-add-on-netlify/blob/main/dist/js/main.js#L26">github</a> repo. Let’s click on the Update Note button and navigate back to the Fauna database page to confirm this action as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TQxs4ZnuHmulBx2z.png" /></figure><p>Now let’s perform the last CRUD action which is the delete action on our database. Click on the Delete Note button and navigate back to the Fauna database page to confirm this action as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4Ktl4VINAKohrmYW.png" /></figure><p>Now we don’t have <strong>Document</strong> in our collection as the deleteOne function had made a fetch request to the serverless action, delete, on our database.</p><h3>Conclusion</h3><p>I’m glad you followed the tutorial to this point, hope you’ve learned how to use <a href="https://docs.fauna.com/fauna/current/integrations/netlify">Fauna Add-on Netlify</a> tool to integrate <a href="https://docs.fauna.com/fauna/current/">Fauna</a> into a Netlify site or functions. The combination of Fauna with Netlify concepts provides you the capacity to build great web application, from e-commerce application to Notes keeping application, or any web application without exposing your secret keys which would be stored and retrieved through the Add-on tool on the application. Here’s the <a href="https://github.com/IkehAkinyemi/fauna-add-on-netlify">GitHub link</a> to code sample we used within our tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ba9ae177a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a multiplayer online form with Next.js and Liveblocks]]></title>
            <link>https://ikehakinyemi.medium.com/how-to-create-a-multiplayer-online-form-with-next-js-and-liveblocks-d90f11649dde?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d90f11649dde</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[collaboration]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 23:48:17 GMT</pubDate>
            <atom:updated>2021-11-24T00:04:20.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLmHO8Vv5KFRrjmStLBc-g.png" /></figure><h3>Goal</h3><p>In this tutorial guide, we will be building a multiplayer form where multiple users can make changes to the form fields in real-time. We will be using Liveblocks’ products (presence block and storage block) and Next.js to build our multiplayer online form. This guide aims to show how Liveblocks will be utilized to create multiplayer forms.</p><p>By the end of this guide, you will:</p><ul><li>Learn what Liveblocks is and how to implement multiplayer online form using Liveblocks</li><li>Understand how Liveblocks’ presence block and storage block works</li><li>Learn to install and connect to Liveblocks</li><li>Learn to use some of Liveblocks hooks such as useObject(), useUpdateMyPresence() and few others</li></ul><h3>Prerequisites</h3><p>To properly follow along with this tutorial, we assume you have some experience using</p><ul><li><a href="https://nextjs.org/docs/getting-started">Next</a>.js</li><li><a href="https://reactjs.org/docs/getting-started.html">React.js</a> and React hooks</li><li>JavaScript and ES6 syntax such as destructuring, arrow functions etc.</li><li><a href="https://docs.npmjs.com/getting-started/">npm</a></li><li>Environment variables</li></ul><p>If you have some experience, then you should be good to go as we assume you have installed Next.js.</p><h3>Presence block and Storage block</h3><p>Liveblocks presence block is what we use to indicate the “presence” of connected users and active users. This helps us identify all collaborators currently in the room.</p><p>Liveblocks storage block on the other hand is our “source of truth” for data being set or updated by all users in the room. Multiple users can edit at the same time and data is kept in sync. It also persists even after everyone leaves the room.</p><p>You can read more about <a href="https://liveblocks.io/docs/api-reference/liveblocks-react#Presence">Liveblocks presence</a> and <a href="https://liveblocks.io/docs/api-reference/liveblocks-react#Storage">Liveblocks storage</a>.</p><h3>What exactly is a multiplayer online form</h3><p>You might be wondering what this term means, well the word <em>multiplayer</em> simply implies more than one player. Essentially, a multiplayer online form is an online form whose content can be interacted with and changed by more than one user in <strong>real-time</strong>. This is what Liveblocks storage block helps us achieve as you are going to learn later on in this tutorial. Multiple users can login and simultaneously edit input fields of the online form or interact with its buttons and every user can see what user made those changes and where they made those changes in almost the exact time (save a few milliseconds) those changes were made.</p><p>Here is a sneak peek of what we’d be building:</p><p>We will call it <strong>Writers Club</strong> app, so get your fingers ready because we are about to start coding our project!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_eGGfxmepNjApWLPthd2Q.png" /><figcaption>This is the final demo that would be built in this tutorial.</figcaption></figure><h3>File structure</h3><p>After you must have set up your Next.js environment, your folder structure should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*0CiA7cqF3GIAVCLRNmhnrw.png" /><figcaption>The folder structure of the project</figcaption></figure><p>We are going to be creating our component files and their style files in the /pages folder. We will place our authentication file in /pages/api folder. Our general styles will go into the /styles folder.</p><p>Please create a constant.js file in the pages folder and add these:</p><pre>export const AVATAR_SIZE = 32;<br>export const COLORS = [&quot;#E9D8A6&quot;, &quot;#BB3E03&quot;, &quot;#059669&quot;, &quot;#0A9396&quot;, &quot;#DB2777&quot;]</pre><p>This is the size we’d use for our avatars and also the colors we’d be using to indicate a user actively making changes.</p><p>We’d also share a link to the code at the end of the tutorial for your reference.</p><h3>Add Liveblocks to your project</h3><p>To add Liveblocks to your project, you need to run the following command in your terminal:</p><pre>npm install @liveblocks/client @liveblocks/react @liveblocks/node</pre><p>The dependencies:</p><ul><li>@liveblocks/client lets us connect to Liveblocks servers.</li><li>@liveblocks/react contains React utilities to make it easier to consume @liveblocks/client</li><li>@liveblocks/node helps us to authenticate.</li></ul><p>After installing Liveblocks, your package.json file should have them listed like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*IdAI79tbb8z0KlTRlqdPUw.png" /><figcaption>package.json file</figcaption></figure><h3>Authentication</h3><p>To use Liveblocks, we have to authenticate using our secret key. Create a file in the pages/api folder and name it auth.js.</p><p>Also, we are going to use userInfo field to add information about the current user that will not be changed throughout the session. This is helpful to implement user’s avatar/image or display the user’s name to indicate their presence for identification purpose.</p><blockquote><strong><em>kindly note that you need to have access to the private beta for the storage block. Please contact Liveblocks at hello@liveblocks.io if you want access to the storage block private beta</em></strong></blockquote><p>For this tutorial, we’ll use random names and random avatars to indicate the presence of a user. Here is the code snippet of what the auth.js file should look like.</p><pre>import { authorize } from &quot;@liveblocks/node&quot;;</pre><pre>// Create and environment variable and add your liveblocks secret_key</pre><pre>const API_KEY = process.env.LIVEBLOCKS_SECRET_KEY;</pre><pre>export default async function auth(req, res) {</pre><pre>/* You can implement your security checks here just like we did below */</pre><pre>if (!API_KEY) {<br>  return res.status(403).end();<br>}</pre><pre>// For the avatar example, we&#39;re generating random users<br>// We will also generate random names for the user<br>// and set their info from the authentication endpoint<br>// See https://liveblocks.io/docs/api-reference/liveblocks-node#authorize for more information</pre><pre>const response = await authorize({<br>  room: req.body.room,<br>  secret: API_KEY,<br>  userInfo: {<br>    name: NAMES[Math.floor(Math.random() * NAMES.length)],<br>    picture: `/assets/avatars/${Math.floor(Math.random() * 10)}.png`,<br>  }<br>});</pre><pre>  return res.status(response.status).end(response.body);<br>}</pre><pre>const NAMES = [<br>  &quot;Ikeh Akinyemi&quot;,<br>  &quot;Naru Designs&quot;,<br>  &quot;Steve Fabre&quot;,<br>  &quot;Guillaume Salles&quot;,<br>  &quot;Fortune Kay&quot;<br>];</pre><h3>Connect to Liveblocks server</h3><p>Inside the pages folder, create a file and name it _app.js. In this file, we will connect to Liveblocks and create a client. A <strong>Liveblocks client</strong> is responsible for communicating with Liveblocks servers. You can create a client using your public key but in this tutorial, we’d be using the authEndpoint to handle authentication in our auth.js file that would be created later on in the pages/api folder.</p><pre>import &quot;../styles/globals.css&quot;;<br>import { createClient } from &quot;@liveblocks/client&quot;;<br>import { LiveblocksProvider, RoomProvider } from &quot;@liveblocks/react&quot;;<br>import React from &quot;react&quot;;</pre><pre>//create liveblocks client</pre><pre>const client = createClient({<br>  authEndpoint: &quot;/api/auth&quot;,<br>});</pre><pre>function MyApp({ Component, pageProps }) {<br>  return (<br>     &lt;LiveblocksProvider client={client}&gt;<br>       &lt;RoomProvider id=&quot;writers-club&quot;&gt;<br>         &lt;Component {...pageProps} /&gt;<br>       &lt;/RoomProvider&gt;<br>     &lt;/LiveblocksProvider&gt;<br>  );<br>}</pre><pre>export default MyApp;</pre><h3>Create multiplayer form</h3><p>This is where we’ll use the Liveblocks presence block and storage block to create the multiplayer form where all the users can collaborate. Here are some of the Liveblocks hooks we will be importing, and what we will be using them for:</p><ul><li>useOthers() we will use this to get info about other users connected in the room.</li><li>useUpdateMyPresence() we will use this to update presence of the current user, show what form element is currently in focus and which user is acting on them.</li><li>useSelf() we will use this to get info of the current user once the user is connected to the room.</li><li>useObject()<strong> </strong>— this returns the liveObject associated with the provided key (which we used during authentication). We will create our initial data (state) which will be stored in Liveblocks storage block and share the state with all connected users using this hook.</li></ul><p>For more information: see <a href="https://liveblocks.io/docs/api-reference/liveblocks-react#useObject">useObject()</a>. Data is created using this hook like so:</p><pre>//initial data</pre><pre>const data = useObject(&quot;editor&quot;, {<br>  title: &quot;Title&quot;,<br>  content: &quot;Content&quot;,<br>  theme: &quot;light&quot;,<br>});</pre><p>And to update the data we’ll use the set() method as below:</p><pre>data.set(&quot;title&quot;, e.target.value);</pre><p>In this tutorial, we will not cover how to implement live avatars, you can learn about this in another article <a href="https://liveblocks.io/blog/how-to-add-a-live-avatar-stack-to-your-product-with-react-firebase-liveblocks">here</a>. The avatars are the pictorial representation of current users that are online.</p><p>Navigate to the pages folder and create a file Avatar.js and update it with the below component code snippet:</p><pre>import React from &quot;react&quot;;<br>import styles from &quot;./Avatar.module.css&quot;;<br>import { AVATAR_SIZE } from &quot;./constants&quot;;</pre><pre>export default function Avatar({ picture, name, color }) {<br>  return (</pre><pre>    &lt;div className={styles.avatar} style={{ width: `${AVATAR_SIZE}px`, height: `${AVATAR_SIZE}px`, boxShadow: color ? `0 0 0 1px var(--color-background), 0 0 0 3px ${color}` : undefined, }} data-tooltip={name} &gt;</pre><pre>     &lt;img src={picture} height={AVATAR_SIZE} width={AVATAR_SIZE} className={styles.avatar_image} style={{ border: color ? `1px solid var(--color-background)` : undefined, }} /&gt;</pre><pre>   &lt;/div&gt;<br> );<br>}</pre><p>Next, we have to style our avatar component. Create a file Avatar.module.css file and add the below code snippet:</p><pre>.avatar {<br>  position: relative;<br>  border-radius: 50% 50%;<br>  margin: 0 6px;<br>}</pre><pre>.avatar:before {<br>  content: attr(data-tooltip);<br>  position: absolute;<br>  top: -32px;<br>  opacity: 0;<br>  padding: 4px 8px;<br>  color: white;<br>  font-size: 12px;<br>  left: 50%;<br>  transform: translateX(-50%);<br>  border-radius: 4px;<br>  z-index: 1;<br>  background: rgba(0, 0, 0, 0.96);<br>  white-space: nowrap;<br>}</pre><pre>.avatar:hover:before { <br>  opacity: 1;<br>}</pre><pre>.avatar:not([data-tooltip-persistent]):before {<br>  pointer-events: none;<br>}</pre><pre>.avatar_image {<br>  border-radius: 50% 50%;<br>}</pre><h3>Create Selection component</h3><p>With the Selection component, we will be able to indicate the presence of the user currently online and is making changes to the form. Within the /pages folder, create a Selection.js file and add the code snippet:</p><pre>import React from &quot;react&quot;;</pre><pre>import styles from &quot;./Selection.module.css&quot;;</pre><pre>export default function Selection({name, color}) {</pre><pre>return ( <br>  &lt;div className={styles.selection}&gt;<br>    &lt;div className={styles.selection_border} style={{ borderColor: color, }} /&gt;<br>      &lt;div className={styles.selection_name} style={{ background: color }}&gt;<br>      {name}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre> );<br>}</pre><p>To style this component, create a Selection.module.css file in the pages folder and add the following code snippet:</p><pre>.selection {<br>  position: absolute;<br>  pointer-events: none;<br>  top: 0;<br>  right: 0;<br>  bottom: 0;<br>  left: 0;<br>}</pre><pre>.selection_border {<br>  position: absolute;<br>  top: -5px;<br>  right: -5px;<br>  bottom: -5px;<br>  left: -5px;<br>  border-radius: 11px;<br>  opacity: 0.2;<br>  border-width: 5px;<br>  border-style: solid;<br>}</pre><pre>.selection_name {<br>  position: absolute;<br>  top: -29px;<br>  padding: 0 6px;<br>  border-radius: 3px;<br>  font-size: 12px;<br>  line-height: 20px;<br>  height: 20px;<br>  color: white;<br>  right: 0;<br>}</pre><h3>Create MultiplayerForm component</h3><p>Next we will build our Multiplayer online form using the 3 main components we discussed earlier. These 3 main components are:</p><ul><li>MultiplayerForm component: which contains the form itself and the preview part. It will also house all other components.</li><li>Avatars component: this will wrap the avatars of all connected users.</li><li>Selections component: this will house the Selection component which we added above.</li></ul><p>Whenever any of the form elements, input, textarea, or button is on focus, we will update the presence with the id of the form element. When it is blurred, we will update the presence with null. This id is passed to the Selections which re-renders the Selection component based on the id and then the Selection component indicates which user is actively taking actions on the form element.</p><p>When a change is made to a form element, input or textarea, or a button is clicked, we update the data value in the storage block simultaneously with the value of the element or the corresponding theme to the button which was clicked.</p><p>Next, create an index.js file in the pages folder. This file is the primary file of our application that will be rendered in our browser. The index.js contains the MultiplayerForm component which contains all of our other components.</p><p>The full code snippet for the MultiplayerForm component can be found <a href="https://github.com/IkehAkinyemi/Liveblocks-multiplayer-form/blob/main/pages/index.js#L37">here</a>. And within the index.js file, we will focus on the below code snippet to illustrate the above explanation:</p><pre>&lt;div className={styles.selection_container}&gt;</pre><pre>  &lt;input id=&quot;input-name&quot; type=&quot;text&quot; className={styles.input} value={title} onFocus={(e) =&gt; updateMyPresence({ focusedId: e.target.id })} onBlur={() =&gt; updateMyPresence({ focusedId: null })} onChange {(e) =&gt; { data.set(&quot;title&quot;, e.target.value); }} maxLength={20} /&gt;  <br>  <br>  &lt;Selections id=&quot;input-name&quot; /&gt;<br>&lt;/div&gt;</pre><p>Now we are done coding our application, let’s view the final working UI by simply running the following command. This would open the application on localhost:3000 for preview.</p><pre>npm run dev</pre><h3>Conclusions</h3><p>The Liveblocks presence block and storage block are awesome products to build collaborative projects. While presence handles user identification to prevent conflicts, storage block keeps a shared state between all connected users. One user makes a change and all connected users are aware simultaneously (at once). Even when everyone leaves the room, this state persists and the users can return to meet the same data state.</p><p>The full codebase for the project can be found on <a href="https://github.com/IkehAkinyemi/Liveblocks-multiplayer-form">GitHub</a>. And that marks the end of the tutorial, thank you for sticking around!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d90f11649dde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Doppler: Building Express Application With Doppler And FaunaDB]]></title>
            <link>https://ikehakinyemi.medium.com/intro-to-doppler-building-express-application-with-doppler-and-faunadb-c665780076e8?source=rss-ac4a72da674d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c665780076e8</guid>
            <category><![CDATA[doppler]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[faunadb]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Ikeh]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 16:59:55 GMT</pubDate>
            <atom:updated>2021-09-28T16:59:55.128Z</atom:updated>
            <content:encoded><![CDATA[<p>Building full-stack Express applications would always involve connecting to a database or external resources that are needed to have functional applications. When connecting to these external resources we would need a means of verifying our identity before making a successful connection. We use special secret keys or API keys that are peculiar to our application to verify our identity. These keys should always be kept secret from the public eye as the Web is an open village or we stand to lose our application to cybersecurity attacks. Managing secret API keys on the backend application has been strenuous and many solutions like using the .env file have been proposed, but these solutions have not been any efficient when deployed to the Web.</p><h3>Introduction to Doppler Secret Management</h3><p>Doppler has since its invention made secret management easier by reducing the complexity involved in securing the secret resources needed within our application for it to work. Doppler as a tool integrated into our application helps our application scale as it increases in functionalities providing it with fine-grained access controls, logs, versioning.</p><p>Doppler provides a secure and scalable Universal Secrets Manager that makes development for developers easier by removing any need for .env files, or the unnecessary hardcoded secrets and copy-pasted credentials. This Universal Secrets Manager works for almost all the programming languages regardless of their steadily growing list of integrations. Doppler can be integrated into an existing project or your first project by following the self-explanatory docs for installing Doppler. The Doppler CLI tool makes it a whole lot easier to access the secrets in any environment, either the development environment or production. Also, we’re provided with a dashboard to manage our application configurations.</p><p>To avoid breaking code in production, Doppler automatically creates a snapshot of our latest secrets and stores it in an encrypted file. During development, if we couldn’t get access to the API that we connect to with the secret keys, the Doppler CLI smartly fallsback to the snapshot from the encrypted file.</p><p>Next, let’s start building and implementing the different parts of our backend application. This will involve a series of simple steps to define and then start our server. Let’s create a folder named Doppler project, change directory into this folder, and then at the root of the folder initialize an Express application:</p><pre>mkdir &quot;Doppler project&quot;<br>cd Doppler\ project/ <br>npm init -y</pre><p>Let’s install the dependencies needed within our application to implement some functionalities:</p><pre>npm install express faunadb</pre><p>The above command would install the Express library, and the JavaScript Driver, faunadb, for connecting to the database. Click here to set up a Fauna account if you don’t have anyone. In the dashboard, click on the “NEW DATABASE” button, provide a name for your database then press the SAVE button. Once you’ve created your database, you’ll need to create a collection named Posts. This is what we’ll be interacting with within our source code to create a Document (a post) within our application. Now let create our /server.js file, and update it with the following code to implement a server for our application:</p><pre>const express = require(&quot;express&quot;);<br>const faunadb = require(&quot;faunadb&quot;),</pre><pre>const q = faunadb.query;</pre><pre>const secret = process.env.FAUNADB_SERVER_SECRET;<br>const client = new faunadb.Client({<br>   secret: secret,<br>});</pre><pre>const app = express();</pre><pre>app.use(express.json());</pre><pre>const PORT = process.env.PORT || 8000;</pre><pre>app.listen(PORT, () =&gt; console.log(`🚀🚀 Server listening at port ${PORT} 🚀`));</pre><p>Now let’s define the different routes that would connect our backend application to the database and perform CRUD actions on it when we send requests to the server.</p><pre>...<br>app.post(&quot;/posts&quot;, async (req, res) =&gt; {</pre><pre>try {</pre><pre>const { post, description } = req.body;</pre><pre>const { data } = await client.query(</pre><pre>q.Create(q.Collection(&quot;Posts&quot;), { data: { post, description } })</pre><pre>);</pre><pre>res.status(201).json(data);</pre><pre>} catch (error) {</pre><pre>res.status(500).json({ error: error.description });</pre><pre>}</pre><pre>});</pre><pre>...</pre><p>In the above code, we’re creating a post data (Document) in our database when we make a POST request on the /posts path of our application. To test our application routes, we’ll use any HTTPS client, and for this tutorial, we’ll be using the Postman application to test it. Before we start testing our application, let’s implement another route, to get all the Documents (posts) within our application.</p><pre>...<br>app.get(&quot;/posts&quot;, async (req, res) =&gt; {</pre><pre>try {</pre><pre>let { data } = await client.query(</pre><pre>q.Map(</pre><pre>q.Paginate(q.Documents(q.Collection(&quot;Posts&quot;))),</pre><pre>q.Lambda(&quot;X&quot;, q.Get(q.Var(&quot;X&quot;)))</pre><pre>)</pre><pre>);</pre><pre>res.status(200).json(data[0][&quot;data&quot;]);</pre><pre>} catch (error) {</pre><pre>res.status(500).json({ error: error.description });</pre><pre>}</pre><pre>});</pre><pre>...</pre><p>Now we’ve implemented the routes for our application, let’s set up Doppler for our project to manage our environment variables, aka secret keys. Let’s create a Doppler account by clicking here. Follow the user-friendly steps to create an account, and once created, go ahead to create a workspace with any name you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*pVwyTHlOYJosWqzK" /></figure><p>After creating a workspace, follow the Doppler friendly walkthrough to understand some of the functionalities and features of Doppler. Next, let’s create a new project on Doppler. Click on the Project link, then click on the plus icon to create and add a new project to the workspace. We’ll name it Doppler-Express. Once created, we’re provided with three environments for our project namely:</p><ul><li>Development</li><li>Staging</li><li>Production These are environments for managing the secret resources we’ll use within our application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GS1mIib0hctTs0-X" /></figure><p>Now we have our project set up on the Doppler website, let setup our local environment on our local machine using the Doppler CLI.</p><h3>Set Up Doppler On The Local Environment Using The Doppler CLI</h3><p>Let’s proceed ahead to install the Doppler CLI which will help us in the development stage of our application.</p><pre># Install pre-reqs sudo apt-get update &amp;&amp; sudo apt-get install -y apt-transport-https ca-certificates curl gnupg  # Add Doppler&#39;s GPG key curl -sLf --retry 3 --tlsv1.2 --proto &quot;=https&quot; &#39;https://packages.doppler.com/public/cli/gpg.DE2A7741A397C129.key&#39; | sudo apt-key add -  # Add Doppler&#39;s apt repo echo &quot;deb https://packages.doppler.com/public/cli/deb/debian any-version main&quot; | sudo tee /etc/apt/sources.list.d/doppler-cli.list  # Fetch and install latest doppler cli sudo apt-get update &amp;&amp; sudo apt-get install doppler</pre><p>Now we’ve finished configuring and installing Doppler CLI on our local machine, run the following code to confirm that it was installed successfully.</p><p>Next, let’s authenticate our local development with the remote development environment as they would need to be in sync with each other.</p><p>This opens the browser to log into your account and authenticate your local environment. Fill in your email or login with Google, then copy and paste the auth token that’s displayed on the terminal, to authenticate Doppler. Inside the root, run the doppler setup command and select the right option to configure your local environment:</p><pre>doppler setup ? Select a project: doppler-express ? Select a config: dev ┌─────────┬─────────────────┬─────────────────────────────────────────────────┐ │ NAME │ VALUE │ SCOPE │ ├─────────┼─────────────────┼─────────────────────────────────────────────────┤ │ config │ dev │ /home/ikehakinyemi/Projects/NodeJS/Doppler proj │ │ │ │ ect │ │ project │ doppler-express │ /home/ikehakinyemi/Projects/NodeJS/Doppler proj │ │ │ │ ect │ └─────────┴─────────────────┴─────────────────────────────────────────────────┘</pre><p>Now let’s return back to our remote project on the website and click on the dev section of the project. Then click on the Add Secret to add a new secret as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iKoqo_UvE3ZI7dYc" /></figure><p>Add the name of your secret key and paste in the value of the secret key, which is the secret key itself. Click on the Save button to add the secret key to the dev environment. Return back to your terminal and run the following command to confirm that your secret key is in sync with your remote environment:</p><pre>echo $(doppler secrets get FAUNADB_SERVER_SECRET fnAEUIdhSoACXXXXXXXX-n6QxpBZXXXXXXXXpkBp</pre><p>Now let’s use Postman to test our application and make sure our routes are accessing the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*eV0m8Q0BVXrs86r9" /></figure><p>The first Document has been successfully been created on the database. Log into your database and confirm it. Next, let’s check the second route which is a GET request, to return all the Documents from the database as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/0*FDquuRf6-In8R3pT" /></figure><h3>Conclusion</h3><p>We’ve successfully set up Doppler for an Express application to securely hide and manage our secret keys used for its development. We eliminated the need to have a .env file, and can now easily manage these secret keys among our friends or team by giving them access to the Workspace on the Doppler website. And we can integrate Doppler services in any Node.JS application as it uses the native approach of retrieving the environment variables through the process.env[“YOUR_SECRET_KEY”]. The code used in this tutorial can be found on <a href="https://github.com/IkehAkinyemi/Doppler-Express">GitHub</a>.</p><p><em>Originally published at </em><a href="https://ikehakinyemi.hashnode.dev/intro-to-doppler-building-express-application-with-doppler-and-faunadb"><em>https://ikehakinyemi.hashnode.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c665780076e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>