<?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"><channel><title><![CDATA[David Williford]]></title><description><![CDATA[Bug fixes, tutorials, and general information about software topics I am interested in.]]></description><link>https://blog.davidwilliford.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 12 Nov 2026 14:23:12 GMT</lastBuildDate><atom:link href="https://blog.davidwilliford.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Essential Soft Skills for Software Engineers]]></title><description><![CDATA[As a technical person, it’s always been easy for me to focus on hard skills, numbers, and statistics. This worked well through school, personal projects…]]></description><link>https://blog.davidwilliford.dev/essential-soft-skills-for-software-engineers</link><guid isPermaLink="true">https://blog.davidwilliford.dev/essential-soft-skills-for-software-engineers</guid><category><![CDATA[Soft Skills]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[networking]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Sun, 28 Sep 2025 17:08:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Fa9b57hffnM/upload/eb9a7801593a4ae60d18ff8f2ac399a1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a technical person, it’s always been easy for me to focus on hard skills, numbers, and statistics. This worked well through school, personal projects and smaller teams; environments where I could accomplish a ton on my own.</p>
<p>But now I’m working in a large corporate &amp; collaborative environment, where I’ve had to change how I approach my engineering role. Primarily the soft skills. So here’s a list of the soft skills that will help you in the real tech industry.</p>
<hr />
<h2 id="heading-be-approachable">Be Approachable</h2>
<ul>
<li><p>In software, there are going to be problems. People are going to have questions. Make sure that your colleagues feel comfortable addressing you with their concerns.</p>
</li>
<li><p>Do <strong>NOT</strong> be smug, arrogant or egocentric (we all know devs like this, and working with them is a nightmare).</p>
</li>
<li><p>For being approachable, my most important piece of advice is to communicate in a friendly and understanding way.</p>
</li>
<li><p>Don’t be afraid to smile and laugh!</p>
</li>
<li><p>Don’t be afraid to be vulnerable, particularly about times in your career where you’ve made mistakes or didn’t know everything.</p>
</li>
</ul>
<p>Being relatable like this will make you much more approachable. Don’t be the person who people are scared to communicate with when something goes wrong.</p>
<hr />
<h2 id="heading-present-yourself-well">Present Yourself Well</h2>
<p>I have seen this specific soft skill determine entire careers.</p>
<p>You can be a genius engineer with all the accomplishments who graduated from a top school, and still have issues finding employment if you’re not presenting yourself properly.</p>
<ul>
<li><p>Make sure you are well groomed! Keep your hair maintained (both facial and head hair), and dress well.</p>
</li>
<li><p>Dressing well doesn’t mean wearing a full suit everywhere you go. Learn about the different dress codes: Casual, business casual, business etc., and find outfits within these styles that fit your personality and body type.</p>
</li>
<li><p>And finally: speak clearly. Especially in IT industries, where many don’t speak English as their first language.</p>
<ul>
<li><p>Try to avoid slang, swearing, and make sure to pronounce properly.</p>
</li>
<li><p>Especially around new people.</p>
</li>
</ul>
</li>
</ul>
<hr />
<h2 id="heading-take-responsibility">Take Responsibility</h2>
<ul>
<li><p>You’re going to make mistakes. And that’s okay. No one expects you to be perfect.</p>
</li>
<li><p>But what they do expect is honesty and proactivity.</p>
</li>
<li><p>When something goes wrong, don’t be scared to let people know.</p>
</li>
<li><p>Address these problems head-on, and be proactive about finding a solution.</p>
</li>
</ul>
<p>This will both help your team solve the issue, as well as build respect from your team as they see you addressed the issue honestly.</p>
<hr />
<h2 id="heading-be-patient">Be Patient</h2>
<p>In the corporate world, it is not as simple as just writing code that works. There will be other factors, like:</p>
<ul>
<li><p>the organization’s coding standards</p>
</li>
<li><p>extensive testing</p>
</li>
<li><p>scalability</p>
</li>
<li><p>compliance</p>
</li>
</ul>
<p>Learn to conform to these practices, even if you don’t want to.</p>
<p>As much as I wanted to dislike these things at first, I soon realized that they are in place for a reason. You must understand that the corporate environment is much different than school and your personal projects.</p>
<p>These companies are managing thousands of engineers, and have to make sure their products and infrastructure are safe from developer error, outside threats and hardware failure.</p>
<hr />
<h2 id="heading-dont-participate-in-the-blame-game">Don’t Participate in the Blame Game</h2>
<p>This one is easy. When there is a problem, don’t immediately go…</p>
<blockquote>
<p>“Our dev environment is broken because &lt;name_here&gt; did X,Y &amp; Z.”</p>
</blockquote>
<p>Instead, frame it in a way that is not accusatory. Maybe say…</p>
<blockquote>
<p>“Our dev environment is down. I was wondering if there were any changes recently that could have led to this? If so, can you send some links so I can see what changed? (PRs, Documentation, etc).”</p>
</blockquote>
<p>This way you can collaborate on finding and understanding the solution, without creating a potential rift in your professional relationship.</p>
<hr />
<h2 id="heading-always-bring-up-something-positive-in-negative-situations">Always Bring Up Something Positive in Negative Situations</h2>
<p>I like to think that there is always a positive outlook on something.</p>
<p>There have been many instances where a bug or a failure has led me to learning something extremely valuable. I have had issues where I’ve had to redo a large part of an application.</p>
<ul>
<li><p>This might seem annoying at first, and you are completely justified to be annoyed.</p>
</li>
<li><p>But you may learn a thing or two, and likely it will be even better the second time.</p>
</li>
</ul>
<p>And at the end when you’re all done, make sure to bring up how much you’ve learned because of it.</p>
<p>And this isn’t just about bugs or even just IT. This can be generally good life advice. Whether you encounter a problem or have to give negative criticism, there is always a way to frame it that does not completely ruin the morale of the people involved.</p>
]]></content:encoded></item><item><title><![CDATA[Embed Yotpo Reviews Widgets in Headless Stores]]></title><description><![CDATA[In this article I explain step-by-step how to implement Yotpo reviews widgets into a headless site, easily and securely.]]></description><link>https://blog.davidwilliford.dev/embed-yotpo-reviews-widgets-in-headless-stores</link><guid isPermaLink="true">https://blog.davidwilliford.dev/embed-yotpo-reviews-widgets-in-headless-stores</guid><category><![CDATA[shopify]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[Yotpo]]></category><category><![CDATA[ecommerce]]></category><category><![CDATA[APIs]]></category><category><![CDATA[integration]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Wed, 29 Jan 2025 15:54:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/FCHlYvR5gJI/upload/a5ba65e9bd2a4fa83294859ce4b74701.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently wrote an article detailing how to embed Yotpo’s loyalty widgets on a headless site. As I was writing it, I thought “<em>there is no way that the reviews widget will be this troublesome</em>”. I was wrong, it was just as troublesome. For 2 primary reasons.</p>
<ol>
<li><p>There’s not a ton of documentation on installing these widgets on a headless source. They have this guide (linked below), but it does not show any of the code examples.</p>
<ul>
<li><a target="_blank" href="https://support.yotpo.com/docs/generic-other-platforms-installing-yotpo-reviews-v3">https://support.yotpo.com/docs/generic-other-platforms-installing-yotpo-reviews-v3</a></li>
</ul>
</li>
<li><p>If your Yotpo account is already connected to your Shopify store, the Yotpo reviews dashboard will only generate the embed codes needed for the Shopify store.</p>
</li>
</ol>
<hr />
<p>Now, on with the tutorial</p>
<h2 id="heading-enable-yotpo-in-csp">Enable yotpo in CSP</h2>
<p>CSP stands for content security policy. This allows you to import scripts and media from URLs from outside of your site. If you are using Hydrogen, your CSP is located in <code>entry.server.jsx</code> .</p>
<p>If you are using another framework or vanilla JS, you will likely not have a CSP unless you have configured one manually. You can go to the next step if so.</p>
<p>Here are the CSP links you need to allow to use Yotpo in your Hydrogen app.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> {nonce, header, NonceProvider} = createContentSecurityPolicy({
    <span class="hljs-attr">connectSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>,
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>,
    ],
    <span class="hljs-attr">scriptSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>, <span class="hljs-comment">// Loader script</span>
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>, <span class="hljs-comment">// Potential dynamic script loading</span>
    ],
    <span class="hljs-attr">styleSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>,
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>,
    ],
    <span class="hljs-attr">imgSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>, <span class="hljs-comment">// Yotpo-hosted images</span>
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>,
    ],
    <span class="hljs-attr">mediaSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>,
    ],
    <span class="hljs-attr">defaultSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>,
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>,
    ],
});
</code></pre>
<p>This could be overkill haha, but I added it in most sources just in case. You likely will only need it in default and script sources.</p>
<h2 id="heading-copy-script-tag-to-rootjsx">Copy script tag to root.jsx</h2>
<p>Copy this script tag into your root component. For Hydrogen, your root component is in the file <code>root.jsx</code>.</p>
<pre><code class="lang-javascript">&lt;script src=<span class="hljs-string">"https://cdn-widgetsrepository.yotpo.com/v1/loader/&lt;app_key&gt;"</span> <span class="hljs-keyword">async</span>&gt;&lt;/script&gt;
</code></pre>
<p>Notice that it is asking for your <code>app_key</code>, not your <code>guid</code> (like for the loyalty widgets). This means, if you want to use both Yotpo loyalty widgets and Yotpo reviews widgets, you will need 2 imports.</p>
<h2 id="heading-copy-client-script-to-client-component">Copy client script to client component</h2>
<p>Go into your Yotpo Reviews dashboard. Select Display On-Site. Select the reviews widget (or any other you want to add) and click the <mark>&lt;/&gt;</mark> button in the top right. Select <strong>get the code</strong> and copy the code.</p>
<p>Since you are not using Liquid, you will need to alter this a bit like so:</p>
<pre><code class="lang-javascript">{<span class="hljs-comment">/* Yotpo Reviews Widget */</span>}
&lt;div
  className=<span class="hljs-string">"yotpo-widget-instance"</span>
  data-yotpo-instance-id=<span class="hljs-string">"&lt;your_instance_id&gt;"</span>
  data-yotpo-product-id={product.id.split(<span class="hljs-string">'/'</span>).pop()}
  data-yotpo-name={product.title}
  data-yotpo-url={<span class="hljs-string">`<span class="hljs-subst">${store_url}</span>/products/<span class="hljs-subst">${product.handle}</span>`</span>}
  data-yotpo-image-url={product.selectedVariant.image.url}
  data-yotpo-price={<span class="hljs-built_in">parseFloat</span>(product.selectedVariant.price.amount).toFixed(<span class="hljs-number">2</span>)}
  data-yotpo-currency={product.selectedVariant.price.currencyCode}
  data-yotpo-description={escapeHtml(product.description)}
&gt;&lt;/div&gt;
</code></pre>
<h2 id="heading-initialize-yotpo-widgets-in-browser-console">Initialize Yotpo Widgets in browser console</h2>
<p>For some reason, this is not done automatically. You will need to manually initialize the widgets once the DOM has loaded. This is how I accomplished this within a useEffect hook.</p>
<pre><code class="lang-javascript">  <span class="hljs-comment">// initialize yotpo widgets</span>
  useEffect(<span class="hljs-function">() =&gt;</span> {

    <span class="hljs-keyword">const</span> initializeWidgets = <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">if</span> (
        <span class="hljs-built_in">window</span>.yotpoWidgetsContainer &amp;&amp;
        <span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span>.yotpoWidgetsContainer.initWidgets === <span class="hljs-string">"function"</span>
      ) {
        yotpoWidgetsContainer.initWidgets();
      }
    };


    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">document</span>.readyState === <span class="hljs-string">"complete"</span>) {
      initializeWidgets();
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">const</span> handleLoad = <span class="hljs-function">() =&gt;</span> {
        initializeWidgets();
      };
      <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"load"</span>, handleLoad);


      <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">"load"</span>, handleLoad);
    }
  }, []);
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This should be it! If not, carefully go back and look over all of your code and read the text I have included. If you are still having issues, you can reach out to me or view the Yotpo documentation. Yotpo also has a very good support chat, but keep in mind that some of the Yotpo support team is not aware of issues surrounding headless stores and integration.</p>
]]></content:encoded></item><item><title><![CDATA[Embed Yotpo Loyalty Widgets in Headless Stores]]></title><description><![CDATA[Using Yotpo loyalty and rewards is great. In this article I explain how to implement Yotpo widgets into a headless site, easily and securely]]></description><link>https://blog.davidwilliford.dev/embed-yotpo-loyalty-widgets-in-headless-stores</link><guid isPermaLink="true">https://blog.davidwilliford.dev/embed-yotpo-loyalty-widgets-in-headless-stores</guid><category><![CDATA[Yotpo]]></category><category><![CDATA[shopify]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><category><![CDATA[APIs]]></category><category><![CDATA[embedded]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Mon, 27 Jan 2025 20:25:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/vpOeXr5wmR4/upload/12bb77626914c262a3a8a654f90c5fd2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Currently, I am working on turning a Liquid-based Shopify store into a headless Hydrogen-based store. Part of this was transferring Yotpo embedded forms to the new headless site. As for the loyalty and referrals portion of Yotpo, you can embed these forms directly into your site without the need of countless API requests and manual styling.</p>
<p>Here are some official Yotpo documents on similar topics. I used these to figure this out myself with some extra digging and tinkering. However, I feel as if these are leaving out key details and don’t directly address many of the headless platforms.</p>
<ul>
<li><p><a target="_blank" href="https://support.yotpo.com/docs/setting-up-yotpo-loyalty-referrals-on-a-headless-platform">https://support.yotpo.com/docs/setting-up-yotpo-loyalty-referrals-on-a-headless-platform</a></p>
</li>
<li><p><a target="_blank" href="https://support.yotpo.com/docs/implementing-loyalty-referrals-on-a-custom-or-generic-ecommerce-platform">https://support.yotpo.com/docs/implementing-loyalty-referrals-on-a-custom-or-generic-ecommerce-platform</a></p>
</li>
</ul>
<hr />
<p>Now, Let’s get on with the tutorial</p>
<h2 id="heading-enable-yotpo-in-csp">Enable yotpo in CSP</h2>
<p>CSP stands for content security policy. This allows you to import scripts and media from URLs from outside of your site. If you are using Hydrogen, your CSP is located in <code>entry.server.jsx</code> . If you are using another React application, you will likely not have a CSP unless you have configured one manually. You can go to the next step if so.</p>
<p>Here are the CSP links you need to allow to use Yotpo in your Hydrogen app.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> {nonce, header, NonceProvider} = createContentSecurityPolicy({
    <span class="hljs-attr">connectSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>,
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>,
    ],
    <span class="hljs-attr">scriptSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>, <span class="hljs-comment">// Loader script</span>
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>, <span class="hljs-comment">// Potential dynamic script loading</span>
    ],
    <span class="hljs-attr">styleSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>,
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>,
    ],
    <span class="hljs-attr">imgSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>, <span class="hljs-comment">// Yotpo-hosted images</span>
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>,
    ],
    <span class="hljs-attr">mediaSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>,
    ],
    <span class="hljs-attr">defaultSrc</span>: [
        <span class="hljs-string">'https://cdn-widgetsrepository.yotpo.com'</span>,
        <span class="hljs-string">'https://loyalty.yotpo.com'</span>,
    ],
});
</code></pre>
<p>This could be overkill haha, but I added it in most sources just in case. You likely will only need it in default and script sources.</p>
<h2 id="heading-copy-script-tag-to-rootjsx">Copy script tag to root.jsx</h2>
<p>Copy this script tag into your root component. For Hydrogen, your root component is in the file <code>root.jsx</code>.</p>
<pre><code class="lang-javascript">&lt;script src=<span class="hljs-string">"https://cdn-widgetsrepository.yotpo.com/v1/loader/&lt;YOUR_YOTPO_GUID&gt;"</span> <span class="hljs-keyword">async</span>&gt;&lt;/script&gt;
</code></pre>
<h2 id="heading-copy-client-script-to-client-component">Copy client script to client component</h2>
<p>Go into your Yotpo Loyalty &amp; Referrals dashboard. Select Display On-Site. Find the widget you want to embed, and click the 3 dots. Then select Embed Code to show the embed code to display your client side widget.</p>
<p>Paste this client div into your desired client component.</p>
<pre><code class="lang-javascript">&lt;div className=<span class="hljs-string">"yotpo-widget-instance"</span> data-yotpo-instance-id=<span class="hljs-string">"&lt;ISTANCE_ID&gt;"</span>&gt;&lt;/div&gt;
</code></pre>
<p><strong>Note:</strong> This will not work yet, since we still have to authenticate the client side. This is covered in the next 2 steps.</p>
<h2 id="heading-pull-yotpo-customer-info-via-server-side">Pull yotpo customer info via server-side</h2>
<p>In a server side component, pull the current customer’s Yotpo information from the Yotpo API. I do this by email, since autheticated customers will have their emails stored in the session object.</p>
<p>See the Yotpo Loyalty API documentation here: <a target="_blank" href="https://loyaltyapi.yotpo.com/reference/reference-getting-started">https://loyaltyapi.yotpo.com/reference/reference-getting-started</a></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> (url, headers) =&gt; {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, { <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>, <span class="hljs-attr">headers</span>: <span class="hljs-keyword">new</span> Headers(headers) });
        <span class="hljs-keyword">if</span> (!response.ok) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json();
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    }
};

<span class="hljs-keyword">const</span> customerEmail = <span class="hljs-string">'&lt;customer_email_here&gt;'</span>;

<span class="hljs-keyword">const</span> apiKey = context.env.YOTPO_API_KEY;
<span class="hljs-keyword">const</span> guid = context.env.YOTPO_GUID;

<span class="hljs-keyword">const</span> customerDetails = <span class="hljs-keyword">await</span> fetchData(
    <span class="hljs-string">`https://loyalty.yotpo.com/api/v2/customers?customer_email=<span class="hljs-subst">${customerEmail}</span>&amp;with_history=true`</span>, 
    {
        <span class="hljs-string">'x-guid'</span>: guid,
        <span class="hljs-string">'x-api-key'</span>: apiKey,
    }
);
</code></pre>
<h2 id="heading-create-customer-signature">Create Customer Signature</h2>
<p>For authentication over a headless source, Yotpo requires a customer signature. This signature is hex representation of a <strong>sha256</strong> hashed concatenation of the customer email and Yotpo API Key:</p>
<p><code>&lt;customer_email&gt;&lt;apiKey&gt;</code></p>
<p>Make sure you implement this in your server side logic, to make sure that your customer information and API keys are not exposed anywhere to the end user. You can (and must for the next step) pass this signature safely to the client.</p>
<p>If you are using Hydrogen, you can make your Yotpo API calls and customer signature in your loader function. Then pull these values client side as needed.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateYotpoSignature</span>(<span class="hljs-params">customerEmail, apiKey</span>) </span>{
    <span class="hljs-keyword">const</span> payload = <span class="hljs-string">`<span class="hljs-subst">${customerEmail}</span><span class="hljs-subst">${apiKey}</span>`</span>;
    <span class="hljs-keyword">const</span> hash = crypto.createHash(<span class="hljs-string">'sha256'</span>);
    hash.update(payload);
    <span class="hljs-keyword">return</span> hash.digest(<span class="hljs-string">'hex'</span>);
}

<span class="hljs-keyword">const</span> signature = generateYotpoSignature(
    customerDetails.email,
    apiKey
);
</code></pre>
<h2 id="heading-yotpo-client-authentication-div">Yotpo Client Authentication div</h2>
<p>This div utilizes the signature that is created above, and connects the correct customer to the widget.</p>
<p>Say you are implementing a custom rewards page. If your customer is authenticated on your store, they will also be authenticated on this widget. So they will see their amount of points, ability to redeem them, etc.</p>
<p>Make sure this is included on the client side of any component that uses an embedded yotpo widget.</p>
<pre><code class="lang-javascript">&lt;div
    id=<span class="hljs-string">"swell-customer-identification"</span>
    data-authenticated=<span class="hljs-string">"true"</span>
    data-email={customerDetails.email}
    data-id={customerDetails.third_party_id}
    data-token={signature}
    style={{ <span class="hljs-attr">display</span>: <span class="hljs-string">"none"</span> }}
