<?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[time2hack - Medium]]></title>
        <description><![CDATA[All the stories from time2hack.com - Medium]]></description>
        <link>https://medium.com/time2hack?source=rss----4f11abffcd7b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>time2hack - Medium</title>
            <link>https://medium.com/time2hack?source=rss----4f11abffcd7b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:51:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/time2hack" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Organize TypeScript types with namespaces]]></title>
            <link>https://medium.com/time2hack/organize-typescript-types-with-namespaces-586847d7fbc3?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/586847d7fbc3</guid>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 08:35:07 GMT</pubDate>
            <atom:updated>2023-07-17T08:35:07.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBZpukrY87eryDUTH_XJww.jpeg" /></figure><p>I am leaning more and more towards typed languages, and the presence of TS eases the Frontend Development for me, not just because of type safety but the Documentation via Editor Autocomplete (Intellisense in VSCode).</p><p>Though the way we use types on small projects and large projects is very different.</p><p>As the scale of the project increases, you will encounter situations where you have so many types that they don’t sit in one place. And because they don’t sit in one place, you will encounter type collisions/conflicts.</p><p>Ideally, the type-collision should be avoidable when the project is planned and discussed. But as I said, the scale of the project is increasing, and some will slip.</p><h3>Problem</h3><p>Consider the scenario where we have a Blog system with Users, Posts, and Posts related to Users as either Authors or Editors.</p><pre>type User = {<br>  id: string;<br>  email: string;<br>  homepage: string;<br>  name: string;<br>  userName: string;<br>  role: &#39;editor&#39; | &#39;writer&#39;;<br>};<br><br>type Author = { posts: Array&lt;Post&gt;; } &amp; Pick&lt;User, &#39;id&#39; | &#39;name&#39; | &#39;homepage&#39;&gt;<br><br>type Editor = { posts: Array&lt;Post&gt;; } &amp; Pick&lt;User, &#39;id&#39; | &#39;name&#39; | &#39;homepage&#39;&gt;<br><br>type Post = {<br>  id: string;<br>  slug: string;<br>  created_at: string;<br>  updated_at: string;<br>  status: &#39;draft&#39; | &#39;published&#39;;<br>  body: string;<br>  bodyAsHTML: string;<br>  bodyAsMarkdown: string;<br>  authors: Array&lt;Author&gt;;<br>  editors: Array&lt;Editor&gt;;<br>}</pre><p>These types serve the API purpose perfectly, but when it comes to the usage in the UI page, React or Angular, or any other system, these types are not that flexible.</p><p>These types would need extensions on the above types for minor adjustments like while editing, validation status, while viewing, status like logged in or not, etc. And here are those extensions:</p><pre>type EditorUser = User &amp; {<br> isLoggedIn: boolean;<br> token?: string;<br>}<br><br>type Editor = {<br>  user: EditorUser;<br>  posts: Array&lt;Post&gt;;<br>  currentlyEditing: Post;<br>  activeSection: &#39;content&#39; | &#39;meta&#39; | &#39;social&#39;;<br>}<br><br>type PostPage = {<br>  post: Post,<br>  // If logged in<br>  user?: Pick&lt;User, &#39;id&#39; | &#39;name&#39; | &#39;homepage&#39; | &#39;userName&#39;&gt;<br>}</pre><p>And with that, we can see that there are already too many types of User</p><p>On top of this, let’s imagine that we use the file-based type organization and create two files:</p><p>editor/types.ts</p><pre>type User {<br>  /* fields for Editor User */<br>}</pre><p>entities/types.ts</p><pre>type User {<br>  /* fields for primary User entity mapping the DB columns */<br>}</pre><p>Now in your Application Code, when you want to use the type User you will have three options to use any User type, which will be confusing as all the types are named <strong>User</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lfUpwJviZ29wWefl.png" /></figure><h3>Namespaces</h3><p>In typescript, <strong>Namespaces</strong> are a way to prepare a logical collection of types.</p><p>You can create a namespace in the following way:</p><pre>namespace App {<br>  /** Contents of the the App namespace **/<br>}</pre><p>In the above example, we have created the App namespace. It is empty now; we can add the related typescript entities inside.</p><p>Here is what you can add inside the <strong>namespace</strong>:</p><ul><li>Type</li><li>Interface</li><li>Enum</li><li>Namespace</li></ul><p>And we can choose to expose the namespace members or not.</p><p>Let’s take a look at an example:</p><pre>export namespace API {<br>  export interface ResponseBody&lt;T&gt; {<br>    data: T;<br>  }<br>  export type Date = string;<br>  export enum Methods {<br>    GET = &quot;GET&quot;,<br>    POST = &quot;POST&quot;,<br>    PUT = &quot;PUT&quot;,<br>    PATCH = &quot;PATCH&quot;,<br>    DELETE = &quot;DELETE&quot;,<br>  }<br>  export namespace Errors {<br>    interface InternalError extends Error {<br>      code: number;<br>    }<br>    export interface PayloadError extends InternalError {<br>      message: string;<br>    }<br>    export interface ErrorResponse extends InternalError {<br>      message: string;<br>      response: any;<br>    }<br>  }<br>}<br><br>type Post = {<br>  id: string;<br>  slug: string;<br>  title: string;<br>  publishDate?: API.Date;<br>  // ...<br>};<br><br>const body: API.ResponseBody&lt;Post&gt; = {<br>  data: { id: &quot;randomIDhash&quot;, slug: &quot;post-slug&quot;, title: &quot;Post title&quot; },<br>};<br><br>const request = { method: API.Methods.GET, body };<br><br>const response = {<br>  error1: { code: 0x1 } as API.Errors.InternalError,<br>  // ---------------------------------👆 The following Error on type use<br>  // Namespace &#39;&quot;file:///input&quot;.API.Errors&#39; has no exported member &#39;InternalError&#39;.(2694)<br>  // type API.Errors.InternalError = /*unresolved*/ any<br><br>  error2: {<br>    code: 0x2,<br>    message: &quot;Error&quot;,<br>    name: &quot;Bad Payload&quot;,<br>  } as API.Errors.PayloadError,<br><br>  error3: {<br>    code: 0x2,<br>    message: &quot;Error&quot;,<br>    name: &quot;Bad Payload&quot;,<br>    response: {},<br>  } as API.Errors.ErrorResponse,<br>};</pre><p>Check out the above code in action here: <a href="https://tsplay.dev/WGBXMm?ref=time2hack.com">TS Playground</a>.</p><h3>Refactoring</h3><p>Let’s refactor the above problem case by rearranging our types with the <strong>namespaces.</strong></p><pre>export namespace Entities {<br>  export type User = {<br>    // ...<br>    id: string;<br>    userName: string;<br>  };<br>  export type Author = { posts: Array&lt;Post&gt;; } &amp; Pick&lt;User, &#39;id&#39;&gt;<br><br>  export type Editor = { posts: Array&lt;Post&gt;; } &amp; Pick&lt;User, &#39;id&#39;&gt;<br><br>  export type Post = {<br>    // ...<br>    authors: Array&lt;Author&gt;;<br>  }<br>}<br><br>export namespace Editor {<br>  export type User = Entities.User &amp; {<br>    // ...<br>    isLoggedIn: boolean;<br>  }<br><br>  export type Editor = {<br>    // ....<br>    user: User;<br>    posts: Array&lt;Entities.Post&gt;;<br>    currentlyEditing: Entities.Post;<br>    activeSection: &#39;content&#39; | &#39;meta&#39; | &#39;social&#39;;<br>  }<br>  export type PostPage = {<br>    // ...<br>    post: Entities.Post,<br>    // If logged in<br>    user?: Pick&lt;Entities.User, &#39;id&#39; | &#39;userName&#39;&gt;<br>  }<br>}</pre><h3>Namespaces in TypeDefinition (.d.ts) files</h3><p>Namespaces can also be defined in the Type definition (.d.ts ) files as with other Type constructs. And hence allowing you to use the namespaces without needing to import them individually every time.</p><p>Let’s see an example of a namespace in the type definition file namespaces.d.ts</p><pre>declare namespace API {<br>  export type ResponseData = Object;<br>  <br>  // ... other types<br>}</pre><p>Now one thing you can do, which is only possible with the type definition files, is extend the same namespace to add additional types in a separate type definition file.</p><p>Let’s add another file named custom-namespaces.d.ts along with the above file</p><pre>declare namespace API {<br>  export RequestPayload = Object;<br>  // ... some more types<br>}</pre><p>And now you can use both ResponseData and RequestPayload from above; the namespace is defined partially in two different type definition files, similar to the following</p><pre>const body: API.RequestPayload = {}<br><br>const data: API.ResponseData = {}</pre><p>You scrolled till here, and it seems like you enjoyed this post. Please consider subscribing to the newsletter and get the next post in your Inbox.</p><p>It encourages me to share more of my learnings.</p><p>Please consider subscribing to the newsletter!</p><h3>Conclusion</h3><p>We saw how to manage the types with the help of Namespaces.</p><blockquote>How are you managing the types in your TypeScript application?</blockquote><p>Let me know through comments. or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_&amp;ref=time2hack.com">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack&amp;ref=time2hack.com">@time2hack</a></p><p>If you find this article helpful, please share it with others.</p><p>Subscribe to the blog to receive new posts right to your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=586847d7fbc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/organize-typescript-types-with-namespaces-586847d7fbc3">Organize TypeScript types with namespaces</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practice Project Ideas for Frontend Developers]]></title>
            <link>https://medium.com/time2hack/practice-project-ideas-for-frontend-developers-defab7136251?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/defab7136251</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 09:57:59 GMT</pubDate>
            <atom:updated>2023-07-11T09:57:59.411Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Practice Project Ideas for Frontend Developers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*By3420TuRnmwhKmgJRFpYA.jpeg" /></figure><p>I have been developing front-end applications for over a decade, and some challenges are common everywhere.</p><p>If you can learn to solve them, it will be great to cover the basics and help you gain confidence in your knowledge and capabilities.</p><h3>Frontend Concepts</h3><p>Some challenges that occur in the Frontend again and again are:</p><ul><li>Bundling</li><li>Library publishing</li><li>Typescript</li><li>Tree Shaking</li><li>Code splitting</li><li>Performance</li><li>Font loading</li><li>Images</li><li>Cache</li><li>Service Workers</li><li>CSS → moving away from SCSS and adopting PostCSS and CSS-in-JS</li><li>Making a CLI tool</li><li>Deployment of frontend applications</li><li>Environment specific execution</li><li>Documentation</li><li>Automation</li><li>Dependency Updates</li><li>API Communication &amp; Persistence</li><li>Design System</li><li>Monorepos</li><li>Micro frontends</li><li>Configuration Management</li><li>State Management</li></ul><p>And no matter what framework or library you choose, there will be similar challenges.</p><p>And to get around these challenges, you need to practice to make solutions for them. Each problem is different, so the same solution won’t fit everywhere but practicing will allow you to embrace the dynamicity of the situation.</p><p>Let’s discuss some projects you can build to practice your skills on the above topics.</p><h3>Projects</h3><p>Let’s look at what projects you can build to develop your ideas on some of the above topics.</p><h4>Books Manager</h4><p>Books management or something very similar will help you learn about the basics of the CRUD application.</p><p>You can use one of the dummy APIs to practice building the application with CRUD capabilities, or you can use your imagination to build something that fits your needs.</p><h4>Social Dashboard</h4><p>You can build a Social Dashboard to collect the latest posts from various sources and show them in one place.</p><p>This will allow you to learn how to connect and use third-party APIs.</p><h4>Component Library</h4><p>Learning to build a component library to reuse the code among other projects. This will force you to think and learn about separating the concern between logical and representational components.</p><p>Component Libraries are standard among companies, and their widespread use calls for a hands-on experience with them.</p><p>Along with creating a component library, you will also learn to maintain and document it so you can rely on it. And if you choose to open source it, you will also learn how to work with others on the same project.</p><h4>WYSIWYG Editor</h4><p>WYSIWYG Editors are common, and this problem has been solved several times. But building one by yourself can help you understand how to work with DOM and how such tools work.</p><h4>CLI Utility to generate files</h4><p>You can create a utility to generate files you must manually create every time you work on something. For example, when working with Components, every time you create a new component, you will create a JS File with a designated name, an SCSS/CSS file, a test file, etc.</p><p>And everything would need to be with the same name as the component. Wouldn’t having a CLI utility that generates the files would be cool? You would save brought 30–90 seconds per component.</p><p>Creating such a utility will help you understand what goes around working with Files, CLI tools, node js runtime, its difference from browser runtime, and some unexpected things 😅 (I will let you discover those)</p><h4>Automation</h4><p>You can add automation to test the project on each commit. This is an additional step you can implement on any project. Even if you don’t have testing, you can start small, add some tests for simple functions, and let automation take care of it.</p><p>Another automation you can try to ensure the project is building normally and you don’t accidentally ship the broken build.</p><h3>Going beyond</h3><p>The whole idea is to keep pushing the limits of your knowledge.</p><p>If there is no visible path, try to see existing or similar products in the same field and increase your understanding of the domain and use case.</p><p>Even after that, there are ways to combine use cases from one field to use cases of another.</p><p><em>Three decades ago, nobody thought of hiring taxis over the Internet, but today, it is an overutilized domain, and governments are trying to regulate it</em>.</p><p>And all these advancements in this domain are combined results of rapid development in smartphones, radio, the internet, etc.</p><p>Similarly, you can find things from other domains/use cases and apply them to your domain. <strong>Keep striving</strong></p><h3>Conclusion</h3><p>The list of projects you can build is limitless, but you must pick what you want to build.</p><p>You can keep reading about things, but the learning will only be reinforced when you use the learning or learn while building things.</p><p>Let me know through comments. or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a></p><p>If you find this article helpful, please share it with others.</p><p>Subscribe to the blog to receive new posts right to your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=defab7136251" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/practice-project-ideas-for-frontend-developers-defab7136251">Practice Project Ideas for Frontend Developers</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Too many useState? Let’s useReducer!]]></title>
            <link>https://medium.com/time2hack/too-many-usestate-lets-usereducer-72e7ee8e1610?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/72e7ee8e1610</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 12:46:19 GMT</pubDate>
            <atom:updated>2023-03-28T12:46:18.922Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern Frontend is similar to good old web development, but with one catch: the page in the browser is as sophisticated as the backend.</p><p>Since we learned to load things asynchronously, we want to keep the user as productive as possible and not show any loading screen. This means that the Website became THE WebApp.</p><p>And the most common thing in any WebApp is state management.</p><p>All this prologue was to answer one question: “Why do we have a state in the Frontend Application?”</p><p>This post will examine better state management in our favourite library, React.</p><p>As almost all of you know, the hooks and the most commonly used hook to manage a local state: useState</p><p>useState works great in many scenarios and provides a stable solution without looking into heavier solutions like redux, mobx etc.</p><p>Let’s take a small look into the basic example of the useState hook:</p><pre>const { useState } from &#39;react&#39;;<br><br>const MyComponent = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;article&gt;<br>      &lt;h1&gt;Count: &lt;code&gt;{count}&lt;/code&gt;&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(i =&gt; i++)}&gt;Increase count&lt;/button&gt;<br>    &lt;/article&gt;<br>  )<br>}</pre><p>Looks very straightforward, very innocent.</p><p>And most of the leaf components would look more or less like this, even without the state.</p><p>I would use props most of the time as compared to the state. If you have to use the state, that component must not contain much of the JSX, only the barebones passing the state to other Components as props (of course, there are exceptions).</p><p>But that’s an argument for another time.</p><p>For this post, we will imagine a scenario where we don’t want to introduce the large-scale state management library for one use case, but our state is getting complicated.</p><p>Consider the following wireframe for our application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*6ERxyfb0AnI2Q6Fc.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*wprbMcwxhukecQrG.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*jn85KNpdKArE2peH.png" /></figure><p>Considering the above wireframes, if we were to make the controller component, it would look something like this:</p><pre>const MyApp = () =&gt; {<br>  const [shoudlOpenNewDataForm, toggleNewDataForm] = useState(false);<br>  const [confirmSave, toggleSaveConirmationModal] = useState(false);<br>  const [confirmReset, toggleResetModal] = useState(false);<br>  // ...<br>}</pre><p>Now assume that we need to add one more interaction where we want to allow data editing. This would need us to open the same Form but with some data as the New Data form.</p><p>And upon completion of the data adjustment, we want to confirm if the user wants to save the new state.</p><p>Additionally, we want to allow the deletion of the data from the Data Editing form.</p><p>This would need three additional states to handle this new addition of UI states:</p><pre>const MyApp = () =&gt; {<br>  const [shoudlOpenNewDataForm, toggleNewDataForm] = useState(false);<br>  const [confirmSave, toggleSaveConirmationModal] = useState(false);<br>  const [confirmReset, toggleResetModal] = useState(false);<br>  <br>  const [dataBeingEdited, setData] = useState({});<br>  const [confirmDelete, toggleDeleteConfirmationModal] = useState(false);<br>  // ... <br>}</pre><p>Still simple enough?</p><p>Let’s assume a state of application where we want to allow users to add/update child-level data like access control, permissions, sharing etc. while creating/editing the new data.</p><p>This would need a few more additional useState and useRefs</p><p>I can keep adding a few more use cases to complicate the state.</p><p>And one thing will happen; <strong><em>the controller logic will keep getting bigger and more prone to bugs</em></strong>.</p><p>Let’s not make the situation insane and look at one of the ways we can keep the problem manageable.</p><p>Let’s useReducer</p><h3>useReducer</h3><p>useReducer hook is part of the core library, allowing us to work with the state by dispatching the actions.</p><p>This hook works in <strong>almost</strong> similar ways to useState</p><p>Let’s take a look at a small example:</p><pre>import { useReducer } from &#39;react&#39;;<br><br>const reducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case &quot;open-modal&quot;:<br>      return { modal: action.payload.modal };<br>    case &quot;close-modal&quot;:<br>      return { modal: null };<br>    default:<br>      return state;<br>  }<br>};<br><br>const Modal = ({ close, name }) =&gt; (<br>  &lt;div&gt;<br>    &lt;h3&gt;{name} Modal&lt;/h3&gt;<br>    &lt;button onClick={close}&gt;Close&lt;/button&gt;<br>  &lt;/div&gt;<br>);<br><br>export const MyApp = () =&gt; {<br>  const [state, dispatch] = useReducer(reducer, { modal: null });<br>  const openModal = (modal) =&gt;<br>    dispatch({<br>      type: &quot;open-modal&quot;,<br>      payload: { modal },<br>    });<br>  const closeModal = () =&gt; dispatch({ type: &quot;close-modal&quot; });<br>  return (<br>    &lt;&gt;<br>      {state.modal === &quot;info&quot; &amp;&amp; &lt;Modal close={closeModal} name=&quot;Info&quot; /&gt;}<br>      {state.modal === &quot;confirmation&quot; &amp;&amp; (<br>        &lt;Modal close={closeModal} name=&quot;Confirmation&quot; /&gt;<br>      )}<br>      &lt;button onClick={() =&gt; openModal(&quot;info&quot;)}&gt;Open Info Modal&lt;/button&gt;<br>      &lt;button onClick={() =&gt; openModal(&quot;confirmation&quot;)}&gt;<br>        Open Confirmation Modal<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>In the above example, we created a Modal to show some content based on the passed parameters.</p><p>The above example scenario can be achieved in many ways, but the goal is to exemplify the useReducer hook.</p><p>Here are a few critical elements of useReducer:</p><h3>Parameters</h3><h4>Reducer Function</h4><p>This function is responsible for changing the state based on the type of action. This function is passed to the useReducer hook as the first argument. This function should be pure, i.e. it should not cause any side effects so that it can be tested independently.<br>const [state, dispatch] = useReducer(reducer, { modal: null });</p><h4>Initial State</h4><p>This is supplied as the initial value to the reducer when executed for the first time. It is also the first render value of the state returned by useReducer<br>const [state, dispatch] = useReducer(reducer, { modal: null });</p><h3>Returned Values</h3><p>The useReducer hook returns an array:<br>const [state, dispatch] = useReducer(reducer, { modal: null });</p><h4>Derived state</h4><p>This state must be used in the JSX to determine the next rendered component tree. This is generated by running the reducer function on the previous derived state.<br>const [state, dispatch] = useReducer(reducer, { modal: null });</p><h4>Dispatch Function</h4><p>This is the second element of the returned array from useReducer. This function is used to issue the actions to the reducer function.<br>const [state, dispatch] = useReducer(reducer, { modal: null });</p><p>And here, we can see the above example in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fusereducer-example-forked-2ov3dw%3Ffile%3D%2Fsrc%2FApp.js&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F2ov3dw&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F2ov3dw%2Fscreenshot.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e0957ffb210786e0242e374aa029950/href">https://medium.com/media/5e0957ffb210786e0242e374aa029950/href</a></iframe><h3>Benefits of useReducer</h3><h4>Testability</h4><p>Along with testing the UI, the reducer function should be pure in ideal scenarios. And this enables the testability of this reducer function.</p><h4>Modularity</h4><p>As your function to modify state lives in a separate function instead of the controller Component, you can now move it to a separate file and break it down more to achieve more Modular state derivation.</p><p>In the previous case, you must create a custom hook to encapsulate all the useState hooks.</p><h4>Readability</h4><p>As Modularity and Testability significantly improve the Code readability, your old component is shorter and has less mental overhead.</p><p>Now, let’s refactor our initial useState example. As we have yet to define the fully useState model, our useReducer solution will look a lot bigger now.</p><p>But for a comparable solution which is scalable and manageable, it would be more significant than useReducer</p><pre>const removeModal = (modals, modal) =&gt; modals.filter((item) =&gt; item !== modal);<br><br>export const reducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case &quot;init-add&quot;:<br>      return {<br>        ...state,<br>        currentlyEditing: {},<br>        modals: [...state.modals, &quot;add-item&quot;]<br>      };<br>    case &quot;edit-item&quot;:<br>      return {<br>        ...state,<br>        currentlyEditing: action.payload.item,<br>        modals: [...state.modals, &quot;add-item&quot;]<br>      };<br>    case &quot;init-delete&quot;:<br>      return {<br>        ...state,<br>        modals: [...state.modals, &quot;confirm-delete&quot;],<br>        currentlyEditing: action.payload.item<br>      };<br>    case &quot;delete-item&quot;:<br>      return {<br>        ...state,<br>        modals: removeModal(state.modals, &quot;confirm-delete&quot;),<br>        currentlyEditing: {},<br>        data: state.data.filter((item) =&gt; item.id !== state.currentlyEditing.id)<br>      };<br>    case &quot;init-reset&quot;:<br>      return {<br>        ...state,<br>        modals: [...state.modals, &quot;confirm-reset&quot;]<br>      };<br>    case &quot;reset-editing-item&quot;:<br>      return {<br>        ...state,<br>        modals: removeModal(state.modals, &quot;confirm-reset&quot;),<br>        currentlyEditing: {<br>          ...(state.data.find(({ id }) =&gt; state.currentlyEditing.id) ||<br>            initialState.currentlyEditing)<br>        }<br>      };<br>    case &quot;show-modal&quot;:<br>      return { ...state, modals: [...state.modals, action.payload.name] };<br>    case &quot;hide-modal&quot;:<br>      return {<br>        ...state,<br>        modals: removeModal(state.modals, action.payload.name)<br>      };<br>    case &quot;update-currently-editing&quot;:<br>      return {<br>        ...state,<br>        currentlyEditing: { ...state.currentlyEditing, ...action.payload }<br>      };<br>    case &quot;save-currently-editing&quot;:<br>      const { currentlyEditing } = state;<br>      const probableNewId = new Date().getTime();<br>      const data = state.data<br>        .concat(<br>          currentlyEditing.id<br>            ? []<br>            : [{ ...currentlyEditing, id: probableNewId }]<br>        )<br>        .map((item) =&gt;<br>          item.id === currentlyEditing.id ? { ...currentlyEditing } : item<br>        );<br>      return {<br>        ...state,<br>        data,<br>        currentlyEditing: {},<br>        modals: removeModal(state.modals, &quot;add-item&quot;)<br>      };<br>    default:<br>      return state;<br>  }<br>};<br><br>export const initialState = {<br>  data: [<br>    { name: &quot;A&quot;, id: 1 },<br>    { name: &quot;B&quot;, id: 2 }<br>  ],<br>  currentlyEditing: {},<br>  modals: []<br>};</pre><p>With the above example, all application changes can not be reflected in changes to Data; hence, the code is highly testable and reliable.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fusereducer-example-giedk0%3Ffile%3D%2Fsrc%2Freducer.js&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fgiedk0&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fgiedk0%2Fscreenshot.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/62183f90c90af7ac69c6200e02b36364/href">https://medium.com/media/62183f90c90af7ac69c6200e02b36364/href</a></iframe><p>If we want to check whether the Modal to add a new item is open or not, we need to check the presence of add-item element in the Modals array, let&#39;s look at the example.</p><pre>describe(&#39;data table reducer&#39;, () =&gt; {<br>  it(&#39;should add add-item modal when add is triggered&#39;, () =&gt; {<br>    expect(<br>      reducer({}, { type: &#39;init-add&#39; }).modals<br>    ).toEqual([&#39;add-item&#39;]);<br>  });<br><br>  it(&#39;should add add-item modal when edit is triggered&#39;, () =&gt; {<br>    const action = {<br>      type: &#39;edit-item&#39;,<br>      payload: { item: {a: 1, b: 2} }<br>    };<br>    const updatedState = reducer({}, action);<br>    expect(updatedState.modals).toEqual([&#39;add-item&#39;]);<br>    expect(updatedState.currentlyEditing).toEqual(action.payload.item);<br>  });<br>});</pre><h3>Conclusion</h3><p>Have you used useReducer?</p><p>What are some tips you would consider keeping in mind while using useState and useReducer?</p><p>Let me know through comments. or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a></p><p>If you find this article helpful, please share it with others.</p><p>Subscribe to the blog to receive new posts right in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72e7ee8e1610" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/too-many-usestate-lets-usereducer-72e7ee8e1610">Too many useState? Let’s useReducer!</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Docker Volumes]]></title>
            <link>https://medium.com/time2hack/understanding-docker-volumes-7887624cd16a?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/7887624cd16a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker-volume]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 08:16:10 GMT</pubDate>
            <atom:updated>2023-03-13T08:32:08.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axiBUYyIs0a3d8J5SvJ0vA.jpeg" /></figure><p>Today I wanted to do a deep dive into the Docker Volumes.</p><p>Why? Because this is what kept me confused for a long time and stayed as a mental block for my entrance to the Containerization world.</p><p>For the containers, you can skip mentioning the volume while creating the container, and Docker will manage the files generated by the container internally. It works well if you want to avoid doing anything with the data.</p><p>But it could be better. We want to be able to take this data somewhere and reproduce the application state.</p><p>This is where the Docker volumes come into play.</p><h3>Benefits</h3><p>Here are some benefits of using Docker Volumes:</p><ul><li>It allows us to peek into the container’s filesystem on the subset of the container.</li><li>Serves the purpose of portability of the containers.</li><li>Volumes are mounted by default, but by explicitly mentioning/mounting them, we can take data and use it later to recreate the application/container state.</li></ul><p>Let’s create a simple Volume:</p><pre>docker volume create appVolume</pre><p>Now, this volume can be used when running the container image:</p><pre>docker run -v appVolume:/app/data -it myApp</pre><p>This will attach the appVolume volume to the container running the image tagged as myApp.</p><blockquote>-v is a shorthand for --volume</blockquote><p>And we can see the list of volumes created with the following command:</p><pre>docker volume ls</pre><p>Along with that, if you want to see the internal details of the volume, you can do so with the following command:</p><pre>docker volume inspect appVolume</pre><p>Which should show output like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z-Il70I8HrGLEdWp.png" /></figure><h3>Volumes with --mount flag</h3><p>As in the above example of attaching volume with the -v flag, we also have the --mount flag to do so, which allows all the options of -v. Maybe, a little bit more things than -v</p><p>So why use --mount? Because</p><ul><li>It is very verbose</li><li>accepts all the parameters as key=value pairs</li><li>Docker services creation only works with --mount.</li><li>Docker volume adapter parameters can only be passed with --mount.</li><li>When used for bind mount, this flag will not create the path on the host if the source does not exist.</li></ul><p>How to use --mountflag?</p><p>--mount flag accepts a string of key/value pairs separated by commas. A simple example will look as follows:</p><pre>docker run \<br>  --mount source=appVolume,target=/app/data \<br>  -it myApp</pre><p>Here are the keys and possible values you can pass for the — mount flag:</p><ul><li>type: type of mount, bind, volume and tempfs. If nothing is mentioned, volume it is the default value.</li><li>source: source path or the volume name, and can be shortly named src as well</li><li>target: this key specifies the path of the mount inside the container file system. This key is also a synonym for destination and dest.</li><li>readonly: this key specifies if the mounted volume should be read-only or not and can also be passed as ro</li><li>volume-opt: this key can be added multiple times to give options to the volume drivers.</li><li>volume-driver: The volume driver you want to use for the volume; this key is not needed in most cases. Generally, this option is used when you are creating the volume.</li></ul><h3>Volumes in docker-compose</h3><p>The whole process above is excellent, but it is a manual process. And for containerised applications, it is always better to use a config file like docker-compose.yml</p><p>You can create the volumes in the docker-compose file, like in the following example.</p><p>Docker-compose commands like build would govern this volume, stop, down, etc.</p><pre>...</pre><pre>services:<br>  ...<br>  volumes:<br>    - appVolume:/app</pre><pre>volumes:<br>  appVolume:</pre><p>And in the same fashion, we can create the docker volume externally and use it inside the docker-compose file; as in the following example, we will try to use the docker volume appVolume created with the docker volume create ... command.</p><pre>...</pre><pre>services:<br>  ...<br>  volumes:<br>    - appVolume:/app</pre><pre>volumes:<br>  appVolume:<br>    external: true</pre><h3>Volume drivers</h3><p>As volumes are already allowing us to keep the application data out of the application and give us the ability to backup/restore the data.</p><p>Though, it is also a process of defining how this volume should behave when it is outside the executing state, i.e. backing up, moving, restoring and all sorts of operations for safekeeping.</p><p>In such cases, volume drives come into play where you can choose the nature of volume to be like</p><ul><li>Encrypted</li><li>Store on cloud storage like AWS S3 or DO Spaces</li><li>On a remote machine via SSH.</li><li>Distributed</li><li>etc</li></ul><p>Here we will see an example of volume created with SSH volume driver</p><p>First, we need to install the SSH volume plugin before we can use it:</p><pre>docker plugin install --grant-all-permissions vieux/sshfs</pre><p>Now we can use the driver vieux/sshfs with the --driver flag:</p><pre>docker volume create --driver vieux/sshfs ...</pre><p>Though it is not done, we must pass options like the remote host, auth and path. We will do so with the following command:</p><pre>docker volume create --driver vieux/sshfs \<br>  -o sshcmd=userName@&lt;RemoteIPaddress&gt;:/home/test \<br>  -o password=usersPassword \<br>  mySSHvolume</pre><p>Now, this mySSHvolume can be used in the containers as usual, with -v or --volume or --mount flag.</p><h3>Conclusion</h3><p>Docker volumes have been an eye-opener for me, and the more I understood, the deeper dive I took into containerisation.</p><p>Further, you can explore the Docker volumes from the perspective of multiple services.</p><p>What details about docker volumes surprised you?</p><p>Let me know through comments. or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a></p><p>If you find this article helpful, please share it with others.</p><p>Subscribe to the blog to receive new posts right in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7887624cd16a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/understanding-docker-volumes-7887624cd16a">Understanding Docker Volumes</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 ways you can improve your Reading habits]]></title>
            <link>https://medium.com/time2hack/3-ways-you-can-improve-your-reading-habits-1d5ffbc0e4d8?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/1d5ffbc0e4d8</guid>
            <category><![CDATA[improvement]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[habits]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 21:21:52 GMT</pubDate>
            <atom:updated>2023-03-08T21:21:52.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xG3nqHHuyW-xTrbieuaAQ.jpeg" /></figure><p>Reading has many benefits, but it is a challenging habit. I had struggled to sit and focus long enough to read and finish the books.</p><p>It took a while to get my reading habit in a better shape today, and over time I constrained myself to some restrictions.</p><p>These restrictions allowed me to develop my reading habit and gave me a chance to bring those restrictions to a small step-by-step framework,</p><p>Here are the top 3 (&amp; Bonus) things I did to improve my reading:</p><h3>Read something you enjoy and are already familiar with</h3><p>Stories from past experiences and encounters are always bringing some good memories. And hence reading about something that brings good memories makes reading less painful.</p><p>You can also pick your favourite movies and TV series in book form.</p><p>The books are big enough if you pick them from your favourite Movie or TV Series, but as you know most of the story, there is less pressure to finish it, and you enjoy it.</p><h3>Pick something small to read (like Hemmingway, Penguin classics)</h3><p>Now, as we get better at reading by having something we like, we can expand our habits to the small (thin) books to read or at least not demand a long commitment.</p><p>A small book can be finished quickly, giving a good feeling of finishing something.</p><p>This sense of finishing a book is essential because this will boost your reading confidence and help you pick up the next one.</p><h3>Pick something portable</h3><p>Portability was something that got me more habitual in reading. It would be very few times a week if I waited for a quiet time and place to read.</p><p>So I picked portable books and read whenever I got time — in Bus, Metro, Park, waiting for Covid Test etc. There was no stopping; I could read anywhere and finish the books faster.</p><p>You can carry pocketbooks in your jackets and bigger ones in a small backpack.</p><p>Recently I read two books that I able to finish in (my) record time were:</p><ul><li><a href="https://amzn.to/3T0qilL">The Old man and the Sea</a> by Ernest Hemmingway</li><li><a href="https://amzn.to/3Jp9Acz">Think like an Artist</a> by Will Gompertz</li></ul><p>I carried them all around in my jacket pocket and read whatever I could whenever possible. And this changed my ideas on progressing through a book.</p><p>I still carry more giant books, but I choose the ones I can carry easily while buying new ones.</p><h3>Bonus</h3><p>Now pick something you want to learn and fit at least two criteria above.</p><blockquote><strong><em>Pick the topic from the index if it is not a linear book.</em></strong><br>If it is a linear book and needs to make more sense, set it aside for a while.</blockquote><h4>You scrolled here; you enjoyed this post. Please consider subscribing to the newsletter and get the next post in your Inbox.</h4><h4>It encourages me to share more of my learnings.</h4><p>I have compiled a video covering the above three tips; you can watch the video while still working on your reading habits.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FO-Y9pGYPMLg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DO-Y9pGYPMLg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FO-Y9pGYPMLg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a2e507a4bc2d4af4b20c86dbe164ffc/href">https://medium.com/media/1a2e507a4bc2d4af4b20c86dbe164ffc/href</a></iframe><h3>Conclusion</h3><blockquote><strong>What tips do you recommend for folks struggling with reading habits?</strong></blockquote><p>Let me know through comments. or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a>.</p><p>If you find this article helpful, please share it with others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d5ffbc0e4d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/3-ways-you-can-improve-your-reading-habits-1d5ffbc0e4d8">3 ways you can improve your Reading habits</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize PHP app with Apache on HTTPS]]></title>
            <link>https://medium.com/time2hack/dockerize-php-app-with-apache-on-https-a5c7b32cadc9?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5c7b32cadc9</guid>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 09:11:24 GMT</pubDate>
            <atom:updated>2023-01-10T09:11:24.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*po8fwrPPf3qAXI8KUh0pzw.png" /></figure><p>Recently I came across an application built with the <strong>LA</strong>M<strong>P (Linux, Apache, MySQL and PHP) </strong>stack.</p><p>And this application was critical enough, and one must not mess with it to break anything or increase maintenance.</p><p>But there was one problem, we had to use XAMPP to enable development on this application. XAMPP is a great tool that has served PHP developers for a long time.</p><p>And in modern software development, where we talk about shipping the whole platform with IaaC/IaC (Infrastructure as <em>a</em> Code), this development workflow could be more convenient and help the developer’s productivity.</p><p>After learning a few things about <a href="https://time2hack.com/containerization-docker-fundamentals/">Docker and its benefits</a> and <a href="https://time2hack.com/continuous-deployment-on-digitalocean-droplets-with-gitlab-ci-pipelines/">building dockerized CI/CD process</a>, I set myself to bring Docker to this application and help future devs with easy onboarding and development.</p><p>First, let’s take an example PHP application which shows today’s date and greets the visitor nicely.</p><pre>&lt;!-- File: index.php --&gt;<br>&lt;?php<br>echo date(&#39;l jS \of F Y h:i:s A&#39;);<br>echo &#39;&lt;br /&gt;&#39;;<br>echo &#39;Welcome stranger!&#39;;</pre><p>We must prepare the docker container for the above PHP file via the Docker file. We could use the Docker compose and use the base image directly, but as we need to enable a few plugins and install a few packages, it is better to prepare our custom image and then use it.</p><p>The base image we will use for our PHP application is the official one from php with apache prepackaged: php:7.3-apache.</p><p>As we want to use apache to serve our PHP application, we will need to prepare some configuration for apache. We can use the .conf extension for apache config files. For the initial setup, it should look like this:</p><pre># File: .docker/apache/vhost.conf <br>LoadModule headers_module /usr/lib/apache2/modules/mod_headers.so<br><br>&lt;VirtualHost *:80&gt;<br>    ServerName localhost<br>    DocumentRoot /app<br><br>    &lt;Directory &quot;/app&quot;&gt;<br>        Options Indexes FollowSymLinks Includes execCGI<br>        AllowOverride All<br>        Require all granted<br>        allow from all<br>    &lt;/Directory&gt;<br><br>    ErrorLog ${APACHE_LOG_DIR}/error.log<br>    CustomLog ${APACHE_LOG_DIR}/access.log combined<br>&lt;/VirtualHost&gt;</pre><p>And now, the Dockerfile to build the image:</p><pre>FROM php:7.3-apache<br><br>RUN mkdir /app<br><br>COPY .docker/apache/vhost.conf /etc/apache2/sites-available/000-default.conf<br><br>WORKDIR /app<br><br>RUN chown -R www-data:www-data /app &amp;&amp; a2enmod rewrite</pre><p>With the above Dockerfile, we need to prepare a docker-compose file to ease the service bootstrapping.</p><pre>version: &quot;3&quot;<br><br>services:<br>  my-app:<br>    build:<br>      context: .<br>      dockerfile: .docker/Dockerfile<br>    image: my-app<br>    environment:<br>      - &quot;APACHE_LOG_DIR:/app&quot;<br>    ports:<br>      - 80:80<br>    volumes:<br>      - .:/app</pre><p>With the above simple Docker compose file, we can run the following command and start our container.</p><pre>docker-compose up -d --build</pre><p>And you can see the command to run for a while if you run it for the first time, but subsequent runs will fast to start the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*so0gVitiOps1FoIL6lbyeQ.png" /></figure><p>Editor screenshot when building Docker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdwvdTe2WnmY6YM-101Dpg.png" /></figure><p>Docker’s screenshot with successful execution</p><p>You can visit `<a href="http://localhost`/">http://localhost`</a> to see if the app is working fine or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coUpr46xyI9re-1ateuLJw.png" /></figure><p>Chrome screenshot with URL <a href="http://localhost/](http://localhost/)">http://localhost/</a></p><h3>HTTPS</h3><p>Most internet websites are moving to secure client and server connections. Even Search Engines penalise websites for not serving content with HTTPS.</p><p>It is crucial to develop the applications with a secure protocol. For most web applications, HTTPS is handled by the web server. Apache, in our case of the post.</p><p>Let’s add support for HTTPS on put PHP+Apache application.</p><p>First, we need to tell Apache via Virtual Hosts to serve the website on Secure port, i.e. on 443.</p><p>We would do so with the following entry on the config file we created earlier.</p><pre>LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so<br><br># ... VirtualHost Entry for HTTP port<br><br>&lt;VirtualHost _default_:443&gt;<br><br>  DocumentRoot &quot;/app&quot;<br>  ServerName localhost:443<br>  ErrorLog ${APACHE_LOG_DIR}/error.log<br>  CustomLog ${APACHE_LOG_DIR}/access.log combined<br><br>  SSLEngine on<br><br>  SSLCertificateFile &quot;/etc/apache2/sites-available/ssl/localhost.crt&quot;<br>  SSLCertificateKeyFile &quot;/etc/apache2/sites-available/ssl/localhost.key&quot;<br><br>  &lt;FilesMatch &quot;\.(cgi|shtml|phtml|php)$&quot;&gt;<br>      SSLOptions +StdEnvVars<br>  &lt;/FilesMatch&gt;<br><br>  &lt;Directory &quot;/app&quot;&gt;<br>      Options Indexes FollowSymLinks Includes execCGI<br>      AllowOverride All<br>      Require all granted<br>  &lt;/Directory&gt;<br><br>&lt;/VirtualHost&gt;</pre><p>A few notable things we did above are:</p><ul><li>Load the SSL Module</li><li>Turn the SSL Engine On for the matching server address</li><li>Provide the SSL Certificate and Key files</li><li>Set some additional options for SSL when serving specific files</li></ul><p>With the above config, we need to do two more things:</p><ul><li>Install and Enable the SSL module for the Apache web server</li><li>Generate Certificate and Key files to use with the `localhost` and mount them on the right path</li></ul><h4>Installing and Enabling SSL Module</h4><p>Apache installation comes bundled with the SSL Module. And all we have to do is to enable this module for the Apache server.</p><p>On a server where the Apache server is running, we need to trigger the following command to enable the SSL module:</p><pre>a2enmod ssl</pre><p>But for our docker setup, we need to do this while building the container. And for that, we will need to adjust the last line of the `**Dockerfile**` as:</p><pre>- RUN chown -R www-data:www-data /app &amp;&amp; a2enmod rewrite<br>+ RUN chown -R www-data:www-data /app &amp;&amp; a2enmod rewrite ssl</pre><h4>Generating Certificate files</h4><p>We don’t have any high-level signing authority. We can use the OpenSSL CLI tool to generate the SSL Certificate files. This should work for local development purposes.</p><p>The following command will generate the certificate files:</p><pre>openssl req -x509 -out localhost.crt -keyout localhost.key \<br>  -newkey rsa:2048 -nodes -sha256 \<br>  -subj &#39;/CN=localhost&#39; -extensions EXT -config &lt;( \<br>   printf &quot;[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9MOV1oNY9F0NpkBEJVp5A.png" /></figure><p>After generating these files, we should place them in the following location relative to the root of the project:</p><pre>&lt;project-root&gt;/.docker/apache/localhost.crt<br>&lt;project-root&gt;/.docker/apache/localhost.key</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nn7g8MYTVRfdLXplz5NznA.png" /></figure><p>After placing the files in the right place, we need to create the following placeholder directory on the server build.</p><pre>/etc/apache2/sites-available/ssl</pre><p>So, to create this directory, we will add the following line to our Dockerfile before COPY commands.</p><pre>...<br><br>RUN mkdir /etc/apache2/sites-available/ssl<br><br>...</pre><p>After everything, this is how our `Dockerfile` should look like this:</p><pre>FROM php:7.3-apache<br><br>RUN mkdir /app<br><br>RUN mkdir /etc/apache2/sites-available/ssl<br><br>COPY .docker/apache/vhost.conf /etc/apache2/sites-available/000-default.conf<br><br>WORKDIR /app<br><br>RUN chown -R www-data:www-data /app &amp;&amp; a2enmod rewrite ssl</pre><h4>Providing Certificates to Apache</h4><p>As the Server building is in place, we will now look at the server execution, i.e. executing the Dockerfile and providing it at that time.</p><p>As we created the docker-compose file earlier; we will now mount what we created in the Dockerfile (/etc/apache2/sites-available/ssl)</p><pre>...<br>    volumes:<br>      - ./.docker/apache:/etc/apache2/sites-available/ssl<br>      - .:/app</pre><p>With the above change, our docker-compose.yml file should look like this:</p><pre>version: &quot;3&quot;<br><br>services:<br>  my-app:<br>    build:<br>      context: .<br>      dockerfile: .docker/Dockerfile<br>    image: my-app<br>    environment:<br>      - &quot;APACHE_LOG_DIR:/app&quot;<br>    ports:<br>      - 80:80<br>      - 443:443<br>    volumes:<br>      - ./.docker/apache:/etc/apache2/sites-available/ssl<br>      - .:/app</pre><p>With all the setup done, we will execute the following command again:</p><pre>docker-compose up -d — build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQj4d73p7lrO1qA1K9Ii1A.png" /></figure><p>Now, if we check in Docker Dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbWZzrJ3D9MdeQhQxe8tVQ.png" /></figure><p>And when we try to go to the application with https: <a href="https://localhost/">https://localhost</a>, it will show the warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6D8SFZUlzjC1QpQQm2GJA.png" /></figure><p>It is normal as the certificates are locally generated. You can go to the <strong><em>Advanced section </em></strong>of the warning and <strong><em>proceed to the site anyway</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPl9KY1lET_t0ItwNqDD3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rikZ4xNQc2FOVjNJYmYA3g.png" /></figure><p>🖥️ Checkout the source code at: <a href="https://github.com/time2hack/php-apache-https](https://github.com/time2hack/php-apache-https)">https://github.com/time2hack/php-apache-https</a></p><h4>Conclusion</h4><p>We looked at a basic server on PHP and Apache and then Dockerized it to enable HTTPS.</p><p>Further steps we can go for are</p><p>- Use signed certificates, like those from LetsEncrypt<br>- Use other services like MySQL etc., in the above stack</p><blockquote>Have you managed to enable HTTPS for your local development?</blockquote><blockquote>What is your stack and process to enable HTTPS?</blockquote><p>Let me know through comments 💬 or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a></p><p>If you find this article helpful, share it with others 🗣</p><p>Subscribe to the blog to receive new posts right in your inbox.</p><p><em>Originally published on </em><a href="https://time2hack.com/dockerize-php-app-with-apache-on-https/"><em>time2hack.com</em></a><em> on 21 Dec 2022</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c7b32cadc9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/dockerize-php-app-with-apache-on-https-a5c7b32cadc9">Dockerize PHP app with Apache on HTTPS</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Deployment on DigitalOcean Droplets with Gitlab CI Pipelines]]></title>
            <link>https://medium.com/time2hack/continuous-deployment-on-digitalocean-droplets-with-gitlab-ci-pipelines-62c11dd8bdc0?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/62c11dd8bdc0</guid>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Fri, 07 Oct 2022 10:43:46 GMT</pubDate>
            <atom:updated>2022-10-07T10:43:46.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqJ18KEZU6KrnPgu_rq2UA.png" /></figure><p>Building the software package and delivering those packages are two parts of automated software delivery.</p><p>It is simple when the build is done by the platform where the package is getting deployed, for example on netlify, Vercel, github pages etc. Still, it gets complicated when the builder and separated from the production machine.</p><p>Today we will be looking at achieving Continuous deployment with Gitlab CI Pipelines on DigitalOcean droplets</p><h3>Preparing Application</h3><p>For this, we will try continuously deploying a NextJS application on the DigitalOcean droplet.</p><p>To keep this article concise, let’s start with deploying the initial state of the NextJS app you get after <a href="https://nextjs.org/docs/api-reference/create-next-app">bootstrapping the nextjs app</a> with create-next-app:</p><pre>yarn create next-app --typescript<br><em># or </em><br>npx create-next-app --typescript</pre><p>Now that the NextJS app is up, we will create a <a href="https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile">Dockerfile with the following text</a> to generate a build image for our NextJS application:</p><pre><em># Install dependencies only when needed</em><br>FROM node:16-alpine AS deps<br><em># Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.</em><br>RUN apk add --no-cache libc6-compat<br>WORKDIR /app<br>COPY package.json yarn.lock ./<br>RUN yarn install --frozen-lockfile</pre><pre><em># If using npm with a `package-lock.json` comment out above and use below instead</em><br><em># COPY package.json package-lock.json ./ </em><br><em># RUN npm ci</em></pre><pre><em># Rebuild the source code only when needed</em><br>FROM node:16-alpine AS builder<br>WORKDIR /app<br>COPY --from=deps /app/node_modules ./node_modules<br>COPY . .</pre><pre><em># Next.js collects completely anonymous telemetry data about general usage.</em><br><em># Learn more here: https://nextjs.org/telemetry</em><br><em># Uncomment the following line in case you want to disable telemetry during the build.</em><br><em># ENV NEXT_TELEMETRY_DISABLED 1</em></pre><pre>RUN yarn build</pre><pre><em># If using npm comment out above and use below instead</em><br><em># RUN npm run build</em></pre><pre><em># Production image, copy all the files and run next</em><br>FROM node:16-alpine AS runner<br>WORKDIR /app</pre><pre>ENV NODE_ENV production<br><em># Uncomment the following line in case you want to disable telemetry during runtime.</em><br><em># ENV NEXT_TELEMETRY_DISABLED 1</em></pre><pre>RUN addgroup --system --gid 1001 nodejs<br>RUN adduser --system --uid 1001 nextjs</pre><pre><em># You only need to copy next.config.js if you are NOT using the default configuration</em><br><em># COPY --from=builder /app/next.config.js ./</em><br>COPY --from=builder /app/public ./public<br>COPY --from=builder /app/package.json ./package.json</pre><pre><em># Automatically leverage output traces to reduce image size </em><br><em># https://nextjs.org/docs/advanced-features/output-file-tracing</em><br>COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./<br>COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static</pre><pre>USER nextjs</pre><pre>EXPOSE 3000</pre><pre>ENV PORT 3000</pre><pre>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>Now that the Dockerfile is in place, we will need to create a Gitlab CI pipeline to build this image and publish it to a container registry.</p><h3>Continuous Builds</h3><p>We will publish the image to Gitlab’s container registry for this example.</p><blockquote>One benefit of Gitlab is that if your repo is private, the Docker image is also private. And similar ones can be found on Github.</blockquote><p>Let’s create a Gitlab CI file:</p><pre>touch .gitlab-ci.yml</pre><p>In this Gitlab CI file, we will introduce a simple job to build the image and push it to the container registry</p><pre>docker-build:<br>  image: docker:latest<br>  stage: build<br>  services:<br>    - docker:dind<br>  before_script:<br>    - docker login -u &quot;$CI_REGISTRY_USER&quot; -p &quot;$CI_REGISTRY_PASSWORD&quot; $CI_REGISTRY<br>  script:<br>    - docker build --pull -t &quot;$CI_REGISTRY_IMAGE:latest&quot; .<br>    - docker push &quot;$CI_REGISTRY_IMAGE:latest&quot;<br>  <em># Run this job in a branch where a Dockerfile exists</em><br>  rules:<br>    - if: $CI_COMMIT_BRANCH<br>      exists:<br>        - Dockerfile</pre><p>Let’s try the build on CI by pushing to the remote:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T_e6pOCV73I6Wlja.png" /></figure><p>Now that our build is successful, let’s set up a Droplet on DigitalOcean. If you don’t have a digital ocean account, you can <a href="https://www.digitalocean.com/?refcode=635653da0b3b">sign up here</a></p><h3>Server Creation &amp; Setup</h3><p>Once you have your account with you, you can set up your droplet following this guide from DigitalOcean Docs: <a href="https://docs.digitalocean.com/products/droplets/how-to/create/">How to Create a Droplet from the DigitalOcean Control Panel</a></p><p>Once you have your droplet up and running, let’s deploy our NextJS container image on our droplet.</p><p>For this, I am assuming that you have added an ssh-key to your droplet and you can log in to your droplet via ssh with the following command:</p><pre>ssh root@xxx.xxx.xxx.xxx<br><em># replace xxx.xxx.xxx.xxx with your droplet&#39;s public IP</em></pre><p>Once you can log in to your droplet, either via ssh (recommended) or via the web console, you can install docker with the following commands:</p><pre><em># First, update your existing list of packages:</em><br>sudo apt update</pre><pre><em># Next, install a few prerequisite packages which let apt use packages over HTTPS:</em><br>sudo apt install apt-transport-https ca-certificates curl software-properties-common</pre><pre><em># Then add the GPG key for the official Docker repository to your system:</em><br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -</pre><pre><em># Add the Docker repository to APT sources:</em><br>sudo add-apt-repository &quot;deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable&quot;<br><em># This will also update our package database with the Docker packages from the newly added repo.</em></pre><pre><em># Make sure you are about to install from the Docker repo instead of the default Ubuntu repo:</em><br>apt-cache policy docker-ce</pre><pre><em># You’ll see output like this, although the version number for Docker may be different:</em><br><em># &gt; docker-ce:</em><br><em># &gt;  Installed: (none)</em><br><em># &gt;  ...</em><br><em># Notice that docker-ce is not installed, but the candidate for installation is from the Docker repository for Ubuntu 20.04 (focal).</em></pre><pre><em># Finally, install Docker:</em><br>sudo apt install docker-ce</pre><pre><em># Docker should now be installed, the daemon started, and the process enabled to start on boot. Check that it’s running:</em><br>sudo systemctl status docker<br><em># &gt; ● docker.service - Docker Application Container Engine</em><br><em># &gt;    Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)</em><br><em># &gt;    Active: active (running) since Tue 2020-05-19 17:00:41 UTC; 17s ago</em><br><em># &gt;    ...</em></pre><p>Note: I have borrowed this set of commands from the Docker community tutorial: <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04">https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04</a></p><p>Once this is done and you have a docker engine running in your droplet, we are ready to deploy our application.</p><h3>First Deployment</h3><p>But first, we need to have our small infrastructure present as code somewhere. And to do so, we will create another repository to host the container initialization file i.e. docker-compose.yml file.</p><p>Here is the docker-compose.yml file:</p><pre>version: &quot;3.4&quot;</pre><pre>services:<br>  frontend:<br>    container_name: front<br>    image: registry.gitlab.com/time2hack/digital-ocean-ci/nextjs-on-digitalocean:latest<br>    environment:<br>      - &quot;NEXT_TELEMETRY_DISABLED=1&quot;<br>    restart: always<br>    ports:<br>      - &quot;80:3000&quot;</pre><p>The above docker-compose file is doing the following things:</p><ul><li>Uses version 3.4 of the docker-compose YAML specification</li><li>Creates a service named frontend</li><li>Set the container name of the service as front</li><li>Specifies the image to use from the container registry</li><li>In this case, it is: registry.gitlab.com/time2hack/digital-ocean-ci/nextjs-on-digitalocean:latest</li><li>For different registries, you might need to login into those registries before pulling the images from them</li><li>Marks this service to be restarted always in case it gets shut down automatically</li><li>Maps the ports from the container to the OS</li><li>Port 3000 of the container is mapped to port 80 of the OS</li></ul><p>Now head over to the DigitalOcean droplet and log in to it via SSH/Web Console.</p><p>We will follow the following simple steps to deploy our app on Droplet:</p><ol><li>Navigate to the home directory with cd ~</li><li>Clone the repository in a droplet with<br>git clone <a href="https://gitlab.com/time2hack/digital-ocean-ci/nextjs-deployment.git">https://gitlab.com/time2hack/digital-ocean-ci/nextjs-deployment.git</a></li><li>move to the newly cloned repo with<br>cd nextjs-deployment</li><li>Start the container<br>docker-compose up -d</li><li>You should see output like the following:</li></ol><pre>root@xxxxx:/home/t2h/nextjs-deployment<em># </em><br>docker-compose up -d<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;<br>Pulling front_end (registry.gitlab.com/time2hack/digital-ocean-ci/nextjs-on-digitalocean:latest)...<br>latest: Pulling from time2hack/digital-ocean-ci/nextjs-on-digitalocean<br>2408cc74d12b: Already exists<br>5b80453a567d: Already exists<br>3420de6432e1: Already exists<br>65b549a28248: Already exists<br>93146c325fa7: Pull complete<br>0e62824b8055: Pull complete<br>68e6b293a6f0: Pull complete<br>37f95b8329f4: Pull complete<br>a366af5ead1a: Pull complete<br>d6a22ed87ddf: Pull complete<br>f5c7eb3549e4: Pull complete<br>Digest: sha256:5423ca9170b5e059357fae12db22dda5715d283fc4c026938e14883b4880493a<br>Status: Downloaded newer image for registry.gitlab.com/time2hack/digital-ocean-ci/nextjs-on-digitalocean:latest<br>Recreating front_end ... done</pre><pre>root@xxxxx:/home/t2h/nextjs-deployment<em>#</em></pre><p>The above output says that our container is created from the image and we can check the status with docker ps -al</p><p>Now we are halfway done, we want to auto-deploy this image as soon as we finish building the image.</p><h3>Continuous Deployment</h3><p>This process is simple in theory but needs precision as we might expose ourselves to security vulnerabilities.</p><ol><li>Create a fresh pair of Public-Private keys with ssh-keygen</li></ol><ul><li>I used the guide from <a href="https://www.ssh.com/academy/ssh/keygen">SSH Academy</a> to generate a pair of keys</li><li>I used to use RSA but now, I use <strong>ed25519</strong> as my algorithm to generate keys.</li></ul><ol><li>Our CI will present itself as the root, for that CI must have a Private Key that pairs with a Public key on the server.</li><li>We will add Private Key in the environment variables and populate in the runner on runtime</li><li>Login to Droplet and execute the commands to refresh the Container with the newly published image.</li></ol><h3>Generating Key Pair</h3><p>We will generate the keys with the following command:</p><pre>ssh-keygen -t ed25519 -c &quot;pankaj@time2hack.com&quot;</pre><p>This will ask for the path and the passphrase for the keys. If you already have some keys in place, enter a new path for the keys. As for the passphrase, I am leaving it empty for this case.</p><p>Once the key is generated you should be able to copy them from the path you mentioned. If you have not mentioned anything, it will be id_ed25519 and id_25519.pub files as Private and Public Keys</p><h3>Adding Private Key to CI Secrets</h3><p>Navigate to the CI/CD Settings section of your repository in Gitlab.</p><p>Usually, it is on the path /-/settings/ci_cd from your Repository&#39;s Project Home. For my Project, https://gitlab.com/time2hack/digital-ocean-ci/nextjs-deployment/ the settings are located at <a href="https://gitlab.com/time2hack/digital-ocean-ci/nextjs-deployment/-/settings/ci_cd">https://gitlab.com/time2hack/digital-ocean-ci/nextjs-deployment/-/settings/ci_cd</a></p><p>You should locate the Variables section on the CI/CD settings page and expand it. It will look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fToDheebWxpKBCrY.png" /></figure><p>Once you add the following necessary variables:</p><ul><li>DEPLOY_KEY_PRIVATE Your freshly generated private key</li><li>DEPLOY_USER as the user for ssh login, root in this case</li><li>DEPLOY_HOST as the server address xxx.xxx.xxx.xxx</li><li>DEPLOY_COMMAND is the final command that needs to be executed to deploy the application.</li></ul><p>As it is a Docker image, we just need to recreate the container, so our DEPLOY_COMMAND will be docker pull registry.gitlab.com/time2hack/digital-ocean-ci/nextjs-on-digitalocean:latest; cd ~; cd apps/next-deployment; docker-compose up -d;</p><p>It should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pUaO8xklYAPf1c3C.png" /></figure><h3>Adding Public Key to the Droplet</h3><p>Now from the generated pair, we need to add the Public key to the Droplet so that when the deployment runner tries to log in, the Keys are accepted.</p><p>We will copy the contents of /.ssh/id_ed25119.pub and put it in the new line at the end of /.ssh/authorixed_keys the file of the droplet.</p><p>You can log in via ssh and do so few minutes.</p><p>In case of any trouble, there is this detailed tutorial from the DigitalOcean community:</p><p><a href="https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/to-existing-droplet/">How to Upload an SSH Public Key to an Existing Droplet | DigitalOcean Documentation</a></p><p>Now with variables in place, we will add a .gitlab-ci.yml file on our deployment repo with the following content:</p><pre>deploy:<br>  stage: deploy<br>  image: alpine<br>  environment:<br>    name: production<br>  before_script:<br>    - apk add openssh-client<br>    - eval $(ssh-agent -s)<br>    - mkdir -p ~/.ssh<br>    - chmod 700 ~/.ssh<br>    - echo -e &quot;$DEPLOY_KEY_PRIVATE&quot; &gt; ~/.ssh/id_ed25519<br>    - chmod 700 ~/.ssh/id_ed25519<br>    - echo &quot;$DEPLOY_KEY_PRIVATE&quot; | tr -d &#39;\r&#39; | ssh-add -<br>  script:<br>    - |<br>      ssh -o StrictHostKeyChecking=no &quot;$DEPLOY_USER@$DEPLOY_HOST&quot; &quot;&quot;$DEPLOY_COMMAND&quot;&quot;</pre><p>And commit this file to the repository and push it to the remote.</p><p>With the above file in place, our Continuous Deployment script is in place. But we still need a trigger from the builder pipeline.</p><p>To do so, we need to add the following lines in the builder repo’s .gitlab-ci.yml file:</p><pre>...</pre><pre>trigger-deploy:<br>  trigger:<br>    project: time2hack/digital-ocean-ci/nextjs-deployment</pre><p>You can read the brief intro on cross-project pipelines here:</p><p><a href="https://about.gitlab.com/blog/2019/07/24/cross-project-pipeline/">How to trigger multiple pipelines using GitLab CI/CD</a></p><p>After committing this file to the repo and pushing it, we will be able to see the build-in builder as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tEcwns5D7xek0FtE.png" /></figure><p>Where the failed step is from the deployment repo’s pipeline.</p><p>This is what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RDWsOf3gJ7HcPBpZ.png" /></figure><p>and when expanded, it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QcONkF1jlVgl7lC_.png" /></figure><h3>Conclusion</h3><p>In a nutshell, we saw how to prepare the project for</p><ul><li>Continuous Build on Gitlab</li><li>Deployment configuration as code</li><li>Continuous Deployment on DigitalOcean with cross-project pipeline triggers</li></ul><blockquote>What does your CI/CD for your project look like?</blockquote><p>Let me know you through comments 💬 or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a></p><p>If you find this article helpful, please share it with others 🗣</p><p>Subscribe to the blog to receive new posts right in your inbox.</p><p><em>Originally published on </em><a href="https://time2hack.com/continuous-deployment-on-digitalocean-droplets-with-gitlab-ci-pipelines/"><em>time2hack.com</em></a><em> on 24 Aug 2022</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62c11dd8bdc0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/continuous-deployment-on-digitalocean-droplets-with-gitlab-ci-pipelines-62c11dd8bdc0">Continuous Deployment on DigitalOcean Droplets with Gitlab CI Pipelines</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamically configure Docker Image builds]]></title>
            <link>https://medium.com/time2hack/dynamically-configure-docker-image-builds-82032aa03ba6?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/82032aa03ba6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 08:14:46 GMT</pubDate>
            <atom:updated>2022-06-03T08:15:55.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aiPXkshaSi0Hs_gl0GrBg.png" /></figure><p>Containers are the best way to deliver your software as you are shipping the whole system with needed dependencies.</p><p>But building these Images can be a hassle when you wanna build them for specific purposes.</p><p>You might need some dynamic values while building the Image so that you can generate the most optimal package at the build time; not while executing them.</p><p>BUT, there is no way to pass environment variables to the docker build similar to the way we execute those images:</p><pre><em># build the image with the tag &#39;msql&#39;</em><br>docker build -e NODE_ENV=production -t msql .</pre><pre><em># let&#39;s run the image with the above-built tag</em><br> docker run -d msql -e NODE_ENV=production</pre><p>In the above example, -e in the build command has no effect and will only assume the unassigned/default value case; on the contrary to run</p><p>So how can we pass the dynamic values to the docker build command?</p><h3>ARG and ENV</h3><p>ARG and ENV keywords for Dockerfile are here to the rescue.</p><p>But as we discussed above, ENV has no effect from outside, so why are we using it? <strong>To propagate the values downstream which gain by </strong>ARG<strong> keyword.</strong></p><p>How does ARG keyword work? Let&#39;s take a look at an example Dockerfile:</p><pre>FROM alpine:3.14<br>RUN apk add --no-cache --repository http:<em>//dl-cdn.alpinelinux.org/alpine/v3.14/main/ \</em><br>  nodejs-current \<br>  bash \<br>  npm</pre><pre>ARG PORT<br>ENV PORT ${PORT:-3000}</pre><pre>WORKDIR app</pre><pre>COPY . .</pre><pre>RUN npm ci --prod</pre><pre>ENTRYPOINT [ &quot;node&quot;, &quot;index.js&quot; ]</pre><p>In the above Dockerfile, we are using ARG PORT. This means that we are allowing the build command to accept the PORT argument</p><p>We can execute the following to pass the default PORT at the build time:</p><pre>docker build --build-args PORT=5000 -t mynode-app .</pre><p>One big thing to keep in mind is that the ARG names are case sensitive, and hence should be used carefully.</p><p>Though, as they are case sensitive, they can be used to pick the values from the Environment of execution of the build command.</p><p>For example, we can define the PORT as an environment variable. And now, we don’t need to capture the value from the environment, it is automatically mapped by Docker.</p><pre>export PORT=50001<br>echo $PORT<br><em># 50001</em><br>docker build --build-args PORT -t mynode-app .</pre><p>So that’s how we can customize the builds with ARG and ENV?</p><p>For the majority of applications, you might not need this much customisation of build images.</p><p>But the places where you are working with a lot of automation, this way of customisation becomes highly useful.</p><h3>Conclusion</h3><ul><li>Use ARG to define passable values</li><li>Use ENV to propagate the ARG values to the application code</li><li>Pass defined ARG at the docker build with --build-args flag</li><li>--build-arg can map the ARG name with environment variables</li></ul><p>Let us know <strong><em>how and for what are you customising your Docker images</em></strong> through comments 💬 or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a></p><p>If you find this article helpful, please share it with others 🗣</p><p>Subscribe to the blog to receive new posts right to your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82032aa03ba6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/dynamically-configure-docker-image-builds-82032aa03ba6">Dynamically configure Docker Image builds</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benefits of using TS Generics in your Design System]]></title>
            <link>https://medium.com/time2hack/benefits-of-using-ts-generics-in-your-design-system-6f6940a1ca33?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/6f6940a1ca33</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Tue, 31 May 2022 12:07:58 GMT</pubDate>
            <atom:updated>2022-05-31T12:07:57.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjk7Ry8rknwX6mKfrUawEQ.png" /></figure><p>The design system is a crucial building block in any organisation’s holistic impression.</p><p>And using TypeScript is becoming one of the standard practices.</p><p>Today I wanted to talk about one of the use cases I came recently where the design system component needs to work on the data passed to it.</p><p>But in general, the component does not know the type of the data being passed to it. We can only error check to make sure we are not breaking the application by passing the wrong type of data to those components.</p><p>Let’s assume a simple case of Button which is supposed to pass the data to the onClick callback:</p><pre>export const Button = (<br>  { data, children }: { data: Record&lt;string, any&gt;, children: ReactNode }<br>) =&gt; (<br>  &lt;button onClick={() =&gt; onClick(data)}&gt;<br>    {children}<br>  &lt;/button&gt;<br>)</pre><p>And the above button is used in the page as:</p><pre>export const Page = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;Button<br>      data={count}<br>      onClick={(d: number): number =&gt; setState(d + 1)}<br>    &gt;Add 1&lt;/Button&gt;<br>  )<br>}</pre><p>Here the onClick inside the page knows about the type of data it is operating on but the onClick inside the Button component doesn&#39;t have any idea, except the generic Record&lt;string, any&gt;</p><blockquote>To make the case, I have used any in the above example; but in a real-world app, any MUST be replaced by a strong intersection of most used types in DS, to say the least</blockquote><p>Now let’s consider an alternate solution where we create the Button component in the design system with typescript generics</p><p>But before jumping to the use of TS Generics, what are generics?</p><p>Generics are a simple way to make template style types which can be can be customised and applied when they are used</p><p>For example, in the following TS in the <a href="https://www.typescriptlang.org/play#code/JYOwLgpgTgZghgYwgAgMJysg3gKGf5EOAWwgC5kBnMKUAcwG48DiB7AEwgBsLraRGOAL44coSLEQoAahAAWwBFwgAeACoA+bM3wB3ORG6UKIAK7EARtCYFkdCGAByJCAAp2cMHApqAlLxp6GwJTAAc6KDhOd09vZD8fYVEEVhBqZBhoSNoKdEwAXmxCFwoAcgAxLIxgUoAaZDZOHmQKgEZS5BEUtLBkADd5RWUKWQUlVTytQqxkHWR9Qy5jZAAWWrn7JxdXBAxfIqgHUygQZF2oADoiUk712zCIqLdz-ZnDsGPTmYuf8-rG7gUc4XAFcZAAahaAA8OkJOkkcN1KKxlBcuKw6K5MlBssB6gMxspfIjUsjUejMQShhALptnKQsVVaL5iUiUTSKa4qeMLg9ItFsbiWUA"><strong>playground</strong></a></p><p>We have a Vehicle which can be upgraded but with the help of Generics, we have template type T in the Vehicle definition.</p><pre>interface Car {<br>  name: string;<br>  model: string;<br>}<br><br>interface Vehicle&lt;T&gt; {<br>  wheels: number;<br>  getName(data: T): string;<br>  upgrade(data: T): T<br>}<br><br>const ferrari: Car = { name: &#39;Ferrari&#39;, model: &#39;Roma&#39; }<br>const vehicle: Vehicle&lt;Car&gt; = { <br>  wheels: 4,<br>  getName(car) { return car.name },<br>  upgrade(car) { return { ...car, model: car.model + &#39;X&#39; } }<br>}<br><br>console.log(ferrari, vehicle)<br><em>// [LOG]: { &quot;name&quot;: &quot;Ferrari&quot;, &quot;model&quot;: &quot;Roma&quot; }, { &quot;wheels&quot;: 4 }  </em><br><br>console.log(vehicle.getName(ferrari))<br><em>// [LOG]: &quot;Ferrari&quot;  </em><br><br>console.log(vehicle.upgrade(ferrari))<br><em>// [LOG]: { &quot;name&quot;: &quot;Ferrari&quot;, &quot;model&quot;: &quot;RomaX&quot; }</em></pre><p>When we initialise a variable for the Vehicle interface, we pass the Template to the interface to be used in the rest of the interface declaration.</p><p>Let&#39;s see how it works in React Components. Here we will reimplement the above-mentioned button component with the Generics.</p><pre><em>// 💡 Use Generics for Design System components</em><br>export const Button = &lt;T extends unknown&gt;(<br>  { data, children }: { data: T, children: ReactNode }<br>) =&gt; (<br>  &lt;button onClick={() =&gt; onClick(data)}&gt;<br>    {children}<br>  &lt;/button&gt;<br>)</pre><p>Now here with Generics, we have replaced the need for Record and any with the simple template which can customise the component&#39;s type bindings with correct data.</p><p>Well above was a very simple example, let me show you a complicated component in the Design System which will definitely need the Generics.</p><p>Such component is, though anything that iterates on data collection can follow the same principle.</p><p>Here is a simple Table I needed to come up with very basic tabular interface needs:</p><pre>import { ReactNode } from &#39;react&#39;;<br>import styled, { css } from &#39;styled-components&#39;;</pre><pre>export interface TableCell&lt;T extends unknown&gt; {<br>  label: ReactNode;<br>  key: keyof T;<br>  render?: (row: T) =&gt; ReactNode;<br>  align?: &#39;left&#39; | &#39;right&#39;;<br>  sortable?: boolean;<br>  maxWidth?: string;<br>}</pre><pre>interface TableProps&lt;T&gt; {<br>  rows: Array&lt;T&gt;;<br>  cells: TableCell&lt;T&gt;[];<br>  onRowClick?: (row: T) =&gt; void;<br>  onHeaderClick?: (key: keyof T) =&gt; void;<br>  noResultsMessage?: ReactNode;<br>}</pre><pre>interface AlignmentProps {<br>  align: &#39;left&#39; | &#39;right&#39;;<br>}</pre><pre>export const Label = styled.label`<br>  display: block;<br>  font-size: 1.2rem;<br>  color: #aaa;<br>`;</pre><pre>const Row = styled.tr`<br>  cursor: pointer;<br>  font-size: 1.1rem;</pre><pre>  &amp;:nth-child(even) { background-color: #fafafa; }<br>  &amp;:hover { background-color: #eee; }<br>`;</pre><pre>const defaultCellCss = css&lt;AlignmentProps&gt;`<br>  padding: 0.75rem 0.5rem;<br>  text-align: ${(props) =&gt; props.align ?? &#39;left&#39;};<br>`;</pre><pre>const Cell = styled.td&lt;AlignmentProps &amp; { maxWidth?: string }&gt;`<br>  ${defaultCellCss}</pre><pre>  ${Label} { display: none; }<br>`;</pre><pre>const StyledTable = styled.table`<br>  border-collapse: collapse;<br>  width: 100%;</pre><pre>  @media (max-width: 768px) {<br>    &amp;, tbody, ${Row} { display: grid; }<br>    thead { display: none; }<br>    <br>    ${Row} {<br>      grid-template-columns: 1fr 1fr;<br>      grid-gap: 0.5rem;<br>      padding: 0.5rem;<br>    }</pre><pre>    ${Cell} {<br>      text-align: left;<br>      padding: 0;</pre><pre>      ${Label} {<br>        display: block;<br>        font-size: 0.75em;<br>        line-height: 1.2;<br>      }<br>    }<br>  }<br>`;</pre><pre>const HeaderCell = styled.th&lt;AlignmentProps &amp; { clickable: boolean }&gt;`<br>  ${defaultCellCss}<br>  background-color: #eee;<br>  ${(props) =&gt; props.clickable &amp;&amp; `<br>    cursor: pointer;<br>    text-decoration: underline;<br>    text-decoration-style: dotted;<br>    &amp;:hover { background-color: <em>#ddd; }</em><br>  `};<br>`;</pre><pre>const NOOP = () =&gt; {};</pre><pre>export const Table = &lt;T extends unknown&gt;({<br>  rows,<br>  cells,<br>  onRowClick = NOOP,<br>  onHeaderClick,<br>  noResultsMessage = null,<br>}: TableProps&lt;T&gt;): JSX.Element =&gt; (<br>  &lt;StyledTable&gt;<br>    {Boolean(rows.length &amp;&amp; noResultsMessage) &amp;&amp; (<br>      &lt;thead&gt;<br>        &lt;tr&gt;<br>          {cells.map(({ label, align = &#39;left&#39;, key, sortable }) =&gt; (<br>            &lt;HeaderCell<br>              key={key as string}<br>              align={align}<br>              clickable={Boolean(sortable)}<br>              onClick={() =&gt;<br>                (sortable &amp;&amp; onHeaderClick ? onHeaderClick : NOOP)(key)<br>              }<br>            &gt;<br>              {label}<br>              {sortable &amp;&amp; &lt;small&gt;⇵&lt;/small&gt;}<br>            &lt;/HeaderCell&gt;<br>          ))}<br>        &lt;/tr&gt;<br>      &lt;/thead&gt;<br>    )}<br>    &lt;tbody&gt;<br>      {rows.map((row: T, index: number) =&gt; (<br>        &lt;Row<br>          key={index}<br>          onClick={() =&gt; onRowClick(row)}<br>          title=&quot;Click to open payment details&quot;<br>        &gt;<br>          {cells.map(<br>            ({<br>              label,<br>              key,<br>              render,<br>              align = &#39;left&#39;,<br>              maxWidth,<br>            }: TableCell&lt;T&gt;): ReactNode =&gt; {<br>              const cellKey = key as string;<br>              if (typeof render === &#39;function&#39;) {<br>                return (<br>                  &lt;Cell align={align} key={cellKey} maxWidth={maxWidth}&gt;<br>                    &lt;Label&gt;{label}&lt;/Label&gt;<br>                    {render(row)}<br>                  &lt;/Cell&gt;<br>                );<br>              }<br>              if (key) {<br>                return (<br>                  &lt;Cell align={align} key={cellKey} maxWidth={maxWidth}&gt;<br>                    &lt;Label&gt;{label}&lt;/Label&gt;<br>                    &lt;&gt;{row[key]}&lt;/&gt;<br>                  &lt;/Cell&gt;<br>                );<br>              }<br>              return &lt;Cell align={align} key={cellKey} /&gt;;<br>            }<br>          )}<br>        &lt;/Row&gt;<br>      ))}<br>      {rows.length === 0 &amp;&amp; noResultsMessage &amp;&amp; (<br>        &lt;tr&gt;<br>          &lt;td colSpan={cells.length}&gt;{noResultsMessage}&lt;/td&gt;<br>        &lt;/tr&gt;<br>      )}<br>    &lt;/tbody&gt;<br>  &lt;/StyledTable&gt;<br>);</pre><p>Here we needed to pass the data from each iteration passed on to the cell renderers and click handlers of rows and columns.</p><p>And following use of the above design system component:</p><pre>type MockRow = {<br>  id: string;<br>  created: number;<br>  customer_name: string;<br>};<br>const mockConfig: TableCell&lt;MockRow&gt;[] = [<br>  {<br>    label: &#39;Customer Name&#39;,<br>    key: &#39;customer_name&#39;,<br>  },<br>  {<br>    label: &#39;Created On&#39;,<br>    key: &#39;created&#39;,<br>    render: (row: MockRow) =&gt; &lt;&gt;{new Date(row.created).toLocaleDateString()}&lt;/&gt;,<br>  },<br>];<br><br>const mockRow = {<br>  id: &#39;i2NJhL&#39;,<br>  created: 1649023200000,<br>  customer_name: &#39;Émile Zola&#39;,<br>};<br><br>export const Page = () =&gt; (<br>  &lt;Table<br>    onRowClick={console.log}<br>    cells={mockConfig}<br>    rows={[mockRow]}<br>  /&gt;<br>);</pre><h3>Conclusion</h3><p>With this, I would conclude the need and use of TS generics in the Design System components.</p><p>Are you using generics in your design system component?</p><p>Let us know <strong><em>what are the common use cases in your codebase for Generics </em></strong>through comments 💬 or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a></p><p>If you find this article helpful, please share it with others 🗣</p><p>Subscribe to the blog to receive new posts right to your inbox.</p><p><em>Originally published at </em><a href="https://time2hack.com/benefits-of-typescript-generics-in-reactjs-design-system/"><em>https://time2hack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f6940a1ca33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/benefits-of-using-ts-generics-in-your-design-system-6f6940a1ca33">Benefits of using TS Generics in your Design System</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can I use hover on Touch Devices?]]></title>
            <link>https://medium.com/time2hack/can-i-use-hover-on-touch-devices-d9f039e24899?source=rss----4f11abffcd7b---4</link>
            <guid isPermaLink="false">https://medium.com/p/d9f039e24899</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Pankaj Patel]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 09:27:22 GMT</pubDate>
            <atom:updated>2022-03-09T09:27:22.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlmplgeVGLyW7W4_M-orsQ.png" /></figure><p>Current web development is revolving around responsiveness when it comes to supporting multiple form factors.</p><p>Though the hardware tech is also pacing itself forward we can see a huge variety of handheld devices as they are portable and powerful.</p><h3>Current Challenge</h3><p>But this brings a huge dilemma in front of Frontend developers (a.k.a web developers).</p><p><em>How did we NOT handle hover in mobile/handheld/touch-enabled devices?</em></p><p>With Responsive Media Queries and adding touch event handlers. On smaller devices don’t add hover CSS and add touch handlers to see additional content.</p><p>And it worked great for the following reasons:</p><ul><li>Small form factor meant touch</li><li>Bigger screens always come with mouse support</li></ul><p>But nowadays, we have:</p><ul><li>Huge tablets in both categories of portable &amp; large screen; Devices where screens are like a desktop but you can use these like tablets, which means you won’t have access to a Mouse or precise control of the pointer</li><li>Hover on tablet-y desktops (or desktop-y tablets 🤷‍♂️)</li></ul><p>The good old mouse interactions are no longer available on such devices. Interactions like:</p><ul><li>hover</li><li>right-click</li></ul><h3>Solution</h3><p>CSS3 have now covered this corner now with pointer media queries. It allows you to write CSS for the following values:</p><p>Let’s take a look at an example use of the above media queries:</p><pre>&lt;button<br>  data-title=&quot;Get the best offers!&quot;<br>  data-help=&quot;Call 1800-00-00-123456!&quot;<br>&gt;<br>  Subscribe<br>&lt;/button&gt;</pre><p>And CSS:</p><pre>button {<br>  color: <em>#333;</em><br>  font-size: 1.3rem;<br>  padding: 2rem;<br>  background-color: <em>#eee;</em><br>  border: 1px solid <em>#ddd;</em><br>  position: relative;<br>  transition: all ease 200ms;<br>}<br><br>@media (pointer: fine) {<br>  button:hover {<br>    color: <em>#fff;</em><br>    border-color: <em>#000;</em><br>    background-color: <em>#333;</em><br>  }<br>  button:hover:after {<br>    top: 90%;<br>  	background: <em>#aaa;</em><br>    border-radius: 0.25rem;<br>    content: attr(data-title);<br>    position: absolute;<br>    font-size: 0.7rem;<br>    padding: 0.5rem 0.8rem;<br>    width: max(100%, 200px);<br>    max-width: max-content;<br>  }<br>}<br><br>@media (pointer: coarse) {<br>  button:after {<br>    content: attr(data-title);<br>    display: block;<br>    font-size: 0.75rem;<br>  }<br>  button:hover {<br>    color: <em>#ddd;</em><br>    border-color: <em>#aaa;</em><br>    background-color: <em>#999;</em><br>  }<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fpankajpatel%2Fembed%2Fpreview%2FrNYQJBw%3Fdefault-tabs%3Dcss%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DrNYQJBw&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fpankajpatel%2Fpen%2FrNYQJBw&amp;image=https%3A%2F%2Fshots.codepen.io%2Fpankajpatel%2Fpen%2FrNYQJBw-512.jpg%3Fversion%3D1646290144&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3418f9351f79f944d31bec25d40aacb/href">https://medium.com/media/d3418f9351f79f944d31bec25d40aacb/href</a></iframe><p>And you can also detect if no pointing is present with the device; like in following example:</p><pre><a href="http://twitter.com/media">@media</a> (pointer: none) {<br>  button:before, button:after {<br>    display: block;<br>    font-size: 0.75rem;<br>  }<br>  button:after {<br>    content: attr(data-title);<br>  }<br>  button:before {<br>    content: attr(data-help);<br>  }<br>}</pre><h3>Hover in JS?</h3><p>In our Desktop WebApps, we tend to add much interaction on Hover, But if we want the same apps to be usable on Touch devices, our JS-based interactions seem to have rendered useless.</p><p>We usually leave the hover events in place and attach extra handlers like touch-&amp;-hold or similar.</p><p>But I think that it is not the best way, we should add hover interactions only when we know that hover is possible and the same for touch events.</p><p>For this, we have an all-around solution that allows us to run a CSS media query and see if the operation matched or not.</p><p>Yes we are talking about window.matchMedia</p><p>You can use matchMedia function to see if the window is under any responsive breakpoint or not:</p><pre>console.log(<br>  window.matchMedia(&#39;(max-width: 768px)&#39;)<br>);<br><em>// { matches: false, media: &quot;(max-width: 768px)&quot;, ... }</em></pre><p>Now we can use a similar matchMedia query to determine the pointer support. For example:</p><pre>document.addEventListener(&#39;DOMContentLoaded&#39;, () =&gt; {<br>  const pointerFineSupported = window.matchMedia(&#39;(pointer: fine)&#39;).matches</pre><pre>if (pointerFineSupported) {<br>  document.querySelector(&#39;a&#39;)?.addEventListener(&#39;hover&#39;, (e) =&gt; {<br>    // load the linked content optimistically before click<br>  })<br>  document.querySelector(&#39;image&#39;)?.addEventListener(&#39;mouseenter&#39;, (e) =&gt; {<br>    // show the related caption<br>  })<br>  document.querySelector(&#39;image&#39;)?.addEventListener(&#39;mouseleave&#39;, (e) =&gt; {<br>    // hide the related caption<br>  })<br>}<br>});</pre><p>Similarly, we can attach <a href="https://w3c.github.io/touch-events/#list-of-touchevent-types">Touch Events</a> like touchstart and touchend when the pointer: coarse is available</p><pre>document.addEventListener(&#39;DOMContentLoaded&#39;, () =&gt; {<br>  const touchSupported = window.matchMedia(&#39;(pointer: coarse)&#39;).matches</pre><pre>  if (touchSupported) {<br>    document.querySelector(&#39;image&#39;)?.addEventListener(&#39;touchstart&#39;, (e) =&gt; {<br>      // show the related caption<br>    })<br>    document.querySelector(&#39;image&#39;)?.addEventListener(&#39;touchend&#39;, (e) =&gt; {<br>      // hide the related caption<br>    })<br>  }<br>});</pre><p>Let’s put the above JS snippet to use and make something UX improvements where we have used the pointer media queries to optimize the page navigation.</p><p>The prime difference between the two is:</p><pre>const pointerFineSupported = window.matchMedia(&#39;(pointer: fine)&#39;).matches;</pre><pre>if (pointerFineSupported) {<br>  document.querySelectorAll(&#39;[data-prefetch]&#39;).forEach(el =&gt; {<br> el.addEventListener(&#39;mouseenter&#39;, (e) =&gt; {<br>   const routeName = el.getAttribute(&#39;href&#39;).replace(&#39;#&#39;, &#39;&#39;);<br>   !routes[routeName].content &amp;&amp; fetchTemplateForRoute(routes[routeName]);<br> })<br>  })<br>}</pre><p>Repo: <a href="https://github.com/time2hack/pointer-events">github.com/time2hack/pointer-events</a> Demo without optimization: <a href="https://time2hack.github.io/pointer-events/">time2hack.github.io/pointer-events</a> Demo with optimization: <a href="https://time2hack.github.io/pointer-events/index2.html">time2hack.github.io/pointer-events/index2.h..</a></p><p>In my <a href="https://pankaj.pro/">portfolio website</a>; I have also used the pointer media queries in CSS to show some information that is visible on hover if you are using a desktop with a mouse to visit it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ct8auFzBr8UKvt0a.gif" /></figure><p>Here is the rough outline of the Styled Component for the Card handing pointer media query:</p><pre>import styled from &quot;styled-components&quot;;</pre><pre>export const ImageContainer = styled.div`<br>  ...<br>  &amp; img { ... }<br>`;</pre><pre>export const Description = styled.div` ... `;</pre><pre>export const Article = styled.article`<br>  ...</pre><pre>${ImageContainer} { ... }</pre><pre>&amp;:hover {<br>    &amp; ${Description} { ... }<br>  }</pre><pre><a href="http://twitter.com/media">@media</a> (pointer: coarse) {<br>    ...</pre><pre>${Description} { ... }<br>  }<br>`;</pre><p>You can see the full file here: <a href="https://github.com/pankajpatel/pankajpatel.github.io/blob/master/components%2Fstyled%2FArticle.ts">github.com/pankajpatel/pankajpatel.github.i..</a></p><h3>Conclusion</h3><p>Pointer media queries can help you tailor the UX for devices that have capabilities, like</p><ul><li>Prefetch content on hover for mouse</li><li>Slide interaction for list items on touch devices</li><li>etc.</li></ul><p>What are you going to optimize?</p><p>Let me know through comments 💬 or on Twitter at <a href="https://twitter.com/intent/follow?screen_name=heypankaj_">@heypankaj_</a> and/or <a href="https://twitter.com/intent/follow?screen_name=time2hack">@time2hack</a></p><p>If you find this article helpful, please share it with others 🗣</p><p>Subscribe to the blog to receive new posts right to your inbox.</p><p><em>Originally published at </em><a href="https://time2hack.com/can-i-use-hover-on-touch-devices/"><em>https://time2hack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f039e24899" width="1" height="1" alt=""><hr><p><a href="https://medium.com/time2hack/can-i-use-hover-on-touch-devices-d9f039e24899">Can I use hover on Touch Devices?</a> was originally published in <a href="https://medium.com/time2hack">time2hack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>