<?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 Corfitz. on Medium]]></title>
        <description><![CDATA[Stories by Corfitz. on Medium]]></description>
        <link>https://medium.com/@corfitz?source=rss-f2ce55c9446------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b7qqs56Y4Jd0bh14v6nqmA.png</url>
            <title>Stories by Corfitz. on Medium</title>
            <link>https://medium.com/@corfitz?source=rss-f2ce55c9446------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:51:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@corfitz/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[Solving Framer Motion Page Transitions in Next.js App Router]]></title>
            <link>https://corfitz.medium.com/solving-framer-motion-page-transitions-in-next-js-app-router-bfa7a55e7dec?source=rss-f2ce55c9446------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa7a55e7dec</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-app-router]]></category>
            <category><![CDATA[transitions]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Corfitz.]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 16:27:48 GMT</pubDate>
            <atom:updated>2026-01-15T08:50:18.848Z</atom:updated>
            <content:encoded><![CDATA[<p>At the time of writing, Next.js does not have built-in support for page transitions. This is a feature that many developers have been asking for, and there are a few libraries out there that can help you achieve this. One of the most popular libraries for adding page transitions to Next.js is Framer Motion.</p><p>However, getting Framer Motion to work with Next.js App Router can be a bit tricky, especially if you want to add exit animations to your pages. An issue arises when the Next.js app router causes components to unmount and remount abruptly, disrupting animations. Here’s how we can tackle this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSOVmE9noxGdojeR0QC64A.jpeg" /></figure><p>The versions used at the time of writing are as follows:</p><ul><li>Next.js: 14.2.3</li><li>Framer Motion: 11.2.10</li></ul><p>Update: This proposed solution remains functional as of next@16.0.7 and the updated motion@11.2.10.</p><p>Shoutout to <a href="https://x.com/lochieaxon">@lochieaxon</a> for initially discovering this hack.</p><h3>Setting up Framer Motion</h3><p>The first thing you need to do is install Framer Motion in your Next.js project. You can do this by running the following command in your terminal:</p><pre>bun add framer-motion</pre><p><em>(If you aren’t using bun, I can wholeheartedly recommend you give it a try. Otherwise, you can run </em><em>npm install framer-motion instead.)</em></p><h3>Creating the LayoutTransition component</h3><p>Next, let’s create a new component called LayoutTransition that will handle the page transitions for us:</p><pre>// components/layout-transition.tsx<br>&quot;use client&quot;;<br>import { AnimatePresence, motion } from &quot;framer-motion&quot;;<br>import { usePathname } from &quot;next/navigation&quot;;<br><br>interface LayoutTransitionProps {<br>  children: React.ReactNode;<br>  className?: React.ComponentProps&lt;typeof motion.div&gt;[&quot;className&quot;];<br>  style?: React.ComponentProps&lt;typeof motion.div&gt;[&quot;style&quot;];<br>  initial: React.ComponentProps&lt;typeof motion.div&gt;[&quot;initial&quot;];<br>  animate: React.ComponentProps&lt;typeof motion.div&gt;[&quot;animate&quot;];<br>  exit: React.ComponentProps&lt;typeof motion.div&gt;[&quot;exit&quot;];<br>}<br><br>export function LayoutTransition({<br>  children,<br>  className,<br>  style,<br>  initial,<br>  animate,<br>  exit,<br>}: LayoutTransitionProps) {<br>  const path = usePathname();<br><br>  return (<br>    &lt;AnimatePresence mode=&quot;wait&quot; initial={false}&gt;<br>      &lt;motion.div<br>        className={className}<br>        style={style}<br>        key={path}<br>        initial={initial}<br>        animate={animate}<br>        exit={exit}<br>      &gt;<br>        {children}<br>      &lt;/motion.div&gt;<br>    &lt;/AnimatePresence&gt;<br>  );<br>}</pre><p>In this component, we are using the AnimatePresence component from Framer Motion to handle the page transitions. We are also using the motion.div component to create a container for our page content. The key prop is set to the current path, which will trigger the exit animation when the pathname changes.</p><h3>Using the LayoutTransition component</h3><p>Now that we have our LayoutTransition component, we can use it in our layout components to add page transitions to our Next.js app. Here is an example of how you can use the LayoutTransition component in your layout:</p><pre>// app/layout.tsx<br>import { LayoutTransition } from &quot;@/components/layout-transition&quot;;<br><br>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;LayoutTransition<br>          initial={{ opacity: 0 }}<br>          animate={{ opacity: 1 }}<br>          exit={{ opacity: 0 }}<br>        &gt;<br>          {children}<br>        &lt;/LayoutTransition&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  )<br>}</pre><p>We are getting there! However, this doesn’t really work as intended. Even though we do in fact see an exit animation, it manages to load the next page first, and then animate the exit transition followed by the enter transition. This is not what we want.</p><h3>The Core Issue with Next.js App Router and Framer Motion</h3><p>The primary challenge with using Framer Motion in a Next.js app lies in the router’s handling of component lifecycles. The Next.js app router updates the context frequently during navigation, causing components to unmount and remount abruptly. This disrupts the smooth flow of animations provided by Framer Motion’s AnimatePresence and motion components. The sudden unmounting interrupts ongoing animations, leading to jarring transitions and a suboptimal user experience.</p><h3>Investigating the Problem</h3><ol><li><strong>Router Context Changes:</strong> The router context updates with each navigation action, leading to new instances of components.</li><li><strong>Component Lifecycle Interruption: </strong>These frequent updates force components to unmount and remount, which is detrimental to animations that rely on the stability of the component tree.</li></ol><h3>Proposed Solution</h3><p>To mitigate this, we devise a two-part solution: FrozenRouter and LayoutTransition.</p><h3>Step 1: Custom Hook — usePreviousValue</h3><p>We create a custom hook, usePreviousValue, to retain the previous value of a variable. This hook utilizes a ref to store the previous value, updating it during each render and resetting it when the component unmounts.</p><pre>function usePreviousValue&lt;T&gt;(value: T): T | undefined {<br>  const prevValue = useRef&lt;T&gt;();<br><br>  useEffect(() =&gt; {<br>    prevValue.current = value;<br>    return () =&gt; {<br>      prevValue.current = undefined;<br>    };<br>  });<br><br>  return prevValue.current;<br>}</pre><h3>Step 2: FrozenRouter Component</h3><p>The FrozenRouter component uses useContext to access the current router context and usePreviousValue to track the previous context and layout segment. It then compares the current and previous segments to decide if the context should change. This approach ensures the context only updates when necessary, preventing unnecessary unmounting and remounting of components.</p><pre>function FrozenRouter(props: { children: React.ReactNode }) {<br>  const context = useContext(LayoutRouterContext);<br>  const prevContext = usePreviousValue(context) || null;<br><br>  const segment = useSelectedLayoutSegment();<br>  const prevSegment = usePreviousValue(segment);<br><br>  const changed = segment !== prevSegment &amp;&amp; segment !== undefined &amp;&amp; prevSegment !== undefined;<br><br>  return (<br>    &lt;LayoutRouterContext.Provider value={changed ? prevContext : context}&gt;<br>      {props.children}<br>    &lt;/LayoutRouterContext.Provider&gt;<br>  );<br>}</pre><p>Wait — hold your horses! Here we are using LayoutRouterContext and useSelectedLayoutSegment - what are these?</p><h4>What is LayoutRouterContext?</h4><p>LayoutRouterContext is a context object provided by Next.js, which contains the current layout state of the router. This context helps in managing and propagating layout state changes throughout the application.</p><h4>How We Use LayoutRouterContext</h4><p><strong>Importing the Context: </strong>We import LayoutRouterContext from Next.js and use it within our components.</p><pre>import { LayoutRouterContext } from &quot;next/dist/shared/lib/app-router-context.shared-runtime&quot;;</pre><p><strong>Using it in </strong><strong>FrozenRouter:</strong> In the FrozenRouter component, we access the current context and track the previous context using the usePreviousValue hook. This helps us determine whether the context has changed due to navigation.</p><ul><li><strong>Context Access: </strong>We use useContext(LayoutRouterContext) to get the current router context.</li><li><strong>Previous Context Tracking:</strong> The usePreviousValue hook helps in storing the previous context value.</li><li><strong>Context Decision: </strong>We determine if the context should be updated based on whether the segment has changed. If it has, we provide the previous context to preserve the current state, thus not unmounting the currently shown route.</li></ul><p>This approach prevents the disruption of Framer Motion animations during route changes, ensuring a seamless user experience. By controlling the context updates, we mitigate the issues caused by the Next.js app router’s handling of component lifecycles.</p><h4>What is useSelectedLayoutSegment?</h4><p>useSelectedLayoutSegment is a Next.js navigation hook that retrieves the current layout segment from the router context. This hook helps in determining the layout segment for the current route, allowing us to compare it with the previous segment to decide if the context should be updated.</p><pre>import { useSelectedLayoutSegment } from &quot;next/navigation&quot;;</pre><h4>Why do we use useSelectedLayoutSegment?</h4><p>We used usePathname to get the current path, and set the respective key in the LayoutTransition component. However, what if we wanted to use this animation component in other layout files?</p><p>By using useSelectedLayoutSegment, we can get the current layout segment from the router context, and by comparing the current state and previous state, we can decide whether to perform the animation or not.</p><p>Say you have a layout on root level and another layout in your /posts directory. When we use useSelectedLayoutSegment, we can wrap the LayoutTransition component around the children in the posts layout, which will then be the only place where the animation will be performed when the user navigates within the `/posts` route segment.</p><h3>Step 3: LayoutTransition Component</h3><p>LayoutTransition wraps its children in Framer Motion&#39;s AnimatePresence and motion.div components for animations. By using FrozenRouter, it ensures the context remains stable during animations, preventing the disruption of animations due to component unmounting and remounting.</p><pre>export function LayoutTransition({<br>  children,<br>  className,<br>  style,<br>  initial,<br>  animate,<br>  exit,<br>}: LayoutTransitionProps) {<br>  const segment = useSelectedLayoutSegment();<br><br>  return (<br>    &lt;AnimatePresence mode=&quot;wait&quot; initial={false}&gt;<br>      &lt;motion.div<br>        className={className}<br>        style={style}<br>        key={segment}<br>        initial={initial}<br>        animate={animate}<br>        exit={exit}<br>      &gt;<br>        &lt;FrozenRouter&gt;<br>          {children}<br>        &lt;/FrozenRouter&gt;<br>      &lt;/motion.div&gt;<br>    &lt;/AnimatePresence&gt;<br>  );<br>}</pre><p>Notice how we are now using useSelectedLayoutSegment instead of usePathname to get the current layout segment, and setting it as the key for the motion.div component.</p><p>Here is the complete code for the layout-transition.tsx file:</p><pre>&quot;use client&quot;;<br><br>import { AnimatePresence, motion } from &quot;framer-motion&quot;;<br>import { useSelectedLayoutSegment } from &quot;next/navigation&quot;;<br>import { LayoutRouterContext } from &quot;next/dist/shared/lib/app-router-context.shared-runtime&quot;;<br><br>import { useContext, useEffect, useRef } from &quot;react&quot;;<br><br>function usePreviousValue&lt;T&gt;(value: T): T | undefined {<br>  const prevValue = useRef&lt;T&gt;();<br><br>  useEffect(() =&gt; {<br>    prevValue.current = value;<br>    return () =&gt; {<br>      prevValue.current = undefined;<br>    };<br>  });<br><br>  return prevValue.current;<br>}<br><br>function FrozenRouter(props: { children: React.ReactNode }) {<br>  const context = useContext(LayoutRouterContext);<br>  const prevContext = usePreviousValue(context) || null;<br><br>  const segment = useSelectedLayoutSegment();<br>  const prevSegment = usePreviousValue(segment);<br><br>  const changed =<br>    segment !== prevSegment &amp;&amp;<br>    segment !== undefined &amp;&amp;<br>    prevSegment !== undefined;<br><br>  return (<br>    &lt;LayoutRouterContext.Provider value={changed ? prevContext : context}&gt;<br>      {props.children}<br>    &lt;/LayoutRouterContext.Provider&gt;<br>  );<br>}<br><br>interface LayoutTransitionProps {<br>  children: React.ReactNode;<br>  className?: React.ComponentProps&lt;typeof motion.div&gt;[&quot;className&quot;];<br>  style?: React.ComponentProps&lt;typeof motion.div&gt;[&quot;style&quot;];<br>  initial: React.ComponentProps&lt;typeof motion.div&gt;[&quot;initial&quot;];<br>  animate: React.ComponentProps&lt;typeof motion.div&gt;[&quot;animate&quot;];<br>  exit: React.ComponentProps&lt;typeof motion.div&gt;[&quot;exit&quot;];<br>}<br><br>export function LayoutTransition({<br>  children,<br>  className,<br>  style,<br>  initial,<br>  animate,<br>  exit,<br>}: LayoutTransitionProps) {<br>  const segment = useSelectedLayoutSegment();<br><br>  return (<br>    &lt;AnimatePresence mode=&quot;wait&quot; initial={false}&gt;<br>      &lt;motion.div<br>        className={className}<br>        style={style}<br>        key={segment}<br>        initial={initial}<br>        animate={animate}<br>        exit={exit}<br>      &gt;<br>        &lt;FrozenRouter&gt;{children}&lt;/FrozenRouter&gt;<br>      &lt;/motion.div&gt;<br>    &lt;/AnimatePresence&gt;<br>  );<br>}</pre><h3>Conclusion</h3><p>You should now have beautiful page transitions in your Next.js app using Framer Motion and app router.</p><p>By using FrozenRouter to manage router context and prevent unmounts, we can maintain smooth transition experiences in Next.js applications with Framer Motion. This approach ensures a seamless user experience even during complex layout transitions.</p><p>For further details, visit the <a href="https://github.com/vercel/next.js/issues/49279">GitHub issue page</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa7a55e7dec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s deal with ’em pesky fake accounts]]></title>
            <link>https://corfitz.medium.com/lets-deal-with-em-pesky-fake-accounts-608efe34762f?source=rss-f2ce55c9446------2</link>
            <guid isPermaLink="false">https://medium.com/p/608efe34762f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[fake]]></category>
            <category><![CDATA[email]]></category>
            <dc:creator><![CDATA[Corfitz.]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 13:17:44 GMT</pubDate>
            <atom:updated>2023-03-22T10:36:11.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*AXLcvWdkC9HtFzNWeZ4iPQ.png" /><figcaption>Generated by Midjourney</figcaption></figure><p>As more and more services move online, web applications have become an integral part of our daily lives. From social networking to online shopping, we use web applications for a variety of purposes. However, with the increase in the number of users, the problem of spam and fake accounts has become a significant challenge for web application developers. To address this challenge, it is encouraged that developers start using temporary email filters to prevent spam and fake accounts. One of my favourite tools for this purpose is the NPM package called <a href="https://fakefilter.net/">Fakefilter</a>.</p><p>Fakefilter is a simple and easy-to-use tool that helps web application developers to filter out temporary email addresses. 100% open-source and backed by the community. It uses a curated list of known temporary email providers to identify and block temporary email addresses which can be useful during the user registration process, when adding to your email newsletter, or when collecting lead data in exchange for i.e. webinar access or downloadables (is that a word Winston?).</p><p>There are other similar tools, but the approach taken by the team behind Fakefilter differs in that they actively monitor all providers in their list and have implemented automated systems to help continuously validate the domain/email providers, and make sure to update their NPM package daily with all the latest data.</p><p>They also supply a free REST API, which can be useful in cases where your own application isn’t regularly deployed and thus not using the latest version of the Fakefilter package. The online API calls function comes built-in to the package making it easy for you to create your own middleware function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d9c28f8fe92490e53f3484f4d29935c/href">https://medium.com/media/3d9c28f8fe92490e53f3484f4d29935c/href</a></iframe><p>There are several benefits of adding this additional layer of validation to your web application. Here are some of the most significant ones:</p><ol><li><strong>Prevent Spam and Fake Accounts: </strong>One of the most significant benefits is that it helps you prevent spam and fake accounts from being created on your platform. Temporary email addresses are often used by spammers and bots to create fake accounts and send spam messages. By filtering out temporary email addresses, you can significantly reduce the number of spam accounts on your platform.</li><li><strong>Improved User Experience: </strong>Fake accounts can harm the user experience on your platform. They can create a false sense of activity, making it difficult for genuine users to find and connect with other real users. By filtering out fake accounts, you can improve the overall user experience on your platform.</li><li><strong>Reduced Workload: </strong>Moderating user-generated content on a large platform can be a daunting task, and the presence of fake accounts can make it even more challenging. By filtering out fake accounts, you can reduce the workload of your moderation team, allowing them to focus on more important tasks.</li><li><strong>Increased Trust:</strong> Fake accounts can damage the trust that users have in your platform. If users feel that there are too many fake accounts on your platform, they may stop using it altogether. By filtering out fake accounts, you can increase the trust that users have in your platform, making it more attractive to genuine users.</li><li><strong>Easy Integration: </strong>Fakefilter is easy to integrate into any web application. It is an NPM package that can be installed with just a single line of code: pnpm install fakefilter. Once installed, you simply import { isFakeEmail } from &#39;fakefilter&#39;; and call it with the submitted email address isFakeEmail(&#39;test@fakeemail.tld&#39;).</li></ol><p>In conclusion, if you are a web application developer, using Fakefilter can be a great way to prevent spam and fake accounts from being created on your platform. It can help improve the user experience, reduce the workload of your moderation team, increase trust, and is easy to integrate.</p><p>Actually — I don’t see any downsides at all. Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=608efe34762f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding colour swatches to Shopify collection page — the easy, simple and free way.]]></title>
            <link>https://corfitz.medium.com/adding-colour-swatches-to-shopify-collection-page-the-easy-simple-and-free-way-30a5fc605ba9?source=rss-f2ce55c9446------2</link>
            <guid isPermaLink="false">https://medium.com/p/30a5fc605ba9</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[meta-fields]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[liquid]]></category>
            <dc:creator><![CDATA[Corfitz.]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 18:59:02 GMT</pubDate>
            <atom:updated>2022-04-25T19:07:46.650Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adding colour swatches to Shopify collection page — the easy, simple and free way.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWr_aQV2K_kcTUuTJ1kCqQ.png" /><figcaption>Example taken from an upcoming ecommerce site: www.pandaghost.com</figcaption></figure><p>Shopify has proved to be one of the most intuitive and user friendly platforms if you wish to build an online business selling custom goods. With thousands of apps and integrations — and dedicated Shopify service providers, you are pretty much only limited by your imagination when starting your new business venture.</p><p>And with the new Shopify 2.0 theme engine and loads of new features, a <em>LOT</em> of desires can now be fulfilled much easier than ever before. Colour swatches on your collection pages is not a new thing, but it has often required that you found a theme that supported the feature or installed an app that could achieve same.</p><p>Today we will endeavour to build our own simple colour swatches section that will be displayed on a product card in a collection. Let’s start by clarifying the goal and challenges:</p><h4>Our goal!</h4><p>We want to create a simple list of colour swatches available for a given product. We are not interested in implementing additional functionality to the swatches at this point. All we care about is informing our visitors in an easy and simple way, that this particular product exists in <em>“this array of colour options”</em>. Once we enter the product details page, the theme will take care of the variant selection the way it already does, showing the image for the selected variant for better detail etc.</p><h4>Challenge: The constraints</h4><p>Existing apps or themes tend to require you to use a certain naming convention for the variant option such as <strong><em>“Color”</em></strong> in order to function. The script will then loop through variants using that key to render either an image with a reference using the colour property or a dot with an estimated background colour based on same.</p><p>One can quickly see how such constraint may feel limiting, especially if the website is not made for English speakers.</p><h4>Challenge: Dealing with images</h4><p>The way apps and themes use the image method is by converting the variant option name to lowercase characters, replacing spaces with underscores, and adding an image extension such as .jpg, .png, or .gif. This will then require the store manager to create relevant pictures with the same names, following a sizing standard and file format, and upload them to the assets directory in the theme codebase.</p><p>This can be intimidating for some, not to mention problematic should you have two different products with a Blue colour, but you want the nuance slightly different between the two products. Then you would have to come up with fancy naming conventions for your products in order to avoid naming conflicts and issues with existing image files.</p><blockquote>NB: The benefit however for using images, is that you can represent patterns and textures that you wouldn’t be able to create simply using colours. We will get back to that.</blockquote><h4>Challenge: Dealing with colours</h4><p>Should you choose <em>NOT</em> to go for the image standard, and allow the app or theme to automatically render swatches based on your variant colours, you may experience new limits and possibly misrepresentations of your colour. Say you have a shirt that comes in red and blue. You would be inclined to simply call them red and blue. But the red is like a Crimson Red and the blue is more of a Cornflower Blue — so you will realise, that if you don’t use colour names from the official <a href="https://www.w3.org/wiki/CSS/Properties/color/keywords">CSS colour table</a>, you will have displayed a different nuance or tint of the colour compared to what it really is.</p><h3>Let’s get started</h3><p>The best way to create a list of colour swatches, where we have complete control of the hex values and easily can work with them on the product page in Shopify admin, will be to use <a href="https://help.shopify.com/en/manual/metafields?st_source=admin&amp;st_campaign=metafields_footer&amp;utm_source=admin&amp;utm_campaign=metafields_footer">Shopify metafields</a>!</p><p>In Shopify, you can find metafields under Settings in your admin panel. The URL would be something like: <a href="https://your-store-name.myshopify.com/admin/metafields">https://your-store-name.myshopify.com/admin/metafields</a>. We want to assign this metafield to a product, so we click on <strong>Products</strong> and then next on <strong>Add a definition</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WV8wdrWmKbEgpzlj5tSRCA.png" /></figure><p>Creating a new metafield is straight forward. The only thing we want to ensure we do correctly while creating the metafield is to set the namespace and key to product_info.color , select <strong>Color</strong> as content type and making sure we check “Accept list of values”.<em> Note that you can’t change these values once saved.</em> Feel free to give the metafield a name of your liking and description as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-o3L64NiPOjHr99rdNnHw.png" /></figure><p>Now — if we go to a product in Shopify admin, we can find our metafield in the very bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-jmaYpDJqXb0lLR3QSY6A.png" /></figure><p>Let’s proceed by adding the colours that we wish to display for our product on the collection pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQOjrGoZ4LEfUFdVBm7mDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqgDnsirZKrKokGx-F07RA.png" /></figure><p>I am not kidding when I say that this was the hard part. At this point, you will just have to copy a few snippets I will include for you here, and you should be good to go. I will make sure to explain how it all works as well so you are aware of what you are adding and how it works.</p><p>So — this is the point where we have to play around in the codebase. This may seem intimidating to many, if you have no experience with code, but one beautiful thing about Shopify’s theming engine and the liquid language, is that it is a templating language, meaning that you don’t rely on lots of functions and event calling, but simply render data. And if you do anything wrong, you simply revert your changes and everything will work as before.</p><blockquote><strong>Full disclaimer: </strong>I am working in the default Dawn theme so the files I am changing will be referring to those of the Dawn theme. If you are working in a different theme, make sure to add these code changes to the equivalent snippets and sections in your theme files.</blockquote><p>Let’s open the theme code editor in Shopify admin and locate the file for our product card. (In the Dawn theme it is called product-card.liquid and is located in the Snippets directory). Here we will add below code snippet so it appears under the product title.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57922007a27345987dcd484cb05d5dbd/href">https://medium.com/media/57922007a27345987dcd484cb05d5dbd/href</a></iframe><p>Basically what is happening here is that we start by checking if any colours actually have been added to the metafield. And if so, we create a wrapper we call “color-options”. In here we loop through the values of this list of colours, and display a “color-options__item” with a background-color set to each color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ip8qelFRvPI0Uq0Qz91aIg.png" /></figure><p>And then we want to update the css stylesheet for the product card to make our colour swatch look nice. In the Dawn theme, this is under the Assets directory and called component-card.css .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40e1ad42cd35e4c531f5643a05388248/href">https://medium.com/media/40e1ad42cd35e4c531f5643a05388248/href</a></iframe><p>We add display:flex to our wrapper, to make sure the colours are listed nicely next to each other. we allow them to wrap so they don’t overlap on smaller screens, and then we add an initial negative margin, to compensate for the margins added to the swatch items.</p><p>The swatch items have a fixed size of 14px x 14px. We disable flex-shrink so they preserve their size and shape, add some margin so they are nicely spaced out, make them circular by setting border-radius to 50%, and then we add a solid border with an alpha value, which works as a frame around a white colour, but also adds a little bit of shadow to the other colours.</p><p>Finally we make sure to increase the size and spacing a little on bigger screens using a media query set to screens wider than 990px.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCtBPrKV7OiFNtSW5_NaHg.png" /></figure><p>And that’s it! Now you should see a beautiful line of coloured dots that perfectly represents the colours of your product variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-Jxy-KBE9RGoP2DsS1KEA.png" /></figure><h3>What’s next?</h3><p>At this point, we have achieved our goal of showing the various colours our product is available in — but what if we wanted to have the option to show patterns or textures?</p><p>We can pretty much use the same concept of metafields and tweak our liquid snippet a little. What we would do then is to create a metafield definition with a namespace and key called product_info.material for example. And then instead of <strong>Color</strong> as a content type, we will choose <strong>Text</strong>, single line, and make sure to accept list values again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUiaopFz_2aNUdWzX4NqbA.png" /></figure><p>What we will do then, is add a text field with an image reference for each material and texture available. In Shopify admin, we can go to settings, and right underneath <strong>Metafields</strong>, we have a button called <strong>Files</strong>. Here we can upload small images (approx. 30px x 30px) in any format we desire: JPEG, PNG, or GIF. We then copy the link and add that to the list of materials for our product in the metafields section.</p><p>We can then duplicate the liquid code we added for colours and make a few tweaks. Firstly we have to make sure we are checking and looping through the correct metafield: product_info.material and then we want to make sure it is a list.single_line_text_field instead of list.color .</p><p>Then we want to change one thing about the color options, so instead of background-color:{{color}}; we want it to say background-image:url(https://medium.com/%7B%7Bcolor%7D%7D); .</p><p>To round it off, we add an extra property to the CSS for .color-options__item saying background-size: cover;</p><pre>.color-options__item {<br>  width:14px;<br>  height:14px;<br>  flex-shrink:0;<br>  margin:2px;<br>  border-radius:50%;<br>  border:1px solid;<br>  border-color:rgba(18, 18, 18, 0.04);<br>  <strong>background-size:cover;</strong><br>}</pre><p>This will make sure to always fill out the swatch shape with the material image so it stays consistent when changing screen size.</p><p>Happy coding! 🤓 🥃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30a5fc605ba9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a custom create-next-project command]]></title>
            <link>https://corfitz.medium.com/create-a-custom-create-next-project-command-2a6b35a1c8e6?source=rss-f2ce55c9446------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a6b35a1c8e6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[oh-my-zsh]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Corfitz.]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 15:40:32 GMT</pubDate>
            <atom:updated>2022-01-17T13:13:04.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jS3KTHCzGGvYizOlDktYAA.jpeg" /><figcaption>Photo by mrsiraphol — <a href="http://www.freepik.com/">www.freepik.com</a> — Edited by Corfitz.</figcaption></figure><p>It is no secret that Next.js is kinda my go-to framework for pretty much anything. Whether being client work, own projects, play grounds etc. But whenever I engage in bigger projects, I usually went through a long process of preparing my repo, getting latest packages and establishing a foundation from which the project could grow. <em>Ohh what a tiresome and long process…</em></p><p>Usually this involved configuration of TypeScript, ES Lint, CI/CD files for Gitlab, setting up src directory structure along with aliases in TS Config, adding .npmrc file with save-exact=true to ensure packages being installed and added to package.json don’t differ from one another when deploying the app 6 months later. (I have spent many them evenings wondering why everything worked well locally but for some reason got messed up once deployed to staging environment — or worse; production 😰).</p><p>March last year, a lad by the name of João Pedro Schmitz (<a href="https://github.com/jpedroschmitz">@jpedroschmitz</a>) from the GraphCMS team, published an un-opinionated boilerplate for Next.js with TypeScript and a couple of other fancy prep-work including Husky, commit linting, Prettier configuration, git commit message helpers etc. along with pretty much all other stuff I spent too long setting up every time I wanted to get rolling on a new project.</p><p><a href="https://github.com/jpedroschmitz/typescript-nextjs-starter">GitHub - jpedroschmitz/typescript-nextjs-starter: Non-opinionated TypeScript starter for Next.js. All the tools you need to build your next project ⚡️</a></p><p>It has become one of my favourite projects on GitHub, and I find myself coming by regularly to fetch the installation script: npx create-next-app ts-next -e https://github.com/jpedroschmitz/typescript-nextjs-starter .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*q_8bkYt5_I_kD1ikqf8iDw.gif" /></figure><p>As one probably will notice, it is one heck of a one-liner to remember when going to start a project. So, lazy as I am, I went to create a little zsh function to spare me the trouble of having to either remember it or looking it up every time.</p><p>Now all I have to do is simply write create-next-project &lt;project-name&gt; and BOOM! I have everything I need to crack on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhNBPNxx94MNgFq1XZPZpg.png" /></figure><h3>Enough talking — now show me!</h3><p>Certainly — but first! <em>A little disclaimer…</em> Please note I am working on a Mac, and I have zsh as my main shell. I am unfortunately not as familiar with the Windows system, so this explanation will focus on those prerequisites. If you have the linux shell enabled on your Windows system, you may be able to follow along. Should anyone out there wish to share the process of achieving same on a Windows machine, please share with me and I can update this article with your explanation.</p><p>Now — back to the show!</p><p>First up — let’s open our terminal of choice. (In my case I am using Hyper terminal with Night-Owl theme and a few plugins). In our user’s home directory, let’s create a .functions file. The reason we make it a a dot-file is simply to hide it from the file-listing when browsing the directory — thus also avoiding the chances of us deleting the file later on by a mistake.</p><p>So we start by simply writing nano .functions which will open up a text editor in our terminal. Here we can begin adding our new function.</p><p><em>Initially I had made this an alias, but realised I couldn’t pass parameters to the alias, hence why we create our own little function here.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/593141da327be0b793e8191bd25e9cc8/href">https://medium.com/media/593141da327be0b793e8191bd25e9cc8/href</a></iframe><p>Copy and past above gist in to your file and press ^c followed by ^x to save and exit the editor.</p><p>As you can read in the gist above, all left to do is add the line source $HOME/.functions to our .bashrc or .zshrc file in our user’s home directory. So next we write nano .zshrc<em> (or .bashrc if that is your choice of shell)</em>, and paste in source $HOME/.functions at the bottom of your file. And then — you guessed it! — press ^c followed by ^x to save and exit the editor.</p><p>Once done, we can now reload our terminal (close it and open again), and we should then be able to write our new create-next-project command and get started on our exciting next project <em>(no pun intended)</em>.</p><p>You now have 3 options for how to execute the command:</p><ol><li>create-next-project &lt;project-name&gt; where you substitute “&lt;project-name&gt;” with the actual name of your project.</li><li>Run create-next-project . inside your desired project folder. The period will tell the command to execute the creation of a new Next.js project inside the folder where you currently are.</li><li>create-next-project without anything, from which the command will assume you are rather lazy and thus naming the project folder “too-lazy-to-come-up-with-a-project-name”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*WhdzaWYGu5wWlqhtjHx0Hg.png" /></figure><p>Should you wish to change the default folder name, you simply change this line in the .functions file:</p><pre>NAME=${1:-too-lazy-to-come-up-with-a-project-name}</pre><p>to something like</p><pre>NAME=${1:-default-project-name}</pre><p>The only thing important is to not remove 1:- within the curly braces. This tells the command to use the first command parameter (1) given — and if not provided it should instead use (:-) — followed by the string to use as fallback.</p><h3>Final thoughts</h3><p>I can really recommend the “Next.js Typescript Starter”-repo as a solid foundation for your future Next.js projects, as it also helps you achieve an overall better code quality, commit standard, and generally helps you build higher quality apps.</p><p>Now I realise not everybody uses Next.js every day, or may be starting a new project once or twice a week, so this can for some seem a little unnecessary, to go through all this trouble to create a helper function— though I thought this would prove to be a fun little gimmick, and something worth sharing.</p><p>And that would pretty much be what this written piece is about. Just me sharing one of my favourite GitHub repos along with some playfullness in building custom functions in the terminal. At the same time, one can now see how easy it actually is to create custom terminal functions to execute common queries — so good luck building. 🤓 🥃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a6b35a1c8e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding refresh token to Strapi v.3]]></title>
            <link>https://medium.com/geekculture/adding-refresh-token-to-strapi-v-3-2b75c01bd704?source=rss-f2ce55c9446------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b75c01bd704</guid>
            <category><![CDATA[strapi]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Corfitz.]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 07:30:30 GMT</pubDate>
            <atom:updated>2021-11-03T09:05:42.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hDxwI_262jX9RFMq9-Mtg.jpeg" /></figure><p>Strapi is an awesome tool. I’m a full stack developer and have built several APIs myself from ground up, but Strapi is my absolute go-to tool for creating simple APIs and at the same time it allows for easy management through their CMS’like interface, when my clients want to make some content updates or provide support.</p><p>One thing that Strapi yet has to do better is a more long-lived authentication experience when you want to allow users and visitor to log in to your front-end and do management that way through. I have found several videos on how to refresh an existing jwt token, but still there are a few security issues with that, as once the jwt has been issued, and the token can be used to renew itself, there is no way for a user to prevent a token-thief from forever getting access to their account. Actually — at that point not even changing your password will make a difference.</p><p>So I sat down and built my extension on the users-permission plugin in Strapi to allow for a better refresh token experience, and thought it might be useful for more developers out there looking to implement same system. Now — please note that this would involve a little bit of coding experience, and you should be aware that we will overwrite Strapi code. Just keep that in mind if you plan on updating Strapi later. Hopefully with the version 4 release of Strapi in the near future and their awesome new Plugin API, we will be able to add this logic in a more elegant way, but we’ll have to see once the public beta is released.</p><h3>TL;DR</h3><p>It is a rather long article, but if you sort of know what you are doing, and just want to get it working, you can find the <a href="https://gist.github.com/imCorfitz/35252d6cadec811693b9c4a23200a1ef">gist here</a>.</p><h3><strong>Let’s begin</strong></h3><p>If you haven’t yet set up your Strapi environment, we would need to do that first. If you already have Strapi running on your machine, you can skip this step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*Kp47cRsGgc8hafH1MfSvPg.png" /></figure><pre>$: yarn create strapi-app my-project --quickstart</pre><p>Now — I just run the quickstart for the purpose of demonstration, but feel free to go through the customising experience without the --quickstart flag.</p><p>After the installation, we open up Strapi in the browser on <a href="http://localhost:1337/admin">http://localhost:1337/admin</a> and begin creating our first admin user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fYeW0p78KKhPU8NHT0CGg.png" /></figure><p>Now we are ready to start implementing our custom refresh token function. Firstly we want to add a custom field to the User collection type. You will see later on why we will need this.</p><p>Go to Content-Types Builder and select User under Collection Types. User is a preconfigured plugin in Strapi to manage users and permissions on an API level. In the bottom of the list of fields, click “Add another field to this collection type”.</p><p>Select “Number” as field type, and call it tokenVersion . Select integer as Number format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAiNHGsYpSJJ03MwuknFeg.png" /></figure><p>Click on the “Advanced Settings” tab and set the default value to 1 and check the checkbox for Private field, as we do not need this to be exposed to the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Tf1X88n_qTCb5oSLYkG1w.png" /></figure><p>Next let’s add a user in our app. Click ‘Users’ in the left menu under Collection Types and click on “Add new Users”. Fill out all the fields, mark it as confirmed and select ‘Authenticated’ as Role. This is default for users that can engage with your app.</p><p>You will notice that our TokenVersion is shown as well — but you can leave this as 1 for now. Click Save and let’s continue with next step in our API client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwhaxaXdOpy81pgm2PK-IA.png" /></figure><p>There are several great tools out there to help you test and work with your APIs. <a href="https://www.postman.com/">Postman</a> is a great tool and free to use for most use cases. If you are using VS Code as your IDE, you can also find great extensions to help you explore APIs and save to your workspace for later use. <a href="https://www.thunderclient.io/">Thunder Client</a> is one of those I enjoy using most, though in most cases I use a paid piece of software called <a href="https://paw.cloud/">Paw</a>. I really enjoy the work experience, and when you work with bigger APIs, maybe both REST and GraphQL and across multiple environments for production and tests, it just can’t get much better IMO.</p><p>Regardless of your chosen API client, let’s proceed and make an authentication request to our Strapi API. We do so by making a POST request to http://localhost:1337/auth/local posting a JSON object with two values: ‘identifier’ and ‘password’.</p><pre>{<br>  &quot;identifier&quot;: &quot;hi@imcorfitz.com&quot;,<br>  &quot;password&quot;: &quot;Qwerty1234!&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WwrJ-38kBnmcjNCuXF-cQ.png" /></figure><p>Wunderbar! Everything is working as expected. We have received a JWT (JSON Web Token) and a user object with some further information about the user that has been authenticated.</p><p>Now — let’s check out what we have in the token. If you open up a new tab in your browser and go to <a href="http://jwt.io/">jwt.io</a> you’ll find a space where you can paste in your token. On the right hand side, it will then show you details about the token including the payload, which we want to check in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXSJJBg1-092j3PcifpBPw.png" /></figure><p>The payload consists of three properties: id which includes the user ID of the authenticated user, iat which includes the timestamp for when this token was “issued at”, and exp which tells us the expiration date for this token. As you can see, we have about 1 month lifetime in one token, which in most cases are sufficient, but in theory, the token could run out at this very day and cause an unfortunate user experience, should they be submitting a 4-page long multistep form and suddenly no longer be allowed access to the API.</p><p>That is why we want a refresh token, so we can request a new access token from the server and keep the site accessible and API active while using our app. Everything up to this point should seem fairly familiar to most of you, if you’ve worked with Strapi previously. In next step, we want to make some preparation for our refresh token experience.</p><h3>Adding new Routes</h3><p>We want to create two new endpoints to Strapi: refreshToken and revoke . Refresh Token will be called by your app whenever it notices the current access token has expired. Our endpoint here will accept two properties to be submitted:</p><ul><li><strong>token</strong> | <em>string</em> | <em>The refresh token to use to generate new tokens</em></li><li><strong>renew</strong> | <em>boolean | If ‘true’ we also return a new refresh token</em></li></ul><p>The revoke endpoint will be called in case a refresh token has been compromised. We are ending up in the same loop, if the one carrying the refresh token can continue to request new access and refresh tokens, so we want a way to invalidate it. This is where we will make use of our Token Version property that we added to our User model.</p><p>The revoke endpoint should then only require the refresh token which to invalidate:</p><ul><li><strong>token</strong> | <em>string</em> | <em>the token to revoke</em></li></ul><p>Next step then is to fire up our favourite IDE (in my case VS Code) and then we want to browse to this directory: extensions &gt; users-permissions &gt; config . In this folder, we want to add a new file called routes.json and add following code:</p><pre>{<br>  &quot;routes&quot;: [<br>    {<br>      &quot;method&quot;: &quot;POST&quot;,<br>      &quot;path&quot;: &quot;/auth/refreshToken&quot;,<br>      &quot;handler&quot;: &quot;Auth.refreshToken&quot;,<br>      &quot;config&quot;: {<br>        &quot;policies&quot;: [],<br>        &quot;prefix&quot;: &quot;&quot;<br>      }<br>    },<br>    {<br>      &quot;method&quot;: &quot;POST&quot;,<br>      &quot;path&quot;: &quot;/auth/revoke&quot;,<br>      &quot;handler&quot;: &quot;Auth.revoke&quot;,<br>      &quot;config&quot;: {<br>        &quot;policies&quot;: [],<br>        &quot;prefix&quot;: &quot;&quot;<br>      }<br>    }<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzZ1A2U5WdlR1hpjWxw8-w.png" /></figure><p>Before you save this file, we want to create a new directory under extensions &gt; users-permissions called “controllers” and in here we will create a new file called Auth.js and add following code:</p><pre>&quot;use strict&quot;;</pre><pre>/**<br><em>* Auth.js controller<br>*<br>* </em>@description<em>: A set of functions called &quot;actions&quot; for managing `Auth`.<br></em>*/</pre><pre>module<em>.</em>exports = {<br><em>  async</em> <em>refreshToken</em>(ctx) {<br>    //<em> Refresh token<br>    ctx.send</em>({<br>      refreshed: true,<br>    })<br>  },<br><em>  async</em> <em>revoke</em>(ctx) {<br>    //<em> Refresh token<br>    ctx.send</em>({<br>      revoked: true,<br>    })<br>  },<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZVy_-9SbfFqrLba0xH2tw.png" /></figure><p>Save both files and check your terminal to verify everything is still working correctly. You may have to restart your Strapi server. The quick eye will catch my little mistake here in creating a routes object referring to a handler in the Auth controller prior to have created these handlers. This would cause Strapi to complain when files are saved as Strapi will automatically restart itself and validate the codebase anew. But once you’ve saved both files, you should be good to run yarn develop once again, and get your server running.</p><p>Next up, we want to enter Strapi and expose these two new endpoints for public use. We do that by going in to settings and selecting ‘Roles’ under the ‘Users &amp; permissions plugin’ section and then clicking on ‘Public’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKPFQtKMekkBPIgYMppFRw.png" /></figure><p>Down at the bottom of the list, you will expand the “users-permissions” accordion and notice our two new endpoints listed under ‘Auth’. Enable both of these and click ‘Save’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBBY4FjzZ--4hb6zrmr-fA.png" /></figure><p>Next — let’s go back to our API client and test our new endpoints. We set up a POST request, add http://localhost:1337/auth/refreshToken as the endpoint. Run it and you should expect a status 200 response with a JSON body containing a property saying: refreshed: true .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leuZJ-9-LFyxkcatHjRrZQ.png" /></figure><p>Great job so far! Until now nothing fancy has happened, but everything is working well and we have built the foundation for our custom implementation now. So let’s get started on that.</p><h3>The Refresh Token</h3><p>At this point, we are going to extend a little further on Strapi, as we want to inherit the entire ‘Auth.js’ file and extend with some custom return data. We want to extend the return object at authentication with a refresh token as well. Therefor we need to do a little custom coding in this section.</p><p>To get started, we will go to the ‘users-permissions’ repository at Strapi…</p><p><a href="https://github.com/strapi/strapi/tree/master/packages/strapi-plugin-users-permissions">strapi/strapi</a></p><p>… and locate the <a href="https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js">Auth.js</a> file under ‘controllers’.</p><p>We want to copy all of its content and paste it in to our own Auth.js file. Note that we can’t have two modules.exports objects in one file, so we will simply copy our two new handlers in to the top of the module.exports object we’ve just pasted in. If you are unsure about how to do this, you can always have a look at the <a href="https://gist.github.com/imCorfitz/35252d6cadec811693b9c4a23200a1ef">gist here</a>.</p><p>At the top of the file, just above the exported modules object, we add our custom function to generate refresh tokens.</p><pre>const<em> generateRefreshToken </em>=<em> </em>(<em>user</em>)<em> </em>=&gt;<em> </em>{<br>  <em>return strapi.plugins</em>[&quot;users-permissions&quot;]<em>.services.jwt.issue</em>(<br>    {<br>      <em>tkv</em>:<em> user.tokenVersion</em>,<em> </em>//<em> Token Version<br>    </em>},<br>    {<br>      <em>subject</em>:<em> user.id.toString</em>(),<br>      <em>expiresIn</em>:<em> </em>&quot;60d&quot;,<br>    }<br>  );<br>}</pre><p>We use the same JWT service that is used by Strapi to issue normal JWT tokens, but instead of the user ID in the payload, we add the token version, and we then add the user ID as the subject of our token in the JWT options object along with a longer expiration date. In this case I have simply doubled the lifetime of a standard token, which should suffice in most cases. There are no real standards of this, as some APIs have refresh tokens living for years while others for months. In our case, 60 days should be just fine.</p><p>Next up, we want to find all the places in Auth.js where a JWT token is being issued and extend the object with a refresh property containing the token returned by our new function: refresh: generateRefreshToken(user) . <em>(Last time I did this, I found 5 places to add this on lines: 163, 199, 245, 565, 604.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fn__DprMTaiqX9X2grrUag.png" /></figure><p>If we go back to our API client once again and run the authentication call, we should now see, that we also get a refresh token back. Wunderbar!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R15El3ckocwpdfncnthu_A.png" /></figure><p>And to be sure that the refresh token is being created correctly, let’s just verify the contents of its payload at jwt.io again. Now we see that the expiration date is 60 days away and it also includes tkv and sub which are our token version and user id. So that is great!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpPBRTwXWKSZbH8o-uyFwQ.png" /></figure><p>Next up we are going to actually build our refreshToken handler. In short, it will unpack the refresh token and start by verifying it isn’t expired. Hereafter we fetch the user based on the subject property and verify that the token version in the refresh token matches the token version for the user.</p><p>This is where we create the higher level of security. If a refresh token has been compromised or stolen, we can then simply increase the token version by 1 for the user, and then the refresh token will no longer be valid. For the extra level of security, we could also extend the resetPassword handler to automatically increase this to invalidate all current refresh tokens and thereby require the user to log in again on all browsers and devices.</p><p>If that’s all good, we then create a new jwt token (and refresh token if requested) and return to the caller.</p><pre><em>async</em> <em>refreshToken</em>(ctx) {<br>  const<em> params </em>=<em> _.assign</em>(<em>ctx.request.body</em>);<br>  <br>  //<em> Params should consist of:<br>  </em>//<em> * token - string - jwt refresh token<br>  </em>//<em> * renew - boolean - if true, also return an updated refresh token.</em></pre><pre><em>  </em>//<em> Parse Token<br>  try</em> {<br>    //<em> Unpack refresh token<br>    </em>const<em> </em>{<em>tkv</em>,<em> iat</em>,<em> exp</em>,<em> sub</em>}<em> </em>=<em> await strapi.plugins</em>[&quot;users-permissions&quot;]<em>.services.jwt.verify</em>(<em>params.token</em>);</pre><pre>    //<em> Check if refresh token has expired<br>    </em>if (Date<em>.now</em>() / 1000 &gt; exp) <em>return</em> <em>ctx.badRequest</em>(null, &quot;Expired refresh token&quot;);</pre><pre>    //<em> fetch user based on subject<br>    </em>const<em> user </em>=<em> await </em>strapi<em>.query</em>(&quot;user&quot;, &quot;users-permissions&quot;)<em>.findOne</em>({ id: sub });</pre><pre>    //<em> Check here if user token version is the same as in refresh token<br>    </em>//<em> This will ensure that the refresh token hasn&#39;t been made invalid by a password change or similar.<br>    </em>if (tkv !== <em>user.</em>tokenVersion) <em>return</em> <em>ctx.badRequest</em>(null, &quot;Refresh token is invalid&quot;);</pre><pre>    //<em> Otherwise we are good to go.<br>    ctx.send</em>({<br>      jwt: <em>strapi.</em>plugins[&quot;users-permissions&quot;]<em>.services.jwt.issue</em>({<br>        id: <em>user.</em>id,<br>      }),<br>      refresh: <em>params.</em>renew ? <em>generateRefreshToken</em>(user) : null<br>    });<br>  } <em>catch</em> (e) {<br>    <em>return</em> <em>ctx.badRequest</em>(null, &quot;Invalid token&quot;);<br>  }<br>},</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyFbVS8rJqZQDgC0LBKy8Q.png" /></figure><p>Let’s see if everything works when we call our refresh token endpoint from our API client now. This time we have to make sure we add the ‘token’ property and the optional ‘renew’ property in the JSON body when calling the endpoint. If everything is going according to plan, you should have received a new jwt and possibly refresh token in the callback. 💪</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_a9J5wKFhsvpPA-ZPvGCw.png" /></figure><h3>Revoke the token</h3><p>Now we are going to do almost the same for the revoke handler. The code will be more or less the same with a few changes. Once we have validated the refresh token we then call an update on our user, increasing the token version by 1 and return a simple confirmation to the caller.</p><pre><em>async</em> <em>revoke</em>(ctx) {<br>  const<em> params </em>=<em> _.assign</em>(<em>ctx.request.body</em>);<br>  <br>  //<em> Params should consist of:<br>  </em>//<em> * token - string - jwt refresh token</em></pre><pre>  //<em> Parse Token<br>  try</em> {<br>    //<em> Unpack refresh token<br>    </em>const<em> </em>{<em>tkv</em>,<em> iat</em>,<em> exp</em>,<em> sub</em>}<em> </em>=<em> await strapi.plugins</em>[&quot;users-permissions&quot;]<em>.services.jwt.verify</em>(<em>params.token</em>);</pre><pre>    //<em> Check if refresh token has expired<br>    </em>if (Date<em>.now</em>() / 1000 &gt; exp) <em>return</em> <em>ctx.badRequest</em>(null, &quot;Expired refresh token&quot;);</pre><pre>    //<em> fetch user based on subject<br>    </em>const<em> user </em>=<em> await </em>strapi<em>.query</em>(&quot;user&quot;, &quot;users-permissions&quot;)<em>.findOne</em>({ id: sub });</pre><pre>    //<em> Check here if user token version is the same as in refresh token<br>    </em>//<em> This will ensure that the refresh token hasn&#39;t been made invalid by a password change or similar.<br>    </em>if (tkv !== <em>user.</em>tokenVersion) <em>return</em> <em>ctx.badRequest</em>(null, &quot;Refresh token is invalid&quot;);</pre><pre>    //<em> Update the user.<br>    await</em> strapi<em>.query</em>(&quot;user&quot;, &quot;users-permissions&quot;)<em>.update</em>({ id: sub }, { tokenVersion: <em>user.</em>tokenVersion + 1 });</pre><pre>    //<em> Otherwise we are good to go.<br>    ctx.send</em>({<br>      confirmed: true,<br>    });<br>  } <em>catch</em> (e) {<br>    <em>return</em> <em>ctx.badRequest</em>(null, &quot;Invalid token&quot;);<br>  }<br>},</pre><p>Let’s test this out by copying the refresh token we used in the test we made towards our refresh token endpoint, and pass it as the token property in a JSON body that we send to a POST request to http://localhost:1337/auth/revoke .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fqzh88EE65XguPJmXlLybw.png" /></figure><p>Awesome! We got a confirmation back. Because we are curious creatures, let’s have a look in the Strapi admin and see if the token version for the user has in fact been updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m99oH30dVYaqoHdVkVHLGg.png" /></figure><p>Way to go! The token version now says 2, and now our refresh token should in theory no longer be valid. Let’s open up our API client and trigger the refresh token endpoint call again with the same data as earlier. And would you look at that — Bad request, status 400 with error message: “Refresh token is invalid”. Usually not a status and API reply you are happy to see as a developer, but in this case, it couldn’t be much better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zItaLQI4dlnV32qeqOIwMg.png" /></figure><p>At this point, we are good to go and can continue the development of our APIs, data structure and new app that we want to build. I wish you all the best and good luck with the work ahead! Cheers!</p><p><em>Corfitz, wait! I am not using REST apis but GraphQL. How can we do the same in GraphQL?</em></p><p>I am glad you asked. As we already have all the logic in place, it is simply a matter of creating the mutations needed, add to the GraphQL API, and use our new handlers to do the work. Let’s set it up.</p><h3>Now in technicolor GraphQL</h3><p>Firstly — if you haven’t already, we need to install the GraphQL extension for Strapi. Go to your Strapi admin, under Marketplace and click the download button for GraphQL. This will run the installation and restart the server. It may take a few seconds to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVgMylVZu-EsDGCsUYgAaA.png" /></figure><p>Next up, we are going back to our IDE and let’s create a new file under extensions &gt; users-permissions &gt; config called schema.graphql.js .</p><p>We start by requiring ‘lodash’ at the very top:</p><pre>const _ = require(&quot;lodash&quot;);</pre><p>Below this we will create a module.exports object consisting of 3 properties:</p><ul><li><strong>Definition</strong> | <em>GraphQL TypeDefs</em></li><li><strong>Mutation</strong> | <em>The mutations and their params and return values</em></li><li><strong>Resolver</strong> | <em>The JS code to resolve the mutation calls</em></li></ul><p>The definitions will look like this:</p><pre>definition: <em>/* GraphQL */</em> `<br>  type UsersPermissionsRefreshTokenPayload {<br>    jwt: String!<br>    refresh: String<br>  }<br>  type UsersPermissionsRevokeTokenPayload {<br>    confirmed: Boolean<br>  }<br>`,</pre><p>This will be our mutations:</p><pre>mutation: `<br>  refreshToken(token: String!, renew: Boolean): UsersPermissionsRefreshTokenPayload!<br>  revokeToken(token: String!): UsersPermissionsRevokeTokenPayload!<br>`,</pre><p>And then we have our resolvers:</p><pre>resolver: {<br>  Mutation: {<br>    refreshToken: {},<br>    revokeToken: {},<br>  },<br>}</pre><p>Under the refreshToken object, we will add three properties:</p><ul><li><strong>description</strong> | <em>string</em> | <em>Description of the mutation</em></li><li><strong>resolverOf</strong> | <em>string</em> | <em>System reference to the handler</em></li><li><strong>resolver</strong> | <em>function</em> | <em>Async function resolving the call</em></li></ul><p>let’s create it like this:</p><pre>description: &quot;Refresh JWT Token&quot;,<br>resolverOf: &quot;plugins::users-permissions.auth.refreshToken&quot;,<br><em>resolver</em>: <em>async</em> (obj, options, { context }) =&gt; {<br>  <em>context.</em>query = <em>_.toPlainObject</em>(options);</pre><pre>  <em>await</em> <em>strapi.</em>plugins[&quot;users-permissions&quot;]<em>.controllers.auth.refreshToken</em>(context);<br>  let<em> </em>output<em> </em>=<em> context.body.toJSON </em>? <em>context.body.toJSON</em>() : <em>context.</em>body;</pre><pre><em>  checkBadRequest</em>(output);</pre><pre><em>  return</em> output;<br>},</pre><p><em>Wait… checkBadRequest? Where does that come from?</em></p><p>True. We have to create this function as well. So in the top of our file, above our module exports, we will add following function:</p><pre>/**<br><em>* Throws an ApolloError if context body contains a bad request<br>* </em>@param<em> contextBody - body of the context object given to the resolver<br>* </em>@throws<em> ApolloError if the body is a bad request<br></em>*/</pre><pre>function <em>checkBadRequest</em>(contextBody) {<br>  if (<em>_.get</em>(contextBody, &quot;statusCode&quot;, 200) !== 200) {<br>    const<em> message </em>=<em> _.get</em>(contextBody,<em> </em>&quot;error&quot;,<em> </em>&quot;Bad Request&quot;);<br>    const<em> exception </em>=<em> </em>new<em> Error</em>(message);<br>    <em>exception.</em>code = <em>_.get</em>(contextBody, &quot;statusCode&quot;, 400);<br>    <em>exception.</em>data = contextBody;<br>    <em>throw</em> exception;<br>  }<br>}</pre><p>This is just a little error handler, that throws an error with the details from the Auth handler, should the result be a bad request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhtJSrwiBt3enzVlvkuhxQ.png" /></figure><p>Finally, let’s do the same for our revokeToken mutation resolver object:</p><pre>description: &quot;Revoke Refresh Token&quot;,<br>resolverOf: &quot;plugins::users-permissions.auth.revoke&quot;,<br><em>resolver</em>: <em>async</em> (obj, options, { context }) =&gt; {<br>  <em>context.</em>query = <em>_.toPlainObject</em>(options);</pre><pre><em>  await</em> <em>strapi.</em>plugins[&quot;users-permissions&quot;]<em>.controllers.auth.revoke</em>(context);<br>  let<em> </em>output<em> </em>=<em> context.body.toJSON </em>? <em>context.body.toJSON</em>() : <em>context.</em>body;</pre><pre>  <em>checkBadRequest</em>(output);</pre><pre><em>  return</em> output;<br>},</pre><p>And that’s it! If we open up our API client once again and create a GraphQL request, we can then pull the schema data and see that our two new mutation are in fact added to our GraphQL schema. Great stuff. If your API client doesn’t support GraphQL requests, you can also visit http://localhost:1337/graphql which will open the GraphQL playground on your Strapi server.</p><p>Let’s test it out! Firstly, we may have to authenticate anew and get a new refresh token, as our previous one is now invalid due to the revoke token call we made earlier.</p><p>Then we’ll create a mutation query for refreshToken in our GraphQL client, which takes in the refresh token as ‘token’ parameter, and let’s just pass ‘renew’ as true as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlhHisrctbJkJ-1dRXjFBA.png" /></figure><p>Yis! Starting to seem like a productive day! We got our new jwt token and refresh token back. Now — LET’S REVOKE ‘EM! Muahahaha!!!!</p><p>Create another mutation call to the revokeToken mutation with the refresh token, and let’s see what happens. If you are as fortunate as I, you should see a nice data callback with a property of confirmed: true . We are happy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bysTc-1QJBhPE_TtugJ7rQ.png" /></figure><p>To round it all off, let’s run our refreshToken again to see it the token has in fact been invalidated… And I believe we are done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFJn_mEJtwYFX6W1lJ0B2A.png" /></figure><h3>Final thoughts</h3><p>This is a good addition to your Strapi setup whenever you allow for users to engage with your API and data from a front-end or app and want to optimise the UX by keeping their session alive as long as they use your app.</p><p>I am surprised this simple implementation isn’t a standard part of the users-permissions extension for Strapi, but with a version 4 just around the corner, they might show us some new and exiting stuff they have worked on. nevertheless, I hope this will be helpful for a few of you.</p><p>Have a great one! 🤓 🥃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b75c01bd704" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/adding-refresh-token-to-strapi-v-3-2b75c01bd704">Adding refresh token to Strapi v.3</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Editing Shopify Metafields without an app or a plugin]]></title>
            <link>https://corfitz.medium.com/editing-shopify-metafields-without-an-app-or-a-plugin-4fe66ffbec00?source=rss-f2ce55c9446------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fe66ffbec00</guid>
            <category><![CDATA[liquid]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[svelte]]></category>
            <dc:creator><![CDATA[Corfitz.]]></dc:creator>
            <pubDate>Fri, 11 Jun 2021 14:14:46 GMT</pubDate>
            <atom:updated>2021-06-15T16:45:07.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7l-kveCeAfGxdLVzBq3sA.jpeg" /></figure><p>As a Shopify store owner, you quickly realise how heavy you rely on third party plugin providers and app developers in order to create a little bit of bespoke functionality to your online store.</p><p>Working with your products inside Shopify admin, you have access to all the standard data fields for inventory, variants, title, description, pricing etc. but the moment you wish to add, say specs for a device, or characteristics of a product, you are limited to writing these additional data in the product description field, or turn to a Shopify App for a solution.</p><p>Custom Fields apps are all over Shopify, and granted they allow for very bespoke and advanced customisation of your product details — but you may simply wish to add minor additional data such as colour or region of a wine, or measurements of a piece of furniture or maybe just want a nice way to write that a shirt is made of 100% cotton and can be ironed, without the info drowning in the boring and tasteless product description area.</p><h4>You are right! What can I do?</h4><p>I’ll tell ya! Now — most of these Custom Fields apps simply make use of a hidden and apparently secret Shopify functionality: <em>Metafields</em>. A standard feature in the Shopify platform, and a fairly simple solution to a problem most are facing, yet Shopify has failed to implement a basic table like layout for adding these custom fields in the Shopify Admin.</p><p>Well… At least they haven’t made it obvious.</p><p>In reality, Shopify does in fact allow you to manage Metafields on a global scope for products using the bulk editor combined with some fancy parameters in the query URL.</p><p>If you access you Shopify admin area on the URL: <em>https://my-shopify-store.myshopify.com/admin/bulk?resource_name=Product&amp;edit=metafields.global.custom_field_name</em>, you will find a neat overview of all your products, along with input fields allowing you to populate custom meta data for your products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_Vz6Ic7x3virN2F958ZkA.jpeg" /><figcaption>The Bulk editor with custom metafields in Shopify Admin</figcaption></figure><p>Hereafter you will simply write out the metafield in your liquid code like this: &lt;p&gt;&lt;b&gt;Colour:&lt;/b&gt; {{ product.metafields.global.colour }}&lt;/p&gt; and you are now displaying additional custom data. Now isn’t that cool?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*WBskUeTPYK9AEmLHNyE3NQ.png" /><figcaption>Example of what metafields can be used for on a product page</figcaption></figure><p>Now all you have to do, is remember this URL every time you want to add or update these metafields, and you should be good to go.</p><h4><em>But Corfitz. Isn’t there an easier way to access this overview?</em></h4><p>I am glad you asked. I couldn’t find any direct access from within the Shopify Admin itself, so what I did instead was to create a little tool, that helps you generate the url with all the metafields you need, and make it easy for you to save and reuse later.</p><p><a href="https://shopify-metafields-editor-link.vercel.app/">Shopify | Generate Metafields Editor Link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4UIQzls4WoQ3eB_I-exRg.png" /><figcaption>Shopify Metafields Editor Link Generator (Now — that’s a mouth full)</figcaption></figure><p>This simple tool allows you to add your Shopify store url and list the metafields you wish to add to your products, and it will then automatically generate the correct URL:</p><p>mywinecellar.com/admin/bulk?resource_name=Product&amp;edit=metafields.global.colour%2Cmetafields.global.region%2Cmetafields.global.year</p><p>Once generated, you can easily copy and paste this URL in the browser and get cracking, and then you simply save this URL as a favourite in your browser, or in your documentation file for later use by you or others in your company.</p><p>The code for this tool is free to use and available here:</p><p><a href="https://github.com/imCorfitz/shopify-metafields-editor-link">imCorfitz/shopify-metafields-editor-link</a></p><h4>Final remarks</h4><p>This was a fun little project. And with a couple of ‘firsts’ in this one. I watched a video by <a href="https://www.youtube.com/watch?v=UbwhADWZzvQ">Code with Chris on YouTube</a> about this very topic — and thought that this tool could be useful for not only developers but merchats themselves when managing their ecommerce and product catalogue.</p><p>I built it in Svelte, as I long have wanted to explore that framework, and it didn’t take me long to understand, build and deploy the tool. Approximately 2 hours was all that was needed, which proves to me how fast and simple the development experience is in Svelte. Definitely a new personal favourite.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fe66ffbec00" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>