Shopify Headless 前端对接教程

Shopify Headless Commerce 让你可以使用 Shopify 强大的后端处理商品、订单和支付,同时用自己的技术栈构建完全自定义的前端体验。通过 Storefront API(GraphQL),你可以在搬瓦工 VPS 上部署的前端应用中获取 Shopify 商店的所有数据。本文将详细介绍 Shopify Headless 架构的搭建方法。

一、Headless Commerce 架构概述

Shopify Headless 的核心是将前端展示层与 Shopify 后端服务完全解耦:

  • Shopify 后端:处理商品管理、库存、订单、支付、物流等业务逻辑。
  • Storefront API:提供 GraphQL 接口,暴露商品、购物车、结账等数据。
  • 自定义前端:使用 React/Next.js/Remix 等框架构建,部署在自己的服务器上。

二、获取 Storefront API 访问令牌

在 Shopify 管理后台中创建自定义应用:

  • 进入"设置 > 应用和销售渠道 > 开发应用"。
  • 点击"创建应用"并命名(如"Headless Frontend")。
  • 在"API 凭据"中配置 Storefront API 的访问范围。
  • 勾选必要的权限:读取产品、读取集合、读取购物车、写入购物车、读取客户等。
  • 安装应用并获取 Storefront API 访问令牌。

三、使用 Hydrogen 框架搭建前端

Hydrogen 是 Shopify 官方推出的 React 框架,基于 Remix,专为 Headless Commerce 设计。

3.1 创建 Hydrogen 项目

# 确保已安装 Node.js 20+
node -v

# 创建 Hydrogen 项目
npx @shopify/create-hydrogen@latest my-store
cd my-store

创建过程中,选择连接到你的 Shopify 商店或使用示例数据。

3.2 配置环境变量

# 创建 .env 文件
SESSION_SECRET="你的随机会话密钥"
PUBLIC_STOREFRONT_API_TOKEN="你的Storefront API令牌"
PUBLIC_STORE_DOMAIN="your-store.myshopify.com"
PRIVATE_STOREFRONT_API_TOKEN="你的私有API令牌"

3.3 本地开发

# 启动开发服务器
npm run dev

四、使用 Next.js 对接 Storefront API

如果你更熟悉 Next.js,可以直接使用 Storefront API 构建前端。

4.1 创建 Next.js 项目

npx create-next-app@latest shopify-store --typescript --app
cd shopify-store
npm install @shopify/storefront-api-client

4.2 创建 Shopify 客户端

创建 lib/shopify.ts

import { createStorefrontApiClient } from '@shopify/storefront-api-client';

const client = createStorefrontApiClient({
  storeDomain: process.env.SHOPIFY_STORE_DOMAIN!,
  apiVersion: '2024-10',
  publicAccessToken: process.env.SHOPIFY_STOREFRONT_TOKEN!,
});

export async function getProducts(first = 12) {
  const query = `{
    products(first: ${first}) {
      edges {
        node {
          id
          title
          handle
          description
          priceRange {
            minVariantPrice { amount currencyCode }
          }
          images(first: 1) {
            edges {
              node { url altText width height }
            }
          }
        }
      }
    }
  }`;
  const { data } = await client.request(query);
  return data.products.edges.map((e: any) => e.node);
}

export async function createCart() {
  const mutation = `mutation { cartCreate { cart { id checkoutUrl } } }`;
  const { data } = await client.request(mutation);
  return data.cartCreate.cart;
}

export async function addToCart(cartId: string, variantId: string, quantity: number) {
  const mutation = `mutation {
    cartLinesAdd(cartId: "${cartId}", lines: [{ merchandiseId: "${variantId}", quantity: ${quantity} }]) {
      cart { id totalQuantity checkoutUrl }
    }
  }`;
  const { data } = await client.request(mutation);
  return data.cartLinesAdd.cart;
}

五、部署到搬瓦工 VPS

5.1 构建和部署

# 构建项目
npm run build

# 安装 PM2 进程管理器
npm install -g pm2

# 使用 PM2 启动(Hydrogen/Remix)
pm2 start npm --name "shopify-store" -- run start

# 或 Next.js 项目
pm2 start npm --name "shopify-store" -- start

# 设置开机自启
pm2 save
pm2 startup

5.2 Nginx 反向代理

server {
    listen 80;
    listen 443 ssl http2;
    server_name store.example.com;

    ssl_certificate /etc/letsencrypt/live/store.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/store.example.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }

    # 静态资源缓存
    location /_next/static/ {
        proxy_pass http://127.0.0.1:3000;
        expires 365d;
        add_header Cache-Control "public, immutable";
    }
}
nginx -t && systemctl reload nginx

六、性能优化

6.1 ISR 增量静态再生

Next.js 的 ISR 功能可以让页面在首次请求时生成静态 HTML,后续请求直接返回缓存,同时在后台重新验证数据:

// app/products/[handle]/page.tsx
export const revalidate = 60; // 每 60 秒重新验证

export default async function ProductPage({ params }: { params: { handle: string } }) {
  const product = await getProductByHandle(params.handle);
  // 渲染商品页面
}

6.2 图片优化

Shopify 的 CDN 支持动态图片变换,可以按需请求不同尺寸的图片:

// 利用 Shopify CDN 的图片变换
function getResizedImage(url: string, width: number) {
  return url.replace(/\.([a-z]+)$/, `_${width}x.$1`);
}

七、Webhook 同步

配置 Shopify Webhook 确保前端数据与 Shopify 后端同步:

# 使用 Shopify CLI 注册 Webhook
shopify webhook create --topic products/update --address https://store.example.com/api/webhooks

创建 Webhook 处理端点,接收商品更新、库存变化等事件,触发前端重新生成相关页面。

总结

Shopify Headless 架构结合了 Shopify 成熟的电商后端和现代前端框架的灵活性。在搬瓦工 VPS 上部署自定义前端,可以完全控制用户体验和页面性能。Hydrogen 框架提供了开箱即用的 Shopify 集成,Next.js 则提供了更大的灵活性。如果你需要完全开源的电商后端,可以参考 MedusaSaleor。选购搬瓦工 VPS 请查看 全部方案,购买时使用优惠码 NODESEEK2026 可享受 6.77% 的折扣,通过 bwh81.net 进入官网购买。

关于本站

搬瓦工VPS中文网(bwgvps.com)是非官方中文信息站,整理搬瓦工的方案、优惠和教程。我们不销售主机,不提供技术服务。

新手必读
搬瓦工优惠码

NODESEEK2026(优惠 6.77%)

购买时填入即可抵扣。