Skip to main content

Shopify 開発のためのプロンプトエンジニアリング

フラストレーションの溜まる Claude Code セッションと生産的なセッションの違いは、プロンプトの書き方に左右されることが多いです。このガイドでは、Shopify 開発に特化した実戦で検証済みのプロンプトテンプレートとテクニックを提供します。

効果的な Shopify プロンプトの原則

テンプレートに入る前に、プロンプトを効果的にする4つの原則を理解しましょう:

  1. Shopify のコンテキストを具体的に示す:API バージョン、アプリタイプ(Remix、カスタム)、テーマバージョン(OS 2.0)、関連する Shopify の概念を記述する
  2. 制約条件を含める:何をするかと同様に、何をしないかも指定する——「Polaris を使用し、カスタム UI コンポーネントは使わない」
  3. 期待する出力の例を提供する:フォーマットが重要な場合、求めるもののスニペットを示す
  4. 「なぜ」を述べる:Claude Code はビジネスロジックを理解することで、より良い判断を下せる
CLAUDE.md の利点

CLAUDE.md ファイルにプロジェクトのコンテキストが既に含まれている場合、これらのプロンプトの多くはより短くなります。CLAUDE.md に「API version: 2025-01」や「UI: Polaris」と記載されていれば、すべてのプロンプトで繰り返す必要はありません。以下のテンプレートは単独使用のために完全なコンテキストを含んでいます——CLAUDE.md が既にカバーしている内容に基づいて省略してください。

すぐに使えるプロンプトテンプレート

App Extensions

1. Theme App Extension を構築する

Prompt: Theme App Extension
Build a Shopify theme app extension that displays product reviews
as a star rating and review list on product pages.

Requirements:
- App block with schema settings for: reviews per page (default 5),
show star rating (boolean), color scheme selector
- Liquid template that renders review data from metafields
- CSS that matches common Shopify theme styles
- JavaScript for "Load More" pagination
- Accessible: screen reader support for star ratings

Put the extension in extensions/product-reviews/.
Use the theme app extension file structure.

2. Checkout UI Extension を構築する

Prompt: Checkout Extension
Build a Shopify checkout UI extension (checkout_ui) that shows
a free shipping progress bar.

Requirements:
- React component using @shopify/ui-extensions-react/checkout
- Show current cart total vs free shipping threshold ($75)
- Progress bar with percentage filled
- Dynamic messaging: "$X away from free shipping!" or "You qualify!"
- Use the Banner and ProgressBar checkout components
- Extension target: purchase.checkout.block.render
- Include shopify.extension.toml configuration

3. Admin Action Extension を構築する

Prompt: Admin Action Extension
Build a Shopify admin action extension that lets merchants bulk-tag
products based on inventory level.

Requirements:
- Admin action that appears on the Products index page
- React UI with Polaris components (Modal, TextField, Select)
- Options: tag name input, threshold selector (< 10, < 50, < 100)
- GraphQL mutation to add tags to matching products
- Loading states and success/error feedback
- Handle pagination for stores with 1000+ products

GraphQL クエリと Mutation

4. ページネーション付きクエリを書く

Prompt: Paginated GraphQL Query
Write a GraphQL query to fetch all orders from the last 30 days
with their line items, fulfillment status, and customer email.

Requirements:
- Cursor-based pagination with first: 50
- Filter by created_at >= 30 days ago using query parameter
- Include financial_status and fulfillment_status
- Include line items with product title, variant title, quantity, price
- Include customer email and order name
- Write the TypeScript types for the response shape
- API version 2025-01

5. 複雑な Mutation を書く

Prompt: GraphQL Mutation
Write a GraphQL mutation to create a product with variants and
set metafields in a single API call.

Requirements:
- ProductCreate mutation with product title, description, vendor
- Include 3 variants with prices and inventory quantities
- Set a custom metafield (namespace: "custom", key: "material", type: "single_line_text_field")
- Include media (image URLs) attachment
- Handle userErrors in the response
- Write the TypeScript variables type
- Wrap it in a reusable async function that takes the admin client

6. Bulk Operation クエリを書く

Prompt: Bulk Operation
Write a Shopify bulk operation query to export all products with
their variant inventory levels across all locations.

Requirements:
- Use bulkOperationRunQuery mutation
- Include the JSONL polling logic to check completion
- Parse the JSONL response into structured data
- Handle the bulk operation lifecycle: CREATED -> RUNNING -> COMPLETED
- Include error handling for FAILED status
- Write this as a complete utility module I can import