&gt;&lt;/div&gt;
</code></pre>
<h2 id="heading-initialize-yotpo-widgets-in-browser-console">Initialize Yotpo Widgets in browser console</h2>
<p>For some reason, this did not work for me until I added this step. My yotpo widgets would not show until I ran <code>yotpoWidgetsContainer.initWidgets();</code> after the DOM was fully loaded in the console. I used a useEffect hook to call this method once the DOM was loaded.</p>
<p>Put this hook in the same client side component as you put the client widget div.</p>
<pre><code class="lang-javascript">useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> initializeWidgets = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (
            <span class="hljs-built_in">window</span>.yotpoWidgetsContainer &amp;&amp;
            <span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span>.yotpoWidgetsContainer.initWidgets === <span class="hljs-string">"function"</span>
        ) {
            yotpoWidgetsContainer.initWidgets();
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Yotpo widgets initialized!"</span>);
        }
    };

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">document</span>.readyState === <span class="hljs-string">"complete"</span>) initializeWidgets()
    <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">const</span> handleLoad = <span class="hljs-function">() =&gt;</span> initializeWidgets();
        <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"load"</span>, handleLoad);
        <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">"load"</span>, handleLoad);
    }
}, []);
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This should be it! If not, carefully go back and look over all of your code and read the text I have included. If you are still having issues, you can reach out to me or view the Yotpo documentation. Yotpo also has a very good support chat, but keep in mind that some of the Yotpo support team is not aware of issues surrounding headless stores and integration.</p>
]]></content:encoded></item><item><title><![CDATA[How to Send Customers to an Authenticated Checkout in Shopify]]></title><description><![CDATA[Learn how to send your customers to an authenticated checkout. Discover how to use customer access tokens and Multipass tokens]]></description><link>https://blog.davidwilliford.dev/how-to-send-customers-to-an-authenticated-checkout-in-shopify</link><guid isPermaLink="true">https://blog.davidwilliford.dev/how-to-send-customers-to-an-authenticated-checkout-in-shopify</guid><category><![CDATA[Shopify Development]]></category><category><![CDATA[ecommerce]]></category><category><![CDATA[shopify hydrogen]]></category><category><![CDATA[authentication]]></category><category><![CDATA[#Multipass]]></category><category><![CDATA[shopify]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Tue, 14 Jan 2025 20:50:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iYoAPaSPBKI/upload/14b7558ff229c7868d3a7d4c215a00ab.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Within Shopify, store owners are restricted from having full control of their store’s checkout page. This is a safety feature on Shopify’s end, protectecting store owners and customers from accidentally (or purposely) exposing private information. This can make something like editing checkout behavior VERY complicated within Shopify.</p>
<p>While building a headless Shopify store, I needed an automated way to link authenticated customers to a checkout that is already authenticated for them. Because if not, customers would have to sign in a second time once they arrive to the checkout. This would greatly degrade our UX.</p>
<p>To link an authenticated user (Storefront API) to an authenticated checkout session, we need to use <strong><mark>customer access tokens</mark></strong> and <strong><mark>multipass tokens</mark>.</strong></p>
<h2 id="heading-what-are-these-tokens">What are these tokens?</h2>
<p><strong>Customer Access Tokens</strong></p>
<ul>
<li>Generated by the storefront API. Requires a user’s email and password as variables, then returns an encrypted access code to authenticate the user’s session without exposing user information.</li>
</ul>
<p><strong>Multipass Tokens</strong></p>
<ul>
<li><p>Allows 3rd-party systems (headless stores, login federation etc) to authenticate users into the Shopify backend without needing to log in manually.</p>
</li>
<li><p>In this tutorialy, these are used to send a storefront-authenticated customer to a pre-authenticated Shopify checkout.</p>
</li>
<li><p><strong>Make sure to get your multipass secret from Shopify Admin before following this tutorial</strong></p>
</li>
</ul>
<hr />
<h1 id="heading-how-to">How To</h1>
<p>Now let’s write some javascript code to automate this process, that runs the neccessary API requests, generates a multipass token and redirects the user to the authenticated checkout URL.</p>
<p>In my example, I am using Hydrogen &amp; Remix, but this code can be refactored to be used with any framework or even vanilla JS.</p>
<h2 id="heading-gather-the-right-data">Gather the right data</h2>
<p>You will need to have access to the following data for this to work</p>
<ul>
<li><p>Customer access token</p>
</li>
<li><p>Customer email</p>
</li>
<li><p>Current cart ID</p>
</li>
</ul>
<h2 id="heading-pull-the-cart-contents-using-cart-id">Pull the Cart Contents using Cart ID</h2>
<p>Use the following request to get the cart line items and the checkout URL, using the cart ID.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Cart API query to return line items and checkout URL</span>
<span class="hljs-keyword">const</span> cartQuery = <span class="hljs-string">`
    query CartQuery($cartId: ID!) {
        cart(id: $cartId) {
            lines(first: 50) {
                nodes {
                    quantity
                    merchandise {
                        ... on ProductVariant {
                            id
                        }
                    }
                }
            }
            checkoutUrl
        }
    }
`</span>;

<span class="hljs-comment">// Make the request using the above query</span>
<span class="hljs-keyword">const</span> cartResponse = <span class="hljs-keyword">await</span> fetch(
    <span class="hljs-string">`https://your-store-domain.myshopify.com/api/2024-01/graphql.json`</span>,
    {
        <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
            <span class="hljs-string">'X-Shopify-Storefront-Access-Token'</span>: <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">access_token_here</span>&gt;</span>,
        },
        body: JSON.stringify({
            query: cartQuery,
            variables: { cartId },
        }),
    }
);

const cartData = await cartResponse.json();

// Error handling
if (!cartResponse.ok || cartData.errors) {
    console.error("Cart fetch failed:", cartData.errors[0]);
    return json({ errors: cartData.errors || 'Failed to fetch cart' }, { status: 400 });
}

// Grab and map the line items into an object array
const lineItems = cartData.data.cart.lines.nodes.map((line) =&gt; ({
    quantity: line.quantity,
    merchandiseId: line.merchandise.id,
}));

// Update checkout URL (will be used later)
let checkoutUrl = cartData.data.cart.checkoutUrl;</span>
</code></pre>
<h2 id="heading-create-a-multipass-token-and-redirect-to-checkout">Create a Multipass Token, and Redirect to Checkout</h2>
<p>Now that we have the <strong>checkout URL</strong>, <strong>customer access token</strong> and <strong>customer email</strong>, we can create a <strong>multipass token</strong>. Here is how I did this. You need a createdAt date, and to create a secure password for each token.</p>
<p><em>see Shopify documentation for more in-depth guidance on creating multipass tokens</em></p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
 * Utility function to generate created_at in ISO8601 format with timezone offset
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateCreatedAt</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> now = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
    <span class="hljs-keyword">const</span> offsetMinutes = now.getTimezoneOffset();
    <span class="hljs-keyword">const</span> offsetHours = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.abs(offsetMinutes) / <span class="hljs-number">60</span>);
    <span class="hljs-keyword">const</span> offsetRemainder = <span class="hljs-built_in">Math</span>.abs(offsetMinutes) % <span class="hljs-number">60</span>;
    <span class="hljs-keyword">const</span> offsetSign = offsetMinutes &gt; <span class="hljs-number">0</span> ? <span class="hljs-string">'-'</span> : <span class="hljs-string">'+'</span>;
    <span class="hljs-keyword">const</span> formattedOffset = <span class="hljs-string">`<span class="hljs-subst">${offsetSign}</span><span class="hljs-subst">${<span class="hljs-built_in">String</span>(offsetHours).padStart(<span class="hljs-number">2</span>, <span class="hljs-string">'0'</span>)}</span>:<span class="hljs-subst">${<span class="hljs-built_in">String</span>(offsetRemainder).padStart(<span class="hljs-number">2</span>, <span class="hljs-string">'0'</span>)}</span>`</span>;
    <span class="hljs-keyword">return</span> now.toISOString().replace(<span class="hljs-string">'Z'</span>, formattedOffset);
}


<span class="hljs-comment">// Pull multipass secret from environment variables</span>
<span class="hljs-keyword">const</span> multipassSecret = context.env.MULTIPASS_SECRET;
<span class="hljs-keyword">if</span> (!multipassSecret) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Multipass secret is missing."</span>);

<span class="hljs-keyword">const</span> multipassify = <span class="hljs-keyword">new</span> Multipassify(multipassSecret);


<span class="hljs-keyword">if</span> (customerAccessToken) {
    <span class="hljs-keyword">const</span> createdAt = generateCreatedAt();

    <span class="hljs-comment">// The required fields for your multipass token</span>
    <span class="hljs-comment">// return_to is vital, since it is what directs user to the checkout</span>
    <span class="hljs-keyword">const</span> multipassPayload = {
        <span class="hljs-attr">created_at</span>: createdAt,
        <span class="hljs-attr">email</span>: customerEmail,
        <span class="hljs-attr">token</span>: customerAccessToken,
        <span class="hljs-attr">return_to</span>: checkoutUrl,
    };

    <span class="hljs-keyword">const</span> multipassToken = multipassify.encode(multipassPayload);

    <span class="hljs-comment">// Generate the Multipass login URL</span>
    <span class="hljs-comment">// Going to this URL validates the multipass token, and then redirects to the return_to link</span>
    <span class="hljs-keyword">const</span> authenticatedCheckoutUrl = <span class="hljs-string">`https://www.your-store-domain.com/account/login/multipass/<span class="hljs-subst">${multipassToken}</span>`</span>;
    <span class="hljs-keyword">return</span> redirect(authenticatedCheckoutUrl);
}



<span class="hljs-comment">// If customer not authenticated, just redirect to normal checkout URL</span>
<span class="hljs-keyword">return</span> redirect(checkoutUrl);
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Your customers should now be redirected to an pre-authenticated Shopify checkout!</p>
<p>Hopefully this tutorial has helped you, not only with authenticated checkouts, but with Multipass in general. Multipass tokens have a wide variation of use cases, including implementing federated logins (Sign in with Google etc.).</p>
]]></content:encoded></item><item><title><![CDATA[How to Implement HSTS into your Hydrogen Project]]></title><description><![CDATA[A simple and quick tutorial on implementing HTTPS Strict-Transport-Security through your Hydrogen app via adding additional response headers]]></description><link>https://blog.davidwilliford.dev/how-to-implement-hsts-into-your-hydrogen-project</link><guid isPermaLink="true">https://blog.davidwilliford.dev/how-to-implement-hsts-into-your-hydrogen-project</guid><category><![CDATA[ Hydrogen ]]></category><category><![CDATA[shopify]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[Remix]]></category><category><![CDATA[ecommerce]]></category><category><![CDATA[#cybersecurity]]></category><category><![CDATA[http]]></category><category><![CDATA[https]]></category><category><![CDATA[encryption]]></category><category><![CDATA[Web Security]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Thu, 26 Dec 2024 14:40:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/_Fx34KeqIEw/upload/861f1bd1047701e2d1254e5d8278f782.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>HSTS is <strong>HTTPS Strict-Transport-Security</strong>. It enforces that only HTTPS is used across your web application, preventing unencrypted traffic being monitored and collected by unwanted entities.</p>
<h2 id="heading-hsts-in-hydrogen">HSTS in Hydrogen</h2>
<p>It can be enabled in your Hydrogen app via <strong>response headers.</strong> These response headers are found in your <strong>entry.server.js</strong> file. At the bottom of the <code>handleRequest</code> function in the <strong>entry.server.js</strong> file, you will see lines like so:</p>
<pre><code class="lang-javascript">responseHeaders.set(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
responseHeaders.set(<span class="hljs-string">'Content-Security-Policy'</span>, header);
</code></pre>
<p>These lines of code control the headers that are returned with the page content to the users. We can add some headers to ensure HSTS, making sure the application delivered to the client’s machine ONLY sends encrypted traffic through HTTPS</p>
<h2 id="heading-adding-the-hsts-headers">Adding the HSTS Headers</h2>
<pre><code class="lang-javascript"><span class="hljs-comment">// HSTS header</span>
responseHeaders.set(
  <span class="hljs-string">'Strict-Transport-Security'</span>,
  <span class="hljs-string">'max-age=31536000; includeSubDomains; preload'</span>,
);

<span class="hljs-comment">// BONUS: Prevent content sniffing</span>
responseHeaders.set(<span class="hljs-string">'X-Content-Type-Options'</span>, <span class="hljs-string">'nosniff'</span>);
</code></pre>
<p>The <strong>max-age</strong> means the amount of time <em>(in seconds)</em> that the browser should enforce the HTTPS-only policy for the domain, the <strong>includeSubDomains</strong> tells us that the policy applies to all subdomains of the specified domain, and <strong>preload</strong> denotes that the domain can be included in browsers' HSTS preload lists to enforce HTTPS by default without the user visiting the site first.</p>
<p>And at the bottom, I also added a simple extra header to prevent content sniffing!</p>
]]></content:encoded></item><item><title><![CDATA[How to implement 'Sign in with Google' for Headless Shopify Stores (React, Next.js, Hydrogen etc.)]]></title><description><![CDATA[Learn how to add 'Sign in with Google' button to your Shopify headless store. This step-by-step guide covers setup for React frameworks.]]></description><link>https://blog.davidwilliford.dev/how-to-implement-sign-in-with-google-for-headless-shopify-stores-react-nextjs-hydrogen-etc</link><guid isPermaLink="true">https://blog.davidwilliford.dev/how-to-implement-sign-in-with-google-for-headless-shopify-stores-react-nextjs-hydrogen-etc</guid><category><![CDATA[ Hydrogen ]]></category><category><![CDATA[headless cms]]></category><category><![CDATA[Headless Commerce]]></category><category><![CDATA[shopify]]></category><category><![CDATA[shopify hydrogen]]></category><category><![CDATA[Google]]></category><category><![CDATA[google cloud]]></category><category><![CDATA[Google Cloud Platform]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Thu, 05 Dec 2024 18:13:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733418386270/eaf6353f-b0f3-40e4-8320-d62387cfa50e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Shopify, by default, does not have pre-configured methods to authenticate customers via their Google accounts. In a Shopify theme environment, there are numerous apps you could use to accomplish <em>social sign-in</em>. But what about headless stores?!</p>
<p>In this tutorial, I will give you a step-by-step guide on implementing a ‘<em>Sign in with Google</em>’ option to your customer authentication.</p>
<p><em>This solution will work with ANY React framework (Hydrogen, Next.js, Remix etc.)</em></p>
<h2 id="heading-requirements">Requirements</h2>
<ul>
<li><p>Storefront API customer authentication</p>
<ul>
<li>If you are using the Customer Account API for authentication, see this article to switch to the Storefront API authentication: <a target="_blank" href="https://blog.davidwilliford.dev/ditching-customer-account-api-authentication-in-hydrogen">https://blog.davidwilliford.dev/ditching-customer-account-api-authentication-in-hydrogen</a></li>
</ul>
</li>
<li><p>Storefront and Admin API access</p>
<ul>
<li>to view &amp; create accounts, and generate access tokens</li>
</ul>
</li>
</ul>
<h2 id="heading-general-steps">General Steps</h2>
<ol>
<li><p><mark>Use Google Cloud Console to generate your Client ID</mark></p>
</li>
<li><p><mark>Enable multipass tokens in your Shopify Admin</mark></p>
</li>
<li><p><mark>Setup npm package </mark> <code>react-oauth/google</code></p>
</li>
<li><p><mark>Make the client component (renders button and Google popup)</mark></p>
</li>
<li><p><mark>Make the server component (authenticates Google token and creates multipass &amp; Shopify access token)</mark></p>
</li>
</ol>
<h2 id="heading-1-get-client-id-from-google-cloud-console">1: Get Client ID from Google Cloud Console</h2>
<p>Enter <a target="_blank" href="https://console.cloud.google.com/">Google Cloud Console</a>. Make an account and a new project if you have not already.</p>
<p>Then, navigate to <strong>APIs &amp; Services</strong> → <strong>Credentials</strong> → <strong>Create Credentials</strong></p>
<p>Fill out the form to create your credentials, adding the correct <strong>callback URIs</strong> and <strong>javascript origins</strong>.</p>
<p>The callback URI is the url that is visited after user successfully signs in via Google. This url is also sent an id_token.</p>
<p>Make sure to <strong>save your client ID,</strong> as it will be crucial for the next steps in this tutorial.</p>
<h2 id="heading-2-enable-multipass-tokens-in-your-shopify-admin">2: Enable Multipass Tokens in your Shopify Admin</h2>
<p>Within your Shopify Admin, navigate to:</p>
<p><strong>Settings</strong> → <strong>Classic Customer Accounts</strong> → <strong>Enable Multipass</strong></p>
<p>Again, make sure to <strong>save your Multipass Secret,</strong> as it will be used later in the tutorial</p>
<h2 id="heading-3-setup-react-oauthgoogle-npm-package">3: Setup ‘react-oauth/google’ NPM Package</h2>
<p><code>npm install react-oauth/google</code></p>
<p><strong>If you are using a CSP</strong> (Hydrogen contains one by default), you will need to enable the google account urls in your CSP (Hydrogen’s is in <code>entry.server.jsx</code>):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> {nonce, header, NonceProvider} = createContentSecurityPolicy({
    <span class="hljs-attr">connectSrc</span>: [
        <span class="hljs-string">'https://accounts.google.com'</span>,  <span class="hljs-comment">// add this line</span>
        <span class="hljs-comment">// any other connectSrc items</span>
    ],
    <span class="hljs-attr">defaultSrc</span>: [
        <span class="hljs-string">'https://accounts.google.com'</span>,  <span class="hljs-comment">// add this line</span>
        <span class="hljs-comment">// any other connectSrc items</span>
    ],
});
</code></pre>
<p>You will also need to wrap your content in the <strong>GoogleAuthProvider</strong> tag, inputting your Google Cloud client id as a parameter. You also need to include the <code>&lt;script&gt;</code> tag for the <strong>google gsi</strong> client.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-comment">// whatever logic you have here</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charSet</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width,initial-scale=1"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"google-site-verification"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"tZeIR-uo2DFULTGGrPpycfZgoligNd9KpFY61czQMFU"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Meta</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Links</span> <span class="hljs-attr">pathname</span>=<span class="hljs-string">{location.pathname}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'font-open'</span>&gt;</span>

          {/* Wrap content in GoogleAuthProvider */}
        <span class="hljs-tag">&lt;<span class="hljs-name">GoogleOAuthProvider</span> <span class="hljs-attr">clientId</span>=<span class="hljs-string">"&lt;YOUR_CLIENT_ID&gt;"</span> &gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Elements</span> <span class="hljs-attr">stripe</span>=<span class="hljs-string">{stripePromise}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Layout</span> {<span class="hljs-attr">...data</span>}&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">Outlet</span> /&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Layout</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">Elements</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">GoogleOAuthProvider</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">ScrollRestoration</span> <span class="hljs-attr">nonce</span>=<span class="hljs-string">{nonce}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Scripts</span> <span class="hljs-attr">nonce</span>=<span class="hljs-string">{nonce}</span> /&gt;</span>

        {/* Use google accounts script */}
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://accounts.google.com/gsi/client"</span> <span class="hljs-attr">async</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">LiveReload</span> <span class="hljs-attr">nonce</span>=<span class="hljs-string">{nonce}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
  );
}</span>
</code></pre>
<h2 id="heading-4-create-the-client-component">4: Create the Client Component</h2>
<p>This component will add the ‘Sign in with Google’ button, and allow the popup for users to select their google account.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { GoogleLogin } <span class="hljs-keyword">from</span> <span class="hljs-string">"@react-oauth/google"</span>;


<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">GoogleAuth</span>(<span class="hljs-params"></span>) </span>{

        <span class="hljs-comment">// on successful google signon, send id token to callback URI</span>
    <span class="hljs-keyword">const</span> handleSuccess = <span class="hljs-function">(<span class="hljs-params">credentialResponse</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> idToken = credentialResponse.credential;
        <span class="hljs-keyword">if</span> (!idToken) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Google ID Token is missing."</span>);
            <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">`/auth/callback/google?id_token=<span class="hljs-subst">${idToken}</span>`</span>;
    };

        <span class="hljs-comment">// Log error if sign-on fails </span>
    <span class="hljs-keyword">const</span> handleError = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Google Sign-In failed."</span>);
    };


    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex justify-center items-center mt-6"</span>&gt;</span>

                {/* Handles google sign-in popup */}
            <span class="hljs-tag">&lt;<span class="hljs-name">GoogleLogin</span>
                <span class="hljs-attr">onSuccess</span>=<span class="hljs-string">{handleSuccess}</span>
                <span class="hljs-attr">onError</span>=<span class="hljs-string">{handleError}</span>
                <span class="hljs-attr">theme</span>=<span class="hljs-string">"outline"</span>
                <span class="hljs-attr">size</span>=<span class="hljs-string">"large"</span>
                <span class="hljs-attr">text</span>=<span class="hljs-string">"signin_with"</span>
            /&gt;</span>

        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}
</code></pre>
<h2 id="heading-5-create-the-server-component">5: Create The Server Component</h2>
<p><em>Make sure the route to this component is the same as the callback URI entered when generating the Google Cloud client id.</em></p>
<p>This server component:</p>
<ul>
<li><p>Gets <strong>id_token</strong> from google authentication</p>
</li>
<li><p>Gets <strong>email</strong> using id_token</p>
</li>
<li><p>Creates <strong>multipass token</strong> for user <mark>(using multipassify npm package)</mark></p>
</li>
<li><p>If new account, create a new customer account with this email via <strong>Admin API</strong></p>
</li>
<li><p>Use multipass to generate <strong>customerAccessToken</strong> from <strong>Storefront API</strong></p>
</li>
<li><p>Redirects user to account page once complete</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Multipassify <span class="hljs-keyword">from</span> <span class="hljs-string">'multipassify'</span>;
<span class="hljs-keyword">import</span> { Buffer } <span class="hljs-keyword">from</span> <span class="hljs-string">'buffer-polyfill'</span>;
<span class="hljs-keyword">import</span> { redirect } <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/remix-oxygen'</span>;
<span class="hljs-keyword">import</span> crypto <span class="hljs-keyword">from</span> <span class="hljs-string">'crypto'</span>;

