≡ Menu

Going Headless: How to Build a Blazing-Fast Shopify Store with Next.js (App Router)

Traditional Shopify themes (Liquid) are excellent for getting started, but as an e-commerce brand scales, performance bottlenecking and rigid design constraints often crawl in.

By decoupling your frontend with Next.js and using Shopify strictly as a headless commerce engine, you unlock sub-second page loads, completely custom UI freedom, and major SEO advantages.

Here is your step-by-step developer’s blueprint to building a production-ready headless Shopify store using the Next.js App Router and the Shopify Storefront API.

1. The Headless Architecture

In a headless setup, Shopify ceases to manage your layout. Instead, it acts as your data warehouse, inventory tracker, and checkout gateway.

  • Presentation Layer: Next.js (React Server Components, Dynamic Streaming).

  • Commerce Data Layer: Shopify Storefront API (GraphQL).

  • Hosting: Vercel, Netlify, or AWS.

2. Step 1: Setting Up Shopify Storefront API

Before writing code, you need to generate public access tokens to query your catalog.

  1. Navigate to your Shopify Admin panel  Settings > Apps and sales channels.

  2. Click Develop apps, then select Allow custom app development.

  3. Click Create an app and name it (e.g., NextJS Storefront).

  4. Under Configuration, click Configure Storefront API scopes. Select access tokens for read_products, read_product_listings, and read_checkout.

  5. Click Install App and securely copy the Storefront API access token.

3. Step 2: Initializing Your Next.js Project

Fire up your terminal and spin up a clean Next.js app with Tailwind CSS and TypeScript:

npx create-next-app@latest headless-shopify --typescript --tailwind --app
cd headless-shopify

Create a .env.local file in your root directory to securely house your credentials:

NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN="your-store-name.myshopify.com"
SHOPIFY_STOREFRONT_ACCESS_TOKEN="your_storefront_access_token_here"

4. Step 3: Creating the Shopify Fetch Client

Because Shopify uses a GraphQL API, you don’t need heavy GraphQL client libraries; a robust native fetch utility handling headers and errors is cleaner and pairs perfectly with Next.js caching algorithms.

Create a file at src/utils/shopify.ts:

const domain = process.env.NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN;
const token = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN;

export async function shopifyFetch<T>({ query, variables = {} }: { query: string; variables?: any }): Promise<{ status: number; body: T } | never> {
  try {
    const result = await fetch(`https://${domain}/api/2024-04/graphql.json`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-Storefront-Access-Token': token!,
      },
      body: JSON.stringify({ query, variables }),
      next: { revalidate: 3600 } // Incremental Static Regeneration (ISR) - Cache for 1 hour
    });

    const body = await result.json();

    if (body.errors) {
      throw new Error(body.errors[0].message);
    }

    return {
      status: result.status,
      body: body.data,
    };
  } catch (error) {
    console.error('Shopify Fetch Error:', error);
    throw new Error('Failed to fetch data from Shopify');
  }
}

5. Step 4: Fetching and Rendering Products

Let’s fetch products cleanly using a React Server Component (RSC). This queries Shopify during server-side compilation, resulting in zero layout shifts and instant page loading for users.

Create a simple product type and standard query structure in src/app/page.tsx:

import Image from 'next/image';
import { shopifyFetch } from '@/utils/shopify';

interface ProductNode {
  id: string;
  title: string;
  handle: string;
  featuredImage: { url: string; altText: string };
  priceRange: { minVariantPrice: { amount: string; currencyCode: string } };
}

interface ShopifyProductsResponse {
  products: { nodes: ProductNode[] };
}

const productsQuery = `
  query getProducts {
    products(first: 6) {
      nodes {
        id
        title
        handle
        featuredImage {
          url
          altText
        }
        priceRange {
          minVariantPrice {
            amount
            currencyCode
          }
        }
      }
    }
  }
`;

export default async function HomePage() {
  const res = await shopifyFetch<ShopifyProductsResponse>({ query: productsQuery });
  const products = res.body?.products.nodes || [];

  return (
    <main className="max-w-7xl mx-auto px-4 py-12">
      <h1 className="text-4xl font-extrabold tracking-tight mb-8">Featured Collection</h1>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
        {products.map((product) => (
          <div key={product.id} className="group relative border rounded-lg p-4 flex flex-col justify-between">
            <div className="aspect-square w-full overflow-hidden rounded-md bg-gray-200 group-hover:opacity-75">
              <Image
                src={product.featuredImage.url}
                alt={product.featuredImage.altText || product.title}
                width={500}
                height={500}
                className="h-full w-full object-cover object-center"
              />
            </div>
            <div className="mt-4 flex justify-between">
              <h3 className="text-sm font-medium text-gray-700">{product.title}</h3>
              <p className="text-sm font-semibold text-gray-900">
                ${parseFloat(product.priceRange.minVariantPrice.amount).toFixed(2)} {product.priceRange.minVariantPrice.currencyCode}
              </p>
            </div>
          </div>
        ))}
      </div>
    </main>
  );
}

Performance Tip: Ensure you whitelist the Shopify CDN domain (cdn.shopify.com) in your next.config.ts configuration under images.remotePatterns to utilize Next.js’s native image optimization algorithms seamlessly.

6. Step 5: Handling Cart and Checkout Flow

Because you are headless, mutations like creating a cart or adding items are performed directly against Shopify’s backend via client actions or React Server Actions.

Shopify API Mutation Purpose
cartCreate Creates a unique cart instance on Shopify and returns a tracking cartId.
cartLinesAdd Appends selected items and variants to the active cart instance.
cartLinesRemove Removes items from the checkout queue.

The Checkout Escape Hatch

Rather than spending months engineering a custom PCI-compliant checkout matrix, simply use the checkoutUrl returned from your cartCreate or cartLinesAdd responses.

When a user clicks “Proceed to Checkout”, redirect them directly to Shopify’s securely hosted storefront checkout page (e.g., window.location.href = cart.checkoutUrl). Once the payment transaction completes, Shopify automatically routes them back to your Next.js success page.

7. Performance Best Practices for Launch

  • Leverage Hybrid Rendering: Use Incremental Static Regeneration (ISR) via Next.js fetch configuration to cache products statically, but revalidate background data every few minutes to keep prices and inventory synchronized without slow runtime database fetches.

  • Prefetch Context: Wrap your site navigational links in Next.js <Link /> components to prefetch subsequent collection dynamic assets prior to click actions.

  • Zero CSS Runtime: Standardize your interface rendering with utility tools like Tailwind CSS v4 or CSS modules to guarantee that no heavy global JavaScript code styling fragments block initial browser processing cycles.

Coding Quote of the Day:

“Our task is to make our software unquestionably the best canvas on which to develop the best businesses of the future. We do this by keeping everyone cutting edge and bringing all the best tools to bear.”Tobias Lütke

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments… add one }

Leave a Comment