Liquid とテーマ開発

7. Liquid Section を作成する

Prompt: Liquid Section
Create a Liquid section called "collection-filter-grid" that displays
a filterable product grid.

Requirements:
- Collection picker in schema settings
- Filter by product type, vendor, and price range
- CSS Grid layout: 4 columns desktop, 2 tablet, 1 mobile
- Lazy-loaded product images with aspect ratio preservation
- Quick-add-to-cart button on hover
- Section schema with settings for: columns per row,
show vendor, show price, enable quick add
- Use section blocks for promotional cards between products
- No external JavaScript dependencies

8. Mega Menu Snippet を作成する

Prompt: Mega Menu
Create a Liquid snippet for a mega menu navigation that supports:

Requirements:
- 3 levels of navigation from linklists
- Desktop: full-width dropdown with columns
- Mobile: accordion-style expand/collapse
- Featured image area per top-level menu item (using metafields)
- Keyboard navigation (arrow keys, escape to close)
- ARIA roles and labels for accessibility
- Smooth CSS transitions (no jQuery)
- works with the "header" section's schema to configure menu handle

9. ダイナミックカートドロワーを構築する

Prompt: Cart Drawer
Create a cart drawer (slide-out panel) using Liquid, CSS, and
vanilla JavaScript.

Requirements:
- Opens from right side on add-to-cart
- Real-time updates via Cart AJAX API (/cart.js, /cart/add.js)
- Line item quantity adjustment with +/- buttons
- Line item removal with undo option (3 second window)
- Free shipping progress bar
- Cart note textarea
- Upsell product recommendation (last item in a specific collection)
- Accessible: focus trap when open, escape to close
- CSS animations for open/close (transform, not left/right)

Shopify Functions

10. Rust でディスカウント Function を生成する

Prompt: Discount Function (Rust)
Generate a Shopify Function in Rust that implements a "Buy X Get Y"
discount.

Requirements:
- Function API: product_discounts
- Input: cart lines, discount configuration from metafields
- Logic: if cart contains product X (by tag), apply percentage
discount to product Y (by tag)
- Handle edge cases: multiple qualifying items, quantity limits
- Include the shopify.extension.toml configuration
- Include run.graphql input query
- Write the Cargo.toml with correct Shopify Function dependencies
- Include unit tests for the discount logic

11. Delivery Customization Function を生成する

Prompt: Delivery Function
Generate a Shopify Function for delivery customization that hides
express shipping for orders containing oversized items.

Requirements:
- Function API: delivery_customization
- Check line items for a "oversized" tag
- If any oversized item exists, rename and reorder delivery options
to remove/hide express options
- Include input query, Rust implementation, and tests
- Handle the case where all items are oversized vs mixed carts

Webhook ハンドラー

12. Webhook ハンドラーをデバッグする

Prompt: Debug Webhook
Debug this webhook handler for orders/create that's returning 500
errors intermittently:

[paste your webhook handler code here]

The error logs show: "Cannot read property 'id' of undefined"
on line 47. This happens on roughly 20% of webhook deliveries.

Check for:
- Payload structure differences between API versions
- Missing null checks on nested objects
- Race conditions with database writes
- Whether the 5-second timeout could be causing issues

13. リトライロジック付き Webhook ハンドラーを作成する

Prompt: Webhook with Retries
Create a webhook handler for PRODUCTS_UPDATE that syncs product
data to an external inventory system.

Requirements:
- HMAC verification using Shopify webhook secret
- Idempotency: track processed webhook IDs to skip duplicates
- Respond to Shopify within 1 second (use background job for heavy work)
- Retry external API calls with exponential backoff (3 attempts)
- Dead letter queue for permanently failed syncs
- Structured logging with webhook ID, product ID, and timing
- Use the Remix webhook handling pattern

テスト

14. 包括的なテストスイートを生成する

Prompt: Test Suite
Write a complete Vitest test suite for the product bundle
creation flow.

Files to test:
- app/routes/app.bundles.new.tsx (form submission)
- app/models/bundle.server.ts (database operations)
- app/graphql/mutations/bundleCreate.ts (GraphQL mutation)

Cover:
- Happy path: create bundle with 3 products
- Validation: empty title, too few products, duplicate products
- Auth: redirect when session expires
- Error: GraphQL errors, database constraint violations
- Edge: Unicode titles, maximum products (20), zero-price variants