globalThis.Buffer = Buffer;


<span class="hljs-comment">// Creates correctly formated date for multipass field </span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateCreatedAt</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> now = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
    <span class="hljs-keyword">const</span> offsetMinutes = now.getTimezoneOffset();
    <span class="hljs-keyword">const</span> offsetHours = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.abs(offsetMinutes) / <span class="hljs-number">60</span>);
    <span class="hljs-keyword">const</span> offsetRemainder = <span class="hljs-built_in">Math</span>.abs(offsetMinutes) % <span class="hljs-number">60</span>;
    <span class="hljs-keyword">const</span> offsetSign = offsetMinutes &gt; <span class="hljs-number">0</span> ? <span class="hljs-string">'-'</span> : <span class="hljs-string">'+'</span>;
    <span class="hljs-keyword">const</span> formattedOffset = <span class="hljs-string">`<span class="hljs-subst">${offsetSign}</span><span class="hljs-subst">${<span class="hljs-built_in">String</span>(offsetHours).padStart(<span class="hljs-number">2</span>, <span class="hljs-string">'0'</span>)}</span>:<span class="hljs-subst">${<span class="hljs-built_in">String</span>(offsetRemainder).padStart(<span class="hljs-number">2</span>, <span class="hljs-string">'0'</span>)}</span>`</span>;
    <span class="hljs-keyword">return</span> now.toISOString().replace(<span class="hljs-string">'Z'</span>, formattedOffset);
}


<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateSecurePassword</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// randomly generates secure passsword</span>
}



<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> loader = <span class="hljs-keyword">async</span> ({ request, context }) =&gt; {

    <span class="hljs-comment">// Environment variables</span>
    <span class="hljs-keyword">const</span> STORE_DOMAIN = <span class="hljs-keyword">await</span> context.env.PUBLIC_STORE_DOMAIN;
    <span class="hljs-keyword">const</span> ADMIN_API_TOKEN = context.env.SHOPIFY_ADMIN_ACCESS_TOKEN;

    <span class="hljs-comment">// Get incoming id_token from URL param (added by Google)</span>
    <span class="hljs-keyword">const</span> url = <span class="hljs-keyword">new</span> URL(request.url);
    <span class="hljs-keyword">const</span> idToken = url.searchParams.get(<span class="hljs-string">"id_token"</span>);
    <span class="hljs-keyword">if</span> (!idToken) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"ID Token is missing."</span>);
    }

    <span class="hljs-comment">// Validate the Google ID Token</span>
    <span class="hljs-keyword">const</span> googleResponse = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://oauth2.googleapis.com/tokeninfo?id_token=<span class="hljs-subst">${idToken}</span>`</span>);
    <span class="hljs-keyword">const</span> googleData = <span class="hljs-keyword">await</span> googleResponse.json();

    <span class="hljs-keyword">if</span> (!googleResponse.ok || !googleData.email) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Failed to validate Google ID Token."</span>);
    }

    <span class="hljs-comment">// Get email from id_token</span>
    <span class="hljs-keyword">const</span> { email } = googleData;

    <span class="hljs-comment">// Get multipass secret from env</span>
    <span class="hljs-keyword">const</span> multipassSecret = context.env.MULTIPASS_SECRET;
    <span class="hljs-keyword">if</span> (!multipassSecret) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Multipass secret is missing from the environment variables."</span>);
    }

    <span class="hljs-comment">// Create multipass token</span>
    <span class="hljs-keyword">const</span> createdAt = generateCreatedAt();
    <span class="hljs-keyword">const</span> multipassify = <span class="hljs-keyword">new</span> Multipassify(multipassSecret);       <span class="hljs-comment">// create multipass</span>
    <span class="hljs-keyword">const</span> multipassPayload = { email, <span class="hljs-attr">created_at</span>: createdAt };
    <span class="hljs-keyword">const</span> multipassToken = multipassify.encode(multipassPayload); <span class="hljs-comment">// encode multipass</span>

    <span class="hljs-comment">// Check if customer exists</span>
    <span class="hljs-keyword">const</span> customerSearchResponse = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://<span class="hljs-subst">${STORE_DOMAIN}</span>/admin/api/2023-10/customers/search.json?query=email:<span class="hljs-subst">${email}</span>`</span>, {
        <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
            <span class="hljs-string">'X-Shopify-Access-Token'</span>: ADMIN_API_TOKEN,
        },
    });
    <span class="hljs-keyword">const</span> customerSearchResult = <span class="hljs-keyword">await</span> customerSearchResponse.json();
    <span class="hljs-keyword">if</span> (!customerSearchResponse.ok) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Error finding account: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(result.errors || result)}</span>`</span>);
    }
    <span class="hljs-keyword">const</span> customerExists = customerSearchResult?.customers.length &gt; <span class="hljs-number">0</span>;


    <span class="hljs-comment">// If customer doesn't exist</span>
    <span class="hljs-keyword">if</span> (!customerExists) {

        <span class="hljs-comment">// Auto-generate secure password (however you want to do this)</span>
        <span class="hljs-comment">// Not showing my password generation due to security reasons </span>
        <span class="hljs-keyword">const</span> password = generateSecurePassword();  

        <span class="hljs-comment">// Create a new customer using the Admin API, if customer does not exist</span>
        <span class="hljs-keyword">const</span> createCustomerResponse = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://<span class="hljs-subst">${STORE_DOMAIN}</span>/admin/api/2023-10/customers.json`</span>, {
            <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
            <span class="hljs-attr">headers</span>: {
                <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
                <span class="hljs-string">'X-Shopify-Access-Token'</span>: ADMIN_API_TOKEN,
            },
            <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
                <span class="hljs-attr">customer</span>: {
                    email,
                    password,
                    <span class="hljs-attr">password_confirmation</span>: password,
                },
            }),
        });
        <span class="hljs-keyword">const</span> createCustomerData = <span class="hljs-keyword">await</span> createCustomerResponse.json();
        <span class="hljs-keyword">if</span> (!createCustomerResponse.ok || createCustomerData.errors) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Failed to create customer: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(createCustomerData.errors || createCustomerData)}</span>`</span>);
        }
    }

    <span class="hljs-comment">// Authenticate user and generate customerAccessToken using Multipass</span>
    <span class="hljs-keyword">const</span> tokenMutation = <span class="hljs-keyword">await</span> context.storefront.mutate(
        <span class="hljs-string">`
        mutation customerAccessTokenCreateWithMultipass($multipassToken: String!) {
            customerAccessTokenCreateWithMultipass(multipassToken: $multipassToken) {
                customerAccessToken {
                    accessToken
                    expiresAt
                }
                customerUserErrors {
                    code
                    field
                    message
                }
            }
        }
        `</span>,
        { <span class="hljs-attr">variables</span>: { multipassToken } }
    );

    <span class="hljs-keyword">const</span> { customerAccessToken, customerUserErrors } = tokenMutation?.customerAccessTokenCreateWithMultipass || {};
    <span class="hljs-keyword">if</span> (customerUserErrors &amp;&amp; customerUserErrors.length &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(
            <span class="hljs-string">`Failed to create Customer Access Token: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(customerUserErrors)}</span>`</span>
        );
    }
    <span class="hljs-keyword">if</span> (!customerAccessToken) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Failed to generate Customer Access Token."</span>);
    }

    <span class="hljs-comment">// Adding access token to session</span>
      <span class="hljs-comment">// Could be different for you, depending on how you are storing &amp; validating tokens</span>
    <span class="hljs-keyword">await</span> context.session.set(<span class="hljs-string">"customerAccessToken"</span>, customerAccessToken.accessToken);

    <span class="hljs-comment">// redirect to account page</span>
    <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">"/account"</span>, {
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-string">"Set-Cookie"</span>: <span class="hljs-keyword">await</span> context.session.commit(),
        },
    });
};
</code></pre>
<p>Note I am using the <code>buffer</code> npm package under the alias <code>buffer-polyfill</code> . When I try to use buffer without an alias, I get an error since <strong>Hydrogen does not use the Node environment</strong>. <mark>AKA, ignore this if you are not deploying to Oxygen environment</mark></p>
<p>To do this, add this line to your package.json dependencies object and run <code>npm install</code></p>
<pre><code class="lang-javascript">buffer-polyfill: <span class="hljs-string">"npm:buffer@^6.0.3"</span>
</code></pre>
<p>Also with <code>crypto</code> , I have to edit my <code>remix.config</code> file to use <code>crypto</code> on the client and server. Here is the fields I added to my module.exports:</p>
<pre><code class="lang-json">serverNodeBuiltinsPolyfill: {
  modules: {
    crypto: <span class="hljs-literal">true</span>, <span class="hljs-comment">// Provide a JSPM polyfill</span>
  },
},
browserNodeBuiltinsPolyfill: { 
  modules: { 
    crypto: <span class="hljs-literal">true</span>,
  }
},
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Test and tinker with your solution so that it works for your authentication process for your store. Hopefully this can help you, and if not, please feel free to leave a comment or reach out.</p>
<p>Thanks for reading!</p>
]]></content:encoded></item><item><title><![CDATA[Solving "Invalid Hook Call" Errors in React]]></title><description><![CDATA[Learn how to identify and resolve React hook order violations with clear examples. Avoid pitfalls like hooks in conditionals, loops, nested functions, and…]]></description><link>https://blog.davidwilliford.dev/solving-invalid-hook-call-errors-in-react</link><guid isPermaLink="true">https://blog.davidwilliford.dev/solving-invalid-hook-call-errors-in-react</guid><category><![CDATA[React]]></category><category><![CDATA[ReactHooks]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[useState]]></category><category><![CDATA[useEffect]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Mon, 18 Nov 2024 20:35:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/1K9T5YiZ2WU/upload/5efd3967ca1066f37dbe0f848c0c5ab8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>The infamous <strong>"Invalid Hook Call"</strong> error can be a massive headache, especially in complex applications using large JavaScript files. The reason this error is obnoxious is that it is found in runtime, so you will not know it exists until you run your application.</p>
<p>In this article, we dive into common causes for this error, some examples, and fixes.</p>
<hr />
<h2 id="heading-understanding-the-error">Understanding the Error</h2>
<p><strong>Error Code in Development:</strong></p>
<p><code>Invalid hook call. Hooks can only be called inside of the body of a function component.</code></p>
<p><strong>Error Code in Production (Minified):</strong></p>
<p><code>Minified React error #321; visit</code> <a target="_blank" href="https://reactjs.org/docs/error-decoder.html?invariant=321"><code>https://reactjs.org/docs/error-decoder.html?invariant=321</code></a></p>
<p>This is likely one of the errors you saw in your console that led you to this article.</p>
<p>These errors often stem from breaking one of React’s <strong>Hook Rules,</strong> or mismanaging your React setup.</p>
<hr />
<h2 id="heading-causes-of-invalid-hook-call">Causes of "Invalid Hook Call"</h2>
<ol>
<li><p><strong>Breaking the Rules of Hooks</strong> (most common):</p>
<ul>
<li>See bottom of article for the 10 react hook rules</li>
</ul>
</li>
<li><p><strong>Mismatching React Versions</strong>:</p>
<ul>
<li>Ensure the same version of React and React DOM is used.</li>
</ul>
</li>
<li><p><strong>Duplicate React Copies</strong>:</p>
<ul>
<li>Happens when dependencies include their own React instance.</li>
</ul>
</li>
<li><p><strong>Calling Hooks Outside React Contexts</strong>:</p>
<ul>
<li>Example: Using a hook in a regular function.</li>
</ul>
</li>
</ol>
<hr />
<h2 id="heading-debugging-the-error">Debugging the Error</h2>
<ol>
<li><p><strong>Check Your Hook Placement</strong>: Ensure hooks are only used in:</p>
<ul>
<li><p>React function components</p>
</li>
<li><p>Custom hooks</p>
</li>
<li><p>See bottom of article for all hook rules</p>
</li>
</ul>
</li>
<li><p><strong>Validate React Versions</strong>: Run <code>npm list react react-dom</code> to confirm versions match.</p>
</li>
<li><p><strong>Inspect for Duplicate React Copies</strong>: Run <code>npm ls react</code> to ensure only one React version is installed.</p>
</li>
<li><p><strong>Examine the Stack Trace</strong>: The browser console often points to the file and line number (roughly) causing the issue.</p>
</li>
</ol>
<hr />
<h2 id="heading-my-personal-example">My Personal Example</h2>
<h3 id="heading-the-problem">The Problem</h3>
<p>Here’s an example of my code that was violating the <strong>Rules of Hooks</strong> by calling <code>useLocation()</code> in a regular function, which is not a React component:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">links</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> location = useLocation(); <span class="hljs-comment">// ❌ Invalid Hook Call</span>
  <span class="hljs-keyword">return</span> [{ <span class="hljs-attr">rel</span>: <span class="hljs-string">'canonical'</span>, <span class="hljs-attr">href</span>: <span class="hljs-string">`https://example.com<span class="hljs-subst">${location.pathname}</span>`</span> }];
}
</code></pre>
<p><strong>Why This Fails:</strong></p>
<ul>
<li>Hooks like <code>useLocation()</code> can only be called in a React function component or a custom hook, not in regular functions.</li>
</ul>
<hr />
<h3 id="heading-the-solution">The Solution</h3>
<p>Move the <code>useLocation()</code> call to a valid React component and pass its value down:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Corrected links function</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">links</span>(<span class="hljs-params">pathname</span>) </span>{
  <span class="hljs-keyword">return</span> [{ <span class="hljs-attr">rel</span>: <span class="hljs-string">'canonical'</span>, <span class="hljs-attr">href</span>: <span class="hljs-string">`https://example.com<span class="hljs-subst">${pathname}</span>`</span> }];
}

<span class="hljs-comment">// Valid React component</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> location = useLocation(); <span class="hljs-comment">// ✅ Valid Hook Call</span>
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Links</span> <span class="hljs-attr">pathname</span>=<span class="hljs-string">{location.pathname}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span></span>
  );
}
</code></pre>
<p><strong>Why This Works:</strong></p>
<ul>
<li>The <code>useLocation</code> hook is now called within a valid React component (<code>App</code>), and its result is passed to the <code>links</code> function.</li>
</ul>
<hr />
<h2 id="heading-the-10-rules-of-react-hooks-with-examples-and-fixes">The 10 Rules of React Hooks (With Examples and Fixes)</h2>
<p>If you are getting this error, usually it is because you are breaking one of the below rules.</p>
<h3 id="heading-1-call-hooks-at-the-top-level">1. <strong>Call Hooks at the Top Level</strong></h3>
<p>Hooks should not be placed in conditionals or loops.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ❌ Wrong</span>
<span class="hljs-comment">// Hook is placed within conditional, loop, helper function etc</span>
<span class="hljs-keyword">if</span> (someCondition) {
  useEffect(<span class="hljs-function">() =&gt;</span> { <span class="hljs-comment">/* logic here */</span> }, []);
}

<span class="hljs-comment">// ✅ Correct</span>
useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (someCondition) {
    <span class="hljs-comment">/* logic here */</span>
  }
}, []);
</code></pre>
<h3 id="heading-2-call-hooks-only-in-function-components-or-custom-hooks">2. <strong>Call Hooks Only in Function Components or Custom Hooks</strong></h3>
<p>Hooks cannot be used in regular JavaScript functions.</p>
<h3 id="heading-3-use-the-correct-dependencies">3. <strong>Use the Correct Dependencies</strong></h3>
<p>Include all variables used inside <code>useEffect</code> or other hooks as dependencies.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ❌ Wrong</span>
useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(count); <span class="hljs-comment">// count is missing in dependencies</span>
}, []);

<span class="hljs-comment">// ✅ Correct</span>
useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(count);
}, [count]);
</code></pre>
<h3 id="heading-4-create-reusable-logic-with-custom-hooks">4. <strong>Create Reusable Logic With Custom Hooks</strong></h3>
<p>Extract shared logic into custom hooks.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ✅ Custom Hook</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useFetchData</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState();
  useEffect(<span class="hljs-function">() =&gt;</span> {
    fetch(url).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json()).then(setData);
  }, [url]);
  <span class="hljs-keyword">return</span> data;
}
</code></pre>
<p>This is more so advice than a rule, but it will massively clean up your code if you understand how to abstract reused logic into your React hooks.</p>
<h3 id="heading-5-maintain-the-same-order-of-hooks">5. <strong>Maintain the Same Order of Hooks</strong></h3>
<p>The order of hooks must be consistent. Here are some ways hooks can remain inconsistent:</p>
<ul>
<li><p>Using hooks in conditionals, loops or functions</p>
</li>
<li><p>Dynamically loading components that contain hooks (based on screen size, variables etc)</p>
</li>
<li><p>Returning from a function before a potential hook call</p>
</li>
</ul>
<pre><code class="lang-javascript">  <span class="hljs-comment">// Hook usage inside a conditional (WRONG)</span>
  <span class="hljs-comment">// ❌ Hook skips when `isMobile` is false</span>
  <span class="hljs-keyword">if</span> (isMobile) {
    useEffect(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This runs only if isMobile is true."</span>); 
    }, [isMobile]);
  }

  <span class="hljs-comment">// Hook usage inside a loop (WRONG)</span>
  <span class="hljs-comment">// ❌ Hook order depends on the array length and iteration</span>
  items.forEach(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> {
    useState(item);
  });

  <span class="hljs-comment">// Hook usage inside a nested function (WRONG)</span>
  <span class="hljs-comment">// ❌ Hook order breaks because it's inside a function</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleNested</span>(<span class="hljs-params"></span>) </span>{
    useState(<span class="hljs-string">'nested'</span>); 
  }
  <span class="hljs-keyword">if</span> (items.length &gt; <span class="hljs-number">3</span>) {
    handleNested();
  }

  <span class="hljs-comment">// Dynamically loaded components based on screen size or conditions (WRONG)</span>
  <span class="hljs-comment">// ❌ Hook order changes dynamically  </span>
  <span class="hljs-keyword">if</span> (isMobile) {
    useEffect(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Conditional rendering logic with hooks"</span>);
    }, []);
  }

  <span class="hljs-comment">// Returning early from the component before a hook call (WRONG)</span>
  <span class="hljs-comment">// ❌ Skips subsequent hooks</span>
  <span class="hljs-keyword">if</span> (!items || items.length === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>No items<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>; 
    <span class="hljs-comment">// hook would be in function under this conditional</span>
  }

  <span class="hljs-comment">// Correct usage</span>
  <span class="hljs-comment">// ✅ Conditional logic inside the hook</span>
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (isMobile) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Do something when isMobile is true."</span>); 
    }
  }, [isMobile]);
</code></pre>
<h3 id="heading-6-use-the-use-prefix-for-custom-hooks">6. <strong>Use the</strong> <code>use</code> Prefix for Custom Hooks</h3>
<p>This helps distinguish hooks from regular functions.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ✅ Custom Hook</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCustomHook</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> useState();
}
</code></pre>
<h3 id="heading-7-do-not-call-hooks-in-non-react-code">7. <strong>Do Not Call Hooks in Non-React Code</strong></h3>
<p>Avoid using hooks in unrelated files or external utilities.</p>
<h3 id="heading-8-avoid-hooks-inside-async-functions">8. <strong>Avoid Hooks Inside Async Functions</strong></h3>
<p>Hooks cannot be called within asynchronous code directly.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ❌ Wrong</span>
useEffect(<span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetchData();
}, []);

<span class="hljs-comment">// ✅ Correct</span>
useEffect(<span class="hljs-function">() =&gt;</span> {
  fetchData().then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> setData(data));
}, []);
</code></pre>
<h3 id="heading-9-use-hooks-in-react-contexts">9. <strong>Use Hooks in React Contexts</strong></h3>
<p>Hooks like <code>useContext</code> require a valid context provider.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ✅ Correct</span>
<span class="hljs-keyword">const</span> MyContext = React.createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> value = useContext(MyContext); <span class="hljs-comment">// Valid</span>
}
</code></pre>
<h3 id="heading-10-avoid-direct-state-mutation">10. <strong>Avoid Direct State Mutation</strong></h3>
<p>React state must be updated using the <code>setState</code> function.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ❌ Wrong</span>
state.value = <span class="hljs-number">42</span>;

