Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Headless eCommerce with Shopify and Next JS

By Kokil Thapa | Last reviewed: September 2026

Headless eCommerce with Shopify and Next JS decouples Shopify’s order, inventory, and payment engine from the customer-facing site. You keep Shopify Admin for products, fulfilment, and reporting. You build the storefront in Next.js for layout freedom, Core Web Vitals, and editorial content. That split suits brands outgrowing Liquid themes but not ready to leave Shopify’s checkout and ops stack. If you sell across Nepal and abroad, the pattern also helps with multi-currency storefronts without fighting theme limits. This guide walks through architecture, API wiring, checkout choices, and production gotchas from real eCommerce builds.

What is headless eCommerce with Shopify and Next JS?

Traditional Shopify stores render HTML from Liquid templates on Shopify’s servers. A headless setup moves presentation to your Next.js app on Vercel, Netlify, or your own Node host. Shopify remains the system of record for SKUs, stock, discounts, and orders.

The contract between the two layers is GraphQL. The Shopify Storefront API exposes products, collections, cart lines, and checkout URLs. Your Next app never touches the Admin API from the browser. That boundary keeps private tokens off the client.

On client projects I have shipped with Shopify APIs, the headless split pays off when marketing wants a content-heavy homepage, lookbooks, or custom product configurators. It costs more than a theme. You own frontend deploys, caching, and SEO plumbing that Liquid gives you for free.

Headless Shopify + Next.js TopologyNext.js AppSSR / ISR / RSCStorefront APIGraphQL 2026-07Shopify CoreAdmin + CheckoutCustomer JourneyBrowse Next.js → Cart via API → Pay on Shopify CheckoutOrders sync back to Admin for fulfilment
Headless eCommerce with Shopify and Next JS: presentation in Next.js, commerce logic in Shopify

Monolith theme vs headless split

A Liquid theme keeps routing, templates, and checkout under one domain managed in Shopify. Headless adds a second deploy surface and API versioning discipline. You gain component reuse, modern JS tooling, and edge caching. You lose the simplicity of theme editor tweaks by non-developers.

CriteriaShopify Liquid themeHeadless Shopify + Next.js
Frontend stackLiquid, theme JSONNext.js 15+, React, TypeScript
Product dataServer-rendered in themeStorefront API GraphQL
CheckoutNative Online StoreHosted Checkout URL from cart
Time to MVPDays to weeksWeeks to months
Core Web VitalsTheme-dependentStrong when tuned
Best fitCatalog under ~500 SKUs, small teamEditorial brands, custom UX, multi-front

For a wider platform comparison, see the Magento vs Shopify vs WooCommerce breakdown. Headless Shopify often wins when ops already live in Shopify but the storefront must feel bespoke.

How do you connect Next JS to the Shopify Storefront API?

Start with a Custom App in Shopify Admin. Enable Storefront API access and copy the public Storefront access token plus your shop domain. Pin the API version to 2026-07 or newer so quarterly deprecations do not break queries mid-year.

Install dependencies on Node.js 26 LTS with npm 12:

npm create next-app@latest shop-headless --typescript --app --eslint
cd shop-headless
npm install @shopify/storefront-api-client graphql

Create a server-only client wrapper. Never expose the private Admin token in Next.js client bundles.

/* lib/shopify.ts */
import { createStorefrontApiClient } from '@shopify/storefront-api-client';

export const shopify = createStorefrontApiClient({
  storeDomain: process.env.SHOPIFY_STORE_DOMAIN!,
  apiVersion: '2026-07',
  publicAccessToken: process.env.SHOPIFY_STOREFRONT_TOKEN!,
});

export async function shopifyFetch<T>(query: string, variables?: Record<string, unknown>): Promise<T> {
  const { data, errors } = await shopify.request(query, { variables });
  if (errors) throw new Error(JSON.stringify(errors));
  return data as T;
}

Add environment variables in .env.local:

SHOPIFY_STORE_DOMAIN=your-store.myshopify.com
SHOPIFY_STOREFRONT_TOKEN=shpat_storefront_public_token_here

