<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dharti R on Medium]]></title>
        <description><![CDATA[Stories by Dharti R on Medium]]></description>
        <link>https://medium.com/@cp-dharti-r?source=rss-851a1801eb21------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rmycHVkpvCrTBNfGffSxhg.png</url>
            <title>Stories by Dharti R on Medium</title>
            <link>https://medium.com/@cp-dharti-r?source=rss-851a1801eb21------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:51:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cp-dharti-r/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Next.js: How to validate forms on the server side using Zod]]></title>
            <link>https://medium.com/@cp-dharti-r/next-js-how-to-validate-forms-on-the-server-side-using-zod-f1ee83e03dcd?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1ee83e03dcd</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[server-side-validation]]></category>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[form-validation]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 13:53:55 GMT</pubDate>
            <atom:updated>2024-12-02T13:53:55.456Z</atom:updated>
            <content:encoded><![CDATA[<h4>Strengthening Your Next.js Applications with Robust Server-Side Validation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_967D5dao1cj7BhMUGn-aQ.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Introduction</h3><p>In the fast-paced world of web development, form validation is a crucial aspect to ensure that the data submitted by users is accurate and secure.</p><p>Next.js, a popular React framework, provides a robust environment for building server-rendered applications.</p><p>In this post, we’ll explore how to implement server-side form validation using <a href="https://zod.dev/"><strong>Zod</strong></a>, a powerful TypeScript-first schema declaration and validation library.</p><p>Now, Let’s get started! 🎯</p><h3>Sponsored</h3><p>Witness your goals unfold with each intentional habit, turning your ambitions into a reality with <a href="https://justly.life/"><strong>Justly</strong></a>.</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Why Form Validation Matters?</h3><p>Forms are a fundamental part of web applications, facilitating user interaction and data submission. However, the data entered by users is only sometimes reliable.</p><p>Client-side validation, executed on the user’s device, enhances the user experience by providing instant feedback. Despite its importance, relying solely on client-side validation leaves your application vulnerable to malicious or erroneous data submissions.</p><p>Server-side validation acts as a safeguard, ensuring that only validated and sanitized data reaches your server, thereby fortifying your application against potential security risks.</p><h3>Prerequisites</h3><p>Before we dive into the implementation, make sure you have the following prerequisites in place:</p><ol><li>A Next.js project set up.</li><li>Basic knowledge of HTML, CSS, and Form.</li></ol><p>Also, I have used <a href="https://tailwindcss.com/docs/installation"><strong>tailwind CSS</strong></a> to style the form. so, it would be easy if you had a basic idea about it.</p><h4><strong>Setting up a Next.js Project</strong></h4><p>If you haven’t already, start by setting up a Next.js project. You can create one using the following commands:</p><pre>npx create-next-app my-next-app<br>cd my-next-app</pre><h4><strong>Installing Zod</strong></h4><p>Next, install Zod in your project using:</p><pre>npm install zod       # npm<br>yarn add zod          # yarn<br>bun add zod           # bun<br>pnpm add zod          # pnpm</pre><h3>Building a Form Component</h3><p>In the initial version, our primary objective is to establish a foundational structure for our Next.js application, featuring a basic form.</p><pre>&quot;use client&quot;;<br><br>import { useState } from &quot;react&quot;;<br>import { TagsInput } from &quot;react-tag-input-component&quot;;<br><br>export default function Home() {<br>  const [name, setName] = useState&lt;string&gt;(&quot;&quot;);<br>  const [email, setEmail] = useState&lt;string&gt;(&quot;&quot;);<br>  const [hobbies, setHobbies] = useState([]);<br><br>  const onSubmit = async (e: any) =&gt; {<br>    e.preventDefault();<br><br>    try {<br>      console.log(name, email, hobbies);<br>    } catch (error) {<br>      console.error(error);<br>    }<br>  };<br><br>  return (<br>    &lt;main className=&quot;flex min-h-screen flex-col p-24&quot;&gt;<br>      &lt;div className=&quot;mb-6 flex gap-3 sm:items-center&quot;&gt;<br>        &lt;h2 className=&quot;text-2xl font-semibold text-black dark:text-white&quot;&gt;<br>          Add User<br>        &lt;/h2&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;rounded-sm border&quot;&gt;<br>        &lt;div className=&quot;border-b px-6 py-4&quot;&gt;<br>          &lt;h3 className=&quot;font-medium text-black dark:text-white&quot;&gt;<br>            User Details<br>          &lt;/h3&gt;<br>        &lt;/div&gt;<br>        &lt;form<br>          className=&quot;flex flex-col gap-10 p-10&quot;<br>          method=&quot;post&quot;<br>          onSubmit={onSubmit}<br>        &gt;<br>          &lt;div&gt;<br>            &lt;label className=&quot;mb-3 block text-sm font-medium text-black dark:text-white&quot;&gt;<br>              Name &lt;span className=&quot;text-red-500&quot;&gt;*&lt;/span&gt;<br>            &lt;/label&gt;<br>            &lt;input<br>              type=&quot;text&quot;<br>              placeholder=&quot;Name&quot;<br>              className=&quot;w-full rounded-lg border-[1.5px] px-5 py-3 text-black outline-none transition focus:border-blue-500 active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary&quot;<br>              onChange={(e) =&gt; setName(e.target.value)}<br>            /&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;label className=&quot;mb-3 block text-sm font-medium text-black dark:text-white&quot;&gt;<br>              Email &lt;span className=&quot;text-red-500&quot;&gt;*&lt;/span&gt;<br>            &lt;/label&gt;<br>            &lt;input<br>              type=&quot;text&quot;<br>              placeholder=&quot;Email&quot;<br>              className=&quot;w-full rounded-lg border-[1.5px] px-5 py-3 text-black outline-none transition focus:border-blue-500 active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary&quot;<br>              onChange={(e) =&gt; setEmail(e.target.value)}<br>            /&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;label className=&quot;mb-3 block text-sm font-medium text-black dark:text-white&quot;&gt;<br>              Tags &lt;span className=&quot;text-red-500&quot;&gt;*&lt;/span&gt;<br>            &lt;/label&gt;<br>            &lt;TagsInput<br>              value={hobbies}<br>              onChange={setHobbies}<br>              placeHolder=&quot;Write Your Hobbies Here&quot;<br>            /&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;text-end&quot;&gt;<br>            &lt;button<br>              type=&quot;submit&quot;<br>              className=&quot;h-10 w-32 rounded-md bg-blue-600 font-medium text-white&quot;<br>            &gt;<br>              Save<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyCZusWDo8tBGXd_S09wOA.png" /><figcaption>Build a form component</figcaption></figure><p>In this initial code, we set up a basic form component within a Next.js application. It uses the useState hook from React to manage state variables such as name, email, and hobbies.</p><p>The form includes fields for a user&#39;s name, email, and hobbies. The onSubmit function logs the entered values for testing purposes.</p><h3>Adding Basic Zod Validation</h3><p>In this section, our focus shifts towards fortifying our form with server-side validation using basic Zod validation.</p><p>Now next, let’s import Zod, a schema validation library for TypeScript. It utilizes the z object from Zod to define a schema that validates the form inputs.</p><pre>const onSubmit = async (e: any) =&gt; {<br>  e.preventDefault();<br>  setIsLoading(true);<br><br>  try {<br>    // prepare validation rules for each field<br>    const mySchema = z.object({<br>      name: z.string().min(3),<br>      email: z.coerce.string().email().min(5),<br>      hobbies: z<br>        .array(z.string().min(2))<br>        .min(1, { message: &quot;Hobbies is required&quot; }),<br>    });<br><br>    // validate form data<br>    mySchema.parse({<br>      name: name,<br>      email: email,<br>      hobbies: hobbies,<br>    });<br><br>    setErrors([]);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUflbZmAj0yeA7QuEenigw.png" /><figcaption>Zod validation to see errors</figcaption></figure><p>The onSubmit function is modified to use this schema for validation. If the validation succeeds, the errors state is cleared, and if it fails, the errors are logged to the console.</p><h3>Displaying Validation Errors</h3><p>Building upon the foundation laid in the above section, this iteration aims to enhance the user interface by providing real-time feedback on validation errors.</p><h4>Validate and Refine Errors</h4><p>Now, let’s initialize the errors state using useState to manage and display validation errors.</p><pre>const [errors, setErrors] = useState&lt;any[]&gt;([]);<br>const [isLoading, setIsLoading] = useState&lt;boolean&gt;(false);<br><br>const onSubmit = async (e: any) =&gt; {<br>  e.preventDefault();<br>  setIsLoading(true);<br><br>  try {<br>    const mySchema = z.object({<br>      name: z.string().min(3),<br>      email: z.coerce.string().email().min(5),<br>      hobbies: z<br>        .array(z.string().min(2))<br>        .min(1, { message: &quot;Hobbies is required&quot; }),<br>    });<br><br>    // store validation response<br>    const response = mySchema.safeParse({<br>      name: name,<br>      email: email,<br>      hobbies: hobbies,<br>    });<br><br>    // refine errors<br>    if (!response.success) {<br>      let errArr: any[] = [];<br>      const { errors: err } = response.error;<br>      for (var i = 0; i &lt; err.length; i++) {<br>        errArr.push({ for: err[i].path[0], message: err[i].message });<br>      }<br>      setErrors(errArr);<br>      throw err;<br>    }<br><br>    setErrors([]);<br>  } catch (error) {<br>    console.error(error);<br>  } finally {<br>    setIsLoading(false);<br>  }<br>};</pre><p>Parsing the validation errors and transforming them into a more structured format to simplify handling and display.</p><p>🔴 Now it’s time to show errors.</p><h4>Show Errors</h4><p>So, in this code, we will enhance the user interface by displaying validation errors for each form field.</p><pre>&lt;form className=&quot;flex flex-col gap-10 p-10&quot; method=&quot;post&quot; onSubmit=&quot;{onSubmit}&quot;&gt;<br>  &lt;div&gt;<br>    &lt;label<br>      className=&quot;mb-3 block text-sm font-medium text-black dark:text-white&quot;<br>    &gt;<br>      Name &lt;span className=&quot;text-red-500&quot;&gt;*&lt;/span&gt;<br>    &lt;/label&gt;<br>    &lt;input type=&quot;text&quot; placeholder=&quot;Name&quot; className=&quot;w-full rounded-lg border-[1.5px] px-5 py-3 text-black outline-none transition focus:border-blue-500 active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary&quot; <br>      onChange={(e) =&gt; setName(e.target.value)} autoComplete=&quot;off&quot; required /&gt;<br>    &lt;div className=&quot;mt-1 text-xs text-red-500&quot;&gt;<br>      {errors.find((error) =&gt; error.for === &quot;name&quot;)?.message}<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div&gt;<br>    &lt;label<br>      className=&quot;mb-3 block text-sm font-medium text-black dark:text-white&quot;<br>    &gt;<br>      Email &lt;span className=&quot;text-red-500&quot;&gt;*&lt;/span&gt;<br>    &lt;/label&gt;<br>    &lt;input type=&quot;text&quot; placeholder=&quot;Email&quot; className=&quot;w-full rounded-lg border-[1.5px] px-5 py-3 text-black outline-none transition focus:border-blue-500 active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary&quot; <br>      onChange={(e) =&gt; setEmail(e.target.value)} autoComplete=&quot;off&quot; required /&gt;<br>    &lt;div className=&quot;mt-1 text-xs text-red-500&quot;&gt;<br>      {errors.find((error) =&gt; error.for === &quot;email&quot;)?.message}<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div&gt;<br>    &lt;label<br>      className=&quot;mb-3 block text-sm font-medium text-black dark:text-white&quot;<br>    &gt;<br>      Tags &lt;span className=&quot;text-red-500&quot;&gt;*&lt;/span&gt;<br>    &lt;/label&gt;<br>    &lt;TagsInput<br>      value=&quot;{hobbies}&quot;<br>      onChange=&quot;{setHobbies}&quot;<br>      placeHolder=&quot;Write Your Hobbies Here&quot;<br>    /&gt;<br>    &lt;div className=&quot;mt-1 text-xs text-red-500&quot;&gt;<br>      {errors.find((error) =&gt; error.for === &quot;hobbies&quot;)?.message}<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div className=&quot;text-end&quot;&gt;<br>    &lt;button<br>      type=&quot;submit&quot;<br>      className=&quot;h-10 w-32 rounded-md bg-blue-600 font-medium text-white disabled:cursor-not-allowed disabled:opacity-30&quot;<br>      disabled=&quot;{isLoading}&quot;<br>    &gt;<br>      {isLoading ? &quot;Saving...&quot; : &quot;Save&quot;}<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/form&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjMPMF94L9Y4a3atsHlOig.png" /><figcaption>Show errors using Zod validation</figcaption></figure><p>If there are validation errors, they are captured and stored in the errors state. The form fields are now equipped with error messages that dynamically appear below them, providing feedback to the user.</p><p>The submit button is also disabled and shows a &quot;Saving...&quot; message when the form is being processed to prevent multiple submissions.</p><h3>Show Success popup</h3><p>In this iteration, our focus shifts towards enhancing the user experience by incorporating a successful popup feature.</p><pre>&quot;use client&quot;;<br><br>import { useState } from &quot;react&quot;;<br>import { z } from &quot;zod&quot;;<br>import { TagsInput } from &quot;react-tag-input-component&quot;;<br><br>export default function Home() {<br>  // already defined stats<br><br>  const [success, setSuccess] = useState&lt;boolean&gt;(false);<br><br>  const onSubmit = async (e: any) =&gt; {<br>    e.preventDefault();<br>    setIsLoading(true);<br><br>    try {<br>      <br>      /* current error handling code */<br><br>      // set success `true` to show popup<br>      setSuccess(true);<br>    } catch (error) {<br>      console.error(error);<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  };<br><br>  const closeSuccessPopup = () =&gt; {<br>    // set success `false` to hide popup<br>    setSuccess(false);<br>  };<br><br>  return (<br>    &lt;main className=&quot;flex min-h-screen flex-col p-24&quot;&gt;<br>    {/* Form code */}<br>    {/* Success Popup */}<br>    {success &amp;&amp; (<br>      &lt;div className=&quot;fixed top-0 left-0 w-full h-full flex items-center justify-center bg-black bg-opacity-50&quot;&gt;<br>        &lt;div className=&quot;bg-white p-8 rounded-md text-center&quot;&gt;<br>          &lt;p className=&quot;text-green-500 text-lg font-semibold mb-4&quot;&gt;<br>            Data Successfully Saved!<br>          &lt;/p&gt;<br>          &lt;button<br>            className=&quot;bg-blue-600 text-white px-4 py-2 rounded-md&quot;<br>            onClick={closeSuccessPopup}&gt;<br>            Close<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )}<br>    &lt;/main&gt;<br>  );<br>}</pre><p>The onSubmit function has been extended to simulate the data insertion or API call process. Once the submission is successful, the success state is set to true. The form fields and errors are then cleared to prepare for potential new entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTAWiej4Kr8HRRQUNk1xhg.png" /><figcaption>Show success popup</figcaption></figure><p>This success popup is implemented as a modal overlay with a semi-transparent background, ensuring that it captures the user’s attention without obstructing the entire view. It contains a success message and a button to close the popup.</p><p>The close button triggers the closeSuccessPopup function, updating the success state to false and hiding the success popup.</p><p><strong>The complete source code — </strong><a href="https://github.com/cp-dharti-r/nextjs-server-side-validation"><strong>Next Js: Server Side Validation Using Zod</strong></a></p><p>That’s it for today. Keep Coding! 👋</p><h3>Conclusion</h3><p>Implementing server-side form validation adds an extra layer of security to your application. we’ve not only implemented robust server-side validation but also considered the user interface’s responsiveness and feedback mechanisms.</p><p>With each iteration, we refined the user interface, providing real-time feedback to users through dynamic error messages. These messages guide users in correcting their inputs and contribute to a more intuitive and responsive form-filling experience.</p><p>To further enhance user satisfaction, we introduced a success popup to acknowledge successful form submissions. This visual cue assures users that their data has been successfully saved, contributing to an overall positive user experience.</p><p>Remember to customize the schema according to your specific form requirements.</p><p>Happy coding! 🤖</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1ee83e03dcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to do Data Serialization and Deserialization in Golang]]></title>
            <link>https://medium.com/canopas/how-to-do-data-serialization-and-deserialization-in-golang-90c80b0b6d58?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/90c80b0b6d58</guid>
            <category><![CDATA[deserialization]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[json-serialization]]></category>
            <category><![CDATA[data-serialization]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Thu, 30 May 2024 07:43:29 GMT</pubDate>
            <atom:updated>2024-06-18T07:57:55.206Z</atom:updated>
            <content:encoded><![CDATA[<h4>Covered popular formats such as JSON, XML, Gob, Protocol Buffers (protobuf), MessagePack, and YAML</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsKlGtJB4knNX6eDKMVYOw.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">Home</a>! 🚀</blockquote><h3>Background</h3><p>Serialization and deserialization are essential processes in modern software development, enabling data to be efficiently transported and stored.</p><p>In Go (Golang), these processes are straightforward. Thanks to its robust standard library and the availability of third-party packages.</p><p>In this blog post, we will delve into the basics of serialization and deserialization in Go, covering popular formats such as JSON, XML, Gob, Protocol Buffers (protobuf), MessagePack, and YAML.</p><p>So, Let’s get started! 🎯</p><h3>Sponsored</h3><p>Stop the habit of wishful thinking and start the habit of thoughtful wishes with <a href="https://justly.life/"><strong>Justly</strong></a>.</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>What are Serialization and Deserialization?</h3><p><strong>Serialization</strong> is the process of converting an in-memory data structure into a format that can be easily saved to a file or transmitted over a network.</p><p><strong>Deserialization</strong> is the reverse process, where the serialized data is converted back into an in-memory data structure.</p><p>Common formats for serialization include JSON, XML, and binary formats like Gob, Protocol Buffers, MessagePack, and YAML.</p><p>Each format has its own use cases and advantages:</p><ul><li><strong>JSON</strong>: Great for web APIs and interoperability.</li><li><strong>XML</strong>: Useful when a strict schema is needed.</li><li><strong>Gob</strong>: Ideal for Go-specific, high-performance serialization.</li><li><strong>Protocol Buffers</strong>: Efficient and versatile, especially for large-scale systems.</li><li><strong>MessagePack</strong>: Compact and efficient for bandwidth-sensitive applications.</li><li><strong>YAML</strong>: Human-readable, often used for configuration files.</li></ul><blockquote><em>Choosing the right format depends on the use case, such as human readability, performance, and compatibility requirements.</em></blockquote><h3>JSON Serialization and Deserialization</h3><p>JSON (JavaScript Object Notation) is a lightweight data-interchange format that’s easy for humans to read and write, and easy for machines to parse and generate.</p><p>In Go, the encoding/json package provides methods to work with JSON.</p><h4>Example</h4><pre>package main<br><br>import (<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br>)<br><br>type Person struct {<br> Name  string `json:&quot;name&quot;`<br> Age   int    `json:&quot;age&quot;`<br> Email string `json:&quot;email&quot;`<br>}<br><br>func main() {<br> // Serialization<br> p := Person{Name: &quot;Alice&quot;, Age: 30, Email: &quot;alice@example.com&quot;}<br><br> data, err := json.Marshal(p)<br> if err != nil {<br>  fmt.Println(&quot;Error serializing:&quot;, err)<br>  return<br> }<br><br> fmt.Println(&quot;Serialized JSON:&quot;, string(data))<br><br> // Deserialization<br> var p2 Person<br><br> err = json.Unmarshal(data, &amp;p2)<br> if err != nil {<br>  fmt.Println(&quot;Error deserializing:&quot;, err)<br>  return<br> }<br><br> fmt.Printf(&quot;Deserialized struct: %+v\n&quot;, p2)<br>}</pre><h4>Output</h4><pre>Serialized JSON: {&quot;name&quot;:&quot;Alice&quot;,&quot;age&quot;:30,&quot;email&quot;:&quot;alice@example.com&quot;}<br>Deserialized struct: {Name:Alice Age:30 Email:alice@example.com}</pre><p>In this example, json.Marshal is used for serialization and json.Unmarshal is used for deserialization.</p><h4>Advanced Tips</h4><ol><li><strong>Custom JSON Field Names</strong>: Use struct tags to customize JSON field names.</li><li><strong>Omitting Empty Fields</strong>: Add omitempty to struct tags to omit empty fields from the serialized output.</li><li><strong>Error Handling</strong>: Always handle errors during serialization and deserialization to avoid data corruption or crashes.</li><li><strong>Streaming</strong>: Use json.Encoder and json.Decoder for working with streams, such as reading from or writing to files.</li></ol><h3>XML Serialization and Deserialization</h3><p>XML (Extensible Markup Language) is another format used for serialization, particularly in applications that require strict data schemas.</p><p>Go provides the encoding/xml package for working with XML.</p><h4>Example</h4><pre>package main<br><br>import (<br> &quot;encoding/xml&quot;<br> &quot;fmt&quot;<br>)<br><br>type Person struct {<br> XMLName xml.Name `xml:&quot;person&quot;`<br> Name    string   `xml:&quot;name&quot;`<br> Age     int      `xml:&quot;age&quot;`<br> Email   string   `xml:&quot;email&quot;`<br>}<br><br>func main() {<br> // Serialization<br> p := Person{Name: &quot;Bob&quot;, Age: 25, Email: &quot;bob@example.com&quot;}<br><br> data, err := xml.MarshalIndent(p, &quot;&quot;, &quot;  &quot;)<br> if err != nil {<br>  fmt.Println(&quot;Error serializing:&quot;, err)<br>  return<br> }<br><br> fmt.Println(&quot;Serialized XML:\n&quot;, string(data))<br><br> // Deserialization<br> var p2 Person<br><br> err = xml.Unmarshal(data, &amp;p2)<br> if err != nil {<br>  fmt.Println(&quot;Error deserializing:&quot;, err)<br>  return<br> }<br><br> fmt.Printf(&quot;Deserialized struct: %+v\n&quot;, p2)<br>}</pre><h4>Output</h4><pre>Serialized XML:<br> &lt;person&gt;<br>  &lt;name&gt;Bob&lt;/name&gt;<br>  &lt;age&gt;25&lt;/age&gt;<br>  &lt;email&gt;bob@example.com&lt;/email&gt;<br>&lt;/person&gt;<br>Deserialized struct: {XMLName:{Space: Local:person} Name:Bob Age:25 Email:bob@example.com}</pre><p>In this example, xml.MarshalIndent is used for serialization with indentation for readability and xml.Unmarshal is used for deserialization.</p><h4>Advanced Tips</h4><ol><li><strong>Customizing Element Names</strong>: Use struct tags to customize XML element names.</li><li><strong>Attributes</strong>: Use struct tags to serialize struct fields as XML attributes.</li><li><strong>Namespaces</strong>: Manage XML namespaces using the XMLName field.</li><li><strong>Error Handling</strong>: Ensure proper error handling for robustness.</li></ol><h3>Gob Serialization and Deserialization</h3><p>Gob is a binary serialization format specific to Go, which is efficient and compact.</p><p>The encoding/gob package facilitates working with Gob.</p><h4>Example</h4><pre>package main<br><br>import (<br> &quot;bytes&quot;<br> &quot;encoding/gob&quot;<br> &quot;fmt&quot;<br>)<br><br>type Person struct {<br> Name  string<br> Age   int<br> Email string<br>}<br><br>func main() {<br> // Serialization<br> p := Person{Name: &quot;Charlie&quot;, Age: 28, Email: &quot;charlie@example.com&quot;}<br><br> var buffer bytes.Buffer<br> encoder := gob.NewEncoder(&amp;buffer)<br><br> err := encoder.Encode(p)<br> if err != nil {<br>  fmt.Println(&quot;Error serializing:&quot;, err)<br>  return<br> }<br><br> fmt.Println(&quot;Serialized Gob:&quot;, buffer.Bytes())<br><br> // Deserialization<br> var p2 Person<br><br> decoder := gob.NewDecoder(&amp;buffer)<br> err = decoder.Decode(&amp;p2)<br> if err != nil {<br>  fmt.Println(&quot;Error deserializing:&quot;, err)<br>  return<br> }<br><br> fmt.Printf(&quot;Deserialized struct: %+v\n&quot;, p2)<br>}</pre><h4>Output</h4><pre>Serialized Gob: [17 255 129 3 1 1 6 80 101 114 115 111 110 1 255 130 0 1 1 4 78 97 109 101 1 12 0 1 3 65 103 101 1 4 0 1 5 69 109 97 105 108 1 12 0 0 0 26 255 130 1 6 67 104 97 114 108 105 101 1 28 1 15 99 104 97 114 108 105 101 64 101 120 97 109 112 108 101 46 99 111 109 0]<br>Deserialized struct: {Name:Charlie Age:28 Email:charlie@example.com}</pre><p>In this example, gob.NewEncoder and Encode are used for serialization and gob.NewDecoder and Decode are used for deserialization.</p><h4>Advanced Tips</h4><ol><li><strong>Efficiency</strong>: Gob is more efficient than JSON and XML in terms of size and speed.</li><li><strong>Type Safety</strong>: Gob ensures type safety during encoding and decoding.</li><li><strong>Streaming</strong>: Use encoders and decoders with network connections or files for large data sets.</li><li><strong>Registering Types</strong>: Register complex or interface types with gob.Register to avoid encoding errors.</li></ol><h3>Protocol Buffers (Protobuf)</h3><p>Protocol Buffers, developed by Google, is a language-neutral and platform-neutral mechanism for serializing structured data. They are more efficient than JSON and XML, especially in terms of size and speed.</p><h4>Example</h4><p>First, you need to define your data structure in a .proto file:</p><pre>syntax = &quot;proto3&quot;;<br><br>message Person {<br>  string name = 1;<br>  int32 age = 2;<br>  string email = 3;<br>}</pre><p>Next, compile the .proto file using the protoc compiler to generate Go code.</p><p>Here’s how you can serialize and deserialize using Protobuf:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br><br> &quot;github.com/golang/protobuf/proto&quot;<br> &quot;your_project_path/personpb&quot; // Import the generated protobuf package<br>)<br><br>func main() {<br> // Create a new person<br> p := &amp;personpb.Person{<br>  Name:  &quot;Dave&quot;,<br>  Age:   35,<br>  Email: &quot;dave@example.com&quot;,<br> }<br><br> // Serialization<br> data, err := proto.Marshal(p)<br> if err != nil {<br>  log.Fatal(&quot;Marshaling error: &quot;, err)<br> }<br><br> fmt.Println(&quot;Serialized Protobuf:&quot;, data)<br><br> // Deserialization<br> var p2 personpb.Person<br> err = proto.Unmarshal(data, &amp;p2)<br> if err != nil {<br>  log.Fatal(&quot;Unmarshaling error: &quot;, err)<br> }<br><br> fmt.Printf(&quot;Deserialized struct: %+v\n&quot;, p2)<br>}</pre><h4>Output</h4><pre>Serialized Protobuf: [10 4 68 97 118 101 16 35 26 14 100 97 118 101 64 101 120 97 109 112 108 101 46 99 111 109]<br>Deserialized struct: {Name:Dave Age:35 Email:dave@example.com}</pre><h4>Advanced Tips</h4><ol><li><strong>Backward Compatibility</strong>: Protobuf supports backward and forward compatibility.</li><li><strong>Schema Evolution</strong>: You can add new fields to your messages without breaking existing code.</li><li><strong>Performance</strong>: Protobuf is highly efficient in both size and speed compared to text formats.</li><li><strong>Third-party Libraries</strong>: Use libraries like protoc-gen-go for easy integration in Go projects.</li></ol><h3>MessagePack Serialization and Deserialization</h3><p>MessagePack is an efficient binary serialization format that is more compact than JSON. It is useful for scenarios where bandwidth is a concern.</p><h4>Example</h4><p>First, install the MessagePack library:</p><pre>go get -u github.com/vmihailenco/msgpack/v5</pre><p>Here’s an example of how to use MessagePack:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br><br> &quot;github.com/vmihailenco/msgpack/v5&quot;<br>)<br><br>type Person struct {<br> Name  string<br> Age   int<br> Email string<br>}<br><br>func main() {<br> // Create a new person<br> p := Person{Name: &quot;Eve&quot;, Age: 22, Email: &quot;eve@example.com&quot;}<br><br> // Serialization<br> data, err := msgpack.Marshal(p)<br> if err != nil {<br>  log.Fatal(&quot;Marshaling error: &quot;, err)<br> }<br><br> fmt.Println(&quot;Serialized MessagePack:&quot;, data)<br><br> // Deserialization<br> var p2 Person<br> err = msgpack.Unmarshal(data, &amp;p2)<br> if err != nil {<br>  log.Fatal(&quot;Unmarshaling error: &quot;, err)<br> }<br><br> fmt.Printf(&quot;Deserialized struct: %+v\n&quot;, p2)<br>}</pre><h4>Output</h4><pre>Serialized MessagePack: [129 164 78 97 109 101 163 69 118 101 162 65 103 101 22 165 69 109 97 105 108 171 101 118 101 64 101 120 97 109 112 108 101 46 99 111 109]<br>Deserialized struct: {Name:Eve Age:22 Email:eve@example.com}</pre><h4>Advanced Tips</h4><ol><li><strong>Efficiency</strong>: MessagePack is very efficient in terms of both speed and size.</li><li><strong>Human Readability</strong>: Although binary, tools exist to convert MessagePack to JSON for readability.</li><li><strong>Compatibility</strong>: Ensure the client and server both support MessagePack.</li></ol><blockquote><em>This post only has implementation until </em><strong><em>MessagePack Serialization and Deserialization</em></strong><em>, to read the complete guide including </em><strong><em>YAML Serialization and Deserialization</em></strong>,<em> please visit </em><a href="https://canopas.com/how-to-do-data-serialization-and-deserialization-in-golang-90c80b0b6d58"><strong><em>this blog</em></strong></a><strong><em>.</em></strong></blockquote><blockquote><em>The post is originally published on </em><a href="https://canopas.com/blog"><strong><em>canopas.com</em></strong></a><strong><em>.</em></strong></blockquote><h3>Conclusion</h3><p>In this blog post, we covered the basics of serialization and deserialization in Go using several formats: JSON, XML, Gob, Protocol Buffers, MessagePack, and YAML.</p><p>By leveraging Go’s standard libraries and third-party packages, you can efficiently serialize and deserialize data to suit your application’s needs.</p><p>Additionally, remember to handle errors properly and consider the specific requirements of your application when choosing a serialization format.</p><h3>Similar Articles</h3><ul><li><a href="https://canopas.com/function-types-and-higher-order-functions-in-go-8ea2e95d1860">Function Types and Higher-Order Functions in Go</a></li><li><a href="https://canopas.com/how-to-use-enums-in-golang">How to use Enums in Golang</a></li><li><a href="https://canopas.com/golang-date-time-utilities-part-2-b1192eb04842">Golang - Advanced Date-Time Utility functions</a></li></ul><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Please share your thoughts in the comments section below. Your input enriches our content and fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90c80b0b6d58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-do-data-serialization-and-deserialization-in-golang-90c80b0b6d58">How to do Data Serialization and Deserialization in Golang</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Secure Your Supabase Database and Storage]]></title>
            <link>https://medium.com/canopas/how-to-secure-your-supabase-database-and-storage-ce9e5fc16ab2?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9e5fc16ab2</guid>
            <category><![CDATA[security-storage]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[database-security]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 12:51:21 GMT</pubDate>
            <atom:updated>2024-04-11T12:51:21.384Z</atom:updated>
            <content:encoded><![CDATA[<h4>Safeguarding Your Data by Proactive Measures</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IowiP0bag2XvBLa76vlcLg.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">home</a>! 🚀</blockquote><h3>Introduction</h3><p>In the era of data breaches and cybersecurity threats, safeguarding sensitive information is paramount for businesses and developers.</p><p>With the rise of cloud-based databases and storage solutions, such as Supabase, Firebase, AWS, or Google Cloud Firestore ensuring the security of your data is more critical than ever.</p><p><a href="https://supabase.com/"><strong>Supabase</strong></a> is an open-source platform that provides developers with a set of tools to build scalable and secure web applications.</p><p>Leveraging PostgreSQL as its database engine and integrating with popular authentication providers like Auth0 and Firebase, Supabase offers a comprehensive solution for managing data and user access in modern web applications.</p><p>In this blog post, we’ll explore the best practices and strategies for securing your <strong>Supabase Database</strong> and <strong>Storage</strong>, helping you mitigate risks, and protecting your valuable data assets.</p><h3>Sponsored</h3><p>We believe that everyone deserves the opportunity to succeed and thrive, and <a href="https://justly.life/"><strong>Justly</strong></a> is designed to provide the guidance and support needed to make that a reality.</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Database Security</h3><p>A robust database security strategy is essential for protecting your data from unauthorized access, manipulation, or theft. Here are the step-by-step implementations to consider.</p><h3>Create a table with the required fields</h3><p>In Supabase, creating a table is straightforward. we can do this through the SQL editor provided in the Supabase dashboard.</p><p>Navigate to the SQL editor and execute a CREATE TABLE statement to define the structure of your <strong>&quot;users&quot;</strong> table. For example,</p><pre>create table users (<br>  id bigint primary key generated always as identity,<br>  auth_uid text not null, // optional - to store auth user id from supabase.auth<br>  name text not null,<br>  email text not null,<br>  created_at timestamp with time zone default current_timestamp<br>);</pre><p>In this definition, auth_uid field is optional. It will required if we want to grant access to all the supabase authenticated users. We’ll see later how it works.</p><p>Also, we can create it by using the Supabase table editor like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJFFUgxagR6WsJXxKuzv8A.png" /><figcaption>Create a table using the Supabase table editor</figcaption></figure><p>Customize the fields based on your application’s requirements. In this example, we have fields for user ID, name, email, and creation timestamp.</p><h3>Create a user for authentication</h3><p>The auth methods can be accessed via the supabase.auth namespace.</p><p>When we use supabase.auth to handle authentication in your application, it interacts directly with the Supabase authentication system.</p><p>This means that when a user signs up using your application&#39;s authentication flow (powered by supabase.auth), Supabase automatically creates a corresponding user record in the authentication system.</p><pre>const { data, error } = await supabase.auth.signUp({<br>  email: &#39;example@email.com&#39;,<br>  password: &#39;example-password&#39;,<br>})</pre><p>However, there might be scenarios where we need to manually create user records, such as during development or for administrative purposes.</p><p>In such cases, we can add users directly from the Supabase dashboard using the following steps:</p><p>1. Navigate to the Authentication tab in your Supabase dashboard.</p><p>2. Under the Users section, we can manually create a user by clicking the <strong>Add user — Create new user </strong>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3MV1SXkb9gvQO1m4hZxLQ.png" /><figcaption>Create a user for authentication</figcaption></figure><p>3. Fill in the required user details such as email and password to create a new user account.</p><p>This step simulates the creation of a user account in your application, allowing us to test authentication and access control policies.</p><h3>Create policies for the users table</h3><p>In the Supabase dashboard, navigate to the <strong>Policies</strong> section from the <strong>Authentication</strong> tab.</p><p>Here, you’ll find a list of tables in your database schema. Locate the<strong> “users”</strong> table that we created earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcC_drjVNk7x6bskahK7dg.png" /><figcaption>Create policies for user&#39;s table</figcaption></figure><p>To create a policy for records from the <strong>“users”</strong> table, click on the <strong>“Add new policy”</strong> button.</p><p>This will open a dialogue box where we can specify the details of the new policy.</p><h4>— Select record policy</h4><p>In the dialogue box, you’ll see a list of available policy templates.</p><p>Click on the first template labeled <strong>“Select”</strong> to create a select record policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k68P48gmLUw_KDQ8D8o2ZQ.png" /><figcaption>Add select record policy for the user&#39;s table</figcaption></figure><p>The policy name and required settings will be automatically populated based on the selected template. Review the settings to ensure they align with your requirements. We can customize the policy further if needed.</p><p>After configuring the policy settings, click on the <strong>“Save policy”</strong> button to save your changes.</p><h4>— Insert record policy</h4><p>Now, let’s walk through the process of setting up an insert record policy for the <strong>“users”</strong> table.</p><p>In the dialogue box, click on the template labeled <strong>“Insert”</strong> to create an insert record policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nQGh_f6FuMJfpZC_QE6Dw.png" /><figcaption>Add insert record policy for user&#39;s table</figcaption></figure><p>The policy name and required settings will be automatically populated based on the selected template. Review the settings to ensure they align with your requirements. We can customize the policy further if needed.</p><p>After configuring the policy settings, click on the <strong>“Save policy”</strong> button to save your changes.</p><h4>— Update record policy</h4><p>Now, let’s outline the steps for implementing an update record policy for the <strong>“users”</strong> table, taking into account different scenarios:</p><p><strong>— — — — — — — Granting access to all Supabase</strong> <strong>auth users — — — — — — —</strong></p><p>For all supabase auth users, setting up an update record policy is straightforward.</p><p>1. In the <strong>“Add new policy”</strong> dialogue box, select the template for updating records.</p><p>2. In the policy configuration, set the Target Roles to <strong>“Authenticated”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjA9vj1O2RMdRRfz2OQdoQ.png" /><figcaption>Add update record policy for all Supabase auth users</figcaption></figure><p>This allows any authenticated user, regardless of their specific role, to update the user record in the <strong>“users”</strong> table.</p><p>3. Save the policy to apply the update record restrictions for the <strong>“users”</strong> table.</p><p><strong>— — — — — Granting access to the specific Supabase auth user — — — — —</strong></p><p>For the specific Supabase auth user, the process is slightly different.</p><p>The <strong>first</strong> and <strong>second</strong> points are the same as above described for all Supabase auth users.</p><p>Now, you’ll need to identify them based on unique identifiers such as their email address.</p><p>3. Set the appropriate conditions in the policy configuration to match the email address of the specific user attempting to update their record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0JBkZKUNzakCPMn8RCLNA.png" /><figcaption>Add update record policy for specific auth user</figcaption></figure><p>This allows only specified authenticated users, regardless of their specific role, to update the user record in the <strong>“users”</strong> table.</p><p>4. Save the policy to apply the update record restrictions for the <strong>“users”</strong> table.</p><h4>Delete record policy</h4><p>Now, let’s detail the steps for implementing a delete record policy for the <strong>“users”</strong> table, using the user’s ID:</p><p><strong>— — — — — — — Granting access to all Supabase</strong> <strong>auth users — — — — — — —</strong></p><p>For all supabase auth users, configuring a delete record policy follows a similar process as before.</p><p>1. In the <strong>“Add new policy”</strong> dialogue box, select the template for deleting records.</p><p>2. In the policy configuration, set the Target Roles to <strong>“Authenticated”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkF4pIrC_094iFeMzLnD3w.png" /><figcaption>Add delete record policy for all supabase auth users</figcaption></figure><p>This allows any authenticated user, regardless of their specific role, to delete a user record in the <strong>“users”</strong> table.</p><p>3. Save the policy to apply the delete record restrictions for the <strong>“users”</strong> table.</p><p><strong>— — — — — Granting access to the specific Supabase auth user — — — — —</strong></p><p>For the specific Supabase auth user, adjust the policy to use the user’s ID:</p><p>The <strong>first</strong> and <strong>second</strong> points are the same as above described for all Supabase auth users.</p><p>Now, for the specific user, you’ll need to identify them based on their user ID.</p><p>3. Set the appropriate conditions in the policy configuration to match the user ID of the user attempting to delete their record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGbX-AHoWsvz_3yruQBMPQ.png" /><figcaption>Add delete record policy for specific auth user</figcaption></figure><p>This allows only specified authenticated users, regardless of their specific role, to delete the user record in the <strong>“users”</strong> table.</p><p>4. Save the policy to apply the delete record restrictions for the <strong>“users”</strong> table.</p><p>Now, we can see we have <strong>Select, Insert, Update,</strong> and <strong>Delete</strong> policies for the <strong>“users”</strong> table. We can edit or delete it if we find any issues with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miO-s9ggTtL9Y5_CIMBHPQ.png" /><figcaption>All the policies to access the records of the “users” table</figcaption></figure><p><strong>Awesome!!</strong>👌<strong>Now, our database is secured.</strong></p><p>Customize the policy settings as needed, specifying which roles or users have permission to perform the operations on the <strong>“users”</strong> table.</p><h3>Storage Security</h3><p>In addition to database security, securing data stored in cloud storage is equally important. Here are step-by-step implementations for enhancing storage security.</p><h3>Create a bucket</h3><p>1. Click on the <strong>“Storage”</strong> from the Supabase dashboard.</p><p>2. In the storage sidebar, click <strong>New Bucket</strong>.</p><p>3. Add a name for your bucket, then set the <strong>Public bucket </strong>toggle to <strong>true </strong>to grant access for showing all the files from the bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYUUuvfXyImw_xZPS1DqOA.png" /><figcaption>Create a bucket to store the user profile</figcaption></figure><p>4. Click “<strong>Save”</strong> when done.</p><h3>Create policies for the bucket</h3><p>1. Back in the Storage sidebar, click <strong>Policies</strong>.</p><p>2. Under Storage Policies, locate the bucket we just created and click <strong>New Policy.</strong></p><p>Now, we can see the dialogue has two options for creating the policy. Let’s go through both step by step:</p><h4><strong>Steps for Getting Started Quickly</strong></h4><p>3. Click on the “Get started quickly: Create a policy from a template<strong>” </strong>to create a policy from the template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mofoQkdOKus6sTTISmrqYQ.png" /><figcaption>Create policy from a quick start template</figcaption></figure><p>4. In the modal sidebar, there are five templates to create a policy. We can select as per your requirement and click on <strong>Use this template.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPiVL2KYM5ZZTX29I3Vmhw.png" /><figcaption>Select a template according to the requirement</figcaption></figure><p>5. On the next page, under <strong>Allowed operation</strong>, check the <strong>select</strong>, <strong>insert, </strong>and<strong> delete </strong>box to enable inserting and deleting of images into Storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VikCPNrNbmWBR6Lt6EY1Q.png" /><figcaption>Add additional required changes</figcaption></figure><p>6. Set the Target Roles to <strong>“Authenticated”</strong>.</p><p>7. Click on the <strong>Review.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GN42MRbXcxkaAZ4siJH_BA.png" /><figcaption>Review and save policy</figcaption></figure><p>8. Review the policies added using the template, and then click <strong>Save policy</strong>.</p><h4><strong>Steps for full customization</strong></h4><p>3. Click “For full customization: Create a policy from scratch<strong>” </strong>to create a policy from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJQZsRdbSeFwgLamflqV9g.png" /><figcaption>Create a fully customized policy</figcaption></figure><p>4. On the next modal, under <strong>Allowed operation</strong>, check the <strong>select</strong>, <strong>insert, </strong>and<strong> delete </strong>box to enable inserting and deleting of images into Storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmaRKFX5UxFrSwUUb_tHHw.png" /><figcaption>Customize policy as per requirement</figcaption></figure><p>5. Set the Target Roles to <strong>“Authenticated”</strong>.</p><p>6. Click on the <strong>Review.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2w5k_b7rrnt6XIF1C0Jhyw.png" /><figcaption>Review the added policies</figcaption></figure><p>7. On the next page, review the policies we created, then click <strong>Save policy.</strong></p><p>Now, we can see we have <strong>Select, Insert,</strong> and <strong>Delete</strong> policies for the <strong>“User Profile”</strong> bucket. We can edit or delete it if we find any issues with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRj9g2wN9ADjyRPmlmgcEw.png" /><figcaption>All the policies for the “User Profile” bucket</figcaption></figure><p>Customize the policy settings as needed, specifying which roles or users have permission to perform the operations on the <strong>“User Profile” </strong>bucket.</p><p>𝐓𝐚-𝐝𝐚!! 🎉 <strong>we have</strong> <strong>secured our supabase database and storage.</strong></p><p>Thanks for reading!! 👋👋👋</p><blockquote><em>To read this blog on our platform, please visit </em><a href="https://canopas.com/how-to-secure-your-supabase-database-and-storage-ce9e5fc16ab2"><strong><em>this blog</em></strong></a><em>.</em></blockquote><blockquote><em>The post is originally published on </em><a href="https://canopas.com/blog"><strong><em>canopas.com</em></strong></a><strong><em>.</em></strong></blockquote><h3>Conclusion</h3><p>Securing your data is not just a matter of compliance, it’s a fundamental aspect of building trust with your users and safeguarding your business reputation.</p><p>By implementing robust database security and storage security measures, we not only protect sensitive information but also demonstrate your commitment to data privacy and integrity.</p><p>Remember, data security is an ongoing journey, and continual evaluation and adaptation are key to staying ahead of emerging threats in the ever-changing landscape of cybersecurity.</p><h3>Similar Useful Articles</h3><ul><li><a href="https://blog.canopas.com/google-recaptcha-enterprise-integrate-the-im-not-a-robot-challenge-in-vue-js-8a83f7d0e374">Google reCAPTCHA Enterprise: Integrate the “I’m not a robot” Challenge In Vue.js</a></li><li><a href="https://blog.canopas.com/jwt-in-golang-how-to-implement-token-based-authentication-298c89a26ffd">JWT in Golang — How to Implement Token-Based Authentication</a></li><li><a href="https://canopas.com/next-js-how-to-validate-forms-on-the-server-side-using-zod">Next.js: How to validate forms on the server side using Zod</a></li></ul><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9e5fc16ab2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-secure-your-supabase-database-and-storage-ce9e5fc16ab2">How to Secure Your Supabase Database and Storage</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang — Date Time Utilities Part 2]]></title>
            <link>https://medium.com/canopas/golang-date-time-utilities-part-2-b1192eb04842?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1192eb04842</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[time-utilization]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[utilities]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 10:15:05 GMT</pubDate>
            <atom:updated>2024-01-17T10:15:05.809Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Golang — Advanced Date-Time Utility functions</strong></h3><h4>Enhancing Time Package Functionality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gOVKG8bc74ybPI1KaVNaQ.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>In the world of programming, working with dates and times is a common task that often requires precision and flexibility.</p><p>While the Go programming language’s standard library provides the time package for handling time-related operations, there are instances where developers need additional utilities to simplify time-dependent tasks.</p><p>In this blog post, we will explore a set of utility functions that serve as a wrapper around the time package to facilitate operations. If you are unaware of the <a href="https://pkg.go.dev/time"><strong>time</strong></a> package, consider referring to it before going deep with advanced utilities.</p><p>Refer to the <a href="https://blog.canopas.com/golang-time-utility-functions-you-will-always-need-d7840d091468"><strong>Time utility functions you will always need</strong></a> for basic ones.</p><p>🎯 So, let’s delve deep into implementation.</p><h3>Table of Contents</h3><pre> 1. <a href="#a398">Get Start of Month</a><br> 2. <a href="#ccd0">Get End of Month</a><br> 3. <a href="#6855">Get Start Day of Every Week</a><br> 4. <a href="#affa">Get The End Day of Every Week</a><br> 5. <a href="#53fd">Get The Start and End Day of Every Week of a Given Month</a><br> 6. <a href="#61e5">Get The Week Number of a Month From The Date</a><br> 7. <a href="#d277">Get Start of Year</a><br> 8. <a href="#e1a3">Get End of Year</a><br> 9. <a href="#1558">Get Start of Quarter</a><br>10. <a href="#9997">Get End of Quarter</a><br>11. <a href="#e54d">Get The Current Week Range</a><br>12. <a href="#98bb">Calculate Duration Between Two Dates</a><br>13. <a href="#7679">Get Dates For The Day of The Week of The Given Month</a><br>14. <a href="#d152">Add Business Days to a Date</a><br>15. <a href="#f2b3">Format Duration as Human-Readable String</a><br>- <a href="#2fb3">Conclusion</a></pre><h3>Sponsored</h3><p>Stop the habit of wishful thinking and start the habit of thoughtful wishes with <a href="https://justly.life/"><strong>Justly</strong></a>.</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>1. Get Start of Month</h3><p>The start of a month is a fundamental reference point for many date-related calculations. Let’s create a function that takes a date as input and returns the first day of the respective month as per the system’s timezone:</p><pre>func StartOfMonth(date time.Time) time.Time {<br>    return time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, date.Location())<br>}<br><br>// function called<br>StartOfMonth(time.Now())<br><br>// output<br>2024-01-01 00:00:00 +0530 IST</pre><p>This function sets the day of the month to 1, leaving the other components unchanged.</p><h3>2. Get End of Month</h3><p>Conversely, getting the end of a month is equally important. The following function returns the last second of the last day of a given month:</p><pre>func EndOfMonth(date time.Time) time.Time {<br>    firstDayOfNextMonth := StartOfMonth(date).AddDate(0, 1, 0)<br>    return firstDayOfNextMonth.Add(-time.Second)<br>}<br><br>// function called<br>EndOfMonth(time.Now())<br><br>// output<br>2024-01-31 23:59:59 +0530 IST</pre><p>This function utilizes the previously defined StartOfMonth function to find the first day of the next month and subtracts one second to obtain the end of the current month.</p><h3>3. Get Start Day of Every Week</h3><p>For tasks like creating a calendar or displaying weekly data, it’s helpful to know the starting day of each week. The following function provides the first day of the week for a given date:</p><pre>func StartOfDayOfWeek(date time.Time) time.Time {<br>    daysSinceSunday := int(date.Weekday())<br>    return date.AddDate(0, 0, -daysSinceSunday)<br>}<br><br>// function called<br>StartOfDayOfWeek(time.Now()) // time.Now() = 2024-01-16 16:00:12.901778919 +0530 IST<br><br>// output<br>2024-01-14 11:31:37.344224696 +0530 IST</pre><p>This function calculates the number of days since <strong>Sunday</strong> and subtracts this value from the given date.</p><h3>4. Get The End Day of Every Week</h3><p>Similarly, getting the last day of the week is often necessary. Here’s a function that accomplishes this:</p><pre>func EndOfDayOfWeek(date time.Time) time.Time {<br>    daysUntilSaturday := 6 - int(date.Weekday())<br>    return date.AddDate(0, 0, daysUntilSaturday)<br>}<br><br>// function called<br>EndOfDayOfWeek(time.Now()) // time.Now() = 2024-01-16 16:00:12.901778919 +0530 IST<br><br>// output<br>2024-01-20 11:31:37.344227536 +0530 IST</pre><p>This function calculates the number of days until <strong>Saturday</strong> and adds this value to the given date.</p><h3>5. Get The Start and End Day of Every Week of a Given Month</h3><p>To obtain a comprehensive view of each week in a month, we can combine the previous two functions. The following function returns a slice containing the start and end day of each week in a given month:</p><pre>func StartAndEndOfWeeksOfMonth(year, month int) []struct{ Start, End time.Time } {<br>   <br>    startOfMonth := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)<br>    weeks := make([]struct{ Start, End time.Time }, 0)<br>    <br>    for current := startOfMonth; current.Month() == time.Month(month); current = current.AddDate(0, 0, 7) {<br>        startOfWeek := StartOfDayOfWeek(current)<br>        endOfWeek := EndOfDayOfWeek(current)<br><br>        if endOfWeek.Month() != time.Month(month) {<br>            endOfWeek = EndOfMonth(current)<br>        }<br>        weeks = append(weeks, struct{ Start, End time.Time }{startOfWeek, endOfWeek})<br>    }<br><br>    return weeks<br>}<br><br>// function called<br>StartAndEndOfWeeksOfMonth(2024, 1)<br><br>// output<br>[{2023-12-31 00:00:00 +0530 IST 2024-01-06 00:00:00 +0530 IST}<br> {2024-01-07 00:00:00 +0530 IST 2024-01-13 00:00:00 +0530 IST}<br> {2024-01-14 00:00:00 +0530 IST 2024-01-20 00:00:00 +0530 IST}<br> {2024-01-21 00:00:00 +0530 IST 2024-01-27 00:00:00 +0530 IST}<br> {2024-01-28 00:00:00 +0530 IST 2024-01-31 23:59:59 +0530 IST}]</pre><p>This function iterates through each week of the given month, determining each week&#39;s start and end days.</p><h3>6. Get The Week Number of a Month From The Date</h3><p>Lastly, determining the week number of a month from a specific date can be achieved with the following function:</p><pre>func WeekNumberInMonth(date time.Time) int {<br>    startOfMonth := StartOfMonth(date)<br>    _, week := date.ISOWeek()<br>    _, startWeek := startOfMonth.ISOWeek()<br>    return week - startWeek + 1<br>}<br><br>// function called<br>WeekNumberInMonth(time.Now()) // time.Now() = 2024-01-16 16:00:12.901778919 +0530 IST<br><br>// output<br>3</pre><p>This function calculates the ISO week number of the given date and subtracts the ISO week number of the first day of the month, adding 1 to get the relative week number within the month.</p><h3>7. Get Start of Year</h3><p>To retrieve the first moment of the year for a given date, we can create a function as follows:</p><pre>func StartOfYear(date time.Time) time.Time {<br>    return time.Date(date.Year(), time.January, 1, 0, 0, 0, 0, date.Location())<br>}<br><br>// function called<br>StartOfYear(time.Now())<br><br>// output<br>2024-01-01 00:00:00 +0530 IST</pre><p>This function sets the month to January and the day to 1, providing the start of the year.</p><h3>8. Get End of Year</h3><p>Similarly, we can define a function to obtain the last second of the last day of the year:</p><pre>func EndOfYear(date time.Time) time.Time {<br>    startOfNextYear := StartOfYear(date).AddDate(1, 0, 0)<br>    return startOfNextYear.Add(-time.Second)<br>}<br><br>// function called<br>EndOfYear(time.Now())<br><br>// output<br>2024-12-31 23:59:59 +0530 IST</pre><p>This function leverages the StartOfYear function to find the first day of the next year and subtracts one second to get the end of the current year.</p><h3>9. Get Start of Quarter</h3><p>For tasks requiring quarterly data, we can create a function to obtain the start of the quarter for a given date:</p><pre>func StartOfQuarter(date time.Time) time.Time {<br>    // you can directly use 0, 1, 2, 3 quarter<br>    quarter := (int(date.Month()) - 1) / 3<br>    startMonth := time.Month(quarter * 3 + 1)<br>    return time.Date(date.Year(), startMonth, 1, 0, 0, 0, 0, date.Location())<br>}<br><br>// function called<br>StartOfQuarter(time.Now())<br><br>// output<br>2024-01-01 00:00:00 +0530 IST</pre><p>This function calculates the quarter of the given date and sets the month to the first month of that quarter.</p><h3>10. Get End of Quarter</h3><p>To complement the previous function, we can create one to find the end of the quarter for a given date:</p><pre>func EndOfQuarter(date time.Time) time.Time {<br>    startOfNextQuarter := StartOfQuarter(date).AddDate(0, 3, 0)<br>    return startOfNextQuarter.Add(-time.Second)<br>}<br><br>// function called<br>EndOfQuarter(time.Now())<br><br>// output<br>2024-03-31 23:59:59 +0530 IST</pre><p>This function utilizes the StartOfQuarter function to determine the first day of the next quarter and subtract one second to get the end of the current quarter.</p><h3>11. Get The Current Week Range</h3><p>Obtaining the start and end of the current week in a specific timezone can be useful. Here’s a function that does just that:</p><pre>func CurrentWeekRange(timeZone string) (startOfWeek, endOfWeek time.Time) {<br>    loc, _ = time.LoadLocation(timeZone)<br><br>    now := time.Now().In(loc)<br>    startOfWeek = StartOfDayOfWeek(now)<br>    endOfWeek = EndOfDayOfWeek(now)<br><br>    return startOfWeek, endOfWeek<br>}<br><br>// function called<br>start, end := CurrentWeekRange(&quot;America/New_York&quot;)<br><br>// output<br>2024-01-14 05:47:38.093990643 -0500 EST, 2024-01-20 05:47:38.093990643 -0500 EST</pre><p>This function uses the previously defined StartOfDayOfWeek and EndOfDayOfWeek functions to get the range for the current week in the specified timezone. It considers the system’s timezone unless specified.</p><h3>12. Calculate Duration Between Two Dates</h3><p>Calculating the duration between two dates is a common task. This function returns the duration between two time.Time instances</p><pre>func DurationBetween(start, end time.Time) time.Duration {<br>    return end.Sub(start)<br>}<br><br>// function called<br>DurationBetween(time.Now(), time.Now().AddDate(0, 0, 7)) // time.Now() = 2024-01-16 16:00:12.901778919 +0530 IST<br><br>// output<br>168h0m0.000000056s</pre><p>This simple utility function can be helpful when you need to measure the time elapsed between two events.</p><h3>13. Get Dates For The Day of The Week of The Given Month</h3><p>This function takes the year, month, and target day of the week as arguments and then returns a slice of time.Time values representing all occurrences of the specified day in the given month.</p><pre>func GetDatesForDayOfWeek(year, month int, day time.Weekday) []time.Time {<br>  var dates []time.Time<br>  <br>  firstDayOfMonth := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)<br>  diff := int(day) - int(firstDayOfMonth.Weekday())<br>  if diff &lt; 0 {<br>    diff += 7<br>  }<br>  <br>  firstDay := firstDayOfMonth.AddDate(0, 0, diff)<br>  for current := firstDay; current.Month() == time.Month(month); current = current.AddDate(0, 0, 7) {<br>    dates = append(dates, current)<br>  }<br>  <br>  return dates<br>}<br><br>// function called<br>GetDatesForDayOfWeek(2024, 1, time.Sunday)<br><br>// output<br>[2024-01-07 00:00:00 +0000 UTC 2024-01-14 00:00:00 +0000 UTC 2024-01-21 00:00:00 +0000 UTC 2024-01-28 00:00:00 +0000 UTC]</pre><p>This function can be customized for different months and days of the week, providing a versatile solution for obtaining specific date occurrences in a month.</p><h3>14. Add Business Days to a Date</h3><p>If your application deals with business days, this function can be handy for adding a certain number of business days to a given date:</p><pre>func AddBusinessDays(startDate time.Time, daysToAdd int) time.Time {<br>    currentDate := startDate<br>    for i := 0; i &lt; daysToAdd; {<br>        currentDate = currentDate.AddDate(0, 0, 1)<br>        if currentDate.Weekday() != time.Saturday &amp;&amp; currentDate.Weekday() != time.Sunday {<br>            i++<br>        }<br>    }<br>    return currentDate<br>}<br><br>// function called<br>AddBusinessDays(time.Now(), 50) // time.Now() = 2024-01-16 16:00:12.901778919 +0530 IST<br><br>// output<br>2024-03-26 12:21:55.727849491 +0530 IST</pre><p>This function iterates through days, skipping weekends until the desired number of business days is reached.</p><h3>15. Format Duration as Human-Readable String</h3><p>When presenting durations to users, formatting them in a human-readable way can enhance the user experience. This function converts a duration to a string in a user-friendly format:</p><pre>func FormatDuration(duration time.Duration) string {<br>    days := int(duration.Hours() / 24)<br>    hours := int(duration.Hours()) % 24<br>    minutes := int(duration.Minutes()) % 60<br>    seconds := int(duration.Seconds()) % 60<br>    return fmt.Sprintf(&quot;%dd %02dh %02dm %02ds&quot;, days, hours, minutes, seconds)<br>}<br><br>// function called<br>FormatDuration(time.Hour * 24 * 3 + time.Hour * 4 + time.Minute * 15 + time.Second * 30)<br><br>// output<br>3d 04h 15m 30s</pre><p>This function breaks down the duration into days, hours, minutes, and seconds for a more user-friendly display.</p><p><strong>Find the complete source code at — </strong><a href="https://github.com/cp-dharti-r/golang-date-time-utils"><strong>Golang: Date Time Utilities</strong></a></p><p>That’s it for today. Keep Coding! 👋</p><h3>Conclusion</h3><p>By implementing these fifteen additional advanced utility functions, we have expanded the capabilities of our date-time package wrapper, which provides developers with a comprehensive set of tools for handling various time-related operations.</p><p>Whether you&#39;re building a scheduling application, generating reports, or working on any project involving temporal data or working with daily, weekly, monthly, or quarterly data, these functions can be seamlessly integrated into your codebase to simplify complex date and time manipulations.</p><h3>Similar Useful Articles</h3><ul><li><a href="https://blog.canopas.com/golang-14-shorthand-tricks-you-might-not-know-8d8d21954c49">Golang: 14 Shorthand Tricks You Might Not Know!</a></li><li><a href="https://blog.canopas.com/golang-test-driven-development-tdd-with-gin-and-mysql-e3d353b978f8">Golang: Test-Driven Development(TDD) with Gin and MySQL</a></li><li><a href="https://blog.canopas.com/the-ultimate-guide-to-the-most-useful-go-packages-34dd0728e34d">The Ultimate Guide to the Most Useful Go Packages</a></li></ul><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1192eb04842" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/golang-date-time-utilities-part-2-b1192eb04842">Golang — Date Time Utilities Part 2</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[20 Button Effects That Will Wow Your Users]]></title>
            <link>https://medium.com/canopas/20-button-effects-that-will-wow-your-users-ea415620a692?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea415620a692</guid>
            <category><![CDATA[button-animation]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[button-design]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 10:02:21 GMT</pubDate>
            <atom:updated>2023-12-27T10:02:21.332Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unleashing the Power of Tailwind CSS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWU12icgDWwn84HDgcQQnw.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Why Do Button Effects Matter?</h3><p>Integrating button effects into simple buttons provides users with intuitive feedback and guides them through the interface.</p><p>The visual cues offered by these effects, such as changes in color or motion, immediately communicate the interactivity of the buttons, reducing uncertainty and improving user confidence.</p><p>Consistent and well-designed effects also play a role in establishing brand identity, as users may come to associate specific animations or styles with a particular brand. Furthermore, the incorporation of engaging button effects can lead to increased click-through rates, making users more likely to interact with the interface.</p><p>In this blog post, we’ll explore 20 different button effects using the popular CSS framework, <a href="https://tailwindcss.com/docs/installation"><strong>Tailwind CSS</strong></a>. These effects are not only visually stunning but also functional, providing users with a delightful and engaging interface.</p><h3>Table of Contents</h3><pre>1. <a href="#a2e6">Gradient Hover Effect</a><br>2. <a href="#f61c">Slide and Color Transition</a><br>3. <a href="#2e50">Button Fill on Hover</a><br>4. <a href="#2cb8">Unveiling Shadow &amp; Text Transition</a><br>5. <a href="#7ec5">Border Inversion on Hover</a><br>6. <a href="#2a5e">Sliding Icon on Hover</a><br>7. <a href="#ab80">Gradient Fill and Text Reveal on Hover</a><br>8. <a href="#ceab">Gradient Border Unfolding on Hover</a><br>9. <a href="#3003">Dual Transition on Hover</a><br>10. <a href="#fe6f">3D Effect with Border Transitions</a><br>11. <a href="#aff1">Gradient Hover with Ring and Shadow Effect</a><br>12. <a href="#62ea">Dotted Border Toggle on Hover</a><br>13. <a href="#25d1">Colorful Blooms on Hover</a><br>14. <a href="#cd86">Slide and Unveil on Hover</a><br>15. <a href="#1bed">Slide and Icon Transition on Hover</a><br>16. <a href="#9f0a">Skewing Background on Hover</a><br>17. <a href="#0549">Folding Corner and Slide on Hover</a><br>18. <a href="#a874">Dual Background Blend on Hover</a><br>19. <a href="#7744">Diagonal Slide and Gradient Hover</a><br>20. <a href="#efa4">Gradient Reveal and Circle Expansion on Hover</a><br>- <a href="#685f">Conclusion</a></pre><h3>Sponsored</h3><p>“Empower your journey to well-being with <a href="https://justly.life/"><strong>Justly</strong></a>. Your life is your greatest wealth — let us be your guide on the path to a happier you!”</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><p>Let’s delve deep into different types of button effects.</p><h3>1. Gradient Hover Effect</h3><p>This button effect utilizes a gradient hover effect to add a dynamic and visually appealing transition when users interact with the button. The transition is controlled by the transition and ease-out classes, ensuring a seamless and delightful effect.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-center overflow-hidden rounded-md border-4 border-double border-black px-6 py-3 font-bold text-black shadow-2xl hover:border-transparent hover:text-white&quot;&gt;<br>    &lt;span class=&quot;absolute inset-0 h-full w-full bg-gradient-to-br from-pink-600 via-purple-700 to-blue-400 opacity-0 transition duration-300 ease-out group-hover:opacity-100&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*sowC7QHYILUhfU7Q9dtlyg.gif" /><figcaption>Gradient Hover Effect</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/1jWHgDajYF"><strong>playground</strong></a>.</p><h3>2. Slide and Color Transition</h3><p>This button features a captivating effect that combines both movement and color transition. The transition effects are orchestrated using the transition-all and duration-300 classes, creating a seamless and engaging user interaction.</p><pre>&lt;button class=&quot;group relative m-1 cursor-pointer overflow-hidden rounded-md border-2 border-pink-500 px-5 py-3 font-mono font-semibold&quot;&gt;<br>    &lt;span class=&quot;ease absolute top-1/2 h-0 w-64 origin-center -translate-x-20 rotate-45 bg-pink-500 transition-all duration-300 group-hover:h-64 group-hover:-translate-y-32&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;ease relative text-pink-500 transition duration-300 group-hover:text-white&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*3dUZBcaJLgerIxgkqbxbJg.gif" /><figcaption>Slide and Color Transition</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/c63niP25r3"><strong>playground</strong></a>.</p><h3>3. Button Fill on Hover</h3><p>This button introduces a captivating effect where, upon hovering, a purple-colored background elegantly fills the button’s border. The effect is achieved through a combination of the transition-all, duration-300, and ease-out classes, providing a smooth and visually appealing transition.</p><pre>&lt;button class=&quot;group relative inline-block overflow-hidden rounded border-4 border-double border-purple-500 px-8 py-3 font-medium text-purple-600&quot;&gt;<br>    &lt;span class=&quot;absolute left-0 top-0 mb-0 flex h-full w-0 translate-x-0 transform bg-purple-600 opacity-90 transition-all duration-300 ease-out group-hover:w-full&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative group-hover:text-white&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*r3KbUxGC8Ia2-rpyFwVEAw.gif" /><figcaption>Button Fill on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/asqHCy1E6b"><strong>playground</strong></a>.</p><h3>4. Unveiling Shadow &amp; Text Transition</h3><p>This button offers a distinctive effect that unfolds as users hover over it. A rotating, shadow-casting element gradually reveals itself, creating a dynamic effect.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-start overflow-hidden rounded-full px-5 py-3 font-bold&quot;&gt;<br>    &lt;span class=&quot;absolute left-0 top-0 h-32 w-32 -translate-y-2 translate-x-12 rotate-45 bg-black opacity-[3%]&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;absolute left-0 top-0 -mt-1 h-48 w-48 -translate-x-56 -translate-y-24 rotate-45 bg-black opacity-100 transition-all duration-500 ease-in-out group-hover:-translate-x-8&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative w-full text-left text-black transition-colors duration-200 ease-in-out group-hover:text-white&quot;&gt;Button Text&lt;/span&gt;<br>    &lt;span class=&quot;absolute inset-0 rounded-full border-2 border-black&quot;&gt;&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Vsh-otPRT8bP9UflNkO7vg.gif" /><figcaption>Unveiling Shadow &amp; Text Transition</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/v1UqwSR5E3"><strong>playground</strong></a>.</p><h3>5. Border Inversion on Hover</h3><p>This button introduces a sleek effect where, upon hovering, the border color of the button undergoes a swift inversion, creating a striking contrast.</p><p>The transition effects are controlled by the transition-all, duration-100, and ease-linear classes, resulting in a visually appealing and responsive button interaction.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-start overflow-hidden rounded border-2 border-blue-600 bg-blue-600 px-5 py-3 font-medium transition-all hover:bg-white&quot;&gt;<br>    &lt;span class=&quot;absolute inset-0 rounded border-0 border-white transition-all duration-100 ease-linear group-hover:border-[25px]&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative w-full text-left text-white transition-colors duration-200 ease-in-out group-hover:text-blue-600&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*HRYC5zHrvg6MPqmcyFAINQ.gif" /><figcaption>Border Inversion on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/0yFo0zLPqg"><strong>playground</strong></a><strong>.</strong></p><h3>6. Sliding Icon on Hover</h3><p>This button’s background color transforms, and the text smoothly translates to the right. The transition effects are controlled by the transition-all, duration-300, and ease-out classes, resulting in a visually dynamic and responsive button interaction.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-center overflow-hidden border-2 border-purple-500 p-4 px-6 py-3 font-medium text-indigo-600 shadow-md transition duration-300 ease-out hover:border-4 hover:border-double&quot;&gt;<br>    &lt;span class=&quot;ease absolute inset-0 flex h-full w-full -translate-x-full items-center justify-center bg-purple-500 text-white duration-300 group-hover:translate-x-0&quot;&gt;<br>      &lt;svg class=&quot;h-6 w-6&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;&lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot; d=&quot;M14 5l7 7m0 0l-7 7m7-7H3&quot;&gt;&lt;/path&gt;&lt;/svg&gt;<br>    &lt;/span&gt;<br>    &lt;span class=&quot;ease absolute flex h-full w-full transform items-center justify-center text-purple-500 transition-all duration-300 group-hover:translate-x-full&quot;&gt;Button Text&lt;/span&gt;<br>    &lt;span class=&quot;invisible relative&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*XvnttMdPou18fvRdB6nrKw.gif" /><figcaption>Sliding Icon on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/lRM1prgN3x"><strong>playground</strong></a>.</p><h3>7. Gradient Fill and Text Reveal on Hover</h3><p>This button showcases an intricate effect where, upon hovering, a gradient background elegantly fills the button. The color transition and text reveal effects are orchestrated using the transition-all, duration-400, and ease-out classes.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-center overflow-hidden rounded-md p-0.5 font-bold&quot;&gt;<br>    &lt;span class=&quot;absolute h-full w-full bg-gradient-to-br from-[#ff8a05] via-[#ff5478] to-[#ff00c6] group-hover:from-[#ff00c6] group-hover:via-[#ff5478] group-hover:to-[#ff8a05]&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;duration-400 relative rounded-md bg-white px-6 py-3 transition-all ease-out group-hover:bg-opacity-0&quot;&gt;<br>      &lt;span class=&quot;relative bg-gradient-to-br from-[#ff8a05] via-[#ff5478] to-[#ff00c6] bg-clip-text text-transparent group-hover:text-white&quot;&gt;Button Text&lt;/span&gt;<br>    &lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*apRbpgCjGu3Ux5QkwSKIGA.gif" /><figcaption>Gradient Fill and Text Reveal on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/0Ll4ClY0JA"><strong>playground</strong></a>.</p><h3>8. Gradient Border Unfolding on Hover</h3><p>This button transition is controlled by the transition-all, duration-200, and ease-out classes. The combination of the unfolding border and text color transition results in an engaging and polished button interaction.</p><pre>&lt;button class=&quot;group relative m-1 inline-flex cursor-pointer items-center justify-center overflow-hidden rounded border-b-4 border-l-2 border-lime-700 bg-gradient-to-tr from-lime-700 to-lime-400 px-7 py-4 font-mono text-white shadow-lg hover:text-lime-800&quot;&gt;<br>    &lt;span class=&quot;absolute h-0 w-0 bg-lime-200 transition-all duration-200 ease-out group-hover:h-full group-hover:w-full&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*PcXB1Vq3VvnwJXRXzXxpTw.gif" /><figcaption>Gradient Border Unfolding on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/QzMYYsVnkL"><strong>playground</strong></a>.</p><h3>9. Dual Transition on Hover</h3><p>This button introduces a captivating dual-transition effect on hover. The transitions are controlled by the transition-all and duration classes, resulting in a seamless and polished button interaction.</p><pre>&lt;button class=&quot;group relative inline-flex items-center overflow-hidden rounded-full border-2 border-fuchsia-800 px-12 py-3 text-lg font-medium text-fuchsia-800 hover:bg-gray-50 hover:text-white&quot;&gt;<br>    &lt;span class=&quot;duration-400 ease absolute left-0 top-1/2 block h-0 w-full bg-fuchsia-800 opacity-100 transition-all group-hover:top-0 group-hover:h-full&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;ease absolute right-0 flex h-10 w-10 translate-x-full transform items-center justify-start duration-500 group-hover:-translate-x-2&quot;&gt;<br>      &lt;svg class=&quot;h-5 w-5&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;&lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot; d=&quot;M14 5l7 7m0 0l-7 7m7-7H3&quot;&gt;&lt;/path&gt;&lt;/svg&gt;<br>    &lt;/span&gt;<br>    &lt;span class=&quot;relative transform duration-700 group-hover:-translate-x-3&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Jk-_gZFv9pfRsNlz3AqY9A.gif" /><figcaption>Dual Transition on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/IftYmD7SZt"><strong>playground</strong></a>.</p><h3>10. 3D Effect with Border Transitions</h3><p>This button showcases a sophisticated 3D effect with intricate border transitions. The transitions are achieved through the transition and ease-out classes, resulting in a visually intriguing and polished button interaction.</p><pre>&lt;button class=&quot;group relative px-6 py-3 text-black&quot;&gt;<br>    &lt;span class=&quot;absolute inset-0 h-full w-full -translate-x-2 -translate-y-2 transform bg-red-200 transition duration-300 ease-out group-hover:translate-x-0 group-hover:translate-y-0&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;absolute z-[1] h-full w-full -translate-x-8 -translate-y-5 border-b-2 border-e-2 border-white group-hover:border-none&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;absolute inset-0 h-full w-full translate-x-2 translate-y-2 transform border-s-2 border-t-2 border-white bg-red-200 transition duration-300 ease-out group-hover:translate-x-0 group-hover:translate-y-0&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;absolute inset-0 z-[1] h-full w-full border-2 border-black&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*xAHrD8UYXn18-iTpYegQRA.gif" /><figcaption>3D Effect with Border Transitions</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/awQ1Ozwlio"><strong>playground</strong></a>.</p><h3>11. Gradient Hover with Ring and Shadow Effect</h3><p>This button incorporates a seamless gradient transition on hover, smoothly shifting from a solid gray background to a gradient from gray to a lighter shade. The transition effects are achieved through the transition-all and duration classes, enhancing the overall aesthetic appeal.</p><pre>&lt;button class=&quot;group relative overflow-hidden rounded bg-gray-600 px-8 py-4 text-white transition-all duration-300 ease-out hover:bg-gradient-to-r hover:from-gray-600 hover:to-gray-400 hover:ring-2 hover:ring-gray-600 hover:ring-offset-2&quot;&gt;<br>    &lt;span class=&quot;ease absolute right-0 -mt-12 h-32 w-8 translate-x-12 rotate-12 transform bg-white opacity-10 transition-all duration-700 group-hover:-translate-x-40&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*_XQbPT8aA6B2vbvqSVGegA.gif" /><figcaption>Gradient Hover with Ring and Shadow Effect</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/94URl02gyK"><strong>playground</strong></a>.</p><h3>12. Dotted Border Toggle on Hover</h3><p>This button’s transitions are controlled by the transition and ease-out classes, resulting in a smooth and polished button interaction. The text color also smoothly transitions from black to white during the hover state, enhancing the overall dynamic feel.</p><pre>&lt;button class=&quot;group relative inline-block px-4 py-2 font-medium&quot;&gt;<br>    &lt;span class=&quot;absolute inset-0 h-full w-full translate-x-1 translate-y-1 transform border-2 border-dotted border-black bg-black transition duration-200 ease-out group-hover:-translate-x-1 group-hover:-translate-y-1 group-hover:bg-white&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;absolute inset-0 h-full w-full border-2 border-dotted border-black bg-white group-hover:bg-black&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative text-black group-hover:text-white&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*pb6kAvD2RHslpKedUzREUQ.gif" /><figcaption>Dotted Border Toggle on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/VJBSikvFPp"><strong>playground</strong></a>.</p><h3>13. Colorful Blooms on Hover</h3><p>This button unfolds a mesmerizing effect, resembling blooming flowers. The transitions are orchestrated using the transition and duration classes, ensuring a smooth and delightful experience.</p><pre>&lt;button class=&quot;group relative inline-block items-center justify-center overflow-hidden rounded-lg px-8 py-5 font-medium text-indigo-600 shadow-2xl&quot;&gt;<br>    &lt;span class=&quot;ease absolute left-0 top-0 -ml-3 -mt-10 h-40 w-40 rounded-full bg-red-500 blur-md transition-all duration-700&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;ease absolute inset-0 h-full w-full transition duration-700 group-hover:rotate-180&quot;&gt;<br>      &lt;span class=&quot;absolute bottom-0 left-0 h-24 w-24 rounded-full bg-purple-500 blur-md&quot;&gt;&lt;/span&gt;<br>      &lt;span class=&quot;absolute bottom-0 right-0 h-24 w-24 rounded-full bg-blue-600 blur-md&quot;&gt;&lt;/span&gt;<br>      &lt;span class=&quot;absolute bottom-0 right-0 h-24 w-24 rounded-full bg-sky-500 blur-md&quot;&gt;&lt;/span&gt;<br>      &lt;span class=&quot;absolute bottom-0 right-0 h-24 w-24 rounded-full bg-green-500 blur-md&quot;&gt;&lt;/span&gt;<br>      &lt;span class=&quot;absolute bottom-0 right-0 -mr-10 h-24 w-24 rounded-full bg-orange-500 blur-md&quot;&gt;&lt;/span&gt;<br>      &lt;span class=&quot;absolute bottom-0 right-0 -mr-20 h-24 w-24 rounded-full bg-red-500 blur-md&quot;&gt;&lt;/span&gt;<br>    &lt;/span&gt;<br>    &lt;span class=&quot;relative text-white&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*PpJb6ajz83mxKmtVtlnGFQ.gif" /><figcaption>Colorful Blooms on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/pXEw9wgbk6"><strong>playground</strong></a>.</p><h3>14. Slide and Unveil on Hover</h3><p>This button features a sophisticated effect where, upon hovering, the text container smoothly slides to reveal a gradient background. The transitions are orchestrated using the transition and duration classes, ensuring a seamless and polished button interaction.</p><pre>&lt;button class=&quot;group relative inline-block font-mono text-lg&quot;&gt;<br>    &lt;span class=&quot;relative z-10 block overflow-hidden rounded-lg border border-blue-900 px-5 py-3 font-medium leading-tight text-blue-800 transition-colors duration-300 ease-out group-hover:border-transparent group-hover:text-white&quot;&gt;<br>      &lt;span class=&quot;absolute inset-0 h-full w-full rounded-lg bg-blue-50 px-5 py-3&quot;&gt;&lt;/span&gt;<br>      &lt;span class=&quot;ease absolute left-0 -ml-2 h-48 w-48 origin-top-right -translate-x-full translate-y-12 -rotate-90 bg-gradient-to-br from-blue-500 to-blue-900 transition-all duration-300 group-hover:-rotate-180&quot;&gt;&lt;/span&gt;<br>      &lt;span class=&quot;relative&quot;&gt;Button Text&lt;/span&gt;<br>    &lt;/span&gt;<br>    &lt;span class=&quot;absolute bottom-0 right-0 -mb-1 -mr-1 h-12 w-full rounded-lg bg-blue-900 transition-all duration-200 ease-linear group-hover:mb-0 group-hover:mr-0 group-hover:bg-transparent&quot; data-rounded=&quot;rounded-lg&quot;&gt;&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*N30yGGrQcRGJVmjGIYl-hw.gif" /><figcaption>Slide and Unveil on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/zfZ2dbZyrs"><strong>playground</strong></a>.</p><h3>15. Slide and Icon Transition on Hover</h3><p>This button incorporates a sleek effect where, upon hovering, the text container smoothly slides to reveal a background color change. The transitions are orchestrated using the transition and duration classes, ensuring a seamless and polished button interaction.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-start overflow-hidden rounded bg-indigo-50 py-3 pl-6 pr-16 font-semibold text-indigo-600 transition-all duration-150 ease-in-out hover:pl-16 hover:pr-6&quot;&gt;<br>    &lt;span class=&quot;absolute bottom-0 left-0 h-1 w-full bg-indigo-600 transition-all duration-150 ease-in-out group-hover:h-full&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;absolute right-0 pr-7 duration-200 ease-out group-hover:translate-x-12&quot;&gt;<br>      &lt;svg class=&quot;h-5 w-5 text-green-400&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;&lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot; d=&quot;M14 5l7 7m0 0l-7 7m7-7H3&quot;&gt;&lt;/path&gt;&lt;/svg&gt;<br>    &lt;/span&gt;<br>    &lt;span class=&quot;absolute left-0 -translate-x-12 pl-7 duration-200 ease-out group-hover:translate-x-0&quot;&gt;<br>      &lt;svg class=&quot;h-5 w-5 text-green-400&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;&lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot; d=&quot;M14 5l7 7m0 0l-7 7m7-7H3&quot;&gt;&lt;/path&gt;&lt;/svg&gt;<br>    &lt;/span&gt;<br>    &lt;span class=&quot;relative w-full text-left transition-colors duration-200 ease-in-out group-hover:text-white&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*sd4lL62iuXRpX_26Ocmb0Q.gif" /><figcaption>Slide and Icon Transition on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/P6CyJmaXSM"><strong>playground</strong></a>.</p><h3>16. Skewing Background on Hover</h3><p>This button’s skewing effect is controlled by the transition-all, duration-300, and ease-out classes, resulting in a polished and seamless button interaction. The text color also transforms to yellow during the hover state, enhancing the overall modern and vibrant feel.</p><pre>&lt;button class=&quot;group relative px-7 py-2 font-medium text-white hover:text-yellow-900&quot;&gt;<br>    &lt;span class=&quot;absolute inset-0 h-full w-full translate-x-0 -skew-x-12 transform bg-yellow-400 transition-all duration-300 ease-out group-hover:skew-x-0 group-hover:bg-yellow-700&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;absolute inset-0 h-full w-full skew-x-12 transform bg-yellow-700 transition-all duration-300 ease-out group-hover:-skew-x-0 group-hover:bg-yellow-400&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*HKc637zLSEAIu0Q3j7Y5Jw.gif" /><figcaption>Skewing Background on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/5em7GUV6NG"><strong>playground</strong></a>.</p><h3>17. Folding Corner and Slide on Hover</h3><p>This button presents a dynamic effect where, upon hovering, the top-right corner smoothly folds, revealing a white triangular element. The transitions are orchestrated using the transition-all, duration, and ease-in-out classes, resulting in a polished and visually engaging button interaction.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-start overflow-hidden rounded-xl bg-red-500 px-8 py-4 font-medium transition-all&quot;&gt;<br>    &lt;span class=&quot;absolute right-0 top-0 inline-block h-4 w-4 rounded bg-red-700 transition-all duration-500 ease-in-out group-hover:-mr-4 group-hover:-mt-4&quot;&gt;<br>      &lt;span class=&quot;absolute right-0 top-0 h-5 w-5 -translate-y-1/2 translate-x-1/2 rotate-45 bg-white&quot;&gt;&lt;/span&gt;<br>    &lt;/span&gt;<br>    &lt;span class=&quot;absolute bottom-0 left-0 h-full w-full -translate-x-full translate-y-full rounded-2xl bg-red-600 transition-all delay-200 duration-500 ease-in-out group-hover:mb-14 group-hover:translate-x-0&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative w-full text-left text-white transition-colors duration-200 ease-in-out group-hover:text-white&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*_9znRe5y_AvR4myCl5PG2A.gif" /><figcaption>Folding Corner and Slide on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/tfNFvLpxHe"><strong>playground</strong></a>.</p><h3>18. Dual Background Blend on Hover</h3><p>This button features a captivating effect where, upon hovering, dual backgrounds seamlessly blend into view. The transitions are controlled by the transition and duration-300 classes, ensuring a smooth and polished button interaction.</p><pre>&lt;button class=&quot;group relative rounded-lg px-6 py-3 font-bold text-white&quot;&gt;<br>    &lt;span class=&quot;ease absolute inset-0 h-full w-full -translate-x-1 -translate-y-1 transform bg-blue-800 transition duration-300 group-hover:translate-x-0 group-hover:translate-y-0&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;ease absolute inset-0 h-full w-full translate-x-1 translate-y-1 transform bg-yellow-700 mix-blend-screen transition duration-300 group-hover:translate-x-0 group-hover:translate-y-0&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*BCpCGzyk0IdYpFN6PVeEvg.gif" /><figcaption>Dual Background Blend on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/thLDGOm8Ya"><strong>playground</strong></a>.</p><h3>19. Diagonal Slide and Gradient Hover</h3><p>This button introduces a visually dynamic effect where, upon hovering, a diagonal gradient background elegantly slides into view from the bottom-left corner. The transitions are controlled by the transition-all, duration, and ease-out classes, resulting in a polished and engaging button interaction.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-start overflow-hidden rounded bg-white px-6 py-3 font-medium transition-all hover:bg-white&quot;&gt;<br>    &lt;span class=&quot;absolute bottom-0 left-0 mb-9 ml-9 h-48 w-48 -translate-x-full translate-y-full rotate-[-40deg] rounded bg-gradient-to-br from-[#ff8a05] via-[#ff5478] to-[#ff00c6] transition-all duration-500 ease-out group-hover:mb-32 group-hover:ml-0 group-hover:translate-x-0&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative w-full text-left text-black transition-colors duration-300 ease-in-out group-hover:text-white&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Iq-h_VYhQ_5yCYE8yh_0Mg.gif" /><figcaption>Diagonal Slide and Gradient Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/BHjNo4zUiJ"><strong>playground</strong></a>.</p><h3>20. Gradient Reveal and Circle Expansion on Hover</h3><p>This button showcases an elegant effect where, upon hovering, a gradient background gradually reveals itself from the top, creating a smooth transition effect. The transitions are controlled by the transition-all, duration-500, and ease-out classes, resulting in a polished and engaging button interaction.</p><pre>&lt;button class=&quot;group relative inline-flex items-center justify-center overflow-hidden rounded-lg bg-blue-800 px-10 py-4 font-mono font-medium tracking-tighter text-white&quot;&gt;<br>    &lt;span class=&quot;absolute h-0 w-0 rounded-full bg-green-500 transition-all duration-500 ease-out group-hover:h-56 group-hover:w-56&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;absolute inset-0 -mt-0 h-full w-full rounded-lg bg-gradient-to-b from-transparent to-gray-700&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;relative&quot;&gt;Button Text&lt;/span&gt;<br>&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Ym3ChVXex65u7E3e4wLolQ.gif" /><figcaption>Gradient Reveal and Circle Expansion on Hover</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/rJ51kypb8m"><strong>playground</strong></a>.</p><p>That’s it for today. Keep Animating! 👋</p><h3>Conclusion</h3><p>In the dynamic landscape of web design, the role of button effects extends far beyond mere aesthetics. The diversity showcased, from gradient fills and border inversions to sliding icons and 3D transformations, emphasizes the versatility of button effects.</p><p>So, experiment with these button effects, tailor them to your brand’s identity, and witness how the smallest details can make a significant difference. The world of button effects is expansive and ever-evolving, offering endless possibilities to create interfaces that not only meet but exceed user expectations.</p><p>To see the full demo of these captivating button effects in action, look at the <a href="https://play.tailwindcss.com/XGtVpZAyyR"><strong>playground</strong></a><strong> </strong>and<strong> </strong>witness the artistry unfold.</p><h3>Similar articles</h3><ul><li><a href="https://blog.canopas.com/tailwind-css-how-to-design-advanced-custom-animations-339aa35959f2">Tailwind CSS — How to Design Advanced Custom Animations</a></li><li><a href="https://blog.canopas.com/designing-stunning-progress-bars-made-easy-with-tailwind-css-ae620ba7b4be">Designing Stunning Progress Bars Made Easy with Tailwind CSS</a></li><li><a href="https://blog.canopas.com/tailwind-css-custom-animations-b041a1310aab">Tailwind CSS — Custom animations</a></li></ul><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea415620a692" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/20-button-effects-that-will-wow-your-users-ea415620a692">20 Button Effects That Will Wow Your Users</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Upload Made Easy in Vue.js: A Frontend Guide]]></title>
            <link>https://medium.com/canopas/file-upload-made-easy-in-vue-js-a-frontend-guide-8b2e9d8de72a?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b2e9d8de72a</guid>
            <category><![CDATA[vue-file-upload]]></category>
            <category><![CDATA[file-preview]]></category>
            <category><![CDATA[file-dropzone]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[file-upload]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 09:56:50 GMT</pubDate>
            <atom:updated>2024-01-26T06:15:32.873Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide on managing a file upload component along with a preview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaOloRFihtH5jr3dSegKZw.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3><strong>Background</strong></h3><p>In today’s web applications, users have come to expect a seamless and intuitive file upload experience, but for developers, implementing this functionality can be a complex task. Handling different file types, and sizes, and providing user-friendly previews are just a few of the challenges.</p><p>In this blog post, we will introduce you to <strong>“</strong><a href="https://github.com/canopas/web-file-upload"><strong>web-file-upload</strong></a><strong>”</strong> a powerful file upload library designed to simplify and enhance the file upload experience for <a href="https://github.com/canopas/web-file-upload/tree/main/vue"><strong>VueJs</strong></a> and <a href="https://github.com/canopas/web-file-upload/tree/main/react"><strong>React</strong></a>. With “<a href="https://www.npmjs.com/package/@canopassoftware/vue-file-upload"><strong>@canopassoftware/vue-file-upload</strong></a><strong>”</strong> you can create a polished and user-friendly file upload component with ease.</p><p>We’ll take you through the installation process, customization options, and styling tips to help you integrate this library into your Vue.js project. Whether you’re a seasoned Vue.js developer or just starting out, this tutorial will empower you to provide your users with an exceptional file upload experience.</p><p>Let’s get started!</p><h4>What we’ll implement in this blog?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZQQG7nNapvUjgqBcE0Rwg.gif" /></figure><h3>Table of Contents</h3><pre>· <a href="#671f">Use Cases and Features</a><br>· <a href="#e404">Prerequisites</a><br>· <a href="#e877">Installation</a><br>· <a href="#61f2">Register component</a><br>  ∘ <a href="#dcc8">Approach 1: Using app.component in the main entry file</a><br>  ∘ <a href="#82a3">Approach 2: Using the components option in a Vue file</a><br>· <a href="#a09e">Use Single File Upload Component</a><br>· <a href="#abe7">Use Multiple File Upload Component</a><br>· <a href="#6f0b">Conclusion</a></pre><h3>Sponsored</h3><p>Balance is not something you find; it&#39;s something you create.</p><p><a href="https://justly.life/"><strong>Justly</strong></a> helps you strike that perfect work-life balance, making room for your health and happiness.</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Use Cases and Features</h3><p>The library offers several use cases and features that can enhance the file upload experience in your Vue.js project. Here are some of the notable use cases and features of the library:</p><p><strong>1. Get a callback after each file upload:</strong></p><p>You can use the library to manage post-upload functionality using callbacks.</p><p><strong>For example,</strong></p><ul><li>You want to show a message on a successful file upload</li><li>You can save file information to a database</li><li>You want to send notifications to users upon successful file uploads</li><li>You want to show progress while uploading the files</li></ul><p><strong>2. Separate different files using appropriate icons:</strong></p><ul><li>The library can automatically display file icons based on the file type. This feature makes it easier for users to identify their uploaded files, as different file types can be represented by corresponding icons.</li></ul><p><strong>For example,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGGkgsnQoIqXu2ZI5LCk_A.png" /></figure><p><strong>3. Preview of Images, Videos, and GIFs:</strong></p><ul><li>The library includes built-in support for previewing images, videos, and GIFs. When a user uploads a file of these types, the component can display a thumbnail or preview of the content, allowing users to confirm their uploads.</li></ul><p><strong>4. File Type Validation:</strong></p><ul><li>The library allows you to specify accepted file types and validate files before uploading. You can define which file formats are allowed, ensuring that only valid files are uploaded.</li></ul><p><strong>5. Progress Indicators:</strong></p><ul><li>The library provides progress indicators during file uploads. Users can see the progress of the file being uploaded, which improves the overall user experience and transparency.</li></ul><p><strong>6. Customization Options:</strong></p><ul><li>The library offers various customization options, allowing you to tailor the file upload component to your project’s specific design and functionality requirements. You can adjust the appearance, and behavior to match your application’s needs.</li></ul><p><strong>7. User-Friendly User Interface:</strong></p><ul><li>The library offers a user-friendly and intuitive interface for selecting and uploading files. Users can easily interact with the component to add and manage their files.</li></ul><p>Also, it has provided a <a href="https://github.com/canopas/web-file-upload/tree/main/vue/examples/demo"><strong>Vue project</strong></a> with implementation. so, you can use or refer to it directly.</p><h3>Prerequisites</h3><p>Before we dive into the implementation, make sure you have the following prerequisites in place:</p><ol><li>A Vue.js project set up.</li><li>Basic knowledge of Vue.js props, events, HTML, and CSS.</li></ol><h3>Installation</h3><p>To get started, you need to install the @canopassoftware/vue-file-upload library. You can do this using either npm or yarn:</p><pre>&gt; npm install @canopassoftware/vue-file-upload<br># or<br>&gt; yarn add @canopassoftware/vue-file-upload</pre><h3>Register a component</h3><p>This library has two components to manage file upload:</p><p>1. SingleFileUpload</p><p>2. MultipleFileUpload</p><h4>Approach 1: Using <strong>app.component</strong> in the main entry file</h4><p>In this approach, we need to declare and register the components directly in your main entry file (usually main.js or main.ts) using the app.component method.</p><p>Here&#39;s how it works:</p><pre>import { createApp } from &#39;vue&#39;<br>import App from &#39;./App.vue&#39;<br>import router from &#39;./router&#39;<br><br>// import components from library<br>import { SingleFileUpload, MultipleFileUpload } from &#39;@canopassoftware/vue-file-upload&#39;<br>import &quot;@canopassoftware/vue-file-upload/style.css&quot; // import css<br><br>const app = createApp(App)<br><br>// declare components for your project<br>app.component(&#39;SingleFileUpload&#39;, SingleFileUpload)<br>app.component(&#39;MultipleFileUpload&#39;, MultipleFileUpload)<br><br>app.use(router)<br><br>app.mount(&#39;#app&#39;)</pre><ul><li>Here, we are importing two components, SingleFileUpload and MultipleFileUpload, from the library. These components are provided by the library and can be used to create file upload features in your application.</li><li>Registers the components from the library under the name SingleFileUpload and MultipleFileUpload in your Vue application. You can use this component in your templates by referencing it as &lt;SingleFileUpload /&gt; and &lt;MultipleFileUpload /&gt;.</li></ul><h4>Approach 2: Using the components option in a Vue file</h4><p>In this approach, you import and declare the components within a specific Vue file or component where you intend to use them. This is typically done in a .vue file or a script block within a component file.</p><p>Here&#39;s how it works:</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br>// import components from library<br>import { SingleFileUpload, MultipleFileUpload } from &#39;@canopassoftware/vue-file-upload&#39;<br>import &quot;@canopassoftware/vue-file-upload/style.css&quot; // import css<br><br>export default {<br>  name: &#39;IndexView&#39;,<br>  components: {<br>    SingleFileUpload,    <br>    MultipleFileUpload<br>  },<br>}<br>&lt;/script&gt;</pre><ul><li>This is a more scoped approach, as the components are only available within the scope of the component where they are declared.</li></ul><h3>Use Single File Upload Component</h3><p>Using this component we can easily manage add/update file uploading.</p><p><strong>Vue component</strong></p><pre>&lt;div class=&quot;flex flex-wrap&quot;&gt;<br>   &lt;SingleFileUpload<br>      :uploadBtn=&quot;&#39;Upload&#39;&quot;<br>      :progressBtn=&quot;&#39;Uploading...&#39;&quot;<br>      :uploadedFile=&quot;uploadedFile&quot;<br>      :callback=&quot;handleFileUploading&quot;<br>    &gt;<br>      &lt;template v-slot=&quot;file&quot;&gt;<br>        &lt;!-- add your design or use from library examples --&gt;<br>     &lt;/template&gt;<br>   &lt;/SingleFileUpload&gt;<br>&lt;/div&gt;</pre><ul><li>In this code, you create a file upload component using the SingleFileUpload component provided by the library.</li></ul><p>You pass several props to customize the behavior of the component:</p><ul><li>:uploadBtn=&quot;&#39;Upload&#39;&quot;: Sets the text for the upload button to &quot;Upload.&quot;</li><li>:progressBtn=&quot;&#39;Uploading...&#39;&quot;: Defines the text displayed on the button during the file upload process.</li><li>:uploadedFile=&quot;uploadedFile&quot;: Binds the uploadedFile data property to receive information about the uploaded file.</li><li>:callback=&quot;handleFileUploading&quot;: Binds an async handleFileUploading method for uploading files and showing the progress while uploading the file.</li></ul><p><strong>Vue component script</strong></p><pre>&lt;script lang=&quot;ts&quot;&gt;<br>export default {<br>  name: &#39;IndexView&#39;,<br>  data() {<br>    return {<br>      uploadedFile: {} as {<br>        fileType: string<br>        fileUrl: string<br>        fileName: string<br>      }<br>    }<br>  },<br>  methods: {<br>    async handleFileUploading(file: any) {<br>      // add your fileuploading logic to server and set data to the uploadedFile<br>      this.uploadedFile.fileType = &#39;image&#39; // uploaded file type<br>      this.uploadedFile.fileUrl = &#39;https://picsum.photos/300/224&#39; // uploaded file url<br>      this.uploadedFile.fileName = file.name // uploaded file name<br><br>      await new Promise((resolve) =&gt; setTimeout(resolve, 2000))<br>    },<br>  }<br>}<br>&lt;/script&gt;</pre><p>In the data function, you define the data properties used within the component:</p><ul><li>uploadedFile: An object that will hold information about the uploaded file, such as its type, URL, and name.</li><li>An async handleFileUploading method handles the uploading process of the file. With this method, the library component will handle whether a file is currently being uploaded.</li></ul><p><strong>Awesome!!</strong>👌<strong>we are done with the single file upload implementation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EE0K3OgVDfa3Qc6JvrK83w.gif" /></figure><h3>Use Multiple File Upload Component</h3><p>Using this component we can easily manage add/update files and show the preview of all the files before uploading.</p><p><strong>Vue component</strong></p><pre>&lt;div class=&quot;flex flex-wrap&quot;&gt;<br>    &lt;MultipleFileUpload<br>      :removeBtn=&quot;&#39;remove&#39;&quot;<br>      :uploadBtn=&quot;&#39;Upload&#39;&quot;<br>      :progressBtn=&quot;&#39;Uploading...&#39;&quot;<br>      :uploadedFiles=&quot;uploadedFiles&quot;<br>      :callback=&quot;handleFilesUploading&quot;<br>    &gt;<br>      &lt;template v-slot=&quot;file&quot;&gt;<br>        &lt;!-- add your design or use from library examples --&gt;<br>      &lt;/template&gt;<br>    &lt;/MultipleFileUpload&gt;<br>  &lt;/div&gt;</pre><p>In this code, you create a file upload component using the MultipleFileUpload component provided by the library.</p><p>You pass several props to customize the behavior of the component:</p><ul><li>:removeBtn=&quot;&#39;remove&#39;&quot;: Sets the text for the button to remove selected or already uploaded files.</li><li>:uploadBtn=&quot;&#39;Upload&#39;&quot;: Sets the text for the button.</li><li>:progressBtn=&quot;&#39;Uploading...&#39;&quot;: Defines the text displayed on the button during the file upload process.</li><li>:uploadedFiles=&quot;uploadedFiles&quot;: Binds this data property to store information about the uploaded files.</li><li>:callback=&quot;handleFilesUploading&quot;: Binds an async handleFilesUploading method for uploading files and showing the progress while uploading the files.</li></ul><p><strong>Vue component script</strong></p><pre>&lt;script lang=&quot;ts&quot;&gt;<br>export default {<br>  name: &#39;IndexView&#39;,<br>  data() {<br>    return {<br>      uploadedFiles: [] as Array&lt;{<br>        fileType: string<br>        fileUrl: string<br>        fileName: string<br>      }&gt;<br>    }<br>  },<br>  methods: {<br>    async handleFilesUploading(files: any) {<br>      this.uploadedFiles = []<br><br>      // add your fileuploading logic to server and set data to the uploadedFiles<br>      for (var i = 0; i &lt; files.length; i++) {<br>        this.uploadedFiles.push({<br>          fileType: &#39;image&#39;, // uploaded file type<br>          fileUrl: &#39;https://picsum.photos/300/224&#39;, // uploaded file url<br>          fileName: &#39;example-image.jpg&#39; // uploaded file name<br>        })<br>      }<br><br>      await new Promise((resolve) =&gt; setTimeout(resolve, 2000))<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><p>In the data function, you define the data properties used within the component:</p><ul><li>uploadedFiles: An array that will hold information about the uploaded files, where each file is represented as an object with properties for type, URL, and name.</li><li>An async handleFilesUploading method handles the uploading process of the file. With this method, the library component will handle whether a file is currently being uploaded.</li></ul><p>𝐓𝐚-𝐝𝐚!! 🎉 <strong>we have</strong> <strong>completed the multiple file upload component implementation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tnhIATNx7MeHVWpgogsEg.gif" /></figure><h3>Conclusion</h3><p>By following this guide, you’ve learned how to integrate @canopassoftware/vue-file-upload into your Vue.js project, allowing you to create a file upload component that is not only functional but also visually appealing. You can customize it to match your project’s design, and file type restrictions.</p><p>As you continue to build and improve your web applications, remember that a great file upload experience can make a significant difference in user satisfaction and engagement. With @canopassoftware/vue-file-upload at your disposal, you have the tools to provide your users with a top-tier file-uploading experience.</p><p>We encourage you to explore the library further, experiment with its features, and adapt it to your unique project requirements. Suggestions are most welcome, and if you have any doubts then drop them into the library.</p><p>We hope this guide can help build your web applications.</p><p>Thanks for reading!! 👋👋👋</p><h3>Similar Articles</h3><ul><li><a href="https://blog.canopas.com/designing-stunning-progress-bars-made-easy-with-tailwind-css-ae620ba7b4be">Designing Stunning Progress Bars Made Easy with Tailwind CSS</a></li><li><a href="https://blog.canopas.com/vue-3-component-testing-with-jest-8b80a8a8946b">Vue 3 component testing with Jest</a></li><li><a href="https://blog.canopas.com/integrate-google-recaptcha-enterprise-using-vue-js-and-golang-60a9335e80ac">Integrate Google Recaptcha Enterprise using Vue.js and Golang</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback is most welcome as always, drop them below in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b2e9d8de72a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/file-upload-made-easy-in-vue-js-a-frontend-guide-8b2e9d8de72a">File Upload Made Easy in Vue.js: A Frontend Guide</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to configure SSR in Nuxt3 and deploy it with Serverless Architecture]]></title>
            <link>https://medium.com/canopas/how-to-configure-ssr-in-nuxt3-and-deploy-it-with-serverless-architecture-f86e63ae8b8d?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/f86e63ae8b8d</guid>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[ssrs]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 12:07:49 GMT</pubDate>
            <atom:updated>2023-10-02T09:51:49.226Z</atom:updated>
            <content:encoded><![CDATA[<h4>SEO optimization, high performance, and cost-effective scaling.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCPHnxHu3K8tq4OV6pGkjQ.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p><strong>Serverless:</strong> In a serverless architecture, developers write and deploy code in the form of functions or services without the need to manage servers or worry about infrastructure scaling.</p><p><strong>Server-Side Rendering (SSR):</strong> It is a technique used in web development to render web pages on the server and then send the fully rendered HTML to the client(browser).</p><p>This is in contrast to traditional client-side rendering (CSR), where a web page’s HTML structure is initially delivered to the browser, and then JavaScript is used to populate and render the content.</p><p>Using <strong>Nuxt 3</strong> for SSR with a serverless architecture combines the benefits of a powerful SSR framework with the ease of serverless deployment. This combination can lead to faster development, improved SEO, enhanced user experience, and cost-effective scaling for your web applications.</p><h3>Table of Contents</h3><pre>- <a href="#2b07">Why SSR(Server-Side-Rendering)?</a><br>- <a href="#44c6">Why serverless approach?</a><br>- <a href="#f618">Prerequisites</a><br>- <a href="#189a">Nitro Overview</a><br>- <a href="#d7e2">AWS Lambda Configuration using Nitro</a><br>- <a href="#16ab">Add your code to s3</a><br>- <a href="#94b5">Create Cloudformation stack using AWS CLI</a><br>- <a href="#8adb">Create AWS Lambda Execution Role</a><br>- <a href="#a368">Create AWS Lambda function using Cloudformation</a><br>- <a href="#31c9">Create API Gateway resource using Cloudformation</a><br>- <a href="#8466">Create API Gateway method, resource, and proxy using Cloudformation</a><br>- <a href="#0b25">Lambda permission</a><br>- <a href="#3fee">Configure custom domain to access API Gateways using Cloudformation</a><br>- <a href="#213d">Sitemap</a><br>- <a href="#25d2">Conclusion</a></pre><h3>Sponsored</h3><p>We know that achieving goals and improving quality of life can be a challenging process. <a href="https://justly.life/"><strong>Justly</strong></a> is designed to provide the guidance and support needed to achieve your goals.</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Why SSR(Server-Side-Rendering)?</h3><p>SSR comes with several benefits as below.</p><p>1.<strong> SEO and Performance:</strong> SSR can improve SEO because search engines can crawl fully-rendered HTML content. It can also improve initial page load performance by sending pre-rendered content to the client.</p><p>2. <strong>Full Control:</strong> With SSR, you have more control over the rendering process, allowing you to customize how content is served to users.</p><p>3. <strong>Offline Support: </strong>SSR can provide better offline support because some content is pre-rendered on the server and can be cached for offline use.</p><p>4. <strong>Security: S</strong>SR can enhance security by keeping sensitive code and data on the server, reducing exposure to client-side attacks.</p><p>5. <strong>Complexity: </strong>SSR can simplify some aspects of web development, particularly when dealing with data fetching and authentication.</p><h3>Why Serverless Approach?</h3><p>1.<strong> Scalability: </strong>Serverless architectures, such as AWS Lambda or Azure Functions, automatically scale based on incoming traffic. You only pay for the actual computing resources used, making it cost-efficient.</p><p>2. <strong>Cost Efficiency: </strong>With serverless, you don’t need to maintain and pay for dedicated servers. You’re billed per execution, which can be more cost-effective for low to moderate-traffic applications.</p><p>3. <strong>Deployment and Maintenance:</strong> Serverless providers handle server maintenance and updates, reducing the operational overhead for your development team.</p><p>4. <strong>Flexibility:</strong> Serverless allows you to focus on writing code and building features without worrying about infrastructure. It’s well-suited for event-driven and microservices architectures.</p><h3>Prerequisites</h3><p>Before we begin, make sure you have the following:</p><ul><li>Node.js and npm are installed on your development machine.</li><li>A Nuxt 3 project set up or just create it with npx nuxi@latest init &lt;project-name&gt; .</li></ul><h3>Nitro Overview</h3><p>Nitro can generate different output formats suitable for different hosting providers from the same code base.</p><p>Using built-in presets, you can easily configure Nitro to adjust its output format with almost no additional code or configuration!</p><h3>AWS Lambda Configuration using Nitro</h3><p>A Nuxt application can be deployed on a Node.js server, pre-rendered for static hosting, or deployed to serverless or edge (CDN) environments.</p><p>When running nuxt build with the Node server preset, the result will be an entry point that launches a ready-to-run Node server.</p><pre>&gt; node .output/server/index.mjs</pre><p>Nitro provides a built-in preset to generate an output format compatible with <a href="https://aws.amazon.com/lambda/">AWS Lambda</a>.</p><p>The output entry point in .output/server/index.mjs is compatible with AWS Lambda format.</p><p>Nitro output, by default, uses dynamic chunks for lazy loading code only when needed. However, this sometimes can not be ideal for performance. You can enable chunk inlining behavior using inlineDynamicImports config.</p><p><strong>nuxt.config.ts</strong></p><pre>import { defineNuxtConfig } from &quot;nuxt/config&quot;;<br><br>export default defineNuxtConfig({<br>  app: {<br>    head: {<br>      title: &quot;Title of your website&quot;,<br>      htmlAttrs: {<br>        lang: &quot;en&quot;,<br>      },<br>      meta: [<br>        { charset: &quot;utf-8&quot; },<br>        { name: &quot;viewport&quot;, content: &quot;width=device-width, initial-scale=1&quot; },<br>        { hid: &quot;description&quot;, name: &quot;description&quot;, content: &quot;&quot; },<br>        { name: &quot;format-detection&quot;, content: &quot;telephone=no&quot; },<br>      ],<br>    },<br>  },<br><br>  devtools: { enabled: true },<br><br>  nitro: {<br>    preset: &quot;aws-lambda&quot;,<br>    inlineDynamicImports: true,<br>    serveStatic: true,<br>  },  <br>});</pre><h3>Add your code to s3</h3><p>For making a lambda function to serve our code, we need to give it a zip of our code. Let’s upload the code zip to s3(a smaller zip can be uploaded without s3 as well).</p><p>Install aws-cli on your machine and execute the following commands to set up AWS CLI operations.</p><pre>- aws configure set aws_access_key_id your_aws_acces_key_id<br>- aws configure set aws_secret_access_key your_aws_secret_access_key<br>- aws configure set region your_aws_region<br>- aws s3 cp test_lambda.zip s3://your_aws_bucket</pre><ul><li><strong>test_lambda.zip</strong> contains the actual code of the website which will be deployed on AWS Lambda.</li><li>aws s3 cp command will copy the zip file<strong> </strong>to AWS S3.</li></ul><h3>Create Cloudformation stack using AWS CLI</h3><p>As we have our code handy at s3, let’s address it and create a Clouformation stack. But, Before creating the stack directly I would recommend <strong>validating</strong> the template, that we will use for stack creation.</p><h4><strong>Validate Cloudformation template</strong></h4><pre>- aws cloudformation validate-template --template-body file://serverless_deployment.yml</pre><p>After a successful validation check, let’s create a stack. If any misconfiguration will be there, validation will fail with errors.</p><h4><strong>Create Cloudformation stack using AWS CLI</strong></h4><pre>- aws cloudformation deploy --stack-name test-lambda-stack --template-file serverless_deployment.yml --parameter-overrides <br>      CustomDomainName=example.com ApiGatewayStageName=prod ApiGatewayName=test-web-api<br>      LambdaName=test-website-lambda LambdaBucket=lambda-test-bucket LambdaUrl=test_lambda.zip LambdaRoleArnName=LambdaRole-TestWeb<br>      LambdaFunctionArnName=LambdaArn-TestWeb LambdaRoleName=test-website-lambda-role<br>      --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM</pre><ul><li><strong>stack-name: </strong>A name of the stack we want to create(can be customized).</li><li><strong>template-file: </strong>Path of the Cloudformation template</li><li><strong>parameter-overrides: </strong>Parameters we want to override in the Cloudformation template</li><li><strong>capabilities</strong>: A list of capabilities required to permit AWS Cloudformation to create certain resources like IAM.</li></ul><p>Visit <a href="https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html"><strong>Cloudformation stack deploy using AWS CLI</strong> </a>for more information.</p><h3>Create AWS Lambda Execution Role</h3><p>Let’s create a Lambda execution role, that is required to develop the Lambda function.</p><p>Clouformation creates resources from the <strong>Resources </strong>attributes of the template and gives outcomes as <strong>Outputs </strong>attributes of the template<strong>.</strong></p><p><strong>serverless_deployment.yml</strong></p><pre>AWSTemplateFormatVersion: &quot;2010-09-09&quot;<br>Transform: AWS::Serverless-2016-10-31<br>Description: &gt;<br>  Test website SSR with AWS Lambda<br>Parameters:<br>  LambdaBucket:<br>    Type: String<br>    Description: AWS bucket, where lambda function is stored<br>  LambdaUrl:<br>    Type: String<br>    Description: Path of lambda<br>  LambdaRoleName:<br>    Type: String<br>    Description: Name of the lambda role<br>  LambdaName:<br>    Type: String<br>    Description: Name of the lambda function<br>  LambdaRoleArnName:<br>    Type: String<br>    Description: ARN Name of the role attached with lambda function<br>  LambdaFunctionArnName:<br>    Type: String<br>    Description: Name of the lambda function ARN<br>  ApiGatewayStageName:<br>    Type: String<br>    Description: ApiGateway stage name<br>  ApiGatewayName:<br>    Type: String<br>    Description: ApiGateway name<br>  CustomDomainName:<br>    Type: String<br>    Description: Name of the custom domain<br><br>Outputs:<br>  LambdaRoleARN:<br>    Description: Role for Lambda execution.<br>    Value:<br>      Fn::GetAtt:<br>        - LambdaExecutionRole<br>        - Arn<br>    Export:<br>      Name: !Ref &quot;LambdaRoleArnName&quot;<br>  <br>Resources:<br>  LambdaExecutionRole:<br>    Type: AWS::IAM::Role<br>    Properties:<br>      RoleName: !Ref &quot;LambdaRoleName&quot;<br>      AssumeRolePolicyDocument:<br>        Version: 2012-10-17<br>        Statement:<br>          - Effect: &quot;Allow&quot;<br>            Principal:<br>              Service:<br>                - &quot;lambda.amazonaws.com&quot;<br>            Action: &quot;sts:AssumeRole&quot;<br>      ManagedPolicyArns:<br>        - &quot;arn:aws:iam::aws:policy/AWSLambdaExecute&quot;<br>        - &quot;arn:aws:iam::aws:policy/AmazonS3FullAccess&quot;<br>        - &quot;arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess&quot;<br>        - &quot;arn:aws:iam::aws:policy/AmazonKinesisFullAccess&quot;<br>      Path: &quot;/&quot;</pre><p>The above snippet will create a resource <strong>LambdaExecutionRole, </strong>which will be used to grant required permissions lambda function<strong>.</strong></p><ul><li><strong>LambdaExecutionRole</strong> — A Lambda execution role resource name(can be customized).</li><li><strong>AWS::IAM::Role — </strong>it represents<strong> </strong>the type of resource we want to create(just like a type of variable), it will be different for different resources.</li><li><strong>Properties — </strong>it gives several options like RoleName, RoleArn, AssumeRolePolicyDocument, ManagePolicyArns, etc.</li></ul><p>Explore more at <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html"><strong>Cloudformation IAM Role template format</strong></a> for more details.</p><h3>Create AWS Lambda function using Cloudformation</h3><p>Let’s create a Lambda function, that is required to run or code without setting up the development environment.</p><p>As we have seen in the creation of the LambdaExecutionRole, we will need resources and outputs for Lambda, too.</p><pre>Resources:<br>  LambdaFunction:<br>    Type: AWS::Lambda::Function<br>    DependsOn:<br>      - LambdaExecutionRole<br>    Properties:<br>      FunctionName: !Ref &quot;LambdaName&quot;<br>      Description: LambdaFunction for test website<br>      Runtime: &quot;nodejs18.x&quot;<br>      Code:<br>        S3Bucket: !Ref &quot;LambdaBucket&quot;<br>        S3Key: !Ref &quot;LambdaUrl&quot;<br>      Handler: .output/server/index.handler<br>      MemorySize: 256<br>      Timeout: 100<br>      Role: !GetAtt &quot;LambdaExecutionRole.Arn&quot;</pre><ul><li><strong>LambdaFunction</strong> — A Lambda function resource name(custom).</li><li><strong>AWS::Lambda::Function</strong> — It’s the default type for creating a lambda function.</li><li><strong>Properties</strong> — it consists of several entities like FunctionName, Runtime, Code, Handler, Role, Environment, etc.</li></ul><p>Visit the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html"><strong>AWS Lambda function template Cloudformation</strong></a> to get deeper details.</p><h3>Create API Gateway resource using Cloudformation</h3><p>Now as we already created a lambda function, it’s time to integrate it with API Gateway.</p><p>Let’s create an API gateway resource using Cloudformation.</p><pre>Resources:<br>  ApiGateway:<br>    Type: AWS::ApiGateway::RestApi<br>    Properties:<br>      Description: Test Web API Gateway<br>      EndpointConfiguration:<br>        Types:<br>          - REGIONAL<br>      BinaryMediaTypes: [&quot;*/*&quot;]<br>      DisableExecuteApiEndpoint: false<br>      MinimumCompressionSize: 100<br>      Name: !Ref &quot;ApiGatewayName&quot;<br><br>Outputs:<br>  ApiGatewayInvokeURL:<br>    Value: !Sub https://${ApiGateway}.execute-api.${AWS::Region}.amazonaws.com/${ApiGatewayStageName}</pre><ul><li><strong>ApiGateway</strong> — A name for API gateway resource.</li><li><strong>AWS::ApiGateway::RestApi</strong> — It’s the default type for creating an API Gateway.</li><li><strong>Properties</strong> — It consists of several attributes like Description, EndpointConfiuration, Name, DisableExecuteApiEndpoint, etc.</li></ul><p><strong>Notes:</strong></p><ul><li>If you add DisableExecuteApiEndpoint: true, the endpoint returned by API Gateway(default) won’t work. So, if you want to integrate a custom domain with an API gateway, you can make it true otherwise it should be false.</li><li>If you want the API Gateway should respond to all kinds of files like .png or .jpg you just need to provide the <strong>BinaryMediaTypes </strong>field.</li></ul><p>Refer <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html"><strong>API Gateway RestAPI template</strong></a> for more details.</p><h3>Create API Gateway method, resource, and proxy using Cloudformation</h3><p>We have already created API Gateway, now it’s time to saturate it with required details like root method and proxy method.</p><p><strong>API Gateway Method</strong></p><pre>Resources:<br>  ApiGatewayRootMethod:<br>    Type: AWS::ApiGateway::Method<br>    Properties:<br>      AuthorizationType: NONE<br>      HttpMethod: ANY<br>      Integration:<br>        IntegrationHttpMethod: POST<br>        Type: AWS_PROXY<br>        Uri: !Sub<br>          - arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations<br>          - lambdaArn: !GetAtt LambdaFunction.Arn<br>      ResourceId: !GetAtt ApiGateway.RootResourceId<br>      RestApiId: !Ref ApiGateway</pre><ul><li><strong>ApiGatewayRootMethod</strong> — It’s the name of the API Gateway resource</li><li><strong>AWS::ApiGateway::Method</strong> — API Gateway methods that define the parameters and body that clients must send in their requests</li><li><strong>Properties</strong> — It consists of several attributes like AuthorizationType, HTTPMethod, Integration, RestApiId, etc.</li></ul><h4><strong>API Gateway Resource</strong></h4><pre>Resources:<br>  ApiGatewayRootResource:<br>    Type: AWS::ApiGateway::Resource<br>    DependsOn:<br>      - ApiGatewayRootMethod<br>    Properties:<br>      RestApiId: !Ref ApiGateway<br>      ParentId: !GetAtt ApiGateway.RootResourceId<br>      PathPart: &quot;{proxy+}&quot;</pre><ul><li><strong>ApiGatewayRootResource</strong> — API Gateway resource name.</li><li><strong>AWS::ApiGateway::Resource</strong> — It creates a resource for an API.</li><li><strong>Properties</strong> — It consists of properties like RestApiId, ParentId, PathPart, etc.</li></ul><h4><strong>AWS Lambda proxy method</strong></h4><pre>Resources:<br>  ApiGatewayResourceProxyMethod:<br>    Type: AWS::ApiGateway::Method<br>    DependsOn:<br>      - ApiGatewayRootResource<br>    Properties:<br>      AuthorizationType: NONE<br>      HttpMethod: ANY<br>      Integration:<br>        IntegrationHttpMethod: POST<br>        Type: AWS_PROXY<br>        Uri: !Sub<br>          - arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations<br>          - lambdaArn: !GetAtt LambdaFunction.Arn<br>      ResourceId: !Ref ApiGatewayRootResource<br>      RestApiId: !Ref ApiGateway</pre><p>It’s used to enable APIs to call a Lambda function with a single integration setup on a catch-all ANY method.</p><p>For example,<br>CRUD operations consist of multiple request methods such as POST, GET, PUT, and DELETE and we don’t need to specify all of them to invoke our lambda.</p><h3>Lambda permission</h3><p>Create a Lambda permission to grant API Gateway permission to invoke the Lambda function using Cloudformation</p><p>As we are already done with the API Gateway configuration.<br>Let’s permit our API Gateway to invoke the earlier created Lambda function and deploy it.</p><pre>Resources:<br>  LambdaApiGatewayInvoke:<br>    Type: AWS::Lambda::Permission<br>    Properties:<br>      Action: lambda:InvokeFunction<br>      FunctionName: !GetAtt LambdaFunction.Arn<br>      Principal: apigateway.amazonaws.com<br>      SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGateway}/*/*/*<br><br>  ApiGatewayDeployment:<br>    Type: AWS::ApiGateway::Deployment<br>    DependsOn:<br>      - ApiGatewayResourceProxyMethod<br>    Properties:<br>      RestApiId: !Ref ApiGateway<br>      StageName: !Ref ApiGatewayStageName</pre><ul><li><strong>LambdaApiGatewayInvoke</strong> — A name of Lambda function permission resource.</li><li><strong>AWS::Lambda::Permission</strong> — It grants an AWS service or another account permission to use a function.</li><li><strong>Properties</strong> — It consists of attributes like Action, FucntionName, Principal, SourceArn, etc.</li><li><strong>ApiGatewayDeployment</strong> — A name of API Gateway deployment resource.</li><li><strong>AWS::ApiGateway::Deployment</strong> — It deploys an API Gateway RestApi resource to a stage so that clients can call the API over the internet</li><li><strong>Properties</strong> — It consists of attributes like RestApiId, StageName, etc.</li></ul><p>Visit <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html"><strong>Lambda Invoke Permission</strong></a> and <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html"><strong>API Gateway Deployment</strong></a> for more information.</p><h3>Configure custom domain to access API Gateways using Cloudformation(optional)</h3><p>By default, API Gateway provides a default route using which we can access our application routes, but it keeps changing on every deployment.</p><p>Hence, we need to bind it with the custom domain, which will remain constant, doesn’t matter API gateway changes though.</p><pre>Resources:<br>  ApiGatewayCustomDomainMapping:<br>    Type: AWS::ApiGateway::BasePathMapping<br>    DependsOn:<br>      - ApiGatewayDeployment<br>    Properties:<br>      DomainName: !Ref CustomDomainName<br>      RestApiId: !Ref ApiGateway<br>      Stage: !Ref ApiGatewayStageName</pre><ul><li><strong>ApiGatewayCustomDomainMapping</strong> — A name for custom domain mapping resource.</li><li><strong>AWS::ApiGateway::BasePathMapping</strong> — It creates a base path that clients who call your API must use in the invocation URL</li><li><strong>Properties</strong> — It consists of attributes such as DomainName, RestApiId, and Stage.</li></ul><p>Refer <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-basepathmapping.html"><strong>CustomDomain mapping template</strong></a> and <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html"><strong>API Gateway Custom domain mapping</strong></a> for more details.</p><h3>Sitemap</h3><p>A sitemap is a valuable tool for website owners and webmasters as it provides a structured list of web pages on a site, allowing search engines and users to easily navigate and understand the website’s structure.</p><p><strong>nuxt.config.ts</strong></p><pre>import { defineNuxtConfig } from &quot;nuxt/config&quot;;<br><br>export default defineNuxtConfig({<br>  app: {<br>    head: {<br>      title: &quot;Title of your website&quot;,<br>      htmlAttrs: {<br>        lang: &quot;en&quot;,<br>      },<br>      meta: [<br>        { charset: &quot;utf-8&quot; },<br>        { name: &quot;viewport&quot;, content: &quot;width=device-width, initial-scale=1&quot; },<br>        { hid: &quot;description&quot;, name: &quot;description&quot;, content: &quot;&quot; },<br>        { name: &quot;format-detection&quot;, content: &quot;telephone=no&quot; },<br>      ],<br>    },<br>  },<br><br>  devtools: { enabled: true },<br><br>  nitro: {<br>    preset: &quot;aws-lambda&quot;,<br>    inlineDynamicImports: true,<br>    serveStatic: true,<br>  },<br><br>  sitemap: {<br>    urls: [<br>      {<br>        loc: &quot;/&quot;,<br>        changefreq: &quot;monthly&quot;,<br>        lastmod: new Date(),<br>        priority: 1,<br>      },<br>      {<br>        loc: &quot;/resources&quot;,<br>        changefreq: &quot;monthly&quot;,<br>        lastmod: new Date(),<br>        priority: 0.8,<br>      },<br>      {<br>        loc: &quot;/community&quot;,<br>        changefreq: &quot;monthly&quot;,<br>        lastmod: new Date(),<br>        priority: 0.9,<br>      },<br>      {<br>        loc: &quot;/blog&quot;,<br>        changefreq: &quot;daily&quot;,<br>        lastmod: new Date(),<br>        priority: 0.9,<br>      },<br>    ],<br>  },<br>});</pre><p>Overall, sitemaps contribute to a more efficient and effective online presence by aiding in SEO efforts, enhancing user experience, and assisting in content management and organization. They are a valuable tool for both website owners and their visitors.</p><h3>Conclusion</h3><p>In this blog post, we’ve explored how to deploy a serverless SSR website using Nuxt 3 and AWS Lambda. This approach combines the benefits of serverless computing with the power of Nuxt 3’s SSR capabilities. It simplifies the deployment process and allows you to focus on building exceptional web experiences.</p><p>Serverless SSR is a great choice for applications that require SEO optimization, high performance, and cost-effective scaling. As you continue to develop your Nuxt 3 projects, consider serverless deployment options to streamline your development workflow and improve your users’ experience.</p><p>Thanks for reading!! 👋</p><h3>Similar Articles</h3><ul><li><a href="https://blog.canopas.com/deploy-a-website-with-aws-s3-cloudfront-using-cloudformation-c2199dc6c435">Deploy a website with AWS S3 + CloudFront using CloudFormation</a></li><li><a href="https://blog.canopas.com/simplified-your-deployment-github-workflow-with-ec2-ecr-and-docker-4c9c392d238d">Simplified Your Deployment: GitHub Workflow with EC2, ECR, and Docker</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback is most welcome as always, drop them below in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f86e63ae8b8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-configure-ssr-in-nuxt3-and-deploy-it-with-serverless-architecture-f86e63ae8b8d">How to configure SSR in Nuxt3 and deploy it with Serverless Architecture</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: Test-Driven Development(TDD) with Gin and MySQL]]></title>
            <link>https://medium.com/canopas/golang-test-driven-development-tdd-with-gin-and-mysql-e3d353b978f8?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3d353b978f8</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 10:03:24 GMT</pubDate>
            <atom:updated>2023-08-17T10:03:24.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unleashing the power of writing tests</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSJojCt2CUGth6rD47guOw.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>Test-Driven Development (TDD) is a software development technique in which <strong>You write tests for a piece of code before you write the code itself.</strong></p><p>The tests are used to define the desired behavior of the code and to ensure that the code meets those requirements. The process of writing the tests first helps to ensure that the code is testable and that it meets the requirements of the user or client.</p><p>TDD helps to catch bugs early in the development process and to ensure that the code is maintainable and easy to understand. It also promotes a test-first mindset and encourages the developer to think about the requirements and the desired behavior of the code before writing it.</p><p>Throughout this blog, I’m assuming that you’re familiar with the basic workings of Golang like package importing and all.</p><h3>Table of Contents</h3><pre>* <a href="#2a31">How TDD works?</a><br>* <a href="#6aaa">Define API Routes, Struct, and functions</a><br>* <a href="#0cb8">Create User using TDD</a><br>* <a href="#f7ad">Get User using TDD</a><br>* <a href="#3dc0">Update User using TDD</a><br>* <a href="#ee09">Delete User using TDD</a><br>* <a href="#5033">Final Thoughts</a></pre><h3>Sponsored</h3><p>We believe that everyone deserves the opportunity to succeed and thrive, and <a href="https://justly.life/"><strong>Justly</strong></a> is designed to provide the guidance and support needed to make that a reality.</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>How TDD works?</h3><p><strong>TDD is an iterative process that follows these steps.</strong></p><ol><li>Write a test for a small piece of functionality that doesn’t exist yet.</li><li>Run the test, which should fail because the code doesn’t exist yet.</li><li>Write the minimum amount of code necessary to make the test pass.</li><li>Rerun the test, which should now pass because the code has been written.</li><li>Refactor the code if necessary, making sure that all tests still pass.</li><li>Repeat the process for the next piece of functionality.</li></ol><p><strong>Let’s examine the above steps with a basic example of a sum function. Which calculates the sum of two values.</strong></p><ol><li>Write a test for the function that asserts the expected output is valid for a given input.</li></ol><pre>func TestSum(t *testing.T) {<br>  if sum := Sum(2, 3); sum != 5 {<br>    t.Errorf(&quot;Sum(2, 3) = %d; want 5&quot;, sum)<br>  }<br>  if sum := Sum(0, 0); sum != 0 {<br>    t.Errorf(&quot;Sum(0, 0) = %d; want 0&quot;, sum)<br>  }<br>  if sum := Sum(-2, 2); sum != 0 {<br>    t.Errorf(&quot;Sum(-2, 2) = %d; want 0&quot;, sum)<br>  }<br>  if sum := Sum(-5, 5); sum != 0 {<br>    t.Errorf(&quot;Sum(-5, 5) = %d; want 0&quot;, sum)<br>  }<br>  if sum := Sum(0.5, 0.3); sum != 0.8 {<br>    t.Errorf(&quot;Sum(0.5, 0.3) = %f; want 0.8&quot;, sum)<br>  }<br>}</pre><p>2. Run the test and you will see the test fails, as the Sum function has not been implemented yet.</p><p>3. Write the minimal amount of code to make the test pass. For example:</p><pre>func Sum(a, b float64) float64 {<br>    return a + b<br>}</pre><p>4. Run the test again and see that it passes.</p><p>5. Refactor the code if necessary, and write more test cases to ensure full coverage.</p><p>6. Repeat steps 2–5 as needed until you are satisfied that the function is correct and complete.</p><p>Golang does not have built-in support for floating-point comparison so you might use the assert package for that.</p><p>It’s easy to test simple/one-liners compared to testing complex functionalities. Let’s have a look at how to test APIs along with the Implementation.</p><h3>Define API Routes, Struct, and functions</h3><p>In Golang, the Gin framework is commonly used to create RESTful APIs and handle routes. Here we will see how you might define routes for CRUD operation APIs using Gin.</p><p>For example, Let’s say you want to create endpoints that perform CRUD operations for a user. Like,</p><ul><li>Show all the user&#39;s information,</li><li>Take in a user ID and return the user’s information,</li><li>Create a user,</li><li>Take in a user ID and update user information,</li><li>Take in a user ID and delete a user.</li></ul><p>Add the below routes as in main.go file.</p><pre>package main<br><br>import (<br>  &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func main() {<br>  router := gin.Default()<br><br>  router.POST(&quot;/api/users&quot;, Create)<br>  router.GET(&quot;/api/users/:id&quot;, Get)<br>  router.PUT(&quot;/api/users/:id&quot;, Update)<br>  router.DELETE(&quot;/api/users/:id&quot;, Delete)<br><br>  router.Run()<br>}</pre><p>In this example, four routes are defined respectively to fetch, create, update, and delete the user.</p><p>Define the struct and functions that are needed by API routes in the user.go file.</p><pre>type User struct {<br>  Id    int    `json:&quot;id&quot;`<br>  Name  string `json:&quot;name&quot;`<br>  Email string `json:&quot;email&quot;`<br>}<br><br>// create user<br>func Create(c *gin.Context) {  <br>  c.JSON(http.StatusOK, gin.H{})<br>}<br><br>// get user<br>func Get(c *gin.Context) {<br>  c.JSON(http.StatusOK, gin.H{})<br>}<br><br>// update user<br>func Update(c *gin.Context) {<br>  c.JSON(http.StatusOK, gin.H{})<br>}<br><br>// delete user<br>func Delete(c *gin.Context) {<br>  c.JSON(http.StatusOK, gin.H{})<br>}</pre><h4><strong>Create a test file</strong></h4><p>When creating automated tests in Golang, it’s common practice to organize tests into separate files for each package or module being tested. Here is an example of how you might initialize a test file for a package called user:</p><ol><li>Create a new file called user_test.go in the same directory as the user package.</li><li>Import the necessary packages at the top of the file. For example, you will likely need to import the testingpackage.</li></ol><p><strong>Note: </strong>A test file name must have a suffix _test.go , in order to be recognized by the test command.</p><p>When a database is involved in code, we have to use a test database to interact with our tests rather than the actual database we work with.</p><p>Initialize the test with database initialization, in the user_test.go file:</p><pre>package user<br><br>import (<br>  &quot;testing&quot;<br><br>  &quot;github.com/gin-gonic/gin&quot;<br>  &quot;github.com/jmoiron/sqlx&quot;<br>)<br><br>var testDb *sqlx.DB<br>var err error<br><br>func TestInit(t *testing.T) {<br>  testDb, err = TestDB() // connection of your test database<br>  if err != nil {<br>    t.Errorf(&quot;Error in initializing test DB: %v&quot;, err)<br>  }<br>}</pre><p>Now, Let’s add functions into user_test.go that manages test database operations to operate dummy data while testing the APIs.</p><pre>// create users table<br>func CreateUsersTable(Db *sqlx.DB) {<br>  Db.MustExec(`CREATE TABLE IF NOT EXISTS users <br>  (id int(11) NOT NULL AUTO_INCREMENT,<br>  name varchar(195) default null,<br>  email varchar(195) default null<br>  primary key (id));`)<br>}<br><br>// insert user<br>func InsertIntoUsersTable(Db *sqlx.DB) {<br>  Db.MustExec(&quot;INSERT INTO users(name, email) VALUES(&#39;John Doe&#39;, &#39;john@example.com&#39;);&quot;)<br>}<br><br>// drop users table<br>func DropUsersTable(Db *sqlx.DB) {<br>  Db.MustExec(`DROP TABLE IF EXISTS users`)<br>}<br><br>// make json data structure<br>func GotData(w *httptest.ResponseRecorder, t *testing.T) map[string]interface{} {<br>  var got map[string]interface{}<br>  if len(w.Body.Bytes()) != 0 {<br>  err := json.Unmarshal(w.Body.Bytes(), &amp;got)<br>    if err != nil {<br>      t.Fatal(err)<br>    }<br>  }<br>  return got<br>}</pre><h3>Create a user using TDD</h3><h4><strong>Create User — Bad Request Test (case 1):</strong></h4><p>Let’s say you want to test that if a request body is missing or has invalid data, then the API should return a 400(Bad Request)status code.</p><p>Your test might look something like this:</p><pre>func TestCreateUserBadRequest(t *testing.T) {<br><br>  // required user table operations<br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.POST(&quot;/api/users&quot;, Create)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;POST&quot;, &quot;/api/users&quot;, bytes.NewBuffer([]byte(`{&quot;email&quot;: 123}`)))<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusBadRequest, w.Code)<br>}</pre><p>Modify the Create() function like the below in user.go file.</p><pre>func Create(c *gin.Context) {  <br>  input := User{}<br>  err = c.ShouldBindWith(&amp;input, binding.JSON)<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusBadRequest)<br>    return<br>  }<br>}</pre><h4><strong>Create User — Success test (case 2):</strong></h4><p>Let’s test if a request body is sufficient and the API runs successfully adding users as a result. The API should return a 200(OK) status.</p><p>Your test might look something like this:</p><pre>func TestCreateUserSuccess(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.POST(&quot;/api/users&quot;, Create)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;POST&quot;, &quot;/api/users&quot;, bytes.NewBuffer([]byte(`{&quot;name&quot;:&quot;John Doe&quot;,&quot;email&quot;:&quot;john@example.com&quot;}`)))<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusOK, w.Code)<br>}</pre><p>Modify the Create() function like below.</p><pre>func Create(c *gin.Context) {<br>  input := User{}<br>  err = c.ShouldBindWith(&amp;input, binding.JSON)<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusBadRequest)<br>    return<br>  }<br>  <br>  _, err = db.Exec(&quot;INSERT INTO users (name, email) VALUES (?, ?)&quot;, input.Name, input.Email)<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br>  <br>  c.JSON(http.StatusOK, gin.H{})<br>}</pre><p>Run the test using go test -v user_test.go , you will see the tests passing.</p><h3>Get User using TDD</h3><h4>Get User — Bad Request Test (case 1):</h4><p>When the endpoint doesn’t contain valid params or no params at all, the Get user API should return a 400(Bad Request) code.</p><p>Your test might look like this:</p><pre>func TestGetUserBadRequest(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.GET(&quot;/api/users/:id&quot;, Get)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;GET&quot;, &quot;/api/users/&quot;, nil)<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusBadRequest, w.Code)<br>}</pre><p>Modify Get() function like the below, in the user.go file.</p><pre>func Get(c *gin.Context) {<br>  id, err := strconv.Atoi(c.Param(&quot;id&quot;))<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusBadRequest)<br>    return<br>  }<br>}</pre><h4>Get User — Not Found Test (case 2):</h4><p>Let’s say you want to test a request to non-existing user information and return a 404(Not Found) status code and an empty JSON response. Your test might look something like this:</p><p>Test:</p><pre>func TestGetUserNotFound(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.GET(&quot;/api/users/:id&quot;, Get)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;GET&quot;, &quot;/api/users/1&quot;, nil)<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusNotFound, w.Code)<br>}</pre><p>Modify the Get() function like the below.</p><pre>func Get(c *gin.Context) {<br>  id, err := strconv.Atoi(c.Param(&quot;id&quot;))<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br>  <br>  var user User<br>  row := db.QueryRow(&quot;SELECT id, name, email FROM users WHERE id = ?&quot;, id)<br>  <br>  err = row.Scan(&amp;user.Id, &amp;user.Name, &amp;user.Email)<br>  if err != nil {<br>    if err == sql.ErrNoRows {<br>      c.AbortWithStatus(http.StatusNotFound)<br>      return<br>    }<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br>}</pre><p>In the test, we haven’t added any user to the table, but we’re requesting a user with id=1 and so it will fail with the Not Found(404) status.</p><h4><strong>Get User — Success test (case 3):</strong></h4><p>Let’s test the function when we’ve added a user and we’re receiving it with a valid id. The Get User API should return a user with an OK(200) status code and the user object.</p><p>Test:</p><pre>func TestGetUserSuccess(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br>  InsertIntoUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.GET(&quot;/api/users/:id&quot;, Get)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;GET&quot;, &quot;/api/users/1&quot;, nil)<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusOK, w.Code)<br>  <br>  got := GotData(w, t)<br>  expected := `{&quot;id&quot;:1, &quot;name&quot;:&quot;John Doe&quot;}`<br><br>  assert.Equal(t, expected, got)<br>}</pre><p>Modify the Get() function like the one below, in the user.go file.</p><pre>func Get(c *gin.Context) {<br>  id, err := strconv.Atoi(c.Param(&quot;id&quot;))<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br>  <br>  var user User<br>  row := db.QueryRow(&quot;SELECT id, name, email FROM users WHERE id = ?&quot;, id)<br>  <br>  err = row.Scan(&amp;user.Id, &amp;user.Name, &amp;user.Email)<br>  if err != nil {<br>    if err == sql.ErrNoRows {<br>      c.AbortWithStatus(http.StatusNotFound)<br>      return<br>    }<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br><br>  c.JSON(http.StatusOK, user)<br>}</pre><p>Run the test using go test -v user_test.go</p><h3>Update User using TDD</h3><h4><strong>Update User — Bad Request Test (case 1):</strong></h4><p>Let’s say you want to test that a request with missing or invalid data returns a 400(Bad Request) status code and an empty JSON response.</p><p>Your test might look something like this:</p><pre>func TestUpdateUserBadRequest(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.PUT(&quot;/api/users/:id&quot;, Update)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;PUT&quot;, &quot;/api/users/1&quot;, bytes.NewBuffer([]byte(`{&quot;email&quot;: 123}`)))<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusBadRequest, w.Code)<br>}</pre><p>Modify Update() function like the one below, in user.go file.</p><pre>func Update(c *gin.Context) {<br>  id, err := strconv.Atoi(c.Param(&quot;id&quot;))<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusBadRequest)<br>    return<br>  }<br><br>  input := User{}<br>  err = c.ShouldBindWith(&amp;input, binding.JSON)<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusBadRequest)<br>    return<br>  }<br>}</pre><h4>Update User —Not Found Test (case 2):</h4><p>Let’s say you want to test the case when request data is valid but the user we want to update doesn’t exist at all. The API should return a 404(Not Found) status code and an empty JSON response.</p><p>Your test might look something like this:</p><pre>func TestUpdateUserNotFound(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br>  InsertIntoUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.PUT(&quot;/api/users/:id&quot;, Update)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;PUT&quot;, &quot;/api/users/5&quot;, bytes.NewBuffer([]byte(`{&quot;name&quot;:&quot;John Doe&quot;,&quot;email&quot;:&quot;john@example.com&quot;}`)))<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusNotFound, w.Code)<br>}</pre><p>Modify the Update() function like the below.</p><pre>func Update(c *gin.Context) {<br>  id, err := strconv.Atoi(c.Param(&quot;id&quot;))<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br><br>  input := User{}<br>  err = c.ShouldBindWith(&amp;input, binding.JSON)<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusBadRequest)<br>    return<br>  }<br><br>  var user User<br>  row := db.QueryRow(&quot;SELECT id, name, email FROM users WHERE id = ?&quot;, id)<br>  err = row.Scan(&amp;user.Id, &amp;user.Name, &amp;user.Email)<br>  if err != nil {<br>    if err == sql.ErrNoRows {<br>      c.AbortWithStatus(http.StatusNotFound)<br>      return<br>    }<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br>}</pre><h4>Update User — Success Test (case 3):</h4><p>Let’s test the successful use case of updating user API, where the API returns an OK(200) status code with the updated user. Your test might look something like this:</p><p>Test:</p><pre>func TestUpdateUserSuccess(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br>  InsertIntoUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.PUT(&quot;/api/users/:id&quot;, Update)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;PUT&quot;, &quot;/api/users/1&quot;, bytes.NewBuffer([]byte(`{&quot;name&quot;:&quot;John Doe&quot;,&quot;email&quot;:&quot;john@example.com&quot;}`)))<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusOK, w.Code)<br>  <br>  got := GotData(w, t)<br>  assert.Empty(t, got)<br>}</pre><p>Modify the Update() function like below.</p><pre>func Update(c *gin.Context) {<br>  id, err := strconv.Atoi(c.Param(&quot;id&quot;))<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br><br>  input := User{}<br>  err = c.ShouldBindWith(&amp;input, binding.JSON)<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusBadRequest)<br>    return<br>  }<br><br>  var user User<br>  row := db.QueryRow(&quot;SELECT id, name, email FROM users WHERE id = ?&quot;, id)<br>  err = row.Scan(&amp;user.Id, &amp;user.Name, &amp;user.Email)<br>  if err != nil {<br>    if err == sql.ErrNoRows {<br>      c.AbortWithStatus(http.StatusNotFound)<br>      return<br>    }<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br><br>  _, err = db.Exec(&quot;UPDATE users SET name = ?, email = ? WHERE id = ?&quot;, input.Name, input.Email, id)<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br><br>  c.JSON(http.StatusOK, gin.H{})<br>}</pre><p>Run the test using go test -v user_test.go</p><h3>Delete user with TDD</h3><h4><strong>Delete User — Not Found Test (case 1):</strong></h4><p>Let’s say you want to delete the user which doesn’t exist at all. In that case, an API should return a Not Found(404) status code.</p><p>Your test might look something like this:</p><pre>func TestDeleteUserNotFound(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.DELETE(&quot;/api/users/:id&quot;, Delete)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;DELETE&quot;, &quot;/api/users/5&quot;, nil)<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusNotFound, w.Code)<br>}</pre><p>Modify the Delete() function like below, in user.go file.</p><pre>func Delete(c *gin.Context) {<br>  id, err := strconv.Atoi(c.Param(&quot;id&quot;))<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusBadRequest)<br>    return<br>  }<br>  <br>  var user User<br>  row := db.QueryRow(&quot;SELECT id, name, email FROM users WHERE id = ?&quot;, id)<br>  err = row.Scan(&amp;user.Id, &amp;user.Name, &amp;user.Email)<br>  if err != nil {<br>    if err == sql.ErrNoRows {<br>      c.AbortWithStatus(http.StatusNotFound)<br>      return<br>    }<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br>}</pre><h4><strong>Delete User — Success Test (case 2):</strong></h4><p>Let’s test the delete user&#39;s successful attempt. An API will return a OK(200) status code.</p><p>Test:</p><pre>func TestDeleteUserSuccess(t *testing.T) {<br><br>  DropUsersTable(testDb)<br>  CreateUsersTable(testDb)<br>  InsertIntoUsersTable(testDb)<br><br>  router := gin.Default()<br>  router.DELETE(&quot;/api/users/:id&quot;, Delete)<br><br>  engine := gin.New()<br>  <br>  req, err := http.NewRequest(&quot;DELETE&quot;, &quot;/api/users/1&quot;, nil)<br>  if err != nil {<br>    t.Errorf(&quot;Error in creating request: %v&quot;, err)<br>  }<br>  <br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  <br>  w := httptest.NewRecorder()<br>  engine.ServeHTTP(w, req)<br>  <br>  assert.EqualValues(t, http.StatusOK, w.Code)<br>}</pre><p>Modify the Delete() function like below.</p><pre>func Delete(c *gin.Context) {<br>  id, err := strconv.Atoi(c.Param(&quot;id&quot;))<br>  if err != nil {<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br>  <br>  var user User<br>  row := db.QueryRow(&quot;SELECT id, name, email FROM users WHERE id = ?&quot;, id)<br>  err = row.Scan(&amp;user.Id, &amp;user.Name, &amp;user.Email)<br>  if err != nil {<br>    if err == sql.ErrNoRows {<br>      c.AbortWithStatus(http.StatusNotFound)<br>      return<br>    }<br>    c.AbortWithStatus(http.StatusInternalServerError)<br>    return<br>  }<br>  <br>  db.Exec(&quot;DELETE FROM users WHERE id = ?&quot;, id)<br>  <br>  c.JSON(http.StatusOK, gin.H{})<br>}</pre><p>Run the test using go test -v user_test.go</p><p>Run tests of particular files using the command, like the go test -v &quot;test_file_name” command, in our case it’s go test -v user_test.go . <br>Also, you can run multiple test suits using the commandgo test or go test -v (if you many) on the root directory of the package.</p><p>Repeat all the steps for any additional functionality you want to add to the API.</p><p>It is important to keep in mind that in TDD you should write the minimum code necessary to pass the test. This helps you to focus on the requirements of the code and not on unnecessary features.</p><p>Please note that this is just a basic example and the real-world implementation can be more complex with different types of test cases and more robust testing frameworks.</p><p><strong>Find the complete source code at — </strong><a href="https://github.com/cp-dharti-r/tdd-in-golang-with-gin-and-mysql"><strong>Golang: TDD with Gin and MySQL</strong></a>.</p><h3><strong>Final Thoughts</strong></h3><p>In this blog post, we’ve covered the implementation of crud operation with Test-Driven Development (TDD).</p><p>TDD is a software development approach in which tests are written before the implementation of the code. The goal of TDD is to ensure that the code meets the requirements and behaves as expected by constantly testing the code during the development process.</p><p>This can help to catch bugs early on, improve code quality, and increase confidence in the software.</p><p>TDD is an iterative process that begins with writing a test, running it to confirm it fails, then writing the minimum amount of code to make the test pass and repeating this process until the feature is complete.</p><p>Thanks for reading!! 👋</p><h3>Similar articles</h3><ul><li><a href="https://blog.canopas.com/golang-unit-tests-with-test-gin-context-80e1ac04adcd">Golang: Unit tests with test gin context</a></li><li><a href="https://blog.canopas.com/from-unknown-to-expert-golang-statements-you-need-to-know-a1ac97213c04">From Unknown to Expert: Golang Statements You Need to Know</a></li><li><a href="https://blog.canopas.com/golang-send-firebase-push-notifications-to-apps-45bc83d7cabf">Golang: Send Firebase Push notifications to apps</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedbacks are most welcome as always, drop them below in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3d353b978f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/golang-test-driven-development-tdd-with-gin-and-mysql-e3d353b978f8">Golang: Test-Driven Development(TDD) with Gin and MySQL</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tailwind CSS — How to Design Advanced Custom Animations]]></title>
            <link>https://medium.com/canopas/tailwind-css-how-to-design-advanced-custom-animations-339aa35959f2?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/339aa35959f2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[custom-animation]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 11:20:43 GMT</pubDate>
            <atom:updated>2023-06-26T04:03:39.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tailwind CSS — How to Design Advanced Custom Animations</h3><h4>Mastering animation with Tailwind CSS for an unforgettable user experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdAPWwYikm3_jn31qppFtQ.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>Animation has become an essential aspect of web design, allowing developers to create captivating and interactive user experiences.</p><p>Tailwind CSS, a popular utility-first CSS framework, provides a powerful set of tools that can be leveraged to create stunning animations effortlessly.</p><p>In this blog post, we will explore the exciting world of advanced animations using Tailwind CSS and uncover some mind-blowing techniques that will take your web projects to the next level.</p><p>Refer to <a href="https://blog.canopas.com/tailwind-css-custom-animations-b041a1310aab"><strong>Custom Animations using Tailwind CSS</strong></a> For basic ones.</p><h3>Table of Contents</h3><pre>- <a href="#48d0">The Power of Transition and Transform</a><br>1. <a href="#3a0d">Animate Gradient Text</a><br>2. <a href="#ac9b">Animate Placeholder Area</a><br>3. <a href="#e8ba">Infinitely Rotating Ball</a><br>4. <a href="#4930">Double Bouncy Circles</a><br>5. <a href="#c338">Spinning Dotted Square</a><br>6. <a href="#a8f0">Bouncy Circles</a><br>7. <a href="#0c4b">Forwarding Arrow</a><br>8. <a href="#3221">Rotating Squares</a><br>- <a href="#1041">Combining Animation with Other Tailwind Features(Dark Mode)</a><br>- <a href="#9133">Conclusion</a></pre><h3>Sponsored</h3><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>The Power of Transition and Transform</h3><p>Tailwind CSS provides a range of utility classes that leverage CSS transitions and transforms. These properties allow you to create smooth animations and stunning transformations with minimal effort.</p><p>In addition to transitions and transforms, Tailwind CSS also supports <strong>keyframe animations</strong>. Keyframes allow you to define custom animations by specifying a series of style changes at different points in time.</p><p>Let’s delve deep into different types of animations.</p><h3><strong>1. </strong>Animate <strong>Gradient Text</strong></h3><p>To animate the gradient text, we will include the animate-pulse class. This class applies a pulsating animation to the element, giving it a subtle yet eye-catching effect.</p><p><strong>Example</strong></p><pre>&lt;div class=&quot;ms-52 my-10 text-5xl font-extrabold&quot;&gt;<br>  &lt;span class=&quot;animate-pulse bg-gradient-to-r from-pink-500 via-green-500 to-violet-500 bg-clip-text text-transparent&quot;&gt; Tailwind CSS Animation &lt;/span&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*6_mUP3UasjjeQTouHW8SDQ.gif" /><figcaption>Gradient Text With Animation</figcaption></figure><p>In this example, we have &lt;span&gt; element that contains the text &quot;Gradient Text&quot;. To create the gradient effect, we use the text-transparent class to make the text transparent. Finally, we use the bg-gradient-to-r class to specify a horizontal gradient from purple to blue.</p><blockquote><strong>Usage: </strong>We can use this animation to <strong>highlight</strong> or <strong>focus </strong>the details.</blockquote><p>Check out the live demo in the <a href="https://play.tailwindcss.com/kF3eLRv3kE">playground</a> and feel free to play with it as per your requirements.</p><h3>2. Animate Placeholder Area</h3><p>In this example, we’ll create a placeholder content area using Tailwind CSS for situations when there is no internet connection or data is being loaded :)</p><p><strong>Example</strong></p><pre>&lt;div class=&quot;mx-auto mt-10 w-full max-w-sm rounded-md border border-gray-300 p-4&quot;&gt;<br>  &lt;div class=&quot;animate-pulse space-x-4&quot;&gt;<br>    &lt;div class=&quot;grid&quot;&gt;<br>      &lt;div class=&quot;flex&quot;&gt;<br>        &lt;div class=&quot;w-10 rounded-full bg-slate-200&quot;&gt;&lt;/div&gt;<br>        &lt;div class=&quot;ms-4 w-full space-y-6&quot;&gt;<br>          &lt;div class=&quot;h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>          &lt;div class=&quot;space-y-3&quot;&gt;<br>            &lt;div class=&quot;grid grid-cols-3 gap-4&quot;&gt;<br>              &lt;div class=&quot;col-span-2 h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>              &lt;div class=&quot;col-span-1 h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;mt-5 space-y-6 py-1&quot;&gt;<br>        &lt;div class=&quot;h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>        &lt;div class=&quot;space-y-3&quot;&gt;<br>          &lt;div class=&quot;grid grid-cols-3 gap-4&quot;&gt;<br>            &lt;div class=&quot;col-span-2 h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>            &lt;div class=&quot;col-span-1 h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;h-2 rounded bg-slate-200&quot;&gt;&lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*xusV-JXsEly8zD85zQcCEw.gif" /><figcaption>Animate Placeholder Area</figcaption></figure><p>In this example, we use a nested &lt;div&gt; with the flex class to center the loading text both horizontally and vertically. The justify-center and items-center classes ensure the content is centered within the parent container.</p><p>By applying the animate-pulse class, the entire placeholder area will exhibit a pulsating animation, giving the illusion of activity and indicating to the user that content is being loaded.</p><blockquote><strong>Usage: </strong>We can use this animation to show the requested <strong>data is being loaded</strong>.</blockquote><p>Check out the live demo in the <a href="https://play.tailwindcss.com/f5C11pI9Zr">playground</a> and feel free to play with it as per your requirements.</p><h3>3. Infinitely Rotating Ball</h3><p>This animation code creates a circular element with a border and an animated spinning effect. Inside the circular element, there is a smaller circular element positioned in the top-right corner.</p><p><strong>Example</strong></p><pre>&lt;div class=&quot;my-40 flex&quot;&gt;<br>  &lt;div class=&quot;relative mx-auto h-28 w-28 animate-spin rounded-full border-2 p-4&quot;&gt;<br>    &lt;span class=&quot;absolute right-5 top-2 flex h-3 w-3&quot;&gt;<br>      &lt;span class=&quot;bg-white-500 relative inline-flex h-3 w-3 rounded-full bg-gray-500&quot;&gt; &lt;/span&gt;<br>    &lt;/span&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*UJQmIQSc36mVUIHDGXA0Ow.gif" /><figcaption>Infinitely Rotate Ball</figcaption></figure><p>The above code snippet has a div element with the classes my-40 and flex. Inside of this div we can create a circular element with a spinning animation effect infinitely using animate-spin class. We can use it to show the processing of data load or the uploading process of images or files.</p><blockquote><strong>Usage:</strong> Using this animation we can show the <strong>processing</strong> of data load or image, file <strong>uploading</strong>.</blockquote><p>Check out the live demo in the <a href="https://play.tailwindcss.com/FKu6TJzYm6">playground</a> and feel free to play with it as per your requirements.</p><h3>4. Double Bouncy Circles</h3><p>This animation code creates an animation with two circles. It consists of a larger circular shape that bounces and a smaller circular shape spinning below it. The animation effects give the illusion of loading or activity.</p><p><strong>Example</strong></p><pre>&lt;div class=&quot;my-40 flex&quot;&gt;<br>  &lt;div class=&quot;relative mx-auto h-10 w-10 animate-bounce&quot;&gt;<br>    &lt;div class=&quot;mx-auto h-16 w-16 animate-pulse rounded-full bg-gray-400&quot;&gt;&lt;/div&gt;<br>    &lt;span class=&quot;absolute flex h-5 w-5 animate-spin&quot;&gt;<br>      &lt;span class=&quot;h-4 w-4 rounded-full bg-gray-400&quot;&gt; &lt;/span&gt;<br>    &lt;/span&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*tafQKs1sVCyLaXgTpTIh3w.gif" /><figcaption>Double Bouncy Circles Animation</figcaption></figure><p>In this animation, we have a div with classes for relative positioning, centering, sizing, and a bounce animation effect. Inside the second div, there is another div element with classes for centering, sizing, a pulse animation effect, and gray background color.</p><p>We have applied animate-bounce class on the parent div that’s why all the inner elements have a default bouncy effect. We have also, applied animat-pulse effect on a bigger circle for the pulse effect.</p><blockquote><strong>Usage:</strong> We can use this animation to show the <strong>user’s</strong> <strong>activity</strong> or <strong>data</strong> <strong>loading</strong> effect.</blockquote><p>Check out the live demo in the <a href="https://play.tailwindcss.com/v9uN72EGjL">playground</a> and feel free to play with it as per your requirements.</p><h3>5. Spinning Dotted Square</h3><p>This animation code consists of a rounded box shape that spins, indicating some kind of activity or loading. The box has a dotted gray outline for added visual effect with animate-spin.</p><p><strong>Example</strong></p><pre>&lt;div class=&quot;my-40 flex&quot;&gt;<br>  &lt;div class=&quot;mx-auto h-20 w-20 animate-spin rounded-3xl p-6 outline-dotted outline-2 outline-gray-500&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*C9UKvLZPpf4Ns3AOiv7S1A.gif" /><figcaption>Spinning Dotted Square Animation</figcaption></figure><p>The above code snippet has animate-spin class that applies a spinning animation effect to the inner div. The rounded-3xl class rounds the corners of the inner div to create a more rounded shape. The outline-dotted, outline-2, and outline-gray-500 classes apply a dotted gray outline with a width of 2 units to the inner div.</p><blockquote><strong>Usage:</strong> We can use this animation in multiple places like <strong>highlighting frames</strong>, <strong>loading data</strong>, <strong>file or image processing</strong>, etc.</blockquote><p>Check out the live demo in the <a href="https://play.tailwindcss.com/J5ch6FiXDX">playground</a> and feel free to play with it as per your requirements.</p><h3>6. Bouncy Circles</h3><p>This animation code will create a loading animation effect with two bouncing elements. The outermost element will bounce, and within it, there will be a nested element that also bounces.</p><p>Additionally, there is a smaller dot-like element that moves and bounces along with the other elements.</p><p><strong>Example</strong></p><pre>&lt;div class=&quot;my-40 flex&quot;&gt;<br>  &lt;div class=&quot;relative mx-auto h-10 w-10&quot;&gt;<br>    &lt;div class=&quot;relative mx-auto ms-5 h-24 w-24 animate-bounce rounded-full border-2&quot;&gt;<br>      &lt;div class=&quot;absolute bottom-0 right-10&quot;&gt;<br>        &lt;div class=&quot;relative h-40 animate-bounce&quot;&gt;<br>          &lt;div class=&quot;absolute bottom-0 right-0 h-2 w-2 rounded-full bg-black&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*qqN4OM1ZAomMY-lHGhIiug.gif" /><figcaption>Bouncy Circles Animation</figcaption></figure><p>The outermost div with the class animate-bounce will create a bouncing animation effect.</p><p>Inside that div, there is a nested div with the class animate-bounce, which will also create a bouncing effect. Inside the second nested div, with a black background color (bg-black) and a small size of h-2 and w-2. This creates a small black dot or indicator that will also participate in the bouncing animation.</p><blockquote><strong>Usage:</strong> We can use this animation to show <strong>file or image processing </strong>and<strong> loading.</strong></blockquote><p>Check out the live demo in the <a href="https://play.tailwindcss.com/Drdi5Axnze">playground</a> and feel free to play with it as per your requirements.</p><h3>7. Forwarding Arrow</h3><p>This animation code will create a moving animation effect on the SVG element. The SVG represents a green arrow, and the animation will make the arrow move horizontally back and forth by translating its X position.</p><p><strong>Example</strong></p><pre>&lt;div class=&quot;my-40 flex&quot;&gt;<br>  &lt;div class=&quot;relative mx-auto mt-5 animate-[propel_5s_infinite]&quot;&gt;<br>    &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; viewBox=&quot;0 0 24 24&quot; fill=&quot;green&quot; class=&quot;h-16 w-16&quot;&gt;<br>      &lt;path d=&quot;M3.478 2.405a.75.75 0 00-.926.94l2.432 7.905H13.5a.75.75 0 010 1.5H4.984l-2.432 7.905a.75.75 0 00.926.94 60.519 60.519 0 0018.445-8.986.75.75 0 000-1.218A60.517 60.517 0 003.478 2.405z&quot; /&gt;<br>    &lt;/svg&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Now, add keyframes in your tailwind.config.js file to animate the object. You can modify it according to your requirements.</p><p><strong>tailwind.config.js</strong></p><pre>module.exports = {<br>  content: [&#39;./pages/**/*.{js,ts,jsx,tsx}&#39;, &#39;./components/**/*.{js,ts,jsx,tsx}&#39;],<br>  theme: {<br>    extend: {<br>      keyframes: {<br>         propel: {<br>          &#39;0%&#39;: { transform: &#39;translateX(0)&#39; },<br>          &#39;20%&#39;: { transform: &#39;translateX(25%)&#39; },<br>          &#39;40%&#39;: { transform: &#39;translateX(-25%)&#39; },<br>          &#39;60%&#39;: { transform: &#39;translateX(25%)&#39; },<br>          &#39;100%&#39;: { transform: &#39;translateX(-25%)&#39; },<br>        },<br>      },<br>    },<br>  },<br>  plugins: [],<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*IzgzKpdtd1SAtWhsx86PhA.gif" /><figcaption>Arrow Forwarding Animation</figcaption></figure><p>The outermost div has the classes my-40 and flex, which provides vertical spacing and enables a flexbox layout. Inside the second div, there is an svg element with attributes for the XML namespace, viewBox, and class. The h-16 and w-16 classes set the height and width of the SVG and fill=&quot;green&quot; attribute sets the fill color of the SVG to green.</p><blockquote><strong>Usage:</strong> We can use this animation to <strong>guide</strong>, <strong>focus</strong> and <strong>highlight</strong> areas.</blockquote><p>Check out the live demo in the <a href="https://play.tailwindcss.com/Quv3OcAsQN?file=config">playground</a> and feel free to play with it as per your requirements.</p><h3>8. Rotating Squares</h3><p>This animation code will create a container with a rotating animation effect applied to it, making it displace or rotate back and forth continuously.</p><p>Inside the container, there is a smaller element that also has a flipping animation effect applied to it, making it rotate vertically back and forth continuously.</p><p><strong>Example</strong></p><pre>&lt;div class=&quot;my-40 flex&quot;&gt;<br>  &lt;div class=&quot;relative mx-auto h-28 w-28 animate-[displace_5s_infinite] border border-red-200&quot;&gt;<br>    &lt;div class=&quot;h-14 animate-[flip_5s_infinite] bg-red-100&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Now, add keyframes in your tailwind.config.js file to animate the object.</p><p><strong>tailwind.config.js</strong></p><pre>module.exports = {<br>  content: [&#39;./pages/**/*.{js,ts,jsx,tsx}&#39;, &#39;./components/**/*.{js,ts,jsx,tsx}&#39;],<br>  theme: {<br>    extend: {<br>      keyframes: {<br>        displace: {<br>          &#39;0%&#39;: { transform: &#39;rotate(0deg)&#39; },<br>          &#39;20%&#39;: { transform: &#39;rotate(-90deg)&#39; },<br>          &#39;40%&#39;: { transform: &#39;rotate(0deg)&#39; },<br>          &#39;60%&#39;: { transform: &#39;rotate(0deg)&#39; },<br>          &#39;80%&#39;: { transform: &#39;rotate(90deg)&#39; },<br>          &#39;100%&#39;: { transform: &#39;rotate(0deg)&#39; },<br>        },<br>      },<br>    },<br>  },<br>  plugins: [],<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*DmNoeDh9u_sjZxhaoY_CgA.gif" /><figcaption>Rotating Squares Animation</figcaption></figure><p>The animate-[displace_5s_infinite] class applies the &quot;displace&quot; animation effect to this element, making it rotate back and forth continuously.</p><p>Inside the inner div the classes h-14, animate-[flip_5s_infinite], and bg-red-100 represents the content within the container has a height of 14 units, a red background color, and the &quot;flip&quot; animation effect applied to it, making it rotate vertically back and forth continuously.</p><blockquote><strong>Usage:</strong> We can use this animation for <strong>loading data </strong>and<strong> files or image processing or uploading</strong>.</blockquote><p>Check out the live demo in the <a href="https://play.tailwindcss.com/rpSBTIZV11?file=config">playground</a> and feel free to play with it as per your requirements.</p><h3>Combining Animations with Other Tailwind Features (Dark Mode)</h3><p>Tailwind CSS’s animation capabilities can be seamlessly integrated with other features provided by the framework. For instance, you can combine animations with responsive design classes to create adaptive and engaging user experiences across various devices.</p><p>You can also leverage Tailwind CSS’s dark mode feature to apply different animations based on the user’s preferred color scheme. By utilizing dynamic classes and utility variants, you can create sophisticated and interactive animations that enhance your web design.</p><p>Check out the live demo of dark mode in the <a href="https://play.tailwindcss.com/VLgQrdGnZZ">playground</a> and feel free to play with it as per your requirements.</p><h3>Conclusion</h3><p>The above-designed animations showcase the versatility and creativity that can be achieved using CSS and the Tailwind CSS framework. These examples demonstrate various animation effects, such as spinning, bouncing, pulsing, flipping, and wiggling.</p><p>By leveraging the power of CSS keyframes and Tailwind CSS utility classes, these animations bring dynamic and engaging elements to a blog or website. Whether it’s rotating icons, bouncing shapes, or wiggling text, these animations can capture the attention of users and enhance the visual experience.</p><p>Furthermore, the ability to customize and define keyframes within the Tailwind CSS configuration file allows for fine-tuning and extending the animation capabilities. This flexibility empowers developers to create unique and eye-catching effects tailored to their specific design requirements.</p><p>Overall, incorporating animation effects into a blog can help create a memorable and delightful user experience, leaving a lasting impression on visitors. However, it’s important to use animations judiciously and consider their impact on performance and accessibility to ensure a seamless and inclusive browsing experience for all users.</p><p>That’s it for today. Keep exploring for the best. 👋</p><h3>Similar articles</h3><ul><li><a href="https://blog.canopas.com/how-to-make-unique-shapes-using-tailwindcss-18a85523bc15">How to make Unique shapes using TailwindCSS</a></li><li><a href="https://blog.canopas.com/css-made-simple-a-guide-to-animations-transitions-and-transformations-f9b2ecc8620f">CSS Made Simple: A Guide To Animations, Transitions, And Transformations</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedbacks are most welcome as always, drop them below in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=339aa35959f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/tailwind-css-how-to-design-advanced-custom-animations-339aa35959f2">Tailwind CSS — How to Design Advanced Custom Animations</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Stunning Progress Bars Made Easy with Tailwind CSS]]></title>
            <link>https://medium.com/canopas/designing-stunning-progress-bars-made-easy-with-tailwind-css-ae620ba7b4be?source=rss-851a1801eb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae620ba7b4be</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[progress-bar]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Dharti R]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 10:25:01 GMT</pubDate>
            <atom:updated>2024-06-11T07:18:35.889Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhance the user experience with stunning Progress Bars…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ut3NBozkK8hpC5IHl6bjGA.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>In today’s fast-paced digital world, user experience is a crucial aspect of web development. One effective way to enhance the user experience is by incorporating progress bars into your website or application.</p><p>Consider you are building an online file upload feature for a cloud storage application. When users upload files, they often want to know the progress of their upload to estimate the remaining time or ensure the process is successfully completed.</p><p>By integrating a progress bar into your file upload feature, you can provide real-time feedback to the users, keeping them informed about the progress of their file upload. This enhances the user experience by reducing uncertainty and providing a sense of control over the upload process.</p><p>In this blog post, we will explore the power of progress bars and how you can easily create them using Tailwind CSS, a popular utility-first CSS framework. Let’s dive in!</p><h3>Table of Contents</h3><pre>* <a href="#626d">Why Progress Bar Matters</a><br>* <a href="#e918">Getting Started with Tailwind CSS</a><br>  1. <a href="#141d">Basic progress bar with rounded edges</a><br>  2. <a href="#ebfa">Slim progress bar with sharp edges</a><br>  3. <a href="#fdb9">Progress bar with a label</a><br>  4. <a href="#e510">Animated progress bar</a><br>  5. <a href="#128a">Straight progress bar with bottom text</a><br>  6. <a href="#1743">Vertical progress bars</a><br>  7. <a href="#b11f">Thermometer progress bar</a><br>  8. <a href="#0bf8">Multi-color progress bar</a><br>  9. <a href="#d339">Gradient progress bar</a><br>  10. <a href="#5ae8">Progress bar with multicolors and multi sections</a><br>* <a href="#434d">Conclusion</a></pre><h3>Sponsored</h3><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Why Progress Bar Matters?</h3><p>Progress bars are invaluable tools when it comes to providing visual feedback and managing user expectations.</p><p>They convey a sense of completion, reduce anxiety, and increase user engagement.</p><p>Whether it’s a file upload, form submission, or an operation that requires time, a well-designed progress bar can keep users informed and engaged, leading to a more satisfying user experience.</p><h3>Getting Started with Tailwind CSS</h3><p>Tailwind CSS is a utility-first CSS framework that allows developers to rapidly build beautiful and responsive user interfaces. Its simplicity and flexibility make it an ideal choice for creating progress bars.</p><p>To begin, make sure you have Tailwind CSS installed in your project. If not, head over to the official Tailwind CSS documentation for instructions on installation.</p><h3>1. Basic progress bar with rounded edges</h3><p>This is the basic progress bar with rounded edges and is easy to integrate.</p><h4>Example:</h4><pre>&lt;div class=&quot;mb-5 h-2 rounded-full bg-gray-200&quot;&gt;<br>  &lt;div class=&quot;h-2 rounded-full bg-orange-500&quot; style=&quot;width: 50%&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*ayGKYlO2x9bnsJzj7LqGxg.png" /><figcaption>A basic progress bar with rounded edges</figcaption></figure><p>The above-given code snippet will produce a progress bar with a gray background and an orange fill, indicating progress of 50%.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/qk9qzl9g0H">playground</a> and feel free to play with it as per your requirements.</p><h3>2. Slim progress bar with sharp edges</h3><p>If you prefer a slimmer progress bar with sharp edges, you can modify the classes accordingly.</p><h4>Example:</h4><pre>&lt;div class=&quot;mb-5 h-1 bg-gray-200&quot;&gt;<br>  &lt;div class=&quot;h-1 bg-purple-500&quot; style=&quot;width: 75%&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*jPCsuXH-tTj9x7wypkRLsw.png" /><figcaption>Slim progress bar with sharp edges</figcaption></figure><p>The above-given code snippet will create a slimmer progress bar with a gray background and a purple fill, representing the progress of 75%.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/DILZmOWZUc">playground</a>.</p><h3>3. Progress bar with a label</h3><p>Adding a label to the progress bar can provide additional context. We can achieve this by including a text element within the progress bar.</p><h4>Example:</h4><pre>&lt;div class=&quot;relative mb-5 h-2 rounded-full bg-gray-200&quot;&gt;<br>  &lt;div class=&quot;h-2 rounded-full bg-red-500&quot; style=&quot;width: 25%&quot;&gt;&lt;/div&gt;<br>  &lt;span class=&quot;absolute inset-0 flex items-center justify-center text-sm font-medium text-gray-900&quot;&gt;25%&lt;/span&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*bOEDI_qgiXMyxmUfaBtR8Q.png" /><figcaption>Progress bar with a label</figcaption></figure><p>In this code snippet, a percentage label is positioned in the center of the progress bar, providing a clear visual representation of the progress.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/sbbeAZUdKA">playground</a>.</p><h3>4. Animated progress bar</h3><p>If you want to add a striped animation effect to the progress bar, we can achieve this with some additional CSS classes.</p><h4>Example:</h4><pre>&lt;div class=&quot;mb-5 h-2 overflow-hidden rounded-full bg-gray-200&quot;&gt;<br>  &lt;div class=&quot;h-2 animate-pulse rounded-full bg-gray-800&quot; style=&quot;width: 50%&quot;&gt;<br>    &lt;div class=&quot;h-full w-full translate-x-full transform bg-white&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*gJDpxVJqBFgyLeeAg2wojQ.gif" /><figcaption>Animated progress bar</figcaption></figure><p>This code snippet creates a progress bar with a striped animation effect. The progress bar fills 50% of the container, and the striped animation moves from left to right, giving a visual indication of progress.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/2IRajktrYv">playground</a>.</p><h3>5. Straight progress bar with bottom text</h3><p>This progress bar allows adding external bottom text(progress percentage) along with showing progress.</p><h4>Example:</h4><pre>&lt;div class=&quot;relative mb-5 pt-1&quot;&gt;<br>  &lt;div class=&quot;mb-4 flex h-2 overflow-hidden rounded bg-gray-100 text-xs&quot;&gt;<br>    &lt;div style=&quot;width: 80%&quot; class=&quot;bg-green-500&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;mb-2 flex items-center justify-between text-xs&quot;&gt;<br>    &lt;div class=&quot;text-gray-600&quot;&gt;Progress&lt;/div&gt;<br>    &lt;div class=&quot;text-gray-600&quot;&gt;100%&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*ZO4OqhpkmcdYq56TBFfaPA.png" /><figcaption>Straight progress bar with bottom text</figcaption></figure><p>In this code snippet, a percentage label and text are positioned below the progress bar, providing a clear visual representation of the progress.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/YWhV22vVSi">playground</a>.</p><h3>6. Vertical progress bars</h3><p>This progress bar is vertically directed. The flex-col class is used to align the elements in a column direction.</p><h4>Example:</h4><pre>&lt;div class=&quot;flex&quot;&gt;<br>  &lt;div class=&quot;mb-5 ml-5 flex flex-col items-center&quot;&gt;<br>    &lt;div class=&quot;h-24 w-5 overflow-hidden rounded-md bg-gray-300&quot;&gt;<br>      &lt;div class=&quot;h-full bg-yellow-800&quot; style=&quot;height: 50%&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;span class=&quot;mt-2 text-xs text-gray-600&quot;&gt;50%&lt;/span&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;mb-5 ml-5 flex flex-col items-center&quot;&gt;<br>    &lt;div class=&quot;h-24 w-10 overflow-hidden rounded-full bg-gray-300&quot;&gt;<br>      &lt;div class=&quot;h-full bg-yellow-500&quot; style=&quot;height: 75%&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;span class=&quot;mt-2 text-xs text-gray-600&quot;&gt;75%&lt;/span&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;mb-5 ml-5 flex flex-col items-center&quot;&gt;<br>    &lt;div class=&quot;h-24 w-10 overflow-hidden rounded-full bg-gray-200&quot;&gt;<br>      &lt;div class=&quot;h-full bg-gradient-to-t from-gray-200 via-blue-400 to-blue-600&quot; style=&quot;height: 60%&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;span class=&quot;mt-2 text-xs text-gray-600&quot;&gt;60%&lt;/span&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Q9XBPfVjSw8snneWvUBueQ.png" /><figcaption>Vertical progress bars</figcaption></figure><p>The height of the progress bar is set using the h-24 class and the fill amount is represented by adjusting the height of the inner div with the h-full class.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/ePC58StoNL">playground</a>.</p><h3>7. Thermometer progress bar</h3><p>This progress bar is a circular corner in shape.</p><h4>Example:</h4><pre>&lt;div class=&quot;relative mb-5&quot;&gt;<br>  &lt;div class=&quot;rounded-full border border-red-500 p-1&quot;&gt;<br>    &lt;div class=&quot;flex h-6 items-center justify-center rounded-full bg-red-300 text-xs leading-none&quot; style=&quot;width: 85%; height: 85%;&quot;&gt;<br>      &lt;span class=&quot;p-1 text-white&quot;&gt;85%&lt;/span&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*YETRrURaPe7AGqULY8Q7LQ.png" /><figcaption>Thermometer progress bar</figcaption></figure><p>It’s a way different progress bar, which we made by applying padding as seen in the above snippet.</p><p>The outer div with the rounded-full and border classes create the circular container. The progress is filled based on the specified percentage, and the circular shape is achieved by setting the height and width using percentage values.</p><p>We can also add a circle at 50% or at any other position we want. It will represent some endpoints or goal points to easily get progress in the task.</p><pre>&lt;div class=&quot;relative my-20 mx-5&quot;&gt;<br>  &lt;div class=&quot;rounded-full border border-red-500 p-1&quot;&gt;<br>    &lt;div class=&quot;flex h-6 items-center justify-center rounded-full bg-red-300 text-xs leading-none&quot; style=&quot;width: 85%; height: 85%;&quot;&gt;<br>      &lt;span class=&quot;p-1 text-white&quot;&gt;85%&lt;/span&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;absolute inset-0 flex items-center justify-center&quot;&gt;<br>    &lt;div class=&quot;h-8 w-8 rounded-full bg-red-500&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*zBQ2spNcLgjcjSVWQzRB1g.png" /><figcaption>Thermometer progress bar with middle circle edge</figcaption></figure><p>The inner div represents the progress and is positioned using the absolute class inside the outer container.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/4QbzXhY87d">playground</a>.</p><h3>8. Multi-color progress bar</h3><p>This progress bar is divided into multiple sections with different colors, each representing a specific percentage of the progress.</p><h4>Example:</h4><pre>&lt;div class=&quot;relative my-20 mx-5 pt-1&quot;&gt;<br>  &lt;div class=&quot;mb-4 flex h-2 overflow-hidden rounded bg-gray-100 text-xs&quot;&gt;<br>    &lt;div style=&quot;width: 10%&quot; class=&quot;bg-green-500 transition-all duration-500 ease-out&quot;&gt;&lt;/div&gt;<br>    &lt;div style=&quot;width: 25%&quot; class=&quot;bg-yellow-500 transition-all duration-500 ease-out&quot;&gt;&lt;/div&gt;<br>    &lt;div style=&quot;width: 20%&quot; class=&quot;bg-red-500 transition-all duration-500 ease-out&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;mb-2 flex items-center justify-between text-xs&quot;&gt;<br>    &lt;div class=&quot;text-gray-600&quot;&gt;Progress&lt;/div&gt;<br>    &lt;div class=&quot;text-gray-600&quot;&gt;100%&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*DcPE0PDrDOSgQNV5iXxq8A.png" /><figcaption>Multi-color progress bar</figcaption></figure><p>In this snippet, we have three different colors with different percentages. Which represents overall progress with sub-task progress using different colors.</p><p>Each section is defined by a separate div with the bg-green-500 class and the width is set using percentage values. The different sections can have different colors, and we can adjust the number of sections and their widths as per the requirement.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/9n8VIUTXeJ">playground</a>.</p><h3>9. Gradient progress bar</h3><p>This progress bar utilizes a gradient effect to create a smooth transition of colors.</p><h4>Example:</h4><pre>&lt;div class=&quot;mb-5 h-4 overflow-hidden rounded-full bg-gray-200&quot;&gt;<br>  &lt;div class=&quot;h-4 animate-pulse rounded-full bg-gradient-to-r from-green-500 to-blue-500&quot; style=&quot;width: 75%&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*MBpzeR86irU2Jdumt0xSdA.gif" /><figcaption>Gradient progress bar</figcaption></figure><p>The bg-gradient-to-r class applies a gradient from left to right, starting with the color specified by from-green-500 and ending with the color specified by to-blue-500. The w-1/2 class sets the width of each gradient section to 50%, creating two equal segments.</p><p>We can also modify any style with it so it can be more interactive to show the progress of a task like this,</p><pre>&lt;div class=&quot;relative mb-5 h-5 rounded-full bg-gray-200&quot;&gt;<br>  &lt;div class=&quot;h-full animate-pulse rounded-full bg-blue-500&quot; style=&quot;width: 75%&quot;&gt;<br>    &lt;span class=&quot;absolute inset-0 flex items-center justify-center text-xs font-semibold text-white&quot;&gt;75%&lt;/span&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*CUta09DGbaFR-yXKTRonZA.gif" /><figcaption>Progress bar with progress percentage</figcaption></figure><p>Check out the live demo in the <a href="https://play.tailwindcss.com/iLWki6jlNM">playground</a>.</p><h3>10. Progress bar with multicolors and multi sections</h3><p>This progress bar is divided into multi-color sections, each representing a specific percentage of the progress.</p><h4>Example:</h4><pre>&lt;div class=&quot;relative&quot;&gt;<br>  &lt;div class=&quot;mb-4 flex h-5 overflow-hidden rounded bg-gray-100 text-xs&quot;&gt;<br>    &lt;div class=&quot;flex flex-col justify-center bg-red-500 text-white&quot; style=&quot;width: 25%;&quot;&gt;<br>      &lt;span class=&quot;text-center&quot;&gt;25%&lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;flex flex-col justify-center bg-red-400 text-white&quot; style=&quot;width: 25%;&quot;&gt;<br>      &lt;span class=&quot;text-center&quot;&gt;25%&lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;flex flex-col justify-center bg-red-300 text-white&quot; style=&quot;width: 25%;&quot;&gt;<br>      &lt;span class=&quot;text-center&quot;&gt;25%&lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;flex flex-col justify-center bg-red-200 text-white&quot; style=&quot;width: 25%;&quot;&gt;<br>      &lt;span class=&quot;text-center&quot;&gt;25%&lt;/span&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;mb-2 flex items-center justify-between text-xs&quot;&gt;<br>    &lt;div class=&quot;text-gray-600&quot;&gt;Progress&lt;/div&gt;<br>    &lt;div class=&quot;text-gray-600&quot;&gt;100%&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*6nQO0otIzzfZ8wnT2Cx1Hw.png" /><figcaption>Progress bar with multicolors and multi sections</figcaption></figure><p>In this snippet, we have designed progress steps with different colors and progress percentages. Also, the bottom bar text represents overall progress and the inner text represents the progress of a step.</p><p>Each section is defined by a separate div with the bg-red-500 class and the width is set using percentage values. The different sections can have different colors, and we can adjust the number of sections and their widths as needed.</p><p>Check out the live demo in the <a href="https://play.tailwindcss.com/tY0c3jlJ3l">playground</a>.</p><p>These are just a few examples of the progress bars you can create using Tailwind CSS. By combining various utility classes and customizing the styles, you can create progress bars that match your design requirements.</p><p>Don’t forget to include the necessary Tailwind CSS classes and inline styles to adjust the width, color, and animation of the progress bars to your liking. With Tailwind CSS’s flexible utility classes, the possibilities are endless!</p><h3>Conclusion</h3><p>Throughout the blog, we explored how to create beautiful and customizable progress bars using Tailwind CSS. With its extensive set of utility classes, Tailwind CSS provides a straightforward and efficient way to style and customize progress bars to suit your design needs.</p><p>We started by creating basic rounded and slim progress bars, then added labels to the progress bars that provide additional context to users.</p><p>To add visual interest, we explored animated progress bars with striped effects. Combining classes such as animate-pulse and animate-stripes, we created dynamic and engaging progress bars.</p><p>Furthermore, we experimented with different styles, including gradient progress bars, vertical progress bars, circular progress bars, and multi-color progress bars. These variations allowed us to create visually appealing progress indicators that can be tailored to specific project requirements.</p><p>Keep progressing!</p><h3>Similar articles</h3><ul><li><a href="https://blog.canopas.com/tailwind-css-custom-animations-b041a1310aab">Tailwind CSS — Custom animations</a></li><li><a href="https://blog.canopas.com/fancy-tooltip-arrows-using-pure-css-e82d8f349e44">Fancy tooltip arrows using pure CSS</a></li><li><a href="https://blog.canopas.com/css-made-simple-a-guide-to-animations-transitions-and-transformations-f9b2ecc8620f">CSS Made Simple: A Guide To Animations, Transitions, And Transformations</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedbacks are most welcome as always, drop them below in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae620ba7b4be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/designing-stunning-progress-bars-made-easy-with-tailwind-css-ae620ba7b4be">Designing Stunning Progress Bars Made Easy with Tailwind CSS</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>