<span class="hljs-comment">// ✅ Correct</span>
setState({ <span class="hljs-attr">value</span>: <span class="hljs-number">42</span> });
</code></pre>
<hr />
<h2 id="heading-takeaways">Takeaways</h2>
<p>When debugging an <em>"Invalid Hook Call"</em> error:</p>
<ol>
<li><p>Check your hook usage against <mark>React’s Hook Rules</mark>.</p>
</li>
<li><p>Validate your project setup for version mismatches or duplicate React copies.</p>
</li>
<li><p>Review stack traces and error messages for insights.</p>
</li>
</ol>
<p>By following this guide, you can avoid this error, and ensure smooth development in your React projects.</p>
]]></content:encoded></item><item><title><![CDATA[The Ultimate Guide to Shopify APIs]]></title><description><![CDATA[Learn about Shopify's APIs, including Admin, Storefront, Partner, Analytics, and more. Discover which API is best for your store's development, analytics…]]></description><link>https://blog.davidwilliford.dev/the-ultimate-guide-to-shopify-apis</link><guid isPermaLink="true">https://blog.davidwilliford.dev/the-ultimate-guide-to-shopify-apis</guid><category><![CDATA[shopify]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[APIs]]></category><category><![CDATA[eCommerce Website Development]]></category><category><![CDATA[ecommerce web development]]></category><category><![CDATA[ecommerce]]></category><category><![CDATA[REST API]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Fri, 15 Nov 2024 22:37:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/eveI7MOcSmw/upload/8c6b8e4913360a9956c19a7d2257d5ef.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This guide breaks down the different Shopify’s APIs, their use cases, and who should use them, helping you make an informed decision in your Ecommerce development.</p>
<h2 id="heading-shopify-apis-overview"><strong>Shopify APIs Overview</strong></h2>
<h3 id="heading-1-admin-api"><strong>1️⃣ Admin API</strong></h3>
<p>The Admin API is the backbone of store management, offering unparalleled access to backend operations.</p>
<ul>
<li><p><strong>Key Features</strong>:</p>
<ul>
<li><p>Inventory management</p>
</li>
<li><p>Customer data handling</p>
</li>
<li><p>Product management</p>
</li>
<li><p>Order processing</p>
</li>
<li><p>Discount creation and tracking</p>
</li>
</ul>
</li>
<li><p><strong>Best For</strong>:</p>
<ul>
<li><p>Developers building tools for store admins.</p>
</li>
<li><p>Automating backend workflows.</p>
</li>
</ul>
</li>
<li><p><strong>Pro Tip</strong>: Keep this API behind the scenes—it should never be exposed to customers!</p>
</li>
</ul>
<h3 id="heading-2-storefront-api"><strong>2️⃣ Storefront API</strong></h3>
<p>This API is built for headless commerce and custom storefronts.</p>
<ul>
<li><p><strong>Key Features</strong>:</p>
<ul>
<li><p>Fetch products, collections, and content for any platform.</p>
</li>
<li><p>Allows full control over the customer-facing experience.</p>
</li>
</ul>
</li>
<li><p><strong>Best For</strong>:</p>
<ul>
<li><p>Developers creating custom frontends or headless stores.</p>
</li>
<li><p>Teams needing cross-platform content delivery.</p>
</li>
</ul>
</li>
<li><p><strong>Limitations</strong>:</p>
<ul>
<li>No backend admin tasks (e.g., managing inventory or orders).</li>
</ul>
</li>
</ul>
<h3 id="heading-3-customer-account-api"><strong>3️⃣ Customer Account API</strong></h3>
<p>Simplify customer authentication with this API designed for headless setups.</p>
<ul>
<li><p><strong>Key Features</strong>:</p>
<ul>
<li><p>Password-less login.</p>
</li>
<li><p>Quick and simple setup.</p>
</li>
</ul>
</li>
<li><p><strong>Best For</strong>:</p>
<ul>
<li><p>Initial implementation of customer authentication.</p>
</li>
<li><p>Teams needing a lightweight, easy-to-implement solution.</p>
</li>
</ul>
</li>
<li><p><strong>Pro Tip</strong>: While it’s great for getting started, consider switching to Storefront authentication for advanced functionality as your store grows.</p>
</li>
</ul>
<h3 id="heading-4-partner-api"><strong>4️⃣ Partner API</strong></h3>
<p>Manage multiple stores and apps with ease using the Partner API.</p>
<ul>
<li><p><strong>Key Features</strong>:</p>
<ul>
<li><p>Access to Shopify Partner accounts.</p>
</li>
<li><p>Data for app performance and billing.</p>
</li>
<li><p>Synchronizing settings across multiple stores.</p>
</li>
</ul>
</li>
<li><p><strong>Best For</strong>:</p>
<ul>
<li><p>Shopify app developers.</p>
</li>
<li><p>Agencies managing multiple client stores.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-5-analytics-api"><strong>5️⃣ Analytics API</strong></h3>
<p>Dive deep into your store’s performance metrics.</p>
<ul>
<li><p><strong>Key Features</strong>:</p>
<ul>
<li><p>Traffic, sales, and conversion tracking.</p>
</li>
<li><p>Insights into customer acquisition.</p>
</li>
<li><p>Detailed sales reports.</p>
</li>
</ul>
</li>
<li><p><strong>Best For</strong>:</p>
<ul>
<li><p>Merchants and data analysts.</p>
</li>
<li><p>Teams focusing on growth and optimization.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-6-payment-apps-api"><strong>6️⃣ Payment Apps API</strong></h3>
<p>Extend Shopify’s payment capabilities with this specialized API.</p>
<ul>
<li><p><strong>Key Features</strong>:</p>
<ul>
<li><p>Support for non-native payment methods (e.g., cryptocurrency).</p>
</li>
<li><p>Custom payment gateway integrations.</p>
</li>
</ul>
</li>
<li><p><strong>Best For</strong>:</p>
<ul>
<li><p>Developers building custom payment solutions.</p>
</li>
<li><p>Stores with unique payment processing requirements.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-7-shopify-functions-api"><strong>7️⃣ Shopify Functions API</strong></h3>
<p>Take backend customization to the next level with Shopify Functions.</p>
<ul>
<li><p><strong>Key Features</strong>:</p>
<ul>
<li><p>Extend backend logic with serverless functions.</p>
</li>
<li><p>Event-driven architecture for seamless scaling.</p>
</li>
</ul>
</li>
<li><p><strong>Best For</strong>:</p>
<ul>
<li><p>Developers adding custom discounts, shipping logic, or other advanced features.</p>
</li>
<li><p>Teams that want to extend Shopify without managing servers.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-8-ajax-apis"><strong>8️⃣ Ajax APIs</strong></h3>
<p>The go-to API for theme developers who need dynamic store functionality.</p>
<ul>
<li><p><strong>Key Features</strong>:</p>
<ul>
<li><p>Live cart updates.</p>
</li>
<li><p>Quick search capabilities.</p>
</li>
<li><p>Personalized product recommendations.</p>
</li>
</ul>
</li>
<li><p><strong>Best For</strong>:</p>
<ul>
<li><p>Developers working within Shopify themes.</p>
</li>
<li><p>Teams needing dynamic, customer-facing content in Shopify themes.</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-which-api-should-you-use"><strong>Which API Should You Use?</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Task</strong></td><td><strong>APIs to Use</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Theme Development</strong></td><td>Ajax API</td></tr>
<tr>
<td><strong>Headless Store Development</strong></td><td>Storefront API, Customer Account API</td></tr>
<tr>
<td><strong>Shopify App Development</strong></td><td>Admin API, Shopify Functions API, Payment Apps API</td></tr>
<tr>
<td><strong>Data Analytics</strong></td><td>Admin API, Analytics API, Partner API</td></tr>
</tbody>
</table>
</div><h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Whether you’re building a custom storefront, developing a Shopify app, or optimizing your store's analytics, Shopify has an API tailored to your needs. By understanding what each API offers and aligning it with your goals, you can unlock the full potential of the Shopify platform.</p>
<p><strong>Need help choosing or implementing the right Shopify API? Feel free to reach out!</strong></p>
]]></content:encoded></item><item><title><![CDATA[How to Remove Customer Account API Authentication in Hydrogen]]></title><description><![CDATA[This allows us to build custom authentication forms, and migrate away from the annoying email-code authentication into email/password authentication.]]></description><link>https://blog.davidwilliford.dev/ditching-customer-account-api-authentication-in-hydrogen</link><guid isPermaLink="true">https://blog.davidwilliford.dev/ditching-customer-account-api-authentication-in-hydrogen</guid><category><![CDATA[shopify]]></category><category><![CDATA[authentication]]></category><category><![CDATA[ecommerce]]></category><category><![CDATA[ Hydrogen ]]></category><category><![CDATA[Headless Commerce]]></category><category><![CDATA[User Authentication]]></category><category><![CDATA[Shopify API Integration]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Mon, 04 Nov 2024 14:53:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/lmFJOx7hPc4/upload/edda07c3267a130585695fd23fa949f3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we are going to migrate from the default customer account API authentication in Hydrogen. Which is the <strong>non-customizable</strong>, <strong>email-code</strong> login (like below).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730215936389/6a69bb9c-962f-410d-a887-6d6f333fca86.png" alt class="image--center mx-auto" /></p>
<p>If you are reading this, you likely made a new Hydrogen project after August 2023. Hydrogen projects created after this date are pre-configured with the <strong>customer account API</strong> as the default user authentication method.</p>
<p>This article is going to teach you how to abandon this form of authentication, and implement the storefront API for authentication instead.</p>
<h3 id="heading-notice-before-reading">Notice Before Reading</h3>
<p>Depending on your knowledge level of <strong>JWT (access token)</strong> authentication, and the Shopify APIs, I would highly recommend reading and understand the FULL article, not just skimming.</p>
<p>This is not really too difficult, but will require a good understanding of Shopify’s authentication. If you attempt to implement authentication and do it wrongly or without full oversight, <strong>you risk exposing user data to malicious attacks.</strong></p>
<p>Therefore, it is very important to understand the user authentication process very well before tampering with it.</p>
<h2 id="heading-authentication-methods-in-shopify">Authentication Methods in Shopify</h2>
<p>There are 2 primary methods for authentication in headless Shopify stores:</p>
<ol>
<li><p>The <strong>Customer Account API</strong></p>
</li>
<li><p>The <strong>Storefront API</strong></p>
</li>
</ol>
<h3 id="heading-customer-account-api">Customer Account API</h3>
<p><mark>This is the authentication method we are </mark> <strong><mark>abandoning</mark></strong></p>
<p>Newer Hydrogen builds come with the Customer Account API preconfigured as the default authentication method. You can tell if your Hydrogen project is using this, by looking for these methods in your <strong>account/login</strong> and <strong>account/logout</strong> routes within the loader functions.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
* The Customer Account API methods
*/</span>

context.customerAccount.login();     <span class="hljs-comment">// redirects user to shopify form to login</span>
context.customerAccount.logout();    <span class="hljs-comment">// logs out user</span>
context.customerAccount.authorize(); <span class="hljs-comment">// authorizes current user</span>
context.customerAccount.handleAuthStatus();  <span class="hljs-comment">// checks auth status of current user</span>
</code></pre>
<p>If you are reading this blog, you likely made a Hydrogen build after August 2023, and this was the pre-configured authentication method in your hydrogen build <em>(pictured under article title)</em>.</p>
<p>Even though we are here to abandon this as our authentication method, <strong>there are some benefits to using the customer account API on Hydrogen:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Pros</strong></td><td><strong>Cons</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Effortless setup</td><td>Forced to use email code auth</td></tr>
<tr>
<td>Preconfigured auth form</td><td>Difficult to test queries</td></tr>
<tr>
<td>Ensured Security out of box</td><td>Unable to customize authentication form</td></tr>
<tr>
<td></td><td>Not really “headless”</td></tr>
</tbody>
</table>
</div><h3 id="heading-storefront-api-authentication">Storefront API Authentication</h3>
<p><mark>This is the authentication method we want to switch to</mark></p>
<p>The Storefront API is the original method of authentication for headless storefronts. The Storefront API allows customers to sign in via email &amp; password, and allows developers full control over the authentication process.</p>
<p>This also allows us to make a completely custom login form and keep all of the user authentication within your headless site.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Pros</strong></td><td><strong>Cons</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Better Documentation and Support</td><td>Longer Setup Process</td></tr>
<tr>
<td>Completely Headless</td><td>Less Beginner-friendly</td></tr>
<tr>
<td>Ability to use custom auth form</td><td>Abstracts security responsibility to developers</td></tr>
<tr>
<td>Easy to test endpoints via GraphiQL</td></tr>
</tbody>
</table>
</div><h3 id="heading-example-storefront-api-authentication-queries">Example Storefront API Authentication Queries</h3>
<pre><code class="lang-graphql"><span class="hljs-comment"># To create user</span>
<span class="hljs-keyword">mutation</span> customerCreate(<span class="hljs-variable">$input</span>: CustomerCreateInput!) {
  customerCreate(<span class="hljs-symbol">input:</span> <span class="hljs-variable">$input</span>) {
    customer {
      id
      email
      firstName
    }
    customerUserErrors {
      field
      message
    }
  }
}


<span class="hljs-comment"># Login and return access token via email/password</span>
<span class="hljs-keyword">mutation</span> customerAccessTokenCreate(<span class="hljs-variable">$email</span>: String!, <span class="hljs-variable">$password</span>: String!) {
    customerAccessTokenCreate(<span class="hljs-symbol">input:</span> { <span class="hljs-symbol">email:</span> <span class="hljs-variable">$email</span>, <span class="hljs-symbol">password:</span> <span class="hljs-variable">$password</span> }) {
      customerAccessToken {
        accessToken
        expiresAt
      }
      customerUserErrors {
        code
        field
        message
      }
   }
}


<span class="hljs-comment"># Use accessToken for authenticated requests</span>
<span class="hljs-keyword">query</span> customer(<span class="hljs-variable">$customerAccessToken</span>: String!) {
  customer(<span class="hljs-symbol">customerAccessToken:</span> <span class="hljs-variable">$customerAccessToken</span>) {
    firstName
    lastName
    email
    orders(<span class="hljs-symbol">first:</span> <span class="hljs-number">10</span>) {
      edges {
        node {
          orderNumber
          totalPrice {
            amount
          }
        }
      }
    }
  }
}


<span class="hljs-comment"># refresh accessToken</span>
<span class="hljs-keyword">mutation</span> customerAccessTokenRenew(<span class="hljs-variable">$customerAccessToken</span>: String!) {
  customerAccessTokenRenew(<span class="hljs-symbol">customerAccessToken:</span> <span class="hljs-variable">$customerAccessToken</span>) {
    customerAccessToken {
      accessToken
      expiresAt
    }
    userErrors {
      field
      message
    }
  }
}


<span class="hljs-comment"># Log out</span>
<span class="hljs-keyword">mutation</span> customerAccessTokenDelete(<span class="hljs-variable">$customerAccessToken</span>: String!) {
  customerAccessTokenDelete(<span class="hljs-symbol">customerAccessToken:</span> <span class="hljs-variable">$customerAccessToken</span>) {
    deletedAccessToken
    userErrors {
      field
      message
    }
  }
}
</code></pre>
<p>These methods will be used later in this article, as we switch our Hydrogen application from using the <strong>Customer Account API</strong> to using the <strong>Storefront API</strong> for <strong>customer authentication</strong> (Which will allow us to make our own custom login form on our site).</p>
<h2 id="heading-build-a-custom-login-form-on-frontend">Build A Custom Login Form on Frontend</h2>
<p>For testing purposes, it is smart to build the form on the frontend first. This way, we can test the endpoints we are changing within our application. Keep in mind, the storefront API is email/password authentication.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { useFetcher } <span class="hljs-keyword">from</span> <span class="hljs-string">'@remix-run/react'</span>;
<span class="hljs-keyword">import</span> { json, redirect } <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/remix-oxygen'</span>;


<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{ context }</span>) </span>{
  <span class="hljs-keyword">const</span> customerAccessToken = <span class="hljs-keyword">await</span> context.session.get(<span class="hljs-string">'customerAccessToken'</span>);
  <span class="hljs-keyword">if</span> (!customerAccessToken) {
    <span class="hljs-keyword">return</span> json({ <span class="hljs-attr">isLoggedIn</span>: <span class="hljs-literal">false</span> });
  }

  <span class="hljs-keyword">const</span> { customer } = <span class="hljs-keyword">await</span> context.storefront.query(
  <span class="hljs-string">`query CustomerDetails($customerAccessToken: String!) {
    customer(customerAccessToken: $customerAccessToken) {
      id
    }
  }`</span>, 
  {
    <span class="hljs-attr">variables</span>: { customerAccessToken },
  });

  <span class="hljs-keyword">if</span> (customer) {
    <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'/account/orders'</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
}



<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LoginForm</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>);
    <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">''</span>);
    <span class="hljs-keyword">const</span> fetcher = useFetcher();

    <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        event.preventDefault();
        <span class="hljs-keyword">if</span>(email &amp;&amp; password) {
            <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> FormData();
            formData.append(<span class="hljs-string">'email'</span>, email);
            formData.append(<span class="hljs-string">'password'</span>, password);
            fetcher.submit(formData, { <span class="hljs-attr">method</span>: <span class="hljs-string">'post'</span>, <span class="hljs-attr">action</span>: <span class="hljs-string">'/account/login'</span> });
        }
    };

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (fetcher.data) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Response from action:'</span>, fetcher.data);
        }
    }, [fetcher.data]);

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'bg-white'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">form</span> 
                <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{(event)</span> =&gt;</span> handleSubmit(event)}
                className='max-w-sm mx-auto flex flex-col gap-3 py-10 text-sizzleBlue'
            &gt;
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'text-4xl text-center font-thin mb-2'</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                    <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span>
                    <span class="hljs-attr">value</span>=<span class="hljs-string">{email}</span>
                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setEmail(e.target.value)}
                    placeholder='Email'
                    className='rounded-md border-neutral-300'
                    required
                /&gt;
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                    <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
                    <span class="hljs-attr">value</span>=<span class="hljs-string">{password}</span>
                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setPassword(e.target.value)}
                    placeholder='Password'
                    className='rounded-md border-neutral-300'
                    required
                /&gt;
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> 
                    <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>
                    <span class="hljs-attr">className</span>=<span class="hljs-string">'self-center mt-2 px-10 py-2 bg-sizzleOrange text-white font-thin text-lg rounded-full'</span>
                &gt;</span>
                    Log In
                <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}
</code></pre>
<p>Later you can add creating new accounts, styling etc</p>
<h2 id="heading-switching-from-customer-account-api-to-storefront-api">Switching From Customer Account API to Storefront API</h2>
<p>There are <strong>4 primary components</strong> that need to be updated, when switching from the Customer Account API to the Storefront API:</p>
<ol>
<li><p>Login</p>
</li>
<li><p>Authorization</p>
</li>
<li><p>Logout</p>
</li>
<li><p>Fetching Customer Details</p>
</li>
</ol>
<p><strong>And you will need to create:</strong></p>
<ol>
<li><p>User Creation functionality</p>
</li>
<li><p>Custom Login / Signup form</p>
</li>
</ol>
<p><em>Any other instances of customerAccount methods will need to be replaced with their storefront API equivalents</em></p>
<h3 id="heading-login-component">Login Component</h3>
<p>Your <code>account/login</code> route will go from this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {json} <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/remix-oxygen'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{ request, context }</span>) </span>{
  <span class="hljs-keyword">return</span> context.customerAccount.login();
}
</code></pre>
<p>to this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {json} <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/remix-oxygen'</span>;
<span class="hljs-keyword">import</span> {redirect} <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/remix-oxygen'</span>;