Fetch products with a typed GraphQL query

Use colocated GraphQL strings or codegen. Keep queries minimal to stay under cost limits.

const PRODUCT_QUERY = `
  query Product($handle: String!) {
    product(handle: $handle) {
      id
      title
      descriptionHtml
      featuredImage { url altText width height }
      variants(first: 20) {
        nodes { id title availableForSale price { amount currencyCode } }
      }
    }
  }
`;

/* app/products/[handle]/page.tsx */
export default async function ProductPage({ params }: { params: { handle: string } }) {
  const data = await shopifyFetch<{ product: Product }>(PRODUCT_QUERY, { handle: params.handle });
  if (!data.product) notFound();
  return <ProductDetail product={data.product} />;
}

Validate JSON responses during development with a JSON formatter when debugging GraphQL payloads. Small syntax errors in queries fail silently until runtime.

Next.js Data Fetching for ShopifyBuild TimegenerateStaticParamsRequestSSR fallbackRevalidateISR tag / timeEdge CDNCached HTMLRecommended PatternStatic product shells + ISR revalidate: 300On-demand revalidation via Admin webhooksCart and stock-sensitive UI stays client-side
ISR and static generation patterns for headless Shopify product routes in Next.js

Caching and revalidation

Product handles rarely change. Prices and inventory do. Use Incremental Static Regeneration with a sensible revalidate window, often 60–300 seconds for mid-size catalogs. Wire Shopify webhooks to a Next.js Route Handler that calls revalidatePath or revalidateTag when products update.

Read the dedicated Storefront API guide for pagination, metafields, and rate-limit headers. Metafields power size guides, specs, and SEO blocks your theme used to hard-code.

Should you use Shopify Hydrogen or a custom Next JS storefront?

Shopify Hydrogen is Shopify’s React framework built on Remix and Oxygen hosting. It ships with cart hooks, analytics bridges, and Storefront API helpers. A custom Next.js app gives you full App Router control, Vercel ecosystem plugins, and easier mixing of marketing CMS routes.

Choose Hydrogen when your team wants Shopify’s paved path and may deploy to Oxygen. Choose Next.js when SEO-led content, internationalized routing, or an existing Next monorepo already exists. The Hydrogen vs custom React storefront article compares trade-offs in more depth.

  • Hydrogen: Faster Shopify-native setup, opinionated data layer, Oxygen deploy.
  • Next.js: Flexible rendering modes, broad hosting choice, rich CMS integration.
  • Both: Still redirect to Shopify Checkout unless you qualify for custom checkout solutions.

I normally reach for Liquid or WooCommerce on budget-sensitive Nepal storefronts. When a brand already pays for Shopify Plus or needs editorial UX, headless Next.js is a rational step. See our international florist eCommerce work for multi-currency ops patterns that inform API design even on monolith stacks.

Hydrogen vs Next.js DecisionNew headless project?Team knows Next.jsPick Next.js App RouterShopify-first teamEvaluate HydrogenHeavy content SEONext.js + headless CMSFast Shopify MVPHydrogen starter
Framework choice for headless eCommerce with Shopify and Next JS versus Hydrogen

How do you handle cart, checkout, and payments in headless Shopify?

Modern Storefront Cart API replaces the deprecated Checkout API for buyer-facing flows. You create a cart, add line items by variant ID, attach buyer identity, then read checkoutUrl for payment.

Cart mutations from a Next.js Server Action or Route Handler

const CART_CREATE = `
  mutation CartCreate($lines: [CartLineInput!]!) {
    cartCreate(input: { lines: $lines }) {
      cart { id checkoutUrl totalQuantity }
      userErrors { field message }
    }
  }
`;