Mock the Shopify admin GraphQL client and Prisma.

15. Playwright E2E テストを生成する

Prompt: E2E Tests
Write Playwright end-to-end tests for our Shopify theme's
product page.

Test scenarios:
- Product page loads with correct title and price
- Variant selector changes price and image
- Add to cart with quantity > 1
- Cart drawer opens after add to cart
- Inventory limit prevents over-ordering
- Product with no variants shows simplified UI
- Mobile: variant selector works on touch devices
- Accessibility: page passes axe-core audit

Use Page Object pattern. Base URL: http://localhost:9292

コード生成とリファクタリング

16. Polaris CRUD インターフェースを生成する

Prompt: Polaris CRUD
Create a complete CRUD interface for managing shipping zones using
Shopify Polaris components.

Requirements:
- Index page with ResourceList showing all zones
- Filters: active/inactive, country
- Create/Edit form with: zone name, countries (multi-select),
rate conditions (price-based and weight-based)
- Delete confirmation modal
- Toast notifications for success/error
- Loading skeletons during data fetches
- Empty state with illustration
- Use Remix loader/action pattern for data flow

17. App Bridge 4 へリファクタリングする

Prompt: App Bridge Migration
Refactor our embedded app from App Bridge 3 to App Bridge 4.

Current code uses:
- createApp() initialization
- getSessionToken() for auth
- Redirect.create() for navigation
- ResourcePicker.create() for product selection

Migrate to App Bridge 4 patterns:
- Direct token access from shopify.idToken()
- URL-based navigation via app bridge
- New resource picker API
- Update all import paths
- Remove the app bridge provider wrapper if using Remix template

18. API レート制限ミドルウェアを生成する

Prompt: Rate Limiting
Create rate limiting middleware for our Shopify app's API calls.

Requirements:
- Track Shopify's GraphQL cost points (2000 point bucket)
- Parse X-Shopify-Shop-Api-Call-Limit headers for REST
- Implement leaky bucket algorithm for request throttling
- Queue system for bulk operations
- Per-shop rate tracking (multi-tenant)
- Logging when approaching limits (> 80% consumed)
- Automatic retry with backoff when rate limited
- TypeScript, works with our Remix app structure

19. Shopify App OAuth フローを生成する

Prompt: Custom OAuth
Implement a complete Shopify OAuth flow for a custom (non-Remix
template) Node.js app.

Requirements:
- Install endpoint: generate auth URL with required scopes
- Callback endpoint: exchange code for access token
- HMAC validation on the callback
- Store tokens securely (encrypted at rest in PostgreSQL)
- Handle token refresh for online access mode
- Verify installed shops on subsequent requests
- Handle app uninstall webhook to clean up data
- Include CSRF protection with state parameter

20. マルチロケーション在庫同期を作成する

Prompt: Inventory Sync
Build an inventory synchronization system that keeps Shopify
inventory in sync with an external warehouse API.

Requirements:
- Scheduled job (runs every 15 minutes)
- Fetch inventory levels from external API (REST, paginated)
- Compare with Shopify inventory via GraphQL bulk query
- Calculate deltas and apply adjustments
- Use inventoryAdjustQuantities mutation (not deprecated individual)
- Handle multiple locations (map external warehouse IDs to Shopify location IDs)
- Conflict resolution: external system is source of truth
- Detailed sync log with item-level results
- Alert on sync failures via webhook to Slack

ボーナスプロンプト

21. Metafield 定義を生成する

Prompt: Metafield Setup
Create a migration script that sets up all required metafield
definitions for our product customization app.

Metafields needed:
- products: custom.material (single_line_text_field)
- products: custom.care_instructions (multi_line_text_field)
- products: custom.size_chart (json, with validation)
- variants: custom.weight_grams (number_integer)
- orders: custom.gift_message (single_line_text_field)

Use the metafieldDefinitionCreate mutation. Make it idempotent
(skip if definition already exists). Include validation rules.

22. Hydrogen でカスタムストアフロントを構築する

Prompt: Hydrogen Component
Create a Hydrogen (Remix + Storefront API) product page component
that includes:

- Product image gallery with zoom
- Variant selector with option swatches
- Price display with compare-at-price
- Dynamic add-to-cart with cart optimization
- SEO meta tags and structured data (JSON-LD)
- Streaming with Suspense boundaries for deferred data
- Use Hydrogen's built-in components where available