<span class="hljs-comment">// Will now receive POST requests from custome login form</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">action</span>(<span class="hljs-params">{ request, context }</span>) </span>{

  <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">await</span> request.formData();
  <span class="hljs-keyword">const</span> email = formData.get(<span class="hljs-string">'email'</span>);
  <span class="hljs-keyword">const</span> password = formData.get(<span class="hljs-string">'password'</span>);

  <span class="hljs-comment">// Call the Storefront API's customerAccessTokenCreate mutation</span>
  <span class="hljs-keyword">const</span> { customerAccessTokenCreate } = <span class="hljs-keyword">await</span> context.storefront.mutate(<span class="hljs-string">`
    mutation customerAccessTokenCreate($email: String!, $password: String!) {
      customerAccessTokenCreate(input: { email: $email, password: $password }) {
        customerAccessToken {
          accessToken
          expiresAt
        }
        customerUserErrors {
          code
          field
          message
        }
      }
    }
  `</span>, { <span class="hljs-attr">variables</span>: { email, password } });

  <span class="hljs-comment">// Check if there were any errors in the mutation response</span>
  <span class="hljs-keyword">if</span> (customerAccessTokenCreate.customerUserErrors.length &gt; <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> json({ <span class="hljs-attr">error</span>: customerAccessTokenCreate.customerUserErrors }, { <span class="hljs-attr">status</span>: <span class="hljs-number">400</span> });
  }

  <span class="hljs-comment">// Get the access token</span>
  <span class="hljs-keyword">const</span> accessToken = customerAccessTokenCreate.customerAccessToken.accessToken;

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Access Token: "</span>, accessToken);

  <span class="hljs-comment">// Store the access token in the session</span>
  <span class="hljs-keyword">await</span> context.session.set(<span class="hljs-string">'customerAccessToken'</span>, accessToken);

  <span class="hljs-comment">// Commit the session and send Set-Cookie header back to the client</span>
  <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'/account/orders'</span>, {
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'Set-Cookie'</span>: <span class="hljs-keyword">await</span> context.session.commit(),
    },
  });
}
</code></pre>
<h3 id="heading-authorization-component">Authorization Component</h3>
<p>In my storefront API setup, I no longer utilize the <code>/account/authorization</code> route given by the customer Account API:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{context}</span>) </span>{
  <span class="hljs-keyword">return</span> context.customerAccount.authorize();
}
</code></pre>
<p>Instead, I store access tokens in the <strong>session</strong>. Sessions should already be set up in your Hydrogen application (in <code>lib/session.js</code> ).</p>
<p><strong>Session methods:</strong></p>
<ul>
<li><p><code>context.session.get('key');</code> gets the value of a value stored in the session</p>
</li>
<li><p><code>context.session.set('key', value);</code> stores a new value in the session</p>
</li>
<li><p><code>context.session.unset('key');</code> deletes a session value</p>
</li>
<li><p><code>context.session.commit();</code> saves all of the changes that were made to the session during the component (typically is towards bottom of server component</p>
</li>
</ul>
<h3 id="heading-how-to-check-if-a-user-is-logged-in-and-redirect-accordingly">How to check if a user is logged in, and redirect accordingly</h3>
<p>This code snippet is used to check if a user is logged in, and redirect accordingly. Put this in any page you only want signed-in users to view. <em>Orders page, account page etc.</em></p>
<p>This effectively replaces the <code>authorization</code> component. You could abstract this to a utility function and just reference it access multiple components.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> customerAccessToken = <span class="hljs-keyword">await</span> context.session.get(<span class="hljs-string">'customerAccessToken'</span>);

<span class="hljs-keyword">const</span> { customer } = <span class="hljs-keyword">await</span> context.storefront.query(
  <span class="hljs-string">`query CustomerDetails($customerAccessToken: String!) {
    customer(customerAccessToken: $customerAccessToken) {
      id
    }
  }`</span>, 
  {
    <span class="hljs-attr">variables</span>: { customerAccessToken },
  });

  <span class="hljs-keyword">if</span> (customer) {
    <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'/account/orders'</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
</code></pre>
<h3 id="heading-logout-component">Logout Component</h3>
<p>For my logout code, in route <code>/account/logout</code>, it goes from:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {redirect} <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/remix-oxygen'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'/'</span>);
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">action</span>(<span class="hljs-params">{context}</span>) </span>{
  <span class="hljs-keyword">return</span> context.customerAccount.logout();
}
</code></pre>
<p>to:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// In essence, all this does is delete the access token and redirect</span>

<span class="hljs-keyword">import</span> { redirect } <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/remix-oxygen'</span>;

<span class="hljs-comment">// Mutation to invalidate the access token on Shopify</span>
<span class="hljs-keyword">const</span> CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION = <span class="hljs-string">`
  mutation customerAccessTokenDelete($customerAccessToken: String!) {
    customerAccessTokenDelete(customerAccessToken: $customerAccessToken) {
      deletedAccessToken
      userErrors {
        field
        message
      }
    }
  }
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'/'</span>);
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">action</span>(<span class="hljs-params">{ context }</span>) </span>{
  <span class="hljs-comment">// Get the customerAccessToken from the session</span>
  <span class="hljs-keyword">const</span> customerAccessToken = <span class="hljs-keyword">await</span> context.session.get(<span class="hljs-string">'customerAccessToken'</span>);

  <span class="hljs-keyword">if</span> (customerAccessToken) {
    <span class="hljs-comment">// Invalidate the token in Shopify</span>
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> { data, errors } = <span class="hljs-keyword">await</span> context.storefront.mutate({
        <span class="hljs-attr">mutation</span>: CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION,
        <span class="hljs-attr">variables</span>: { customerAccessToken },
      });

      <span class="hljs-keyword">if</span> (errors?.length || !data.customerAccessTokenDelete.deletedAccessToken) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error invalidating customer access token:'</span>, errors || data.customerAccessTokenDelete.userErrors);
      }
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error while invalidating access token:'</span>, error);
    }
  }

  <span class="hljs-comment">// Clear the session by unsetting the customerAccessToken</span>
  context.session.unset(<span class="hljs-string">'customerAccessToken'</span>);

  <span class="hljs-comment">// Redirect the user to the homepage and commit the session changes</span>
  <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'/'</span>, {
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'Set-Cookie'</span>: <span class="hljs-keyword">await</span> context.session.commit(),
    },
  });
}
</code></pre>
<h3 id="heading-fetching-customer-details">Fetching Customer Details</h3>
<p>Change your <code>/account</code> route from this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{context}</span>) </span>{
  <span class="hljs-keyword">const</span> {data, errors} = <span class="hljs-keyword">await</span> context.customerAccount.query(
    CUSTOMER_DETAILS_QUERY,
  );

  <span class="hljs-keyword">if</span> (errors?.length || !data?.customer) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Customer not found'</span>);
  }

  <span class="hljs-keyword">return</span> json(
    {<span class="hljs-attr">customer</span>: data.customer},
    {
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Cache-Control'</span>: <span class="hljs-string">'no-cache, no-store, must-revalidate'</span>,
        <span class="hljs-string">'Set-Cookie'</span>: <span class="hljs-keyword">await</span> context.session.commit(),
      },
    },
  );
}
</code></pre>
<p>to this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{ context }</span>) </span>{
  <span class="hljs-keyword">const</span> customerAccessToken = <span class="hljs-keyword">await</span> context.session.get(<span class="hljs-string">'customerAccessToken'</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Customer Access Token from session: "</span>, customerAccessToken);

  <span class="hljs-keyword">if</span> (!customerAccessToken) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Customer not authenticated'</span>);
  }

  <span class="hljs-comment">// Using the Storefront API instead of customerAccount API</span>
  <span class="hljs-keyword">const</span> { customer } = <span class="hljs-keyword">await</span> context.storefront.query(CUSTOMER_DETAILS_QUERY, {
    <span class="hljs-attr">variables</span>: { customerAccessToken },
  });

  <span class="hljs-keyword">if</span> (!customer) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Customer not found'</span>);
  }

  <span class="hljs-keyword">return</span> json(
    { customer },
    {
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Cache-Control'</span>: <span class="hljs-string">'no-cache, no-store, must-revalidate'</span>,
        <span class="hljs-string">'Set-Cookie'</span>: <span class="hljs-keyword">await</span> context.session.commit(),
      },
    }
  );
}



<span class="hljs-keyword">const</span> CUSTOMER_DETAILS_QUERY = <span class="hljs-string">`
  query CustomerDetails($customerAccessToken: String!) {
    customer(customerAccessToken: $customerAccessToken) {
      id
      firstName
      lastName
      email
      acceptsMarketing
      createdAt
      phone
      defaultAddress {
        address1
        address2
        city
        province
        country
        zip
      }
    }
  }
`</span>;
</code></pre>
<p>Notice I also changed the graphQL query, since we are now using the Storefront API.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you enjoyed this tutorial. And most importantly, I hope you learned more about the storefront API and the customer account API. Understanding these 2 APIs in Hydrogen will allow you to make this migration seamlessly and specific to your application.</p>
<p>Don’t forget, your application may be different than mine. The main idea here is switching your <strong>customer account API methods</strong> to <strong>storefront API queries</strong> that can accomplish the same task.</p>
<p><mark>Make sure that you have gotten rid of any</mark> <code>context.customerAccount</code> <mark>references. When </mark> <code>context.customerAccount</code> <mark> is referenced, your application will automatically send a GET request to </mark> <code>account/login</code> <mark> if not logged in via customer account API.</mark></p>
]]></content:encoded></item><item><title><![CDATA[Complete Tutorial for Hydrogen Authentication on Local Dev Environments]]></title><description><![CDATA[Learn how to setup your local Hydrogen dev environment so you can run and test customer user authentication, and get rid of the annoying URI mismatch error]]></description><link>https://blog.davidwilliford.dev/how-to-hydrogen-authentication-on-local-dev-server</link><guid isPermaLink="true">https://blog.davidwilliford.dev/how-to-hydrogen-authentication-on-local-dev-server</guid><category><![CDATA[ Hydrogen ]]></category><category><![CDATA[shopify]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[Shopify store,]]></category><category><![CDATA[Headless Commerce]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Fri, 25 Oct 2024 14:07:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729866067164/04601d0e-acae-4d0b-bbd4-8a535a126c83.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One thing you will learn when working with Hydrogen, is the strict security policies surrounding the Shopify Customer Account API. This is Shopify’s new API to handle customer authentication (released August 2023, and now pre-configured by default in new Hydrogen setups).</p>
<p>These security policies will prevent you from running any sort of customer account authentication on localhost. Shopify does not support any http address being authorized to utilize the customer account API. You will see errors like so if you try to run any customer API endpoints on localhost:</p>
<p><img src="https://camo.githubusercontent.com/c35cda756346db99fa5c18d635d1646a7c0dbd43d0398d2807c32d9c3623eb87/68747470733a2f2f73637265656e73686f742e636c69636b2f31382d35342d72313271772d6b387876782e706e67" alt="The error was: &quot;redirect_uri&quot; mismatch when signing in as a customer to a  newly created storefront · Issue #1898 · Shopify/hydrogen · GitHub" /></p>
<h2 id="heading-how-do-we-fix-this">How do we fix this?</h2>
<p>In summary, we are going to set up a <strong>https tunnel domain</strong> via <strong>ngrok</strong>, to run your app locally on a <strong>static https address</strong>. If this sounds new to you, I promise this is not as complicated as it sounds.</p>
<p>Here are the steps we are going to take throughout this article.</p>
<ol>
<li><p>Download ngrok</p>
</li>
<li><p>Create static ngrok domain</p>
</li>
<li><p>Connect local dev server to ngrok domain</p>
</li>
<li><p>Authorize your new ngrok setup</p>
</li>
</ol>
<h2 id="heading-step-1-download-ngrok">Step 1: Download Ngrok</h2>
<p>Visit ngrok and create an account</p>
<p>For <strong>Windows</strong></p>
<ul>
<li>Go to <strong>Setup &amp; Installation</strong>, select <strong>Windows</strong>, then scroll down and select the <strong>Download</strong> tab. There you can install the exe to install ngrok. This is by far the simplest setup method.</li>
</ul>
<p><a target="_blank" href="https://dashboard.ngrok.com/get-started/setup/macos">Download For Mac</a></p>
<p><a target="_blank" href="https://dashboard.ngrok.com/get-started/setup/linux">Download For Linux</a></p>
<h3 id="heading-authorize-ngrok-via-your-auth-token">Authorize Ngrok via your auth token</h3>
<p>You should see a terminal command under your download instructions to add your ngrok auth token. This can be run in your terminal anywhere, since ngrok is installed globally.</p>
<p><code>ngrok config add-authtoken &lt;your-token-here&gt;</code></p>
<h2 id="heading-step-2-create-static-domain-via-ngrok">Step 2: Create Static Domain via Ngrok</h2>
<p>In your ngrok dashboard, select:</p>
<ul>
<li><strong>Domains</strong> &gt; <strong>New Domain</strong></li>
</ul>
<p>This will create a new <strong>static domain</strong> for you to use. This domain will serve as your new local dev server url.</p>
<p>This domain will be the primary component throughout the rest of this tutorial.</p>
<h2 id="heading-step-3-connect-ngrok-domain-to-hydrogen-setup">Step 3: Connect Ngrok domain to Hydrogen Setup</h2>
<p>Here are the steps for connecting your local Hydrogen setup to your new ngrok url</p>
<ol>
<li><p>Run your Hydrogen app locally via <code>npm run dev</code></p>
</li>
<li><p>In a new terminal window, connect your ngrok domain to the local port you are running your Hydrogen app on (3000 for example).</p>
<p> <code>ngrok http --domain=&lt;your-ngrok-domain&gt; 3000</code></p>
</li>
</ol>
<p>Now when you refresh, you can access the dev environment through your ngrok domain.</p>
<p><em>Keep in mind, that anything running on port 3000 now can be accessed via this url.</em></p>
<h2 id="heading-step-4-authorize-ngrok-domain-with-hydrogen-csp-and-shopify">Step 4: Authorize Ngrok Domain with Hydrogen CSP and Shopify</h2>
<p>Now that you have connected your ngrok domain to your <strong>local Hydrogen dev server</strong>, we need to let Hydrogen and Shopify know this url is safe to use.</p>
<h3 id="heading-authorize-with-hydrogen-csp">Authorize with Hydrogen CSP</h3>
<p>Navigate to your CSP setup in Hydrogen. Mine is in the file <code>entry.server.jsx</code>. Add the following code to your CSP:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> {nonce, header, NonceProvider} = createContentSecurityPolicy({
    <span class="hljs-attr">connectSrc</span>: [
      <span class="hljs-string">'wss://&lt;your-ngrok-domain&gt;.app:*'</span>
    ],

    <span class="hljs-comment">// rest of CSP</span>
})
</code></pre>
<p>If you don’t understand the concept of CSPs, feel free to read my breakdown of them <a target="_blank" href="https://blog.davidwilliford.dev/understanding-csps-through-hydrogen">here</a></p>
<h3 id="heading-authorize-with-shopify-admin">Authorize with Shopify Admin</h3>
<p>In your Shopify admin, navigate to the following:</p>
<p><strong>Sales Channels</strong> &gt; <strong>Hydrogen</strong> &gt; <strong>Select your Hydrogen Store</strong> &gt; <strong>Storefront Settings</strong> &gt; <strong>Customer Account API</strong></p>
<p><em>Scroll down till you see the</em> <strong><em>Application Setup</em></strong> <em>panel. Enter the ngrok url in the following places</em></p>
<p><strong>Every yellow box denotes where your ngrok url should be placed</strong>. Don’t forget to add your authorization endpoint to the <strong>Callback URI</strong> field. Mine is <code>/account/authorize</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729864888451/0363d769-47a8-4d91-a98b-966963d45fef.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-step-5-develop-and-test-your-customer-account-api-configuration">Step 5: Develop and Test your Customer Account API configuration</h2>
<p>Everything should work fine now! Start using customer authentication on your Hydrogen local evnironment!</p>
<p>In the future, I plan on writing on how to ditch the customer account API completely. These setups require a ton of configuration, and the <strong>login</strong> and <strong>authorize</strong> endpoints are not exposed publicly to store owners. Therefore, you can not have a custom login form with this setup.</p>
<p>Hope you enjoyed! Please leave a like if this informed you or helped. And feel free to reach out to me if you ever have any questions! I will answer them personally.</p>
<p>Cover Photo by <a target="_blank" href="https://unsplash.com/@guerrillabuzz?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">GuerrillaBuzz</a> on <a target="_blank" href="https://unsplash.com/photos/diagram-ygB1-bqkqlY?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p>
]]></content:encoded></item><item><title><![CDATA[Using seperate background images for mobile and desktop (Squarespace)]]></title><description><![CDATA[I’m currently revamping a client’s website through Squarespace. Even though website builders aren’t my prefered choice for development, they do allow…]]></description><link>https://blog.davidwilliford.dev/using-seperate-background-images-for-mobile-and-desktop-squarespace</link><guid isPermaLink="true">https://blog.davidwilliford.dev/using-seperate-background-images-for-mobile-and-desktop-squarespace</guid><category><![CDATA[squarespace]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[CSS]]></category><category><![CDATA[mobile design]]></category><category><![CDATA[Web Design]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Mon, 23 Sep 2024 00:52:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727052556838/3a2822d0-c948-4df0-bb65-9d70a28ba458.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’m currently revamping a client’s website through Squarespace. Even though website builders aren’t my prefered choice for development, they do allow clients easy access to update their site in the future.</p>
<p>For a particular section, I need there to be a separate background image for desktop and mobile. Surprisingly, there is not a built-in support for this on squarespace without custom CSS.</p>
<p>So here is how I accomplished this…</p>
<h3 id="heading-access-custom-css">Access Custom CSS</h3>
<p>In Squarespace dashboard, go to: <code>Website → Pages → Website Tools → Custom CSS</code>. This is the setting that allows you to implement custom CSS into your squarespace site.</p>
<h3 id="heading-capturing-the-section-id">Capturing The Section ID</h3>
<p>Next, you will need to locate the id of the particular section you want to edit</p>
<ol>
<li><p>Go to your live site url and press F12 to open the browser console</p>
</li>
<li><p>Find the <code>&lt;section&gt;</code> element of the section you would like to edit</p>
</li>
<li><p>Copy the value of the <code>data-section-id</code> tag. Should look something like: <code>63862367f9b5960c6ad5537e</code></p>
</li>
</ol>
<h3 id="heading-writing-the-css">Writing the CSS</h3>
<p>Here is the CSS that should allow you to acheive the desired functionality:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">640px</span>) {
  <span class="hljs-selector-tag">section</span><span class="hljs-selector-attr">[data-section-id=<span class="hljs-string">"your_section_id"</span>]</span> <span class="hljs-selector-class">.section-background</span> <span class="hljs-selector-tag">img</span> {
    <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0</span> <span class="hljs-meta">!important</span>; 
  }

  <span class="hljs-selector-tag">section</span><span class="hljs-selector-attr">[data-section-id=<span class="hljs-string">"your_section_id"</span>]</span> <span class="hljs-selector-class">.section-background</span> {
    <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">'image_url'</span>);
    <span class="hljs-attribute">background-size</span>: cover;
    <span class="hljs-attribute">background-position</span>: center;
    <span class="hljs-attribute">background-repeat</span>: no-repeat;
  }
}
</code></pre>
<p>Values <code>your_section_id</code> and <code>image_url</code> come from the section id you found in the last step, and the image you wish to load as the background on mobile. I would suggest uploading your image to the Squarespace assets, and accessing the link from there.</p>
<hr />
<p>Hopefully this works, feel free to reach out for any questions!</p>
<p><strong>Thank you for reading</strong></p>
]]></content:encoded></item><item><title><![CDATA[Auto-Sync Discounts between Shopify and ReCharge]]></title><description><![CDATA[Learn how to setup a pipeline using webhooks to synchronize discounts from your Shopify admin into ReCharge subscriptions.]]></description><link>https://blog.davidwilliford.dev/auto-sync-discounts-between-shopify-and-recharge</link><guid isPermaLink="true">https://blog.davidwilliford.dev/auto-sync-discounts-between-shopify-and-recharge</guid><category><![CDATA[Python]]></category><category><![CDATA[AWS]]></category><category><![CDATA[aws lambda]]></category><category><![CDATA[shopify]]></category><category><![CDATA[Recharge]]></category><category><![CDATA[subscription service]]></category><category><![CDATA[subscriptions]]></category><category><![CDATA[webhooks]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[ecommerce]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Fri, 16 Aug 2024 18:58:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723834559145/268faba3-744c-487d-9265-3ff771793e94.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>For E-Commerce stores that offer subscription-based products, ReCharge is a powerful application for handling recurring payments and orders. However, ReCharge does not automatically sync discount codes from your Shopify admin, meaning discount codes from your Shopify admin will not automatically register on your ReCharge theme pages.</p>
<p>ReCharge offers a manual way to sync discounts through their web UI, but this can be time consuming for an advanced discount code system. For example, say your site auto-generates discounts for customers with a certain level of loyalty points, and you want these discounts to be available on subscriptions in real-time.</p>
<hr />
<h3 id="heading-my-solution">My Solution:</h3>
<ol>
<li><p>Understanding Shopify <code>discounts/create</code> Webhook</p>
</li>
<li><p>Understanding Shopify and ReCharge API Endpoints</p>
</li>
<li><p>Set Up AWS Lambda and API Gateway</p>
</li>
<li><p>Write Lambda Function Code</p>
</li>
<li><p>Connect your Lambda Function to <code>discounts/create</code></p>
</li>
</ol>
<hr />
<h3 id="heading-the-discountscreate-webhook">The Discounts/Create Webhook</h3>
<p>Shopify has a plethora of webhooks, one of them being for the event <code>disocunts/create</code>. This webhook will send a JSON payload to a specified URL. <a target="_blank" href="https://shopify.dev/docs/api/admin-rest/2024-01/resources/webhook#event-topics">See more Shopify webhooks here</a></p>
<p>In this tutorial, we will utilize this webhook payload to trigger a AWS lambda function (or any hosted function provider of your choice), that will then make an API call to add this discount to ReCharge.</p>
<p>To clarify before we begin, the discounts that I will be syncing will only be for <code>x% off</code> or <code>$x off</code>. You can easily apply the same concept to specific item discounts, <a target="_blank" href="https://developer.rechargepayments.com/2021-11/discounts/discounts_object">read here</a> to see more information on ReCharge's <code>discount</code> object.</p>
<h3 id="heading-shopify-and-recharge-endpoints">Shopify and ReCharge Endpoints</h3>
<p>Now let's go over the endpoints you will need, and what they accomplish.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Endpoint</td><td>Function</td></tr>
</thead>
<tbody>
<tr>
<td><code>/admin/api/2024-01/graphql.json</code></td><td>General-purpose endpoint for Shopify Admin GraphQL requests.</td></tr>
<tr>
<td><a target="_blank" href="http://api.rechargeapps.com/discounts"><code>api.rechargeapps.com/discounts</code></a></td><td>ReCharge endpoint that we will use to create discounts</td></tr>
</tbody>
</table>
</div><p>Now we can derive a gameplan using the webhook and these API endpoints, on how we can sync these discounts.</p>
<ol>
<li><p>Set up <code>discounts/create</code> webhook to send payload to our cloud function (AWS Lambda, in my case)</p>
</li>
<li><p>Within cloud function, make a GraphQL request to get all of the necessary information regarding this newly created discount</p>
</li>
<li><p>Then, make a POST request to ReCharge API to add this discount to ReCharge.</p>
</li>
</ol>
<h3 id="heading-set-up-aws-lambda-and-api-gateway">Set Up AWS Lambda and API Gateway</h3>
<p>If you are not using AWS for your cloud function and API gateway, feel free to skip this step. Just make sure that your cloud function can be triggered by a POST request to an endpoint. This function will be triggered by the Shopify <code>discounts/create</code> webhook.</p>
<p>In AWS, you want to connect your Lambda function to an API endpoint. I suggest you use API Gateway, a native AWS service. This will allow you to trigger this Lambda function via POST request, and the setup is rather easy.</p>
<p>Here is the <a target="_blank" href="https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html">official AWS tutorial</a> for accomplishing this. If you have some experience with AWS already, this should be trivial.</p>
<h3 id="heading-connect-your-lambda-function-to-discountscreate">Connect your Lambda Function to <code>discounts/create</code></h3>
<p>Now we need to let Shopify know where to send the discount payload when a new discount is created.</p>
<ol>
<li><p>Go to your Shopify Admin page</p>
</li>
<li><p>Go to Settings &gt; Notifications &gt; Webhooks</p>
</li>
<li><p>Select 'Create Webhook'</p>
</li>
<li><p>Select 'Discount Creation' for the Event field</p>
</li>
<li><p>Enter the API endpoint to your cloud function in the 'URL' field</p>
</li>
</ol>
<p>Here is an example payload your function will receive:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"admin_graphql_api_id"</span>: <span class="hljs-string">"gid://shopify/DiscountAutomaticNode/1"</span>,
  <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Automatic free shipping"</span>,
  <span class="hljs-attr">"status"</span>: <span class="hljs-string">"ACTIVE"</span>,
  <span class="hljs-attr">"created_at"</span>: <span class="hljs-string">"2016-08-29T08:00:00-04:00"</span>,
  <span class="hljs-attr">"updated_at"</span>: <span class="hljs-string">"2016-08-29T08:00:00-04:00"</span>
}
</code></pre>
<h3 id="heading-write-lambda-function-code">Write Lambda Function Code</h3>
<p>Now that we have the webhook sending the above payload to your cloud function, we need to write the cloud function. I will be using Python, since I found it the easiest for this application. Node.js or any other scripting language available should be fine.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> re
<span class="hljs-keyword">import</span> urllib.request
<span class="hljs-keyword">import</span> urllib.parse
<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime, timedelta

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">lambda_handler</span>(<span class="hljs-params">event, context</span>):</span>

    shopify_graphql_url = <span class="hljs-string">"https://sizzlefish.myshopify.com/admin/api/2024-01/graphql.json"</span>
    shopify_access_token = os.environ[<span class="hljs-string">'SHOPIFY_ACCESS_TOKEN'</span>]  

    recharge_api_url = <span class="hljs-string">"https://api.rechargeapps.com/discounts"</span>
    recharge_access_token = os.environ[<span class="hljs-string">'RECHARGE_ACCESS_TOKEN'</span>]

    <span class="hljs-comment"># Extract data from the incoming event</span>
    body = event.get(<span class="hljs-string">"body"</span>)

    <span class="hljs-keyword">if</span> isinstance(body, str):
        data = json.loads(body)
    <span class="hljs-keyword">else</span>:
        data = body  <span class="hljs-comment"># Assume it's already a dict if not a string</span>

    discount_code = data.get(<span class="hljs-string">"title"</span>)

    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> discount_code:
        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">"statusCode"</span>: <span class="hljs-number">400</span>,
            <span class="hljs-string">"body"</span>: json.dumps({<span class="hljs-string">"message"</span>: <span class="hljs-string">"Discount code (title) not found in the event body"</span>})
        }

    <span class="hljs-comment"># Step 1: Query Shopify GraphQL API to get discount details</span>
    query = <span class="hljs-string">f"""
    query {{
      codeDiscountNodeByCode(code: "<span class="hljs-subst">{discount_code}</span>") {{
        id
        codeDiscount {{
            __typename
            ... on DiscountCodeBasic {{
                title
                status
                createdAt
                codeCount 
                shortSummary
                discountClass
                endsAt
            }}
        }}
      }}
    }}
    """</span>

    headers = {
        <span class="hljs-string">"X-Shopify-Access-Token"</span>: shopify_access_token,
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>
    }

    <span class="hljs-comment"># Create the request for Shopify API</span>
    shopify_request = urllib.request.Request(
        shopify_graphql_url,
        data=json.dumps({<span class="hljs-string">"query"</span>: query}).encode(<span class="hljs-string">'utf-8'</span>),
        headers=headers
    )

    <span class="hljs-keyword">try</span>:
        <span class="hljs-keyword">with</span> urllib.request.urlopen(shopify_request) <span class="hljs-keyword">as</span> response:
            response_body = response.read().decode(<span class="hljs-string">'utf-8'</span>)
            shopify_data = json.loads(response_body)
    <span class="hljs-keyword">except</span> urllib.error.HTTPError <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">"statusCode"</span>: e.code,
            <span class="hljs-string">"body"</span>: json.dumps({<span class="hljs-string">"message"</span>: <span class="hljs-string">"Error querying Shopify API"</span>, <span class="hljs-string">"details"</span>: e.read().decode(<span class="hljs-string">'utf-8'</span>)})
        }

    print(shopify_data)
    code_discount = shopify_data.get(<span class="hljs-string">"data"</span>, {}).get(<span class="hljs-string">"codeDiscountNodeByCode"</span>, {}).get(<span class="hljs-string">"codeDiscount"</span>, {})
    short_summary = code_discount.get(<span class="hljs-string">"shortSummary"</span>, <span class="hljs-string">""</span>)

    <span class="hljs-keyword">if</span> <span class="hljs-string">"0.01"</span> <span class="hljs-keyword">in</span> short_summary:
        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">"statusCode"</span>: <span class="hljs-number">200</span>,
            <span class="hljs-string">"body"</span>: json.dumps({<span class="hljs-string">"message"</span>: <span class="hljs-string">"Discount not created due to shortSummary containing '0.01'"</span>})
        }

    <span class="hljs-comment"># Step 2: Extract value and value_type from shortSummary</span>
    value = <span class="hljs-literal">None</span>
    value_type = <span class="hljs-literal">None</span>

    <span class="hljs-comment"># Match percentage-based discount (e.g., "20% off")</span>
    percentage_match = re.search(<span class="hljs-string">r'(\d+)% off'</span>, short_summary)
    <span class="hljs-keyword">if</span> percentage_match:
        value = percentage_match.group(<span class="hljs-number">1</span>)
        value_type = <span class="hljs-string">"percentage"</span>

    <span class="hljs-comment"># Match amount-based discount (e.g., "$10 off")</span>
    amount_match = re.search(<span class="hljs-string">r'\$(\d+\.?\d*) off'</span>, short_summary)
    <span class="hljs-keyword">if</span> amount_match:
        value = amount_match.group(<span class="hljs-number">1</span>)
        value_type = <span class="hljs-string">"fixed_amount"</span>

    <span class="hljs-comment"># If value and value_type could not be determined, return an error</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> value <span class="hljs-keyword">or</span> <span class="hljs-keyword">not</span> value_type:
        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">"statusCode"</span>: <span class="hljs-number">400</span>,
            <span class="hljs-string">"body"</span>: json.dumps({<span class="hljs-string">"message"</span>: <span class="hljs-string">"Could not parse value and value_type from shortSummary"</span>})
        }

    <span class="hljs-comment"># Calculate the ends_at date (e.g., 30 days from now)</span>
    current_time = datetime.utcnow()
    ends_at = current_time + timedelta(days=<span class="hljs-number">30</span>)
    ends_at_str = ends_at.strftime(<span class="hljs-string">'%Y-%m-%dT%H:%M:%SZ'</span>)

    <span class="hljs-comment"># Step 3: Create the discount in Recharge</span>
    recharge_payload = {
        <span class="hljs-string">"applies_to"</span>: {
            <span class="hljs-string">"purchase_item_type"</span>: <span class="hljs-string">"ALL"</span>
        },
        <span class="hljs-string">"channel_settings"</span>: {
            <span class="hljs-string">"api"</span>: {
                <span class="hljs-string">"can_apply"</span>: <span class="hljs-literal">True</span>
            },
            <span class="hljs-string">"checkout_page"</span>: {
                <span class="hljs-string">"can_apply"</span>: <span class="hljs-literal">True</span>
            },
            <span class="hljs-string">"customer_portal"</span>: {
                <span class="hljs-string">"can_apply"</span>: <span class="hljs-literal">True</span>
            },
            <span class="hljs-string">"merchant_portal"</span>: {
                <span class="hljs-string">"can_apply"</span>: <span class="hljs-literal">True</span>
            }
        },
        <span class="hljs-string">"code"</span>: discount_code,
        <span class="hljs-string">"status"</span>: <span class="hljs-string">"enabled"</span>,
        <span class="hljs-string">"usage_limits"</span>: {
            <span class="hljs-string">"first_time_customer_restriction"</span>: <span class="hljs-literal">False</span>,
            <span class="hljs-string">"one_application_per_customer"</span>: <span class="hljs-literal">False</span>
        },
        <span class="hljs-string">"value"</span>: value,
        <span class="hljs-string">"value_type"</span>: value_type,
        <span class="hljs-string">"ends_at"</span>: ends_at_str
    }

    recharge_headers = {
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
        <span class="hljs-string">"X-Recharge-Version"</span>: <span class="hljs-string">"2021-11"</span>,
        <span class="hljs-string">"X-Recharge-Access-Token"</span>: recharge_access_token
    }

    <span class="hljs-comment"># Create the request for Recharge API</span>
    recharge_request = urllib.request.Request(
        recharge_api_url,
        data=json.dumps(recharge_payload).encode(<span class="hljs-string">'utf-8'</span>),
        headers=recharge_headers
    )

    <span class="hljs-keyword">try</span>:
        <span class="hljs-keyword">with</span> urllib.request.urlopen(recharge_request) <span class="hljs-keyword">as</span> response:
            <span class="hljs-keyword">if</span> response.status != <span class="hljs-number">201</span>:
                <span class="hljs-keyword">return</span> {
                    <span class="hljs-string">"statusCode"</span>: response.status,
                    <span class="hljs-string">"body"</span>: json.dumps({<span class="hljs-string">"message"</span>: <span class="hljs-string">"Error creating discount in Recharge"</span>, <span class="hljs-string">"details"</span>: response.read().decode(<span class="hljs-string">'utf-8'</span>)})
                }
    <span class="hljs-keyword">except</span> urllib.error.HTTPError <span class="hljs-keyword">as</span> e:
        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">"statusCode"</span>: e.code,
            <span class="hljs-string">"body"</span>: json.dumps({<span class="hljs-string">"message"</span>: <span class="hljs-string">"Error creating discount in Recharge"</span>, <span class="hljs-string">"details"</span>: e.read().decode(<span class="hljs-string">'utf-8'</span>)})
        }

    <span class="hljs-keyword">return</span> {
        <span class="hljs-string">"statusCode"</span>: <span class="hljs-number">200</span>,
        <span class="hljs-string">"body"</span>: json.dumps({<span class="hljs-string">"message"</span>: <span class="hljs-string">"Discount created successfully in Recharge"</span>})
    }
</code></pre>
<p>This code looks much more complicated than it is. This python script does the following 3 things:</p>
<ol>
<li><p>Unpacks incoming payload of created discount</p>
</li>
<li><p>Gets more info about the discount using Shopify GraphQL API</p>
</li>
<li><p>Adds the discount to our ReCharge account</p>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Now, discounts will automatically sync from your Shopify admin into ReCharge, increasing quality-of-life for both developers and customers alike. Now, when a customer receives an automatically generated discount code from a loyalty rewards system, it will also be available for subscription-based products. And next time you are manually creating discounts, you only have to create them within Shopify and let our cloud function do the rest!</p>
]]></content:encoded></item><item><title><![CDATA[Understanding CSPs through Hydrogen]]></title><description><![CDATA[Content Security Policy provides security to your application, but can be a pain when implementing 3rd party fonts and media. Learn about them today!]]></description><link>https://blog.davidwilliford.dev/understanding-csps-through-hydrogen</link><guid isPermaLink="true">https://blog.davidwilliford.dev/understanding-csps-through-hydrogen</guid><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Security]]></category><category><![CDATA[shopify]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[shopify hydrogen]]></category><category><![CDATA[ Hydrogen ]]></category><category><![CDATA[csp]]></category><category><![CDATA[ecommerce]]></category><category><![CDATA[headless cms]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Wed, 14 Aug 2024 12:00:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723217153573/ec40e40e-07d1-4d21-aac8-dacc8c891e19.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Content Security Policy (CSP) is a crucial tool in web development that can make or break your site’s security. If you’ve spent time debugging font loading issues or mysterious errors while working with 3rd party imports, you’ve likely bumped into CSP issues.</p>
<p>In this post, I will break down what a CSP is, how it works in Hydrogen (can translate to any other framework), and how you can adjust it to fit your specific needs using a real-world example from my own projects.</p>
<hr />
<p><em>Note: Hydrogen is Shopify's React framework, built on top of Remix</em></p>
<hr />
<h3 id="heading-what-is-content-security-policy-csp">What is Content Security Policy (CSP)?</h3>
<p>Content Security Policy (CSP) is a feature that protects your site cyber attacks like Cross-Site Scripting (XSS) and data injection. Essentially, CSP allows you to define sources from which your site can load resources; such as scripts, styles, and fonts.</p>
<p>By setting up a CSP, you tell the browser exactly which sources are trusted, and the browser will block anything not explicitly allowed. This is extremely useful in securing yourself against unauthorized scripts/styles from executing on your site.</p>
<hr />
<h3 id="heading-how-csp-works">How CSP Works</h3>
<p>CSP works by using HTTP headers to specify the policy. The browser reads this policy and applies it to all resources loaded by your site. If a resource comes from a source not specified in your CSP, it will be blocked, and you might see errors in the console like:</p>
<p><code>Refused to load the font 'https://fonts.gstatic.com/s/opensans/v40/memtYaGs126MiZpBA-UFUIcVXSCEkx2cmqvXlWqWtU6FxZCJgvAQ.woff2' because it violates the following Content Security Policy directive: "font-src 'self' https://fonts.googleapis.com https://maxcdn.bootstrapcdn.com https://use.typekit.net".</code></p>
<p>This is the browser telling you that your current CSP is too restrictive for the resources you’re trying to load.</p>
<hr />
<h3 id="heading-using-csp-in-shopify-hydrogen">Using CSP in Shopify Hydrogen</h3>
<p>In Hydrogen, you’ll typically control the CSP in <code>entry.server.jsx</code> or <code>server.jsx</code>.</p>
<p>Hydrogen is a React-based framework for building headless Shopify storefronts, and managing security in such environments is critical.</p>
<p>Here's a glimpse into how CSP is typically set up in Hydrogen:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {RemixServer} <span class="hljs-keyword">from</span> <span class="hljs-string">'@remix-run/react'</span>;
<span class="hljs-keyword">import</span> isbot <span class="hljs-keyword">from</span> <span class="hljs-string">'isbot'</span>;
<span class="hljs-keyword">import</span> {renderToReadableStream} <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;
<span class="hljs-keyword">import</span> {createContentSecurityPolicy} <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/hydrogen'</span>;
<span class="hljs-keyword">import</span> { CartProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'@shopify/hydrogen-react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleRequest</span>(<span class="hljs-params">
  request,
  responseStatusCode,
  responseHeaders,
  remixContext,
</span>) </span>{
  <span class="hljs-keyword">const</span> {nonce, header, NonceProvider} = createContentSecurityPolicy({
    <span class="hljs-attr">styleSrc</span>: [
      <span class="hljs-string">"'self'"</span>,
      <span class="hljs-string">"'unsafe-inline'"</span>,
      <span class="hljs-string">'https://cdn.shopify.com'</span>,
      <span class="hljs-string">'https://cdnjs.cloudflare.com'</span>,
      <span class="hljs-string">'https://fonts.googleapis.com'</span>,
      <span class="hljs-string">'https://maxcdn.bootstrapcdn.com'</span>,
      <span class="hljs-string">'https://use.typekit.net'</span>,
      <span class="hljs-string">'https://p.typekit.net'</span>, <span class="hljs-comment">// Added for Adobe Fonts</span>
    ],
    <span class="hljs-attr">fontSrc</span>: [
      <span class="hljs-string">"'self'"</span>,
      <span class="hljs-string">'https://fonts.googleapis.com'</span>,
      <span class="hljs-string">'https://maxcdn.bootstrapcdn.com'</span>,
      <span class="hljs-string">'https://use.typekit.net'</span>,
      <span class="hljs-string">'https://fonts.gstatic.com'</span>, <span class="hljs-comment">// Added for Google Fonts</span>
    ],
  });

  <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> renderToReadableStream(
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">NonceProvider</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">CartProvider</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">RemixServer</span> <span class="hljs-attr">context</span>=<span class="hljs-string">{remixContext}</span> <span class="hljs-attr">url</span>=<span class="hljs-string">{request.url}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">CartProvider</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">NonceProvider</span>&gt;</span></span>,
    {
      nonce,
      <span class="hljs-attr">signal</span>: request.signal,
      onError(error) {
        <span class="hljs-built_in">console</span>.error(error);
        responseStatusCode = <span class="hljs-number">500</span>;
      },
    },
  );

  <span class="hljs-keyword">if</span> (isbot(request.headers.get(<span class="hljs-string">'user-agent'</span>))) {
    <span class="hljs-keyword">await</span> body.allReady;
  }

  responseHeaders.set(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
  responseHeaders.set(<span class="hljs-string">'Content-Security-Policy'</span>, header);

  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(body, {
    <span class="hljs-attr">headers</span>: responseHeaders,
    <span class="hljs-attr">status</span>: responseStatusCode,
  });
}
</code></pre>
<p>In this example, CSP is generated using the <code>createContentSecurityPolicy</code> function. The <code>styleSrc</code> and <code>fontSrc</code> directives are updated to allow external resources like fonts and stylesheets from 3rd parties.</p>
<p>In other frameworks, this CSP may be included within a <code>&lt;meta&gt;</code> tag in your root file, or your root server component.</p>
<hr />
<h3 id="heading-real-world-example-adjusting-csp-for-adobe-fonts-and-google-fonts">Real-World Example: Adjusting CSP for Adobe Fonts and Google Fonts</h3>
<p>Recently, I ran into an issue where my Hydrogen app refused to load fonts from Google and Adobe. The errors were indicating that my CSP was too restrictive:</p>
<p><code>Refused to load the stylesheet 'https://p.typekit.net/p.css'... Refused to load the font 'https://fonts.gstatic.com/s/opensans/v40/memtYaGs126MiZpBA-UFUIcVXSCEkx2cmqvXlWqWtU6FxZCJgvAQ.woff2'...</code></p>
<p>Here was my fix:</p>
<ol>
<li><p><strong>Add</strong> <a target="_blank" href="https://use.typekit.net"><code>https://use.typekit.net</code></a> and <a target="_blank" href="https://p.typekit.net"><code>https://p.typekit.net</code></a> to <code>styleSrc</code>: Adobe Fonts need access to these domains for loading styles and tracking images.</p>
</li>
<li><p><strong>Add</strong> <a target="_blank" href="https://fonts.gstatic.com"><code>https://fonts.gstatic.com</code></a> to <code>fontSrc</code>: Google Fonts are served from this domain, so you need to allow it for your fonts to load properly.</p>
</li>
<li><p><strong>Ensure</strong> <code>unsafe-inline</code> is present in <code>styleSrc</code>: This is required by Adobe Fonts, as they use inline styles for rendering fonts.</p>
</li>
</ol>
<p>The updated <code>styleSrc</code> and <code>fontSrc</code> look like so:</p>
<pre><code class="lang-javascript">styleSrc: [
  <span class="hljs-string">"'self'"</span>,
  <span class="hljs-string">"'unsafe-inline'"</span>, 
  <span class="hljs-string">'https://cdn.shopify.com'</span>,
  <span class="hljs-string">'https://cdnjs.cloudflare.com'</span>,
  <span class="hljs-string">'https://fonts.googleapis.com'</span>,
  <span class="hljs-string">'https://maxcdn.bootstrapcdn.com'</span>,
  <span class="hljs-string">'https://use.typekit.net'</span>,
  <span class="hljs-string">'https://p.typekit.net'</span>,
],
<span class="hljs-attr">fontSrc</span>: [
  <span class="hljs-string">"'self'"</span>,
  <span class="hljs-string">'https://fonts.googleapis.com'</span>,
  <span class="hljs-string">'https://maxcdn.bootstrapcdn.com'</span>,
  <span class="hljs-string">'https://use.typekit.net'</span>,
  <span class="hljs-string">'https://fonts.gstatic.com'</span>,
],
</code></pre>
<p>Once these changes were made, the fonts and styles loaded without issues, and the CSP errors were resolved.</p>
<hr />
<h3 id="heading-conclusion">Conclusion</h3>
<p>CSP is a powerful tool that helps protect your site from malicious attacks. However, it can be a bit troublesome, especially when using boilerplate that implements it without you knowing.</p>
<p>Keep in mind, making your CSP more permissive can solve loading issues, but it’s important to strike the right balance between security and functionality. Always consider the changes you make to ensure you’re not unintentionally exposing your site to cyber attacks.</p>
]]></content:encoded></item><item><title><![CDATA[Deleting Subscription Addons Automatically in ReCharge]]></title><description><![CDATA[Deleting Subscription Addons Automatically in ReCharge upon Subscription Cancellation]]></description><link>https://blog.davidwilliford.dev/deleting-subscription-addons-automatically-in-recharge</link><guid isPermaLink="true">https://blog.davidwilliford.dev/deleting-subscription-addons-automatically-in-recharge</guid><category><![CDATA[ecommerce]]></category><category><![CDATA[shopify]]></category><category><![CDATA[Recharge]]></category><category><![CDATA[recharge]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[shopify hydrogen]]></category><category><![CDATA[webhooks]]></category><category><![CDATA[cloud functions]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Tue, 06 Aug 2024 17:18:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722947313827/67516430-3095-4c55-a2a9-31865b3fbdab.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>ReCharge is an amazing app for handling subscriptions in an ecommerce store. However, I recently discovered a missing functionality that has been causing frustration with both our customers and my fellow employees.</p>
<p><strong>Warning</strong>. This fix is pretty extensive, utilizing webhooks and a cloud functions as a temporary fix. ReCharge team, if you are reading this, hire me and I can add this endpoint for you! (Please, I'm broke).</p>
<h3 id="heading-the-problem">The Problem</h3>
<p>When you cancel a subscription in ReCharge, it only cancels the primary item and not the addons. This means that an employee must go in and manually cancel these items after a cancelation, or the customer will be charged for something they believed they canceled.</p>
<p>I've devised a way to utilize the ReCharge API and webhooks to automatically delete addons upon subscription cancellation.</p>
<h3 id="heading-solution-summary">Solution Summary</h3>
<p>Our solution will have 4 steps:</p>
<ol>
<li><p>Writing the Node.js code</p>
</li>
<li><p>Creating a cloud function and API endpoint to get called upon subscription cancellation webhook</p>
</li>
<li><p>Create the webhook via Recharge API</p>
</li>
<li><p>Testing Endpoint</p>
</li>
</ol>
<h3 id="heading-pre-requisites">Pre-Requisites</h3>
<ul>
<li><p>Knowledge of JavaScript and ReCharge</p>
</li>
<li><p>Knowledge of Webhooks</p>
</li>
<li><p>Knowledge of Cloud Functions and REST APIs</p>
</li>
<li><p>ReCharge Documentation: <a target="_blank" href="https://developer.rechargepayments.com/2021-01/subscriptions/subscriptions_delete">https://developer.rechargepayments.com/2021-01/subscriptions/subscriptions_delete</a></p>
</li>
</ul>
<h3 id="heading-nodejs-code">Node.js Code</h3>
<p>This is the code that will handle our addon cancellation.</p>
<p>This function receives the subscription object from the webhook, takes the address_id and finds all of the addons that share this address_id. Then the program loops through them, and cancels them one by one.</p>
<p>Notice that my store's addons are all onetime purchases. If you have subscription addons, you can use <code>/subscriptions/{id}/cancel</code> (<a target="_blank" href="https://developer.rechargepayments.com/2021-11/subscriptions/subscriptions_cancel">documentation here</a>). Don't forget you'll also need to get all of the subscriptions with the same address_id if you have reoccurring addons.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> axios = <span class="hljs-built_in">require</span>(<span class="hljs-string">'axios'</span>);

<span class="hljs-comment">// Function to get all one-time items for a given address ID</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getOneTimeItems</span>(<span class="hljs-params">addressId</span>) </span>{
    <span class="hljs-keyword">const</span> oneTimesUrl = <span class="hljs-string">`https://api.rechargeapps.com/onetimes?address_id=<span class="hljs-subst">${addressId}</span>`</span>;
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(oneTimesUrl, {
            <span class="hljs-attr">headers</span>: {
                <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
                <span class="hljs-string">'X-Recharge-Access-Token'</span>: process.env.RECHARGE_API_TOKEN
            }
        });

        <span class="hljs-keyword">const</span> oneTimes = response.data.onetimes;
        <span class="hljs-keyword">if</span> (oneTimes &amp;&amp; oneTimes.length &gt; <span class="hljs-number">0</span>) {
            <span class="hljs-keyword">return</span> oneTimes;
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'No one-time items found for the address'</span>);
        }
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Error fetching one-time items: <span class="hljs-subst">${error.response ? error.response.data : error.message}</span>`</span>);
    }
}

<span class="hljs-comment">// Function to delete all add-ons for a given subscription address ID</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deleteAllAddons</span>(<span class="hljs-params">addressId</span>) </span>{
    <span class="hljs-keyword">let</span> addOns = [];
    <span class="hljs-keyword">let</span> errorMessages = [];

    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> oneTimes = <span class="hljs-keyword">await</span> getOneTimeItems(addressId);

        <span class="hljs-keyword">if</span> (oneTimes &amp;&amp; oneTimes.length &gt; <span class="hljs-number">0</span>) {
            addOns = oneTimes;
        }

        <span class="hljs-keyword">if</span> (addOns.length === <span class="hljs-number">0</span>) {
            <span class="hljs-keyword">return</span> { <span class="hljs-attr">success</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">"No addons detected"</span> };
        }

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> addOn <span class="hljs-keyword">of</span> addOns) {
            <span class="hljs-keyword">const</span> oneTimeItemId = addOn.id;
            <span class="hljs-keyword">const</span> actionUrl = <span class="hljs-string">`https://api.rechargeapps.com/onetimes/<span class="hljs-subst">${oneTimeItemId}</span>`</span>;
            <span class="hljs-keyword">try</span> {
                <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.delete(actionUrl, {
                    <span class="hljs-attr">headers</span>: {
                        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
                        <span class="hljs-string">'X-Recharge-Access-Token'</span>: process.env.RECHARGE_API_TOKEN
                    }
                });
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'One-time item deleted successfully:'</span>, response.data);
            } <span class="hljs-keyword">catch</span> (error) {
                <span class="hljs-built_in">console</span>.error(<span class="hljs-string">`Error deleting one-time item with ID <span class="hljs-subst">${oneTimeItemId}</span>:`</span>, error.response ? error.response.data : error.message);
                errorMessages.push({
                    <span class="hljs-attr">itemId</span>: oneTimeItemId,
                    <span class="hljs-attr">error</span>: error.response ? error.response.data : error.message
                });
            }
        }

        <span class="hljs-keyword">if</span> (errorMessages.length &gt; <span class="hljs-number">0</span>) {
            <span class="hljs-keyword">return</span> { <span class="hljs-attr">success</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">"Some addons could not be deleted"</span>, <span class="hljs-attr">errors</span>: errorMessages };
        }

        <span class="hljs-keyword">return</span> { <span class="hljs-attr">success</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">"Addons deleted successfully"</span> };

    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-keyword">return</span> { <span class="hljs-attr">success</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">`Failed to fetch one-time items or delete addons: <span class="hljs-subst">${error.message}</span>`</span> };
    }
}

<span class="hljs-comment">// Main Lambda handler function</span>
<span class="hljs-built_in">exports</span>.handler = <span class="hljs-keyword">async</span> (event) =&gt; {
    <span class="hljs-keyword">const</span> subscription = <span class="hljs-built_in">JSON</span>.parse(event.body).subscription;
    <span class="hljs-keyword">const</span> addressId = subscription.address_id;
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> deleteAllAddons(addressId);
    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">statusCode</span>: result.success ? <span class="hljs-number">200</span> : <span class="hljs-number">500</span>,
        <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(result),
    };
};
</code></pre>
<h3 id="heading-hosting-a-cloud-function">Hosting a Cloud Function</h3>
<p>I won't get in too many specifics, since this is not a cloud computing tutorial. The main idea here is that your code needs to run on command whenever this webhook is sent out.</p>
<ol>
<li><p>Take the above code and place it into an cloud function from your preferred cloud provider (AWS Lambda, Google Cloud Functions, Azure Functions, etc.).</p>
</li>
<li><p>Now attach this function you just made to an API endpoint so that it accepts POST requests. I used AWS API Gateway (your cloud service provider should provide an easy way to host your functions on an endpoint).</p>
</li>
</ol>
<h3 id="heading-testing-your-endpoint">Testing your Endpoint</h3>
<p>It is recommended to test the endpoint in Postman with a subscription object before moving on. And for testing, remember that the <code>subscription</code> item will be nested inside the parent JSON object like so:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"subscription"</span>: <span class="hljs-string">"subscription fields here"</span>
}
</code></pre>
<p>To get a subscription object, use ReCharge's GET <code>/subscriptions/{id}</code> endpoint, then copy the response into your POST request to test the cloud endpoint.</p>
<p>Now you should have a working API endpoint!</p>
<h3 id="heading-creating-the-cancel-subscription-webhook">Creating the Cancel Subscription Webhook</h3>
<p>ReCharge has multiple webhook events you can attach to, allowing our cloud function to run every time a subscription is canceled.</p>
<p>Currently, ReCharge only allows creation of webhooks through their API, like so:</p>
<pre><code class="lang-bash">curl -X POST https://api.rechargeapps.com/webhooks \
-H <span class="hljs-string">"Content-Type: application/json"</span> \
-H <span class="hljs-string">"X-Recharge-Access-Token: your_api_token"</span> \
-d <span class="hljs-string">'{
  "address": "https://&lt;your_api_id&gt;.execute-api.&lt;region&gt;.amazonaws.com/&lt;endpoint_name&gt;",
  "topic": "subscription/cancelled"
}'</span>
</code></pre>
<p>Make sure that...</p>
<ul>
<li><p>The <code>address</code> field correctly matches the API endpoint we created in the previous step</p>
</li>
<li><p>Your API token is entered properly.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>If configured properly, your addons will now delete upon subscription cancelation. Make sure to test everything a few times before deploying this to your live site. Hopefully this helps any issues you may have with automatically deleting addons upon subscription cancellation in ReCharge.</p>
]]></content:encoded></item><item><title><![CDATA[Sticky Position does not Work with Grid/Flex parent]]></title><description><![CDATA[Discover how to fix sticky positioning issues in your frontend projects with our simple tutorial. Learn why sticky elements fail with direct flex or grid…]]></description><link>https://blog.davidwilliford.dev/sticky-position-does-not-work-with-gridflex-parent</link><guid isPermaLink="true">https://blog.davidwilliford.dev/sticky-position-does-not-work-with-gridflex-parent</guid><category><![CDATA[CSS]]></category><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Fri, 05 Jul 2024 15:22:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/_t-l5FFH8VA/upload/cc75016e1b42f15001d8a64f48c55d71.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Frontend developers, do you ever experience strange behavior from sticky elements in your code? I surely did, until I learned that <strong>sticky positioning does not work correctly when direct parent elements are flex or grid</strong>. To some of you this may already be obvious, somehow I managed to have years of frontend experience before figuring this out.</p>
<h3 id="heading-problem">Problem</h3>
<p>Imagine a sidebar menu that needs to 'stick' to the left side of the page. So as the user is scrolling through the content of the page, the menu always remains to the side for easy access. This is a common feature for sites with many pages and lots of content (blogs, documentation, ecommerce stores etc.).</p>
<p>Let's use this code as our example:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'grid grid-cols-5'</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">Menu</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'sticky top-0 col-span-1'</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">PageContent</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-span-4'</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p><em>Using react and tailwind, but works the same for any js/css config</em></p>
<p>See we have a sticky element with a direct grid parent. The grid layout will work completely fine, yet the sticky positioning will not!</p>
<h3 id="heading-solution">Solution</h3>
<p>The simplest way to fix this issue and keep your grid / flex layout, is to wrap the sticky component in an additional div.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'grid grid-cols-5'</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-span-1'</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Menu</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'sticky top-0'</span>/&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">PageContent</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-span-4'</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Super simple! Just make sure you move the flex/grid styles to this new div. Now, you can use both flex/grid with sticky positioning.</p>
]]></content:encoded></item><item><title><![CDATA[Making swipe-able websites with JavaScript]]></title><description><![CDATA[Swipe gestures in JavaScript are essential for creating intuitive and responsive touch interfaces on mobile devices and tablets.]]></description><link>https://blog.davidwilliford.dev/making-swipe-able-websites-with-javascript</link><guid isPermaLink="true">https://blog.davidwilliford.dev/making-swipe-able-websites-with-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Wed, 12 Jun 2024 15:23:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1718202880239/0a78cb0e-91f5-47b4-9bfe-a664f7013d1d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today's web landscape, touch screens are everywhere: phones, tablets, and even laptops. With so many devices relying on touch, it's important for web developers to understand swiping and how to program it into their websites. The key component of this is handling swipe events in JavaScript.</p>
<p>Swipe gestures are super common across the web. Think about how often you swipe left or right to browse photos, scroll through lists, or to manage messages. Knowing how to manage these swipes can make your apps feel smooth and responsive.</p>
<h3 id="heading-reasons-to-study-swiping-in-javascript">Reasons To Study Swiping in JavaScript</h3>
<ol>
<li><p><strong>Better User Experience</strong>: Users expect smooth interactions on their touch devices. By handling swipes well, you make your app easier and more enjoyable to use.</p>
</li>
<li><p><strong>Stay Competitive</strong>: Good swiping mechanics on your site can set you apart from other, less experienced developers. If your app feels clunky or outdated on mobile apps, this can make your applications seem clunky and non-optimized.</p>
</li>
<li><p><strong>Unlock Creativity</strong>: Knowing how to handle swipes opens up new possibilities for fun and innovative features in your app. It lets you think outside the box and create unique experiences.</p>
</li>
</ol>
<p>In this article, we'll break down how to handle swipe events in JavaScript, helping you build better, more user-friendly apps.</p>
<h3 id="heading-swipe-events-in-javascript">Swipe Events in JavaScript</h3>
<p>JavaScript has the ability to handle many events, such as clicking, swiping, scrolling etc. We must utilize these events to make custom swiping functionality.</p>
<p><strong>Here are the swiping events utilized by JavaScript</strong></p>
<ul>
<li><p><code>touchstart</code>: Triggered when the touch starts.</p>
</li>
<li><p><code>touchmove</code>: Triggered when the touch moves.</p>
</li>
<li><p><code>touchend</code>: Triggered when the touch ends.</p>
</li>
</ul>
<h3 id="heading-implementation">Implementation</h3>
<p>Here we will build an example of a swipe-able component in JavaScript</p>
<p><strong>The HTML and CSS</strong></p>
<pre><code class="lang-javascript">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"carousel-container"</span>&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"carousel-button left"</span>&gt;</span><span class="hljs-symbol">&amp;lt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"carousel"</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Add your carousel items here --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"carousel-item"</span>&gt;</span>Item 1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"carousel-item"</span>&gt;</span>Item 2<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"carousel-item"</span>&gt;</span>Item 3<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"carousel-button right"</span>&gt;</span><span class="hljs-symbol">&amp;gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
&lt;/div&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
<span class="hljs-selector-class">.carousel-container</span> {
  <span class="hljs-attribute">position</span>: relative;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">overflow</span>: hidden;
}