/* Called from AddToCart button via server action */
export async function addToCart(variantId: string, quantity: number) {
  const cartId = cookies().get('cartId')?.value;
  if (!cartId) {
    const created = await shopifyFetch(CART_CREATE, { lines: [{ merchandiseId: variantId, quantity }] });
    cookies().set('cartId', created.cartCreate.cart.id, { httpOnly: true, secure: true, sameSite: 'lax' });
    return created.cartCreate.cart.checkoutUrl;
  }
  /* cartLinesAdd mutation for existing cart */
}

Redirect the browser to checkoutUrl. Shopify hosts PCI-sensitive payment fields. Nepal merchants often need local payment gateway workarounds because native Shopify Payments availability differs by market. Confirm which gateways your Shopify plan exposes before promising eSewa or Khalti on checkout.

For cross-border stores, display NPR or AUD prices using Shopify Markets or manual currency formatting on the Next layer. Fulfilment logic still lives in Admin. Pair this with cross-border selling guidance for duties and shipping labels.

Headless Checkout SequenceAdd to CartNext.js UICart APIGraphQL mutatecheckoutUrlHosted redirectShopify PayPCI handledPost-PurchaseWebhooks: ORDERS_CREATE → ERP / email / analyticsOptional: custom thank-you page on your domainTrack KPIs from Admin and GA4
Cart mutation and hosted checkout flow in headless eCommerce with Shopify and Next JS

Webhooks and order sync

Register Admin API webhooks for orders/create, products/update, and inventory_levels/update. Point them to a secured Next.js Route Handler. Verify HMAC signatures before processing. This keeps ISR pages fresh and triggers internal alerts.

Deeper Admin automation belongs in a small API integration service if queues, retries, or ERP mapping grow beyond a single handler file. The Shopify Admin API guide covers scopes and token rotation.

How do you deploy, secure, and optimize a Next JS headless Shopify store?

Treat secrets as server-only. The Storefront public token can ship to the client for direct Storefront calls, but many teams proxy GraphQL through Route Handlers to hide query shapes and apply rate limiting. Never expose Admin API tokens in Next.js.

Production checklist

  1. Pin Shopify API version 2026-07 in env and CI.
  2. Enable HTTP security headers in next.config.ts.
  3. Map canonical URLs and structured data on product templates.
  4. Configure Shopify Markets for currency and language targets.
  5. Set up webhook HMAC verification and idempotent handlers.
  6. Monitor Storefront API throttle headers and backoff on 429 responses.
  7. Run Lighthouse on PDP and PLP routes after each release.

SEO does not come free in headless mode. You must render meta tags, Open Graph images, and Product schema yourself. Follow Shopify SEO practices for 2026 and the product page SEO guide. Pair technical markup with technical SEO audits before launch.

Performance work belongs in both layers. Optimize Next.js images with next/image and Shopify CDN URLs. Defer client JS on listing pages. Consider Core Web Vitals tuning if LCP slips above 2.5 seconds on mobile Nepal networks.

Scalability notes

GraphQL cost limits cap burst traffic. Cache product lists at the edge. Paginate collections instead of fetching entire catalogs. For flash sales, prewarm ISR paths and shorten revalidate windows temporarily.

Read scalability patterns for Nepali eCommerce even if you host abroad. Latency to Shopify’s API regions still affects add-to-cart responsiveness.

Analytics and ops

Fire GA4 purchase events from the thank-you route or Shopify pixel where possible. Align metrics with eCommerce KPIs you should track. Ops staff keep using Shopify Admin for refunds, partial fulfils, and customer service.

If you migrate from WooCommerce, plan SKU and redirect mapping first. The Shopify migration guide reduces downtime risk. Custom Laravel carts like Quick And Easy Nepalese Grocery follow different headless patterns but share the same checkout trust requirements.

Common mistakes

  • Calling Admin API from client components and leaking tokens.
  • Ignoring API version sunsets — schedule quarterly review.
  • Building a custom checkout without understanding PCI scope.
  • Skipping redirect rules when replacing an old Liquid domain structure.
  • Over-fetching GraphQL fields and hitting cost ceilings during crawls.

Official references: Next.js App Router documentation for rendering modes, and Shopify Storefront API reference for cart and product objects.

