<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samikaran Adhikari on Medium]]></title>
        <description><![CDATA[Stories by Samikaran Adhikari on Medium]]></description>
        <link>https://medium.com/@dev.samikaran?source=rss-4bfe7253d045------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SR7ysYE30j2RNiSJqDae4Q.jpeg</url>
            <title>Stories by Samikaran Adhikari on Medium</title>
            <link>https://medium.com/@dev.samikaran?source=rss-4bfe7253d045------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:23:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dev.samikaran/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Modern SEO-Friendly E-commerce Platform with Next.js]]></title>
            <link>https://medium.com/@dev.samikaran/building-a-modern-seo-friendly-e-commerce-platform-with-next-js-31b63880ee33?source=rss-4bfe7253d045------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b63880ee33</guid>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[e-commerce-business]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Samikaran Adhikari]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 00:04:44 GMT</pubDate>
            <atom:updated>2024-11-15T00:06:15.755Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Modern SEO-Friendly E-commerce Platform with Next.js 14 + Shopify Integration Guide (Part 2/2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t04M74WOSZrTWsffZDHtbw.jpeg" /></figure><p><a href="https://medium.com/@dev.samikaran/building-a-modern-seo-friendly-e-commerce-platform-with-next-js-14-shopify-integration-guide-a034b037fa76">Link back to Part 1</a></p><h3>Testing and Deployment</h3><p>Our testing suite combines Jest for unit/integration tests and Cypress for end-to-end testing.</p><p><strong>Jest Configuration</strong></p><pre>// jest.config.js<br>const nextJest = require(&quot;next/jest&quot;);</pre><pre>const createJestConfig = nextJest({<br>  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment<br>  dir: &quot;./&quot;<br>});</pre><pre>// Add any custom config to be passed to Jest<br>const customJestConfig = {<br>  setupFilesAfterEnv: [&quot;&lt;rootDir&gt;/jest.setup.ts&quot;],<br>  moduleDirectories: [&quot;node_modules&quot;, &quot;&lt;rootDir&gt;/&quot;],<br>  testEnvironment: &quot;jest-environment-jsdom&quot;,<br>  moduleNameMapper: {<br>    &quot;^@/(.*)$&quot;: &quot;&lt;rootDir&gt;/src/$1&quot;<br>  }<br>};</pre><pre>module.exports = createJestConfig(customJestConfig);</pre><p><strong>Unit Testing Components<br></strong>Here’s how we test our ProductCard component:</p><pre>// __tests__/components/add-to-cart-button.test.tsx<br>import React from &quot;react&quot;;<br>import { render, screen, fireEvent, waitFor } from &quot;@testing-library/react&quot;;<br>import &quot;@testing-library/jest-dom&quot;;<br>import AddToCartButton from &quot;@/components/products/cart/add-to-cart-button&quot;;<br>import * as CartContext from &quot;@/providers/cart-context&quot;;<br>import * as Toast from &quot;@/lib/utils/toast&quot;;</pre><pre>// Mock the dependencies<br>jest.mock(&quot;@/providers/cart-context&quot;, () =&gt; ({<br>  useCartContext: jest.fn()<br>}));</pre><pre>jest.mock(&quot;@/lib/utils/toast&quot;, () =&gt; ({<br>  showToast: {<br>    success: jest.fn(),<br>    error: jest.fn()<br>  }<br>}));</pre><pre>// Mock the Lucide icons<br>jest.mock(&quot;lucide-react&quot;, () =&gt; ({<br>  ShoppingCart: () =&gt; &lt;div data-testid=&quot;shopping-cart-icon&quot; /&gt;,<br>  Eye: () =&gt; &lt;div data-testid=&quot;eye-icon&quot; /&gt;,<br>  Heart: () =&gt; &lt;div data-testid=&quot;heart-icon&quot; /&gt;,<br>  Plus: () =&gt; &lt;div data-testid=&quot;plus-icon&quot; /&gt;,<br>  Minus: () =&gt; &lt;div data-testid=&quot;minus-icon&quot; /&gt;<br>}));</pre><pre>// Test props<br>const defaultProps = {<br>  variantId: &quot;test-variant-123&quot;,<br>  availableForSale: true,<br>  maxQuantity: 10,<br>  productTitle: &quot;Test Product&quot;<br>};</pre><pre>describe(&quot;AddToCartButton&quot;, () =&gt; {<br>  beforeEach(() =&gt; {<br>    jest.clearAllMocks();<br>    (CartContext.useCartContext as jest.Mock).mockReturnValue({<br>      addToCart: jest.fn().mockResolvedValue(undefined)<br>    });<br>  });</pre><pre>  it(&quot;renders the basic add to cart button for product card&quot;, () =&gt; {<br>    render(&lt;AddToCartButton {...defaultProps} isProductCard={true} /&gt;);</pre><pre>    const button = screen.getByRole(&quot;button&quot;);<br>    expect(button).toHaveTextContent(&quot;Add to Cart&quot;);<br>    expect(screen.queryByRole(&quot;spinbutton&quot;)).not.toBeInTheDocument();<br>  });</pre><pre>  it(&quot;renders quantity selector and add to cart button for detail view&quot;, () =&gt; {<br>    render(&lt;AddToCartButton {...defaultProps} /&gt;);</pre><pre>    expect(screen.getByRole(&quot;spinbutton&quot;)).toBeInTheDocument();<br>    expect(<br>      screen.getByRole(&quot;button&quot;, { name: /add to cart/i })<br>    ).toBeInTheDocument();<br>  });</pre><pre>  it(&quot;renders out of stock button when not available for sale&quot;, () =&gt; {<br>    render(&lt;AddToCartButton {...defaultProps} availableForSale={false} /&gt;);</pre><pre>    const button = screen.getByRole(&quot;button&quot;);<br>    expect(button).toHaveTextContent(&quot;Out of Stock&quot;);<br>    expect(button).toBeDisabled();<br>  });</pre><pre>  it(&quot;updates quantity correctly when using increment/decrement buttons&quot;, () =&gt; {<br>    render(&lt;AddToCartButton {...defaultProps} /&gt;);</pre><pre>    const input = screen.getByRole(&quot;spinbutton&quot;) as HTMLInputElement;<br>    const incrementButton = screen.getByRole(&quot;button&quot;, {<br>      name: /increase quantity/i<br>    });<br>    const decrementButton = screen.getByRole(&quot;button&quot;, {<br>      name: /decrease quantity/i<br>    });</pre><pre>    // Test increment<br>    fireEvent.click(incrementButton);<br>    expect(input.value).toBe(&quot;2&quot;);</pre><pre>    // Test decrement<br>    fireEvent.click(decrementButton);<br>    expect(input.value).toBe(&quot;1&quot;);<br>  });</pre><pre>  it(&quot;prevents quantity from going below 1 or above maxQuantity&quot;, () =&gt; {<br>    render(&lt;AddToCartButton {...defaultProps} maxQuantity={5} /&gt;);</pre><pre>    const input = screen.getByRole(&quot;spinbutton&quot;) as HTMLInputElement;<br>    const incrementButton = screen.getByRole(&quot;button&quot;, {<br>      name: /increase quantity/i<br>    });<br>    const decrementButton = screen.getByRole(&quot;button&quot;, {<br>      name: /decrease quantity/i<br>    });</pre><pre>    // Try to go below 1<br>    fireEvent.click(decrementButton);<br>    expect(input.value).toBe(&quot;1&quot;);<br>    expect(decrementButton).toBeDisabled();</pre><pre>    // Try to go above maxQuantity<br>    for (let i = 0; i &lt; 6; i++) {<br>      fireEvent.click(incrementButton);<br>    }<br>    expect(input.value).toBe(&quot;5&quot;);<br>    expect(incrementButton).toBeDisabled();<br>  });</pre><pre>  it(&quot;handles manual input of quantity correctly&quot;, () =&gt; {<br>    render(&lt;AddToCartButton {...defaultProps} maxQuantity={5} /&gt;);</pre><pre>    const input = screen.getByRole(&quot;spinbutton&quot;) as HTMLInputElement;</pre><pre>    // Test valid input<br>    fireEvent.change(input, { target: { value: &quot;3&quot; } });<br>    expect(input.value).toBe(&quot;3&quot;);</pre><pre>    // Test input below minimum<br>    fireEvent.change(input, { target: { value: &quot;0&quot; } });<br>    expect(input.value).toBe(&quot;1&quot;);</pre><pre>    // Test input above maximum<br>    fireEvent.change(input, { target: { value: &quot;10&quot; } });<br>    expect(input.value).toBe(&quot;5&quot;);<br>  });</pre><pre>  it(&quot;successfully adds to cart and shows success toast for product card&quot;, async () =&gt; {<br>    const addToCart = jest.fn().mockResolvedValue(undefined);<br>    (CartContext.useCartContext as jest.Mock).mockReturnValue({ addToCart });</pre><pre>    render(&lt;AddToCartButton {...defaultProps} isProductCard={true} /&gt;);</pre><pre>    const button = screen.getByRole(&quot;button&quot;);<br>    fireEvent.click(button);</pre><pre>    await waitFor(() =&gt; {<br>      expect(addToCart).toHaveBeenCalledWith(&quot;test-variant-123&quot;, 1);<br>      expect(Toast.showToast.success).toHaveBeenCalledWith(<br>        &quot;Test Product added to cart!&quot;<br>      );<br>    });<br>  });</pre><pre>  it(&quot;successfully adds to cart and shows success toast with quantity for detail view&quot;, async () =&gt; {<br>    const addToCart = jest.fn().mockResolvedValue(undefined);<br>    (CartContext.useCartContext as jest.Mock).mockReturnValue({ addToCart });</pre><pre>    render(&lt;AddToCartButton {...defaultProps} /&gt;);</pre><pre>    const input = screen.getByRole(&quot;spinbutton&quot;);<br>    fireEvent.change(input, { target: { value: &quot;3&quot; } });</pre><pre>    const button = screen.getByRole(&quot;button&quot;, { name: /add to cart/i });<br>    fireEvent.click(button);</pre><pre>    await waitFor(() =&gt; {<br>      expect(addToCart).toHaveBeenCalledWith(&quot;test-variant-123&quot;, 3);<br>      expect(Toast.showToast.success).toHaveBeenCalledWith(<br>        &quot;Test Product (3) added to cart!&quot;<br>      );<br>    });<br>  });</pre><pre>  it(&quot;handles add to cart failure correctly&quot;, async () =&gt; {<br>    const addToCart = jest.fn().mockRejectedValue(new Error(&quot;Failed to add&quot;));<br>    (CartContext.useCartContext as jest.Mock).mockReturnValue({ addToCart });</pre><pre>    render(&lt;AddToCartButton {...defaultProps} /&gt;);</pre><pre>    const button = screen.getByRole(&quot;button&quot;, { name: /add to cart/i });<br>    fireEvent.click(button);</pre><pre>    await waitFor(() =&gt; {<br>      expect(Toast.showToast.error).toHaveBeenCalledWith(<br>        &quot;Failed to add to cart. Please try again.&quot;<br>      );<br>    });<br>  });</pre><pre>  it(&quot;handles loading state during add to cart&quot;, async () =&gt; {<br>    const addToCart = jest<br>      .fn()<br>      .mockImplementation(<br>        () =&gt; new Promise((resolve) =&gt; setTimeout(resolve, 100))<br>      );<br>    (CartContext.useCartContext as jest.Mock).mockReturnValue({ addToCart });</pre><pre>    render(&lt;AddToCartButton {...defaultProps} /&gt;);</pre><pre>    const button = screen.getByRole(&quot;button&quot;, { name: /add to cart/i });<br>    fireEvent.click(button);</pre><pre>    expect(button).toHaveTextContent(&quot;Adding...&quot;);<br>    expect(button).toBeDisabled();</pre><pre>    await waitFor(() =&gt; {<br>      expect(button).toHaveTextContent(&quot;Add to Cart&quot;);<br>      expect(button).not.toBeDisabled();<br>    });<br>  });</pre><pre>  // Additional test to verify disabled states<br>  it(&quot;disables increment/decrement buttons at quantity limits&quot;, () =&gt; {<br>    render(&lt;AddToCartButton {...defaultProps} maxQuantity={5} /&gt;);</pre><pre>    const incrementButton = screen.getByRole(&quot;button&quot;, {<br>      name: /increase quantity/i<br>    });<br>    const decrementButton = screen.getByRole(&quot;button&quot;, {<br>      name: /decrease quantity/i<br>    });</pre><pre>    // Initial state: quantity is 1, decrement should be disabled<br>    expect(decrementButton).toBeDisabled();<br>    expect(incrementButton).not.toBeDisabled();</pre><pre>    // Click increment until max quantity<br>    for (let i = 0; i &lt; 4; i++) {<br>      fireEvent.click(incrementButton);<br>    }</pre><pre>    // At max quantity: increment should be disabled<br>    expect(incrementButton).toBeDisabled();<br>    expect(decrementButton).not.toBeDisabled();<br>  });<br>});</pre><p><strong>Cypress Configuration</strong></p><pre>// cypress.config.ts<br>import { defineConfig } from &quot;cypress&quot;;</pre><pre>export default defineConfig({<br>  e2e: {<br>    setupNodeEvents(on, config) {<br>      // implement node event listeners here<br>    },<br>    baseUrl: process.env.NEXT_PUBLIC_SITE_DOMAIN || &quot;http://localhost:3000&quot;,<br>    supportFile: &quot;cypress/support/e2e.ts&quot;,<br>    specPattern: &quot;cypress/e2e/**/*.cy.ts&quot;,<br>    viewportWidth: 1280,<br>    viewportHeight: 720,<br>    video: false<br>  },<br>  component: {<br>    devServer: {<br>      framework: &quot;next&quot;,<br>      bundler: &quot;webpack&quot;<br>    }<br>  }<br>});</pre><p><strong>End-to-End Testing with Cypress</strong></p><pre>// cypress/e2e/add-to-cart-button.cy.ts<br>describe(&quot;Add to Cart Button&quot;, () =&gt; {<br>  beforeEach(() =&gt; {<br>    // Make sure your Next.js development server is running on port 3000<br>    cy.visit(&quot;http://localhost:3000/product/fire-motif-zandana&quot;);<br>  });</pre><pre>  describe(&quot;Basic Add to Cart&quot;, () =&gt; {<br>    it(&quot;should successfully add a product to cart&quot;, () =&gt; {<br>      // Click add to cart button<br>      cy.get(&quot;button&quot;).contains(&quot;Add to Cart&quot;).first().should(&quot;exist&quot;).click();</pre><pre>      // Verify success toast<br>      cy.contains(&quot;added to cart!&quot;).should(&quot;be.visible&quot;);<br>    });</pre><pre>    it(&quot;should show loading state while adding to cart&quot;, () =&gt; {<br>      cy.get(&quot;button&quot;).contains(&quot;Add to Cart&quot;).first().should(&quot;exist&quot;).click();</pre><pre>      // Verify loading state<br>      cy.contains(&quot;Adding...&quot;).should(&quot;be.visible&quot;);<br>    });<br>  });</pre><pre>  describe(&quot;Product Detail Quantity Controls&quot;, () =&gt; {<br>    beforeEach(() =&gt; {<br>      // Click on first product to go to detail page<br>      // Update this selector based on your actual HTML structure<br>      cy.get(&quot;a&quot;).contains(&quot;Product&quot;).first().click();<br>    });</pre><pre>    it(&quot;should change quantity using controls&quot;, () =&gt; {<br>      // Increase quantity<br>      cy.get(&#39;button[aria-label=&quot;Increase quantity&quot;]&#39;).click();<br>      cy.get(&#39;input[type=&quot;number&quot;]&#39;).should(&quot;have.value&quot;, &quot;2&quot;);</pre><pre>      // Decrease quantity<br>      cy.get(&#39;button[aria-label=&quot;Decrease quantity&quot;]&#39;).click();<br>      cy.get(&#39;input[type=&quot;number&quot;]&#39;).should(&quot;have.value&quot;, &quot;1&quot;);<br>    });</pre><pre>    it(&quot;should handle manual quantity input&quot;, () =&gt; {<br>      // Enter valid quantity<br>      cy.get(&#39;input[type=&quot;number&quot;]&#39;)<br>        .clear()<br>        .type(&quot;3&quot;)<br>        .should(&quot;have.value&quot;, &quot;3&quot;);</pre><pre>      // Try entering invalid quantities<br>      cy.get(&#39;input[type=&quot;number&quot;]&#39;)<br>        .clear()<br>        .type(&quot;0&quot;)<br>        .should(&quot;have.value&quot;, &quot;1&quot;);</pre><pre>      cy.get(&#39;input[type=&quot;number&quot;]&#39;)<br>        .clear()<br>        .type(&quot;11&quot;)<br>        .should(&quot;have.value&quot;, &quot;10&quot;);<br>    });<br>  });</pre><pre>  // describe(&quot;Out of Stock Products&quot;, () =&gt; {<br>  //   it(&quot;should show out of stock button state&quot;, () =&gt; {<br>  //     // Find and verify an out of stock button if exists<br>  //     cy.get(&quot;button&quot;)<br>  //       .contains(&quot;Out of Stock&quot;)<br>  //       .should(&quot;be.visible&quot;)<br>  //       .and(&quot;be.disabled&quot;);<br>  //   });<br>  // });<br>});</pre><p><strong>Local Development</strong>:</p><pre>npm run dev</pre><p><strong>Production Build</strong>:</p><pre>npm run build<br>npm run start</pre><p><strong>Vercel Deployment</strong>:</p><ul><li>Connected GitHub repository to Vercel</li><li>Configured environment variables</li><li>Enabled automatic deployments</li></ul><h3>Live Demo and Source Code</h3><ul><li><strong>Demo</strong>: <a href="https://fullstack-ecommerce-nextjs-shopify.vercel.app/">Live Project</a></li><li><strong>Source Code</strong>: <a href="https://github.com/samikaran/fullstack-ecommerce-nextjs-shopify/">GitHub Repository</a></li></ul><h3>Conclusion</h3><p>Building this e-commerce platform was an exciting journey that combined modern web technologies with practical business needs. The project demonstrates how Next.js 14, combined with Shopify’s robust backend, can create a powerful e-commerce solution.</p><h3>Key Takeaways</h3><ul><li>Next.js 14’s app router provides excellent SEO capabilities</li><li>TypeScript ensures type safety across the application</li><li>Tailwind CSS with shadcn/ui creates a beautiful, consistent UI</li><li>Shopify’s API is powerful and flexible</li><li>Stripe integration handles payments securely</li><li>React-toastify improves user experience with notifications</li><li>Comprehensive testing ensures reliability</li><li>Custom API routes provide flexibility and control</li></ul><h3>Future Improvements</h3><ul><li>Add user authentication</li><li>Implement wish list functionality</li><li>Add product reviews and ratings</li><li>Enhance mobile responsiveness</li><li>Add more payment methods</li></ul><p><strong>Getting Help<br></strong>If you run into any issues while following this tutorial or working with the repository:</p><ul><li>Check the <a href="https://github.com/samikaran/fullstack-ecommerce-nextjs-shopify/issues">Issues</a> section of the repository</li><li>Create a new issue if you’ve discovered a bug</li><li>Start a discussion if you need help or have suggestions</li></ul><p><strong>Contributing<br></strong>Your contributions are welcome! Whether it’s:</p><ul><li>Bug fixes</li><li>Feature additions</li><li>Documentation improvements</li><li>Test coverage enhancements</li></ul><p>Feel free to explore the code, fork the repository, and make it your own! If you have any questions or suggestions, don’t hesitate to reach out through GitHub issues.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b63880ee33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modern SEO-Friendly E-commerce Platform with Next.js]]></title>
            <link>https://medium.com/@dev.samikaran/building-a-modern-seo-friendly-e-commerce-platform-with-next-js-14-shopify-integration-guide-a034b037fa76?source=rss-4bfe7253d045------2</link>
            <guid isPermaLink="false">https://medium.com/p/a034b037fa76</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[e-commerce-business]]></category>
            <category><![CDATA[shopify]]></category>
            <dc:creator><![CDATA[Samikaran Adhikari]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 00:56:24 GMT</pubDate>
            <atom:updated>2024-11-15T00:05:08.763Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Modern SEO-Friendly E-commerce Platform with Next.js 14 + Shopify Integration Guide (Part 1/2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t04M74WOSZrTWsffZDHtbw.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>Hey developers! 👋 Today, I’m excited to share my journey of building a full-stack e-commerce platform using Next.js 14 and Shopify. This project showcases how to create a modern, SEO-friendly online store while integrating multiple technologies. Whether you’re a beginner or an experienced developer, this guide will help you understand the complete workflow of building a production-ready e-commerce solution.</p><blockquote><strong>Important Note</strong>: The code snippets shown in this blog are synchronized and simplified for better understanding. For the complete, production-ready implementation, please refer to the <a href="https://github.com/samikaran/fullstack-ecommerce-nextjs-shopify/">GitHub repository</a>.</blockquote><h3><strong>Learning Path Options</strong></h3><p>You have two ways to follow along with this tutorial:</p><p><strong>Option 1: Clone and Run the Project</strong></p><pre> Clone the repository<br>git clone https://github.com/samikaran/fullstack-ecommerce-nextjs-shopify/<br>cd fullstack-ecommerce-nextjs-shopify<br><br># Install dependencies<br>npm install<br><br># Set up environment variables<br>cp .env.example .env.local<br># Update .env.local with your Shopify and Stripe credentials<br><br># Run the development server<br>npm run dev</pre><p><strong>Option 2: Build from Scratch</strong></p><p>Follow along with this tutorial to build your own version of the application. This approach will give you a deeper understanding of each component and implementation detail.</p><h3><strong>Tech Stack Overview</strong></h3><ul><li><strong>Frontend Framework</strong>: Next.js 14 with TypeScript</li><li><strong>Styling</strong>: Tailwind CSS + shadcn/ui</li><li><strong>E-commerce Backend</strong>: Shopify</li><li><strong>Payment Processing</strong>: Stripe</li><li><strong>Notifications</strong>: react-toastify</li><li><strong>Data Migration</strong>: WooCommerce to Shopify</li><li><strong>Testing</strong>: Jest + Cypress</li></ul><h3><strong>Key Features</strong></h3><ul><li>Responsive Homepage with Banner and Latest Products</li><li>Advanced Product Listing with Search and Filters</li><li>Category-based Product Navigation</li><li>Smart Cart Management</li><li>Multi-step Checkout Process</li><li>Secure Payment Integration</li><li>Order Success Tracking</li><li>Comprehensive Test Coverage</li></ul><h3><strong>Project Setup</strong></h3><p><strong>Initial Configuration</strong></p><pre>// Install dependencies<br>npm create next-app@latest my-ecommerce --typescript --tailwind<br>cd my-ecommerce<br><br>// Install additional packages<br>npm install shopify-buy @shopify/shopify-api @stripe/stripe-js react-toastify<br><br>// Setup Jest for Unit Testing<br>npm install --save-dev jest @testing-library/react @testing-library/jest-dom<br><br>// Install Cypress for End-to-End Testing<br>npm install cypress --save-dev</pre><h3><strong>Project Deep Dive</strong></h3><blockquote><strong>Note</strong>: These components are simplified versions for educational purposes. The actual implementation in the repository includes additional error handling, loading states, and edge cases.</blockquote><p><strong>Data Migration: WooCommerce to Shopify<br></strong>One unique aspect of this project was migrating data from WooCommerce to Shopify, which allows to manage products on Shopify and render them on Next.js app via the Shopify API. Here’s how we handled it:</p><ul><li><strong>Export Products from WooCommerce using </strong>WooCommerce’s built-in export tool</li><li><strong>Reformat CSV for Shopify</strong> and import the reformatted CSV into Shopify Admin.</li></ul><p>There are two options for data migration:<br>1. <strong>Data Transformation </strong>Programaticaly:<br>We can use Shopify Admin API for programmatic import:</p><pre>interface WooCommerceProduct {<br>  id: string;<br>  name: string;<br>  regular_price: string;<br>  // ... other fields<br>}<br><br>interface ShopifyProduct {<br>  Handle: string;<br>  Title: string;<br>  &#39;Variant Price&#39;: string;<br>  // ... other fields<br>}<br><br>const transformProduct = (wooProduct: WooCommerceProduct): ShopifyProduct =&gt; {<br>  return {<br>    Handle: slugify(wooProduct.name),<br>    Title: wooProduct.name,<br>    &#39;Variant Price&#39;: wooProduct.regular_price,<br>    // ... transform other fields<br>  };<br>};</pre><p>2. Import to Shopify Manually:<br>Implemented CSV import for bulk data in Shopify Admin panel.</p><p><strong>API Integration</strong></p><blockquote><strong>Note</strong>: Make sure to handle rate limiting and implement proper error handling in production. The repository contains complete implementation with all edge cases covered.</blockquote><p>Shopify API</p><pre>// lib/shopify.ts<br>import Client from &quot;shopify-buy&quot;;<br>import { LATEST_API_VERSION } from &quot;@shopify/shopify-api&quot;;<br>import { createAdminApiClient } from &quot;@shopify/admin-api-client&quot;;<br>import { GraphQLClient } from &quot;graphql-request&quot;;<br><br>// Shopify store configuration<br>// These env variables should be set in .env.local file<br>const endpoint = process.env.NEXT_PUBLIC_SHOPIFY_STORE_ENDPOINT;<br>const admin_access_token = process.env.NEXT_PUBLIC_SHOPIFY_ADMIN_ACCESS_TOKEN;<br>const storefront_access_token = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN;<br><br>// Initialize Shopify Buy SDK client<br>// Used for storefront operations like product listing and cart management<br>// Provides high-level abstractions for common e-commerce operations<br>const shopify = Client.buildClient({<br>  domain: endpoint || &quot;&quot;,<br>  storefrontAccessToken: storefront_access_token || &quot;&quot;,<br>  apiVersion: LATEST_API_VERSION<br>});<br><br>// Initialize Shopify Admin API client<br>// Used for advanced operations like inventory management and order processing<br>// Requires admin access token with appropriate permissions<br>// Uncomment when admin operations are needed<br>const shopifyAdmin = createAdminApiClient({<br>  storeDomain: endpoint || &quot;&quot;,<br>  apiVersion: LATEST_API_VERSION,<br>  accessToken: admin_access_token || &quot;&quot;<br>});<br><br>// Initialize raw GraphQL client for custom queries<br>// Useful for specific storefront operations not covered by the Buy SDK<br>// Provides more flexibility but requires manual query writing<br>const graphqlClient = new GraphQLClient(<br>  `https://${endpoint}/api/${LATEST_API_VERSION}/graphql.json`,<br>  {<br>    headers: {<br>      &quot;X-Shopify-Storefront-Access-Token&quot;: storefront_access_token || &quot;&quot;,<br>      &quot;Content-Type&quot;: &quot;application/json&quot;<br>    }<br>  }<br>);<br><br>export { shopify, shopifyAdmin, graphqlClient };</pre><p>Shopify Client</p><pre>// services/shopify-client.ts<br>// import { shopify, shopifyAdmin } from &quot;@/lib/shopify&quot;;<br>import { shopify } from &quot;@/lib/shopify/client&quot;;<br><br>// Fetches all products from Shopify<br>// Note: Currently fetches all products at once - consider implementing cursor-based pagination<br>// for large catalogs to improve performance<br>// @param page - Page number (currently unused, handled by API route)<br>// @param limit - Products per page (currently unused, handled by API route)<br>export async function fetchProducts(page = 1, limit = 20) {<br>  try {<br>    // Fetch complete product catalog<br>    const products = await shopify.product.fetchAll();<br><br>    if (!products) {<br>      return [];<br>    }<br><br>    return products.map((product) =&gt; {<br>      // Ensure variants have availableForSale property<br>      const variants = product.variants.map((variant) =&gt; ({<br>        ...variant,<br>        availableForSale: variant.availableForSale, // Buy SDK uses &#39;available&#39; instead of &#39;availableForSale&#39;<br>        quantityAvailable: variant.quantityAvailable || 0<br>      }));<br><br>      return {<br>        ...product,<br>        variants<br>      };<br>    });<br><br>    // Debugging log for monitoring data<br>    // console.log(&quot;Total products from Shopify:&quot;, products.length);<br>    // console.log(&quot;Products from Shopify:&quot;, products);<br><br>    // Return full product list for API route to handle pagination<br>    // return products;<br>  } catch (error) {<br>    console.error(&quot;Error fetching products:&quot;, error);<br>    return [];<br>  }<br>}<br><br>// Retrieves a single product by its handle (slug)<br>// @param handle - Product&#39;s unique handle/slug identifier<br>// @returns Product object or null if not found<br>export async function fetchProduct(handle: string) {<br>  try {<br>    const product = await shopify.product.fetchByHandle(handle);<br>    if (!product) {<br>      return null;<br>    }<br><br>    const variants = product.variants.map((variant) =&gt; ({<br>      ...variant,<br>      availableForSale: variant.availableForSale,<br>      quantityAvailable: variant.quantityAvailable || 0<br>    }));<br><br>    return {<br>      ...product,<br>      variants<br>    };<br>    // return product;<br>  } catch (error) {<br>    console.error(&quot;Error fetching product details&quot;, error);<br>    throw error;<br>  }<br>}<br><br>// Fetches products by category slug<br>// Handles nested category paths and returns existence status<br>// @param slug - Category path (can be nested, e.g., &quot;parent/child&quot;)<br>// @returns Object with existence flag and products array<br>export const fetchProductsByCategory = async (slug: string) =&gt; {<br>  try {<br>    // Extract target category from potentially nested path<br>    const categories = slug.split(&quot;/&quot;);<br>    const targetCategory = categories[categories.length - 1].toLowerCase();<br><br>    // Fetch and filter collections by target category<br>    const collections = await shopify.collection.fetchAllWithProducts();<br>    if (!collections) {<br>      return { exists: false, products: [] };<br>    }<br><br>    // Find matching collection (case-insensitive)<br>    const collection = collections.find(<br>      (col) =&gt; col.title.toLowerCase() === targetCategory<br>    );<br><br>    // Handle non-existent category<br>    if (!collection) {<br>      return { exists: false, products: [] };<br>    }<br><br>    // Return products with existence flag<br>    return { exists: true, products: collection.products || [] };<br>  } catch (error) {<br>    console.error(&quot;Error fetching products by category:&quot;, error);<br>    throw error;<br>  }<br>};<br><br>/*  Note: Consider implementing cursor-based pagination for large catalogs<br> * and caching frequently accessed data to improve performance.<br> */</pre><p>Reusable function to get product</p><pre>import { ProductProps } from &quot;@/types&quot;;<br><br>// Fetches paginated list of products<br>// @param page - Page number for pagination (default: 1)<br>// @param limit - Number of products per page (default: 12)<br>// @returns Object containing product array and total count<br>export async function getProducts(<br>  page: number = 1,<br>  limit: number = 12<br>): Promise&lt;{ products: ProductProps[]; total: number }&gt; {<br>  try {<br>    // Fetch products with pagination params<br>    // Using no-store to prevent caching and ensure fresh data<br>    const response = await fetch(<br>      `${process.env.NEXT_PUBLIC_SITE_DOMAIN}/api/products?page=${page}`,<br>      {<br>        cache: &quot;no-store&quot;<br>      }<br>    );<br><br>    if (!response.ok) {<br>      throw new Error(<br>        `Failed to fetch products: ${response.status} ${response.statusText}`<br>      );<br>    }<br><br>    const data = await response.json();<br><br>    // Return empty array if API indicates failure<br>    if (!data.success) {<br>      return { products: [], total: 0 };<br>    }<br><br>    return {<br>      products: data.products || [],<br>      total: data.total || 0<br>    };<br>  } catch (error) {<br>    // Gracefully handle errors by returning empty data<br>    return { products: [], total: 0 };<br>  }<br>}</pre><p>Product API</p><pre>// app/api/products/route.ts<br>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br>import {<br>  fetchProduct,<br>  fetchProducts,<br>  fetchProductsByCategory<br>} from &quot;@/services/shopify-client&quot;;<br>import { PRODUCTS_PER_PAGE } from &quot;@/constants&quot;;<br>import {<br>  ProductProps,<br>  ProductVariant,<br>  ProductImage,<br>  ProductOption<br>} from &quot;@/types&quot;;<br><br>/**<br> * Maps Shopify product data to our ProductProps interface<br> */<br>function mapShopifyProduct(shopifyProduct: any): ProductProps {<br>  return {<br>    id: shopifyProduct.id,<br>    title: shopifyProduct.title,<br>    handle: shopifyProduct.handle,<br>    description: shopifyProduct.description,<br>    publishedAt: shopifyProduct.publishedAt,<br>    createdAt: shopifyProduct.createdAt,<br>    updatedAt: shopifyProduct.updatedAt,<br>    vendor: shopifyProduct.vendor,<br>    productType: shopifyProduct.productType,<br>    tags: Array.isArray(shopifyProduct.tags) ? shopifyProduct.tags : [],<br>    variants: shopifyProduct.variants.map(<br>      (variant: any): ProductVariant =&gt; ({<br>        id: variant.id,<br>        title: variant.title,<br>        price: {<br>          amount: variant.price?.amount || &quot;0&quot;,<br>          currencyCode: variant.price?.currencyCode || &quot;USD&quot;<br>        },<br>        compareAtPrice: variant.compareAtPrice<br>          ? {<br>              amount: variant.compareAtPrice.amount,<br>              currencyCode: variant.compareAtPrice.currencyCode<br>            }<br>          : null,<br>        inventoryQuantity: variant.quantityAvailable || 0,<br>        weight: variant.weight || 0,<br>        weightUnit: variant.weightUnit || &quot;kg&quot;,<br>        availableForSale: variant.available || false,<br>        requiresShipping: variant.requiresShipping || true,<br>        barcode: variant.sku || &quot;&quot;,<br>        available: variant.available || false,<br>        image: variant.image<br>          ? {<br>              url: variant.image.src,<br>              altText: variant.image.altText || &quot;&quot;<br>            }<br>          : undefined<br>      })<br>    ),<br>    options: shopifyProduct.options.map(<br>      (option: any): ProductOption =&gt; ({<br>        id: option.id,<br>        name: option.name,<br>        values: Array.isArray(option.values) ? option.values : [],<br>        type: Array.isArray(option.type) ? option.type : []<br>      })<br>    ),<br>    images: shopifyProduct.images.map(<br>      (image: any): ProductImage =&gt; ({<br>        id: image.id,<br>        src: image.src,<br>        altText: image.altText || &quot;&quot;,<br>        width: image.width || 0,<br>        height: image.height || 0<br>      })<br>    )<br>  };<br>}<br><br>/**<br> * Helper function to get product price<br> * Extracts the price from the first variant if available<br> */<br>function getProductPrice(product: ProductProps): number {<br>  if (product.variants &amp;&amp; product.variants.length &gt; 0) {<br>    const variant = product.variants[0];<br>    if (variant.price &amp;&amp; variant.price.amount) {<br>      const price = parseFloat(variant.price.amount);<br>      return isNaN(price) ? 0 : price;<br>    }<br>  }<br>  return 0;<br>}<br><br>/**<br> * Helper function to check product availability status<br> */<br>function checkAvailability(product: ProductProps, status: string): boolean {<br>  if (!product.variants || product.variants.length === 0) return false;<br><br>  switch (status) {<br>    case &quot;in-stock&quot;:<br>      return product.variants.some(<br>        (variant) =&gt; variant.availableForSale &amp;&amp; variant.inventoryQuantity &gt; 0<br>      );<br>    case &quot;out-of-stock&quot;:<br>      return product.variants.every(<br>        (variant) =&gt; !variant.availableForSale || variant.inventoryQuantity &lt;= 0<br>      );<br>    case &quot;pre-order&quot;:<br>      return product.variants.some(<br>        (variant) =&gt; variant.availableForSale &amp;&amp; variant.inventoryQuantity &lt;= 0<br>      );<br>    default:<br>      return true;<br>  }<br>}<br><br>/**<br> * GET - Advanced product fetching endpoint with filtering, sorting, and pagination<br> */<br>export async function GET(request: NextRequest) {<br>  const { searchParams } = new URL(request.url);<br>  const handle = searchParams.get(&quot;handle&quot;);<br>  const category = searchParams.get(&quot;category&quot;);<br>  const search = searchParams.get(&quot;search&quot;);<br>  const minPrice = Number(searchParams.get(&quot;minPrice&quot;)) || 0;<br>  const maxPrice = Number(searchParams.get(&quot;maxPrice&quot;)) || Infinity;<br>  const availability = searchParams.get(&quot;availability&quot;);<br>  const sort = searchParams.get(&quot;sort&quot;);<br>  const page = Number(searchParams.get(&quot;page&quot;)) || 1;<br><br>  try {<br>    let products: ProductProps[];<br><br>    // Handle single product fetch by handle<br>    if (handle) {<br>      const shopifyProduct = await fetchProduct(handle);<br>      if (!shopifyProduct) {<br>        return NextResponse.json(<br>          { success: false, error: &quot;Product not found&quot; },<br>          { status: 404 }<br>        );<br>      }<br>      const mappedProduct = mapShopifyProduct(shopifyProduct);<br>      return NextResponse.json({ success: true, product: mappedProduct });<br>    }<br>    // Handle category-based product fetch<br>    else if (category) {<br>      const result = await fetchProductsByCategory(category);<br>      if (!result.exists) {<br>        return NextResponse.json(<br>          { success: false, error: &quot;Category not found&quot; },<br>          { status: 404 }<br>        );<br>      }<br>      products = result.products.map(mapShopifyProduct);<br>    }<br>    // Fetch all products if no handle or category specified<br>    else {<br>      const shopifyProducts = await fetchProducts();<br>      products = shopifyProducts.map(mapShopifyProduct);<br>    }<br><br>    // Initialize empty array if no products found<br>    if (!products) {<br>      products = [];<br>    }<br><br>    // Apply filters<br>    let filteredProducts = [...products];<br><br>    // Apply search filter across title, description, and vendor<br>    if (search) {<br>      const searchLower = search.toLowerCase();<br>      filteredProducts = filteredProducts.filter(<br>        (product) =&gt;<br>          product.title.toLowerCase().includes(searchLower) ||<br>          product.description.toLowerCase().includes(searchLower) ||<br>          product.vendor.toLowerCase().includes(searchLower)<br>      );<br>    }<br><br>    // Apply price range filter<br>    if (minPrice &gt; 0 || maxPrice &lt; Infinity) {<br>      filteredProducts = filteredProducts.filter((product) =&gt; {<br>        const price = getProductPrice(product);<br>        return price &gt;= minPrice &amp;&amp; price &lt;= maxPrice;<br>      });<br>    }<br><br>    // Apply availability filter<br>    if (availability &amp;&amp; availability !== &quot;any&quot;) {<br>      filteredProducts = filteredProducts.filter((product) =&gt;<br>        checkAvailability(product, availability)<br>      );<br>    }<br><br>    // Apply sorting<br>    if (sort) {<br>      filteredProducts = [...filteredProducts].sort((a, b) =&gt; {<br>        switch (sort) {<br>          case &quot;price-asc&quot;:<br>            return getProductPrice(a) - getProductPrice(b);<br>          case &quot;price-desc&quot;:<br>            return getProductPrice(b) - getProductPrice(a);<br>          case &quot;name-asc&quot;:<br>            return a.title.localeCompare(b.title);<br>          case &quot;name-desc&quot;:<br>            return b.title.localeCompare(a.title);<br>          default:<br>            return 0;<br>        }<br>      });<br>    }<br><br>    // Apply pagination<br>    const start = (page - 1) * PRODUCTS_PER_PAGE;<br>    const paginatedProducts = filteredProducts.slice(<br>      start,<br>      start + PRODUCTS_PER_PAGE<br>    );<br><br>    // Return paginated results with metadata<br>    return NextResponse.json({<br>      success: true,<br>      products: paginatedProducts,<br>      total: filteredProducts.length,<br>      page: page<br>    });<br>  } catch (error) {<br>    console.error(&quot;Error in API route:&quot;, error);<br>    return NextResponse.json(<br>      { success: false, error: &quot;Internal server error&quot; },<br>      { status: 500 }<br>    );<br>  }<br>}</pre><p>Checkout API</p><pre>// app/api/checkout/route.ts<br>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br>import { calculateTotalCartAmount } from &quot;@/lib/utils&quot;;<br>/**<br> * Initialize Stripe client with secret key<br> * Make sure STRIPE_SECRET_KEY is set in environment variables<br> */<br>const stripe = require(&quot;stripe&quot;)(process.env.STRIPE_SECRET_KEY);<br><br>/**<br> * POST - Creates a Stripe Payment Intent for processing payments<br> *<br> * @param {NextRequest} request - Contains cart data and shipping details<br> * @returns {NextResponse} - Returns client secret for Stripe payment processing<br> *<br> * The function performs the following steps:<br> * 1. Extracts cart and shipping details from request<br> * 2. Calculates total amount from cart<br> * 3. Creates a Stripe payment intent<br> * 4. Returns the client secret to initialize payment flow<br> */<br>export async function POST(request: NextRequest) {<br>  try {<br>    // Extract cart and shipping details from request body<br>    const { cart, shippingDetails } = await request.json();<br><br>    // Calculate total amount from cart items<br>    const { total } = calculateTotalCartAmount(cart);<br><br>    // Create Stripe Payment Intent<br>    // Amount needs to be in cents (multiply by 100)<br>    // Currency is set to Canadian dollars (cad)<br>    const paymentIntent = await stripe.paymentIntents.create({<br>      amount: Math.round(total * 100), // Round to avoid floating point issues<br>      currency: &quot;cad&quot;,<br>      // Enable automatic payment methods for flexible payment options<br>      automatic_payment_methods: { enabled: true },<br>      // Store cart and shipping details in metadata for reference<br>      metadata: {<br>        cartId: cart.id,<br>        ...shippingDetails<br>      }<br>    });<br><br>    // Return client secret to frontend for payment processing<br>    return NextResponse.json({ clientSecret: paymentIntent.client_secret });<br>  } catch (error) {<br>    // Return error message with 400 status code for client-side handling<br>    return NextResponse.json(<br>      { error: (error as Error).message },<br>      { status: 400 }<br>    );<br>  }<br>}</pre><p><strong>SEO Optimization<br></strong>Implemented proper SEO practices using Next.js built-in features:</p><pre>// app/layout.tsx<br>import { Metadata } from &#39;next&#39;;<br><br>export const metadata: Metadata = {<br>  title: &quot;Welcome to OneStopShop - Shopping Made Easier&quot;,<br>    description: &quot;Shop the best products at affordable prices.&quot;,<br>    openGraph: {<br>      title: &quot;Welcome to My E-Commerce Store&quot;,<br>      description: &quot;Find the best deals and offers on our store.&quot;,<br>      url: baseUrl,<br>      // OG image ratio 1.91:1 (1200x630) for optimal display<br>      images: [<br>        {<br>          url: &quot;/homepage-og-image.jpg&quot;,<br>          width: 1200,<br>          height: 630,<br>          alt: &quot;E-Commerce Store Home Page&quot;<br>        }<br>      ]<br>    },<br>};</pre><p>Stay tuned for Part 2 where we’ll cover Testing Strategy, and Deployment!</p><p><a href="https://medium.com/@dev.samikaran/building-a-modern-seo-friendly-e-commerce-platform-with-next-js-31b63880ee33">Continue to part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a034b037fa76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>