<span class="hljs-selector-class">.carousel</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">transition</span>: transform <span class="hljs-number">0.5s</span> ease-in-out;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span> <span class="hljs-number">32px</span>;
}

<span class="hljs-selector-class">.carousel-item</span> {
  <span class="hljs-attribute">min-width</span>: <span class="hljs-built_in">calc</span>(<span class="hljs-number">100%</span> / <span class="hljs-number">3</span>);
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-class">.carousel-button</span> {
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">bottom</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#123963</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">38px</span>;
  <span class="hljs-attribute">z-index</span>: <span class="hljs-number">5</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
}

<span class="hljs-selector-class">.carousel-button</span><span class="hljs-selector-class">.left</span> {
  <span class="hljs-attribute">left</span>: <span class="hljs-number">0</span>;
}

<span class="hljs-selector-class">.carousel-button</span><span class="hljs-selector-class">.right</span> {
  <span class="hljs-attribute">right</span>: <span class="hljs-number">0</span>;
}

<span class="hljs-keyword">@media</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">769px</span>) {
  <span class="hljs-selector-class">.carousel-item</span> {
    <span class="hljs-attribute">min-width</span>: <span class="hljs-number">100%</span>;
  }
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span></span>
</code></pre>
<p>Notice the left/right buttons are absolutely positioned to the left and right. This is because the carousel items will translate left and right, yet we want these buttons to remain in the same spot</p>
<p><strong>The JavaScript (Handling Swipes)</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// runs once all content is loaded on page</span>
<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'DOMContentLoaded'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-comment">// grab relevant HTML items </span>
  <span class="hljs-keyword">const</span> carousel = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.carousel'</span>);
  <span class="hljs-keyword">const</span> leftButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.carousel-button.left'</span>);
  <span class="hljs-keyword">const</span> rightButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.carousel-button.right'</span>);

  <span class="hljs-comment">// variables to record swipe status</span>
  <span class="hljs-keyword">let</span> offset = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">let</span> startX;
  <span class="hljs-keyword">let</span> isSwiping = <span class="hljs-literal">false</span>;

  <span class="hljs-comment">// have width of each item to ensure clean swipes (not required)</span>
  <span class="hljs-comment">// will be used to calculate by how much we shift horizontally on swipe</span>
  <span class="hljs-comment">// you could hardcode a value or just have it move how much you swiped</span>
  <span class="hljs-keyword">const</span> itemWidth = carousel.querySelector(<span class="hljs-string">'.carousel-item'</span>).offsetWidth;

  <span class="hljs-comment">// Swipe functionality</span>
  <span class="hljs-comment">// =======================================================</span>

  <span class="hljs-comment">// When user touches, record the starting point and set isSwiping to true</span>
  carousel.addEventListener(<span class="hljs-string">'touchstart'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    startX = e.touches[<span class="hljs-number">0</span>].clientX;
    isSwiping = <span class="hljs-literal">true</span>;
  });

  <span class="hljs-comment">// runs as the user's touch moves (swiping)</span>
  carousel.addEventListener(<span class="hljs-string">'touchmove'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (!isSwiping) <span class="hljs-keyword">return</span>;
    <span class="hljs-comment">// record current positioning and difference from beggining</span>
    <span class="hljs-comment">// using X values since this is a horizontal scroll</span>
    <span class="hljs-keyword">const</span> currentX = e.touches[<span class="hljs-number">0</span>].clientX;
    <span class="hljs-keyword">const</span> diffX = startX - currentX;

    <span class="hljs-comment">// if this difference is over +50, we Swipe Left</span>
    <span class="hljs-keyword">if</span> (diffX &gt; <span class="hljs-number">50</span>) { 
      <span class="hljs-keyword">const</span> maxOffset = (carousel.children.length - <span class="hljs-number">1</span>) * itemWidth;
      <span class="hljs-keyword">if</span> (offset &lt; maxOffset) {
        offset += itemWidth;
        carousel.style.transform = <span class="hljs-string">`translateX(-<span class="hljs-subst">${offset}</span>px)`</span>;
      }
      isSwiping = <span class="hljs-literal">false</span>;

    <span class="hljs-comment">// if this difference is below -50, we Swipe Right</span>
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (diffX &lt; <span class="hljs-number">-50</span>) { 
      <span class="hljs-keyword">if</span> (offset &gt; <span class="hljs-number">0</span>) {
        offset -= itemWidth;
        carousel.style.transform = <span class="hljs-string">`translateX(-<span class="hljs-subst">${offset}</span>px)`</span>;
      }
      isSwiping = <span class="hljs-literal">false</span>;
    }
  });

  <span class="hljs-comment">// Once swipe ends, turn isSwiping to false</span>
  carousel.addEventListener(<span class="hljs-string">'touchend'</span>, <span class="hljs-function">() =&gt;</span> {
    isSwiping = <span class="hljs-literal">false</span>;
  });
});
</code></pre>
<p>And there you have it! You now have a swipe-able component in your web application! Keep in mind this is easily applicable to other types of swipes with minor tweaks. The main takeaways here should be:</p>
<p><strong>The Events</strong></p>
<ol>
<li><p><code>touchstart</code>: Triggered when the touch starts.</p>
</li>
<li><p><code>touchmove</code>: Triggered when the touch moves.</p>
</li>
<li><p><code>touchend</code> : Triggered when the touch ends</p>
</li>
</ol>
<p><strong>Positioning</strong></p>
<ul>
<li><p><code>offset</code> : how much the touch has moved</p>
</li>
<li><p><code>translate</code> : a CSS property that moves things along a specific axis</p>
</li>
</ul>
<p>Hope you learned something!</p>
]]></content:encoded></item><item><title><![CDATA[Why CockroachDB IDs are Inconsistent in Web Applications]]></title><description><![CDATA[Have you noticed that sometimes when you receive IDs from a CockroachDB database, that they are different value than they are stored as?]]></description><link>https://blog.davidwilliford.dev/why-cockroachdb-ids-are-inconsistent-in-web-applications</link><guid isPermaLink="true">https://blog.davidwilliford.dev/why-cockroachdb-ids-are-inconsistent-in-web-applications</guid><category><![CDATA[cockroachdb]]></category><category><![CDATA[React]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[json]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Thu, 25 Apr 2024 16:06:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713973549923/37522db3-55c8-49ee-a39e-79f34ab39240.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Are you using CockroachDB for a full stack application? Is your frontend a web application? Have you noticed that sometimes when you receive the IDs from the database, that they are different than their actual stored value?</p>
<p>I noticed this when using Cockroach, and it was a frustrating issue to diagnose. I will tell you why this happens, and how to resolve these inconsistent IDs.</p>
<h3 id="heading-why-this-happens">Why This Happens</h3>
<p>I can explain this entire issue in one sentence:</p>
<p><strong>CockroachDB IDs are breaking your application because they are too large.</strong></p>
<p>In JavaScript, the highest safe integer is 9007199254740991, per <a target="_blank" href="https://www.programiz.com/javascript/library/number/max_safe_integer#:~:text=The%20MAX_SAFE_INTEGER%20constant%20has%20a,and%20to%20correctly%20compare%20them.">programiz.com</a>. Many CockrachDB generated IDs will be larger than this, causing errors with your frontend / backend integration.</p>
<h3 id="heading-my-fix">My Fix</h3>
<p>There are multiple ways to work around this issue. I will show how to solve this using <code>json-bigint</code><strong>;</strong> a JavaScript library whose sole purpose is handling large integers. This is essential when handling HTTP requests and JSON objects coming from a CockroachDB database.</p>
<h3 id="heading-install-json-bigint">Install JSON-BigInt</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Install using npm</span>
npm install json-bigint
</code></pre>
<p><strong>OR</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Install using yarn</span>
yarn add json-bigint
</code></pre>
<h3 id="heading-using-json-bigint">Using JSON-BigInt</h3>
<p>Below, I am sending data via a POST request, and expecting the ID of the data I just created, to be returned in the response.</p>
<p>I know that this returned ID will be larger than the JavaScript safe int, so I wrap the response data as <code>JSONbig.parse(data)</code> when it is returned to my frontend.</p>
<p>Now I can safely access this large integer without inconcsistency. In my case, I use this ID to route customers to a page, with this ID as a URL parameter.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> JSONbig <span class="hljs-keyword">from</span> <span class="hljs-string">'json-bigint'</span>;
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>;  <span class="hljs-comment">// for making API calls</span>