Key Takeaways

  • Headless eCommerce with Shopify and Next JS separates storefront UX from Shopify’s commerce core via the Storefront API.
  • Use Cart API mutations server-side, then redirect buyers to Shopify Checkout for PCI-safe payments.
  • Combine ISR, webhooks, and tagged revalidation so prices and stock stay accurate without sacrificing speed.
  • Choose Next.js over Hydrogen when SEO content, CMS fusion, or an existing Next stack drives the decision.
  • Pin API version 2026-07+, guard tokens, and plan SEO schema manually — headless removes Liquid helpers.
  • Budget for longer build time versus a theme; ops still live in Shopify Admin after launch.

People Also Ask

Is Shopify headless free?

Shopify plan fees still apply. You also pay for Next.js hosting, developer time, and any CMS. The Storefront API itself does not add a separate Shopify line item, but operational complexity rises compared with a standard theme.

Can you use Next.js with Shopify without Plus?

Yes. Standard Shopify plans expose the Storefront API and hosted checkout redirect. Shopify Plus adds higher API limits, custom checkout extensibility, and B2B features. Most mid-market headless MVPs launch on standard plans first.

Does headless Shopify hurt SEO?

Not if you implement SSR or ISR with correct metadata, canonical tags, and Product schema. Headless can improve Core Web Vitals when tuned. It hurts SEO when teams ship client-only rendering on product routes or omit redirects after replatforming.

What is the alternative to Next.js for Shopify headless?

Shopify Hydrogen, Nuxt, Astro, or mobile apps consuming the same Storefront API. Some teams pair a Laravel or WordPress marketing site with a Shopify buy button. Pick the framework your team can maintain for three years, not only at launch.

Build headless Shopify the right way

Headless eCommerce with Shopify and Next JS trades theme simplicity for frontend control. Map your catalog API, cart flow, and checkout redirect before writing UI components. Plan SEO, webhooks, and Nepal payment realities early so you do not rebuild at launch.

If you want a storefront audit, migration plan, or full build, contact us or explore eCommerce development services. For related reading, browse search UX patterns, cart abandonment fixes, and starting eCommerce in Nepal.

Frequently Asked Questions

Next.js renders your storefront while Shopify handles products, inventory, cart state, and hosted checkout via the Storefront API. Presentation moves off Shopify servers; commerce logic stays in Admin.

No. Shopify plan fees still apply, plus Next.js hosting and developer time. The Storefront API has no extra Shopify charge, but complexity exceeds a standard Liquid theme.

Yes. Standard Shopify plans expose the Storefront API and hosted checkout redirect. Plus adds higher API limits, custom checkout extensibility, and B2B features.

Create a Custom App in Shopify Admin, enable Storefront API access, and copy your public Storefront token plus shop domain. Pin API version to 2026-07 or newer. On Node.js 26 LTS with npm 12, scaffold a Next.js app and install @shopify/storefront-api-client. Build a server-only client wrapper in lib/shopify.ts that never exposes Admin tokens to the browser. Add SHOPIFY_STORE_DOMAIN and SHOPIFY_STOREFRONT_TOKEN to .env.local. Fetch catalog data with typed GraphQL queries from App Router server components.

Hydrogen is Shopify's React framework on Remix and Oxygen, shipping cart hooks and Storefront API helpers for a paved path. Custom Next.js gives full App Router control, Vercel ecosystem plugins, and easier CMS route mixing. Choose Hydrogen when your team wants Shopify-native tooling and may deploy to Oxygen. Choose Next.js when SEO-led content, internationalized routing, or an existing Next monorepo drives the decision. Both still redirect to Shopify Checkout unless you qualify for custom checkout solutions.

Use the modern Storefront Cart API instead of the deprecated Checkout API. Create a cart, add line items by variant ID via server actions or route handlers, store the cart ID in an httpOnly cookie, then read checkoutUrl and redirect the browser. Shopify hosts PCI-sensitive payment fields on hosted checkout. Cart mutations should run server-side, not from client components. For Nepal merchants, confirm which payment gateways your Shopify plan exposes before promising eSewa or Khalti, as native Shopify Payments availability differs by market.