反復プロンプトテクニック

単一のプロンプトは強力ですが、反復プロンプトこそが複雑な Shopify プロジェクトで Claude Code が真価を発揮するところです。

構築-テスト-改善ループ

Step 1: Build
> Create a webhook handler for ORDERS_CREATE that calculates
loyalty points and stores them in customer metafields.

# Claude Code writes the initial implementation

> Step 2: Test
> Write tests for this handler covering the edge cases we discussed.

# Claude Code writes tests, some may fail

> Step 3: Refine
> The test for zero-dollar orders is failing. The handler should
award 0 points but still update the metafield. Fix the handler.

# Claude Code fixes the specific issue

プログレッシブエンハンスメント

シンプルなところから始めて、段階的に複雑さを重ねていきます:

Progressive prompting
> Create a basic product recommendation section that shows
4 related products from the same collection.

# Get the basics working first

> Now enhance it: add a "You might also like" heading, lazy-load
the images, and add quick-add-to-cart buttons.

# Layer on features

> Now make it personalized: use the customer's order history
(via Storefront API) to weight recommendations. Fall back to
collection-based if no history exists.

# Add sophisticated logic
反復が一括より優れている理由

すべての機能を一度に要求する巨大なプロンプトは、何か問題が起きたときにデバッグしにくいコードを生成しがちです。反復的に構築することで、次のレイヤーを追加する前に各レイヤーが正しく動作していることを確認できます。また、Claude Code のレスポンスを集中的で管理しやすいものに保てます。

マルチファイルプロジェクトのプロンプト

タスクが複数のファイルにまたがる場合は、スコープを明示してください:

Multi-file prompt
> This change needs to touch multiple files:
1. Add a new GraphQL query in app/graphql/queries/loyaltyPoints.ts
2. Create a new route at app/routes/app.loyalty.tsx
3. Add a Prisma model for LoyaltyTransaction in prisma/schema.prisma
4. Create a background job in app/jobs/calculatePoints.server.ts
5. Add the webhook handler in app/webhooks/orders-create.ts
6. Write tests for the calculation logic

Start with the Prisma model, then the GraphQL query, then build
up from there. Run prisma db push after creating the model.

セッション管理コマンド

/compact——コンテキストを回収する

しばらく作業してコンテキストが大きくなったときに /compact を使います:

> /compact
# Summarizes the conversation, freeing up context space
# Your CLAUDE.md context is preserved
# Continue working on the same task with full project awareness

使うタイミング:機能を完成させた後、同じセッションで次の機能を始める前。

/clear——最初からやり直す

まったく別のタスクに切り替えるときに /clear を使います:

> /clear
# Wipes all conversation context
# CLAUDE.md is re-read on next prompt
# Perfect for switching from theme work to app work

使うタイミング:関連のないタスク間を切り替えるとき(例:テーマ開発からアプリのバックエンド作業へ)。

/cost——コストを監視する

> /cost
# Shows tokens consumed and estimated cost
# Use this periodically during long sessions

使うタイミング:アクティブな開発中は30〜60分ごと、または大きなタスクを開始する前。

コンテキストウィンドウの制限

Claude Code のレスポンスが一貫性を失い始めたり、以前の判断を「忘れ」たりする場合、コンテキストウィンドウがいっぱいになっている可能性があります。すぐに /compact を使ってください。それでも改善しない場合は、/clear を使い、焦点を絞ったプロンプトと適切な CLAUDE.md コンテキストで再開してください。

避けるべきアンチパターン

アンチパターン失敗する理由より良いアプローチ
「アプリ全体を作って」曖昧すぎて大きすぎる機能レベルのプロンプトに分割する
「もっと良くして」具体的な方向性がない「ページネーションを追加してパフォーマンスを改善して」
「バグを直して」(コンテキストなし)Claude Code にはエラーの詳細が必要エラーメッセージと関連コードを貼り付ける
毎回のプロンプトでコンテキストを繰り返すトークンの無駄安定したコンテキストは CLAUDE.md に入れる
/compact を使わないコンテキストオーバーフロー機能完成ごとにコンパクト化する

次のステップ

これらのプロンプトテンプレートを手に入れたら、CLAUDE.md テンプレートに進んで、Shopify 開発に最適化された完全なコピー&ペースト対応のプロジェクト設定ファイルを入手してください。