<span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> (e) =&gt; {
        e.preventDefault();

        <span class="hljs-comment">// request data to send to POST request</span>
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">new</span> FormData();
        data.append(<span class="hljs-string">'description'</span>, formData.description);
        data.append(<span class="hljs-string">'name'</span>, formData.setName);

        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios({
                <span class="hljs-attr">method</span>: <span class="hljs-string">'post'</span>,
                <span class="hljs-attr">url</span>: <span class="hljs-string">'http://localhost:8000/createObject/'</span>,
                <span class="hljs-attr">data</span>: data,
                <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'multipart/form-data'</span> },
                <span class="hljs-comment">// wrap response with JSONbig.parse</span>
                <span class="hljs-attr">transformResponse</span>: [<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> JSONbig.parse(data)]
            });
            <span class="hljs-keyword">const</span> cardsetId = response.data.cardset; 
            <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">`/DisplayObject?id=<span class="hljs-subst">${cardsetId}</span>`</span>;
        } 
        <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error:"</span>, error);
        }
    };
</code></pre>
<h3 id="heading-other-methods-for-fixing-this-issue">Other Methods for Fixing This Issue</h3>
<p>Since my fix involved an npm package and React, I will add some more universal solutions below. I won't have time to explain all of these in detail, but here is a list of other ways to solve inconsistend CockroachDB IDs in your javascript client.</p>
<ul>
<li><p>Convert integer IDs to strings when retrieving from the database</p>
</li>
<li><p>JavaScript’s <code>BigInt</code> type (most universal fix)</p>
</li>
<li><p>Making a custom type for IDs in database</p>
</li>
<li><p>Using a buffer or byte array</p>
</li>
</ul>
<hr />
<p>Hopefully this solution helps. This is a common problem with CockroachDB that is not discussed often enough.</p>
<p>More on json-bigint: <a target="_blank" href="https://www.npmjs.com/package/json-bigint">https://www.npmjs.com/package/json-bigint</a></p>
<p>My Website: <a target="_blank" href="https://www.DavidWilliford.dev">https://www.DavidWilliford.dev</a></p>
<p><strong>Thanks for reading!</strong></p>
]]></content:encoded></item><item><title><![CDATA[How to fix "redirect_uri" mismatch in Shopify Hydrogen]]></title><description><![CDATA[A simple, detailed fix of a common user authentication bug within Shopify's Hydrogen framework.]]></description><link>https://blog.davidwilliford.dev/how-to-fix-redirecturi-mismatch-in-shopify-hydrogen</link><guid isPermaLink="true">https://blog.davidwilliford.dev/how-to-fix-redirecturi-mismatch-in-shopify-hydrogen</guid><category><![CDATA[shopify]]></category><category><![CDATA[Headless Commerce]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[Shopify store,]]></category><category><![CDATA[shopify hydrogen]]></category><category><![CDATA[ Hydrogen ]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Mon, 08 Apr 2024 18:07:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712599514718/461ff559-27b7-4726-a28d-6bc55454a28b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A common bug in Hydrogen is getting this <strong>"redirect_uri" mismatch</strong> error upon user sign-in.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712597781606/d1c58dac-4f28-4733-94fc-a605b581b6d9.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712597827261/04808881-cb3c-423c-ae44-17be05a9b2f5.png" alt class="image--center mx-auto" /></p>
<p>The official Shopify documentation for user authentication is not very helpful on this. So I will be sharing my own, simple solution.</p>
<p>There are 2 primary fixes for this.</p>
<ol>
<li><p>Set up a tunnel domain (using Ngrok etc).</p>
</li>
<li><p>Deploy changes on the Oxygen environment</p>
</li>
</ol>
<p>This tutorial will cover #2</p>
<p>Read my article on setting up Ngrok for Hydrogen stores <a target="_blank" href="https://blog.davidwilliford.dev/how-to-hydrogen-authentication-on-local-dev-server">here</a>.</p>
<h3 id="heading-step-1-make-sure-you-are-using-the-oxygen-environment-not-localhost">Step 1: Make sure you are using the Oxygen environment, not localhost</h3>
<p>For security reasons, Shopify does not allow authorization redirects to localhost URLs. Therefore, when you are testing user auth, you are going to want to do that through the Hydrogen app in your Shopify Admin (will be under 'sales channels' when installed)</p>
<p><a target="_blank" href="https://shopify.dev/docs/custom-storefronts/hydrogen/getting-started"><em>For help with Hydrogen setup.</em></a></p>
<p>To access your hosted dev server through Hydrogen, click the Hydrogen sales channel, then the blue URL under your storefront name.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712598402414/d41e0d1e-d772-47db-8b99-bda23ae6385b.png" alt class="image--center mx-auto" /></p>
<p>You should now see your current Hydrogen app in a dev environment, hosted through Oxygen rather than your local machine.</p>
<h3 id="heading-step-2-edit-your-callback-uris">Step 2: Edit your Callback URI(s)</h3>
<p>For some odd reason, Shopify makes you do this manually, rather than auto-configuring this for you.</p>
<p><strong>Go to:</strong><code>Hydrogen sales channel</code> &gt; <code>select storefront</code> &gt; <code>storefront settings</code> &gt; <code>Customer Account API</code> &gt; scroll down to <code>Application Setup</code>.</p>
<p>You will now see a list like so:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712598679910/466ab559-41cf-4d84-8a44-d383896773bc.png" alt class="image--center mx-auto" /></p>
<p>Yours will likely not have the 2nd URIs for callback and logout.</p>
<p><strong>TO FIX:</strong></p>
<p>Add your Hydrogen dev url as a callback URI, and append <code>/account/authorize</code> to the end of it.</p>
<p>Add the regular Hydrogen dev url as a Logout URI.</p>
<p>Add the regular Hydrogen dev url as a Javascript origin URI.</p>
<p><em>Remember the Hydrogen dev URL was the blue link below your listed storefront in the Hydrogen sales channel. And can also be seen at the top left of the settings page.</em></p>
<h3 id="heading-honorable-mention">Honorable Mention</h3>
<p>I originally found a similar solution <a target="_blank" href="https://github.com/Shopify/hydrogen/discussions/1893">here</a>, from Github users <code>eter5</code> and <code>rfried</code> . I found their fix, tweaked it so it worked for me, and added more detail.</p>
]]></content:encoded></item><item><title><![CDATA[How to get product metafields through Shopify's Storefront API]]></title><description><![CDATA[A simplified method for how to get product metafields from Shopify's Storefront API, ideal for developers working on headless Shopify projects.]]></description><link>https://blog.davidwilliford.dev/how-to-get-product-metafields-through-shopifys-storefront-api</link><guid isPermaLink="true">https://blog.davidwilliford.dev/how-to-get-product-metafields-through-shopifys-storefront-api</guid><category><![CDATA[shopify]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Shopify API Integration]]></category><category><![CDATA[shopify hydrogen]]></category><category><![CDATA[shopify store development]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Fri, 05 Apr 2024 13:58:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/mlpsHpUUCHY/upload/095aa651caea78a4387a1e97db76e1ed.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I ran into a problem where I could not get product metafields to return in the Shopify storefront API. This is important, since I plan to use these metafields on the product page of my headless Shopify build. I resolved the issue in a more digestible way than what is on the official Shopify documentation. So here is my simplified approach.</p>
<p><em>This tutorial is assuming that you already have storefront API access for your Shopify store.</em></p>
<h3 id="heading-step-1-enable-storefront-access-of-metafields-through-shopify-admin">Step 1: Enable storefront access of metafields through Shopify Admin</h3>
<p>Go to <code>settings &gt; custom data &gt; products</code> in your Shopify admin. Here you will be able to see your metafields like so:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712324360062/d8c9cc6f-c778-4bab-9b5f-e317dc825d9b.png" alt class="image--center mx-auto" /></p>
<p>Click on a metafield you wish to enable in the storefront API, and enable the <code>Storefronts access</code> button near the bottom. Repeat this for any additional metafields you wish to access.</p>
<h3 id="heading-step-2-obtain-namespace-and-key-of-desired-metafields">Step 2: Obtain namespace and key of desired metafields</h3>
<p>Go to the same page as above: <code>settings &gt; custom data &gt; products</code> . If you look to the image for step 1, you will see the smaller gray text. This text contains your namespace and key.</p>
<p>For example, if the text is <code>product.metafields.my_fields.description</code> , your namespace will be <code>my_fields</code> and your key will be <code>description</code> . You will need these for the API call in the next step.</p>
<h3 id="heading-step-3-make-the-api-call-to-retrieve-metafields">Step 3: Make the API call to retrieve metafields</h3>
<p>Now you can make your API call to the storefront API. Your call to the storefront should like so:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> ProductMetafields{
  product(<span class="hljs-symbol">id:</span> <span class="hljs-string">"your product id"</span>) {
    title
    metafield(<span class="hljs-symbol">namespace:</span> <span class="hljs-string">"my_fields"</span>, <span class="hljs-symbol">key:</span> <span class="hljs-string">"description"</span>) {
      value
    }
  }
}
</code></pre>
<p>This API call will now return your desired metafields. Hope this helped!</p>
]]></content:encoded></item><item><title><![CDATA[Event-driven API calls in Hydrogen]]></title><description><![CDATA[Implement secure, event-driven API calls in Shopify Hydrogen with useFetcher. Read now to integrate into your own storefront]]></description><link>https://blog.davidwilliford.dev/event-driven-api-calls-in-hydrogen</link><guid isPermaLink="true">https://blog.davidwilliford.dev/event-driven-api-calls-in-hydrogen</guid><category><![CDATA[shopify]]></category><category><![CDATA[Shopify Development]]></category><category><![CDATA[Shopify web development company]]></category><category><![CDATA[shopify hydrogen]]></category><category><![CDATA[Remix]]></category><category><![CDATA[react server components]]></category><dc:creator><![CDATA[David Williford]]></dc:creator><pubDate>Wed, 27 Mar 2024 15:56:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1718206188330/b4d33255-77a8-4303-9ad6-840de7e8b32a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I have been assigned the task of transferring my employer's Shopify Storefront into a Hydrogen headless build for the past few weeks now.</p>
<p>Part of our store includes a signup form, where users can sign up for email discounts before checkout. They enter their email and password, select enter, then the info is to be sent to the Storefront API.</p>
<p>This had been giving me headaches for a while. Most of the Shopify Hydrogen documentation focuses on making API calls on component render, and not on event-driven scenarios. However, I finally found a solution and hopefully my solution can help.</p>
<h2 id="heading-solution">Solution</h2>
<p>In Hydrogen, you can not simply make API calls on the client side, like you can in other frameworks. This is to ensure security, so no one can access private storefront information from the client-side. To safely send data to a server component upon an event (form submission in my case), we will be using the <code>useFetcher</code> hook from Remix.</p>
<h3 id="heading-first-make-2-components">First, Make 2 Components</h3>
<p>Make sure both of these components can be routed to. I am making both of them hybrid components, but you can make them client <code>.client.jsx</code> and server <code>.server.jsx</code> respectfully.</p>
<p><strong>We need ...</strong></p>
<ul>
<li><p>A component that contains an event (I will be using form submission)</p>
</li>
<li><p>A component that calls the API via an action function</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// The event triggering component </span>
<span class="hljs-comment">// Collects a form for user's email and password</span>

<span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { useFetcher } <span class="hljs-keyword">from</span> <span class="hljs-string">'@remix-run/react'</span>;

<span class="hljs-comment">// empty loader function</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{context}</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>; 
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CustomerSignUp</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">const</span> [customerInput, setCustomerInput] = useState({
    <span class="hljs-attr">acceptsMarketing</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
    <span class="hljs-attr">password</span>: <span class="hljs-string">""</span>,
  });

  <span class="hljs-keyword">const</span> handleInputChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> { name, value } = e.target;
    setCustomerInput(<span class="hljs-function"><span class="hljs-params">input</span> =&gt;</span> ({
      ...input,
      [name]: value
    }));
  };

  <span class="hljs-keyword">const</span> handleSignup = <span class="hljs-keyword">async</span> (e) =&gt; {
    e.preventDefault();

    <span class="hljs-comment">// where we will call our server component</span>
  };



  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Subscription Signup<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">{customerInput.email}</span>
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span>
          <span class="hljs-attr">required</span>
        /&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">{customerInput.password}</span>
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
          <span class="hljs-attr">required</span>
        /&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">className</span>=<span class="hljs-string">''</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Server Side Component </span>
<span class="hljs-comment">// Will call the Storefront API securely </span>

<span class="hljs-keyword">import</span> { useLoaderData } <span class="hljs-keyword">from</span> <span class="hljs-string">'@remix-run/react'</span>;

<span class="hljs-comment">// empty loader function</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{ request }</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>.
};

<span class="hljs-comment">// action method is required for receiving POST requests </span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> action = <span class="hljs-keyword">async</span> ({ request }) =&gt; {

    <span class="hljs-comment">// the query I need to send to the Storefront API        </span>
    <span class="hljs-keyword">const</span> mutation = <span class="hljs-string">`
      mutation CreateCustomer($input: CustomerCreateInput!) {
        customerCreate(input: $input) {
          customer {
            id
            email
            firstName
            lastName
            acceptsMarketing
            phone
          }
          customerUserErrors {
            code
            field
            message
          }
        }
      }
    `</span>;
};


<span class="hljs-comment">// This is not neccessary</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SignUp</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-implement-usefetcher-hook-from-remix">Implement useFetcher Hook from Remix</h3>
<p>The useFetcher hook will be used in the client component. It allows us to make requests to our server component. In this case, I will be using it for a POST request.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Final Event Component </span>
<span class="hljs-comment">// Implements useFetcher hook</span>
<span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-comment">// import useFetcher</span>
<span class="hljs-comment">// ============================================</span>
<span class="hljs-keyword">import</span> { useFetcher } <span class="hljs-keyword">from</span> <span class="hljs-string">'@remix-run/react'</span>;
<span class="hljs-comment">// ============================================</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{context}</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>; 
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CustomerSignUp</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-comment">// How you initialize a useFetcher instance</span>
  <span class="hljs-comment">// ============================================</span>
  <span class="hljs-keyword">const</span> fetcher = useFetcher();
  <span class="hljs-comment">// ============================================</span>

  <span class="hljs-keyword">const</span> [customerInput, setCustomerInput] = useState({
    <span class="hljs-attr">acceptsMarketing</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
    <span class="hljs-attr">password</span>: <span class="hljs-string">""</span>,
  });

  <span class="hljs-comment">// console logs fetcher data when updated </span>
  <span class="hljs-comment">// ============================================</span>
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (fetcher.data) {
      <span class="hljs-built_in">console</span>.log(fetcher.data);
    }
  }, [fetcher.data]);
  <span class="hljs-comment">// ============================================</span>



  <span class="hljs-keyword">const</span> handleInputChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> { name, value } = e.target;
    setCustomerInput(<span class="hljs-function"><span class="hljs-params">input</span> =&gt;</span> ({
      ...input,
      [name]: value
    }));
  };



  <span class="hljs-keyword">const</span> handleSignup = <span class="hljs-keyword">async</span> (e) =&gt; {
    e.preventDefault();

    <span class="hljs-comment">// How to submit a POST request to another component</span>
    <span class="hljs-comment">// using fetcher</span>
    <span class="hljs-comment">// ============================================</span>
    fetcher.submit({
      <span class="hljs-attr">email</span>: customerInput.email,
      <span class="hljs-attr">password</span>: customerInput.password,
    }, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">"post"</span>,
      <span class="hljs-attr">action</span>: <span class="hljs-string">"/signup"</span>, <span class="hljs-comment">// Route to your server component</span>
    });
    <span class="hljs-comment">// ============================================</span>

 };



  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span> 
        <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSignup}</span> 
      &gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Subscription Signup<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">{customerInput.email}</span>
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span>
          <span class="hljs-attr">required</span>
        /&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">{customerInput.password}</span>
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
          <span class="hljs-attr">required</span>
        /&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">className</span>=<span class="hljs-string">''</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Now that we are sending data to the server component, we must unpack it and send it to the API. Then, we can handle the API response and return it to the client event component. This is what our server component will look like now.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
 * Signup server component
 * Handles API call to storefront API
 */</span>

<span class="hljs-keyword">import</span> { useLoaderData } <span class="hljs-keyword">from</span> <span class="hljs-string">'@remix-run/react'</span>;


<span class="hljs-comment">// empty loader function</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loader</span>(<span class="hljs-params">{ request }</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
};


<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> action = <span class="hljs-keyword">async</span> ({ request }) =&gt; {

    <span class="hljs-comment">// Unpack data from POST Request</span>
    <span class="hljs-comment">// Then make variables for GraphQL query</span>
    <span class="hljs-comment">// ============================================</span>
    <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">await</span> request.formData();
    <span class="hljs-keyword">const</span> email = formData.get(<span class="hljs-string">"email"</span>);
    <span class="hljs-keyword">const</span> password = formData.get(<span class="hljs-string">"password"</span>);

    <span class="hljs-keyword">const</span> variables = {
        <span class="hljs-attr">input</span>: {
          email,
          password,
        },
      };
    <span class="hljs-comment">// ============================================</span>


    <span class="hljs-keyword">const</span> mutation = <span class="hljs-string">`
      mutation CreateCustomer($input: CustomerCreateInput!) {
        customerCreate(input: $input) {
          customer {
            id
            email
            firstName
            lastName
            acceptsMarketing
            phone
          }
          customerUserErrors {
            code
            field
            message
          }
        }
      }
    `</span>;


    <span class="hljs-comment">// Making Storefront API Call</span>
    <span class="hljs-comment">// ============================================</span>
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"Storefront API Link"</span>, {
            <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
            <span class="hljs-attr">headers</span>: {
                <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
                <span class="hljs-string">"X-Shopify-Storefront-Access-Token"</span>: <span class="hljs-string">"your-token"</span>,
            },
            <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">query</span>: mutation, variables }),
        });

        <span class="hljs-keyword">if</span> (!response.ok) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Error: <span class="hljs-subst">${response.status}</span>`</span>);
        }

        <span class="hljs-keyword">const</span> responseData = <span class="hljs-keyword">await</span> response.json();

        <span class="hljs-keyword">if</span> (responseData.data &amp;&amp; responseData.data.customerCreate) {

            <span class="hljs-comment">// succesfull customer creation</span>
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-built_in">JSON</span>.stringify({ 
                <span class="hljs-attr">message</span>: <span class="hljs-string">"Customer created successfully"</span>, 
                <span class="hljs-attr">customer</span>: responseData.data.customerCreate.customer
            }), {
                <span class="hljs-attr">status</span>: <span class="hljs-number">200</span>,
                <span class="hljs-attr">headers</span>: {
                    <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
                },
            });

        <span class="hljs-comment">// handling errors</span>
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (responseData.errors) {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">errors</span>: responseData.errors }), {
                <span class="hljs-attr">status</span>: <span class="hljs-number">400</span>,
                <span class="hljs-attr">headers</span>: {
                    <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
                },
            });
        }

    <span class="hljs-comment">// handling errors </span>
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">error</span>: error.message }), {
            <span class="hljs-attr">status</span>: <span class="hljs-number">500</span>,
            <span class="hljs-attr">headers</span>: {
                <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
            },
        });
    }
    <span class="hljs-comment">// ============================================</span>
};


<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SignUp</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;&gt;</span><span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-summary">Summary</h3>
<p>The <code>useFetcher</code> hook can be used to send data back and forth between components dynamically. It can be configured (like I have done) to make API calls conditionally and on events. It is very useful, and saved me a ton of headache.</p>
<p>Thanks for reading!</p>
]]></content:encoded></item></channel></rss>