Not when you implement SSR or ISR with correct metadata, canonical tags, and Product schema. Headless can improve Core Web Vitals when tuned with next/image and deferred client JS. It hurts SEO when teams ship client-only rendering on product routes or omit redirects after replatforming from a Liquid domain structure. SEO does not come free in headless mode—you must render meta tags, Open Graph images, and structured data yourself that Liquid themes provide automatically.

Product handles rarely change, but prices and inventory do. Use Incremental Static Regeneration with a revalidate window of 60 to 300 seconds for mid-size catalogs. Register Admin API webhooks for products/update and inventory_levels/update, pointing to a secured Next.js Route Handler that verifies HMAC signatures and calls revalidatePath or revalidateTag. This keeps ISR pages fresh without sacrificing edge-cached speed. For flash sales, prewarm ISR paths and shorten revalidate windows temporarily.

The biggest mistake is calling the Admin API from client components and leaking private tokens into Next.js bundles. Keep Admin tokens server-only; the Storefront public token can reach the client, though many teams proxy GraphQL through Route Handlers to hide query shapes and apply rate limiting. Enable webhook HMAC verification before processing orders/create or inventory events. Pin API version 2026-07 in environment and CI so quarterly deprecations do not break production queries mid-year.

A Liquid theme typically reaches MVP in days to weeks because routing, templates, and checkout live under one Shopify-managed domain. Headless Shopify plus Next.js usually needs weeks to months because you own frontend deploys, caching, SEO plumbing, and API versioning. You gain component reuse and modern JS tooling but lose theme editor tweaks by non-developers. Budget accordingly if marketing wants editorial homepages or custom product configurators a standard theme cannot deliver.

Shopify Hydrogen, Nuxt, Astro, or mobile apps consuming the same Storefront API all work. Some teams pair a Laravel or WordPress marketing site with a Shopify buy button for a lighter split. Pick the framework your team can maintain for three years, not only at launch. Hydrogen offers faster Shopify-native setup; Next.js offers flexible rendering modes and broad hosting choice on Vercel, Netlify, or your own Node host.

Pin Shopify API version 2026-07 in env and CI. Enable HTTP security headers in next.config.ts. Map canonical URLs and Product schema on templates. Configure Shopify Markets for currency and language targets. Monitor Storefront API throttle headers and backoff on 429 responses. Optimize images with next/image and Shopify CDN URLs. Run Lighthouse on product listing and detail routes after each release. Cache product lists at the edge and paginate collections instead of fetching entire catalogs to stay under GraphQL cost limits.

Calling the Admin API from client components and leaking tokens tops the list. Teams also ignore API version sunsets without quarterly review, build custom checkout without understanding PCI scope, skip redirect rules when replacing an old Liquid domain structure, and over-fetch GraphQL fields until cost ceilings break during crawls. Small syntax errors in GraphQL queries fail silently until runtime, so validate JSON responses during development. Plan SKU and redirect mapping before migrating from WooCommerce or another platform.

Headless wins when ops already live in Shopify but the storefront must feel bespoke—editorial brands, custom UX, or multi-front deployments. Liquid suits catalogs under roughly 500 SKUs with small teams wanting quick MVP and theme editor access for non-developers. The split also helps multi-currency storefronts across Nepal and abroad without fighting theme limits. If you sell on a budget-sensitive Nepal storefront and do not need editorial UX, a Liquid theme or WooCommerce is often the practical starting point.

Register Admin API webhooks for orders/create, products/update, and inventory_levels/update in Shopify Admin. Point them to a secured Next.js Route Handler that verifies HMAC signatures before processing any payload. Use these events to trigger revalidatePath or revalidateTag so ISR product pages reflect current stock and pricing. Keep handlers idempotent because Shopify may retry deliveries. If ERP mapping, queues, or retries grow beyond a single handler file, move deeper Admin automation into a dedicated API integration service.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: