Shopify開発用CLAUDE.mdテンプレート
CLAUDE.mdファイルは、効果的なClaude Code使用の基盤です。すべてのセッションの開始時にClaude Codeが読み込む永続的なコンテキストを提供し、すべてのプロンプトでプロジェクトの詳細を繰り返す必要をなくします。このガイドでは、Shopify開発プロジェクト向けの完全で実証済みのテンプレートを提供します。
CLAUDE.mdが重要な理由
CLAUDE.mdファイルがなければ、すべてのClaude Codeセッションはゼロから始まります。Claude Codeはプロジェクト構造を発見し、使用しているShopify APIバージョンを特定し、コーディング規約を学習し、アプリアーキテクチャを理解する必要があります -- すべてファイルの読み取りと質問によって。
よく書かれたCLAUDE.mdがあれば、Claude Codeはすべてのセッションで以下を知っている完全にブリーフィングされたチームメンバーとして開始します:
- 正確なShopify設定(APIバージョン、スコープ、アプリタイプ)
- コーディング標準とアーキテクチャ上の決定
- プロジェクトの実行、テスト、デプロイ方法
- 避けるべき間違い
良いCLAUDE.mdを書くのに約5分かかります。すべてのセッションでコンテキストを繰り返す手間を省き、1週間の開発で簡単に数時間のプロンプトエンジニアリングを節約できます。Claude Codeワークフローに対して最もレバレッジの高いことです。
完全テンプレート
このテンプレートをコピーし、括弧内のセクションをプロジェクトに合わせてカスタマイズし、プロジェクトルートにCLAUDE.mdとして保存してください。
# [Project Name]
## Overview
[One paragraph describing what this project does, who it's for, and its current status.]
Example: Remix-based Shopify app that enables merchants to create and manage
product bundles with automatic discount application. Currently in production
serving 200+ stores.
## Tech Stack
- **Framework**: Remix (Shopify app template)
- **Language**: TypeScript (strict mode)
- **Database**: Prisma ORM with PostgreSQL
- **UI**: Shopify Polaris v13 React components
- **Auth**: Shopify managed installation (app proxy + session tokens)
- **Testing**: Vitest (unit), Playwright (e2e)
- **Package Manager**: npm
- **Node Version**: 20 LTS
## Shopify Configuration
- **API Version**: 2025-01 (DO NOT use unstable or older versions)
- **App Type**: Embedded app (App Bridge 4)
- **Access Mode**: Online + Offline access tokens
- **Required Scopes**: read_products, write_products, read_orders, write_orders,
read_inventory, write_inventory, read_customers
- **Webhooks**: ORDERS_CREATE, PRODUCTS_UPDATE, APP_UNINSTALLED
- **Extensions**: Theme app extension (product-bundle-block), Checkout UI extension
## Project Structure
app/ routes/ # Remix routes (app..tsx = authenticated app pages) graphql/ # GraphQL query and mutation strings queries/ # Read operations mutations/ # Write operations models/ # Prisma model helpers (.server.ts) components/ # Shared React components (Polaris-based) utils/ # Utility functions webhooks/ # Webhook handlers jobs/ # Background job processors extensions/ product-bundle/ # Theme app extension checkout-upsell/ # Checkout UI extension prisma/ schema.prisma # Database schema migrations/ # Migration files tests/ unit/ # Vitest unit tests e2e/ # Playwright e2e tests fixtures/ # Test data and mocks
## Commands
```bash
# Development
npm run dev # Start Remix dev server
shopify app dev # Start with Shopify CLI (ngrok tunnel + auth)
npm run dev:extensions # Develop extensions locally
# Database
npx prisma db push # Apply schema changes (development)
npx prisma migrate dev # Create and apply migration
npx prisma studio # Open database GUI
# Testing
npm test # Run all Vitest tests
npm test -- --watch # Watch mode
npm run test:e2e # Run Playwright tests
npm run test:coverage # Generate coverage report
# Build & Deploy
npm run build # Production build
shopify app deploy # Deploy to Shopify
npm run lint # ESLint check
npm run typecheck # TypeScript type checking
Coding Standards
TypeScript
- Strict mode enabled, no
anytypes (useunknownand narrow) - Prefer
interfaceovertypefor object shapes - All functions must have explicit return types
- Use barrel exports (index.ts) for directories
React / Polaris
- Use Polaris components exclusively for UI -- no custom CSS for standard patterns (buttons, forms, cards, modals, data tables)
- Follow Polaris design patterns: Page > Layout > Card hierarchy
- Use
useAppBridge()for App Bridge interactions - Toast for success messages, Banner for persistent info/errors
- Loading states: use Polaris SkeletonPage/SkeletonBodyText
GraphQL
- All queries go in
app/graphql/queries/as exported template literals - All mutations go in
app/graphql/mutations/ - Always include
userErrors { field message }in mutations - Use cursor-based pagination (never offset-based)
- Prefix query names with operation:
GetProducts,CreateBundle - Always specify the exact fields needed (no over-fetching)
Remix Patterns
- Loaders return
json()responses with typed data - Actions handle form submissions with proper validation
- Use
authenticate.admin(request)at the start of every loader/action - Redirect to
/auth/loginon authentication failures - Use
defer()for non-critical data that can stream
Database
- All database operations in
*.server.tsfiles (never in components) - Use Prisma transactions for multi-table operations
- Always include
shopDomainin queries (multi-tenant isolation) - Soft delete with
deletedAttimestamp (never hard delete)
Webhooks
- Verify HMAC on all webhook endpoints
- Respond within 1 second (offload heavy work to background jobs)
- Implement idempotency using webhook ID tracking
- Log webhook receipt with shop domain, topic, and webhook ID
Error Handling
- Never swallow errors silently -- always log with context
- Use Remix CatchBoundary/ErrorBoundary for route-level errors
- GraphQL errors: check userErrors array first, then network errors
- External API calls: retry with exponential backoff (max 3 attempts)
Shopify-Specific Rules
API Usage
- ALWAYS use API version 2025-01
- Use the authenticated admin client from
authenticate.admin(request) - Never hardcode shop domains or access tokens
- Rate limiting: track GraphQL cost points, throttle at 80% capacity
- Use bulk operations for large data sets (1000+ items)
Polaris Guidelines
- Follow the Shopify App Design Guidelines for UX patterns
- Use the AppProvider at the app root with i18n configuration
- Navigation via Polaris NavMenu component
- Forms use Polaris FormLayout with inline validation
- Tables use IndexTable with bulk actions
App Bridge 4
- Do NOT use createApp() (that's App Bridge 3)
- Session tokens are available via the Remix authenticate helper
- Navigation: use standard links, App Bridge handles framing
- Resource pickers: use the app bridge resource picker API
- Title bar: set via Remix route meta or ui.title-bar component
Theme Extensions
- App blocks must be self-contained (own CSS/JS, no global pollution)
- Use CSS custom properties for theme-aware colors
- Liquid: always null-check objects before accessing properties
- Schema settings must have sensible defaults
- Test with multiple themes (Dawn, Refresh, and one vintage theme)
Testing Requirements
- All new features must have unit tests
- Critical paths (checkout, payments, inventory) need e2e tests
- Minimum 80% code coverage on models and utils
- Mock the Shopify admin client in tests (never call real API)
- Test webhooks with sample payloads from
tests/fixtures/webhooks/ - Run
npm testbefore committing (pre-commit hook enforces this)
Deployment Checklist
- All tests pass (
npm test && npm run test:e2e) - TypeScript compiles without errors (
npm run typecheck) - Lint passes (
npm run lint) - Database migrations are committed
- Environment variables are set in production
- Webhook URLs are registered for production domain
- Extensions are deployed (
shopify app deploy) - App review checklist completed (if submitting to app store)
Environment Variables
SHOPIFY_API_KEY- App API key (from Partner Dashboard)SHOPIFY_API_SECRET- App secret keyDATABASE_URL- PostgreSQL connection stringREDIS_URL- Redis connection for background jobsSENTRY_DSN- Error tracking (optional)
DO NOT commit .env files. Use .env.example as a template.
Known Issues
- [List any active bugs, workarounds, or tech debt items]
- Bulk operations occasionally timeout for shops with 50k+ products; current workaround is to chunk into batches of 10k
- The checkout extension doesn't render in Safari < 16 due to a known Shopify bug (tracked in their issue tracker)
Architecture Decisions
- We use offline access tokens for background jobs and online tokens for interactive sessions
- Bundle pricing is calculated server-side and applied via Shopify Functions (not manual discount codes) for checkout integrity
- Customer data is NOT stored locally; always fetch fresh from Shopify to maintain compliance with data protection requirements
## テンプレートのバリエーション
### テーマ専用プロジェクト
Shopifyテーマ(アプリではない)で作業している場合は、この簡略化されたバージョンを使用してください:
```markdown title="テーマプロジェクト用CLAUDE.md"
# [Theme Name]
## Overview
Custom Shopify theme based on Dawn 13.0 for [store name].
Online Store 2.0 compatible with full section-everywhere support.
## Tech Stack
- **Base Theme**: Dawn 13.0
- **Liquid**: Shopify Liquid (OS 2.0)
- **CSS**: Vanilla CSS with custom properties (no preprocessor)
- **JavaScript**: Vanilla ES6+ (no jQuery, no build step)
- **Icons**: Inline SVG from a central snippet
## Structure
assets/ # CSS, JS, and static files config/ # settings_schema.json and settings_data.json layout/ # theme.liquid and password.liquid locales/ # Translation files sections/ # All sections (reusable across templates) snippets/ # Reusable Liquid snippets templates/ # JSON templates (OS 2.0) customers/ # Account page templates
## Commands
```bash
shopify theme dev --store=mystore # Local development
shopify theme push # Push to theme
shopify theme pull # Pull remote changes
shopify theme check # Run Theme Check linter
Coding Standards
- Sections must have complete schemas with sensible defaults
- Always null-check Liquid objects:
{% if product.metafields.custom.x %} - Use
loading="lazy"on all images below the fold - CSS: mobile-first, use custom properties for colors/spacing
- JavaScript: no global scope pollution, use IIFE or modules
- Accessibility: all interactive elements must be keyboard navigable
- Performance: no render-blocking JS, minimize Liquid loops
Shopify-Specific Rules
- Use
{{ image | image_url: width: 800 }}(not img_url filter) - Preload critical images with
fetchpriority="high" - Use
{% render 'snippet' %}(not include) - Section schema: always include
"class"for wrapper styling - Test with Theme Check:
shopify theme check --fail-level error
Known Issues
- [List theme-specific bugs or browser compatibility notes]
### Hydrogen / ヘッドレスプロジェクト
```markdown title="Hydrogenプロジェクト用CLAUDE.md"
# [Project Name] - Hydrogen Storefront
## Overview
Headless Shopify storefront built with Hydrogen 2024.10 and Remix.
## Tech Stack
- **Framework**: Hydrogen (Remix-based)
- **Language**: TypeScript
- **Styling**: Tailwind CSS
- **API**: Shopify Storefront API (2025-01)
- **Hosting**: Oxygen (Shopify's edge hosting)
- **Cache**: Hydrogen's built-in caching strategies
## Shopify Configuration
- **API Version**: 2025-01 (Storefront API)
- **Storefront Access Token**: In environment variables
- **Customer Account API**: Enabled for account features
## Key Patterns
- Use Hydrogen's `<Await>` for deferred data loading
- Cache strategies: CacheLong for collections, CacheShort for cart
- SEO: Use Hydrogen's `getSeoMeta()` helper for all routes
- Analytics: Use Hydrogen's built-in Shopify analytics
- Use `<Money>` and `<Image>` components from @shopify/hydrogen
Claude CodeがCLAUDE.mdを使用する仕組み
Claude CodeがCLAUDE.mdをどのように処理するかを理解すると、より良いものが書けます:
- セッション開始時に読み込み: Claude Codeは最初のプロンプトの前にCLAUDE.mdを読み込みます
- 常にコンテキスト内: 内容はセッション全体を通じてコンテキストウィンドウに残ります
- 階層的マージ: グローバル(
~/.claude/CLAUDE.md)+ プロジェクトルート + サブディレクトリファイルがマージされます - トークンコスト: CLAUDE.mdはコンテキストトークンを消費するため、簡潔にしてください。500語のCLAUDE.mdは約700トークン -- コンテキストウィンドウのわずかな割合です
長すぎるCLAUDE.mdはすべてのインタラクションでコンテキストトークンを無駄にします。300-800語を目指してください。詳細なドキュメントは別のドキュメントに入れてください -- CLAUDE.mdはクイックリファレンスであり、小説ではありません。すべての言葉がその場所に値するべきです。
ベストプラクティスチェックリスト
CLAUDE.mdを書くまたはレビューする際にこのチェックリストを使用してください:
- APIバージョンが指定されている(最も重要な1行)
- 技術スタックが列挙されている(フレームワーク、言語、データベース、UI)
- すべての開発コマンドが文書化されている(dev、test、build、deploy)
- ファイル構造が概説されている(主要なディレクトリとその目的)
- コーディング標準が明示的(曖昧な「きれいなコードを書く」ではない)
- Shopify固有のルールが記述されている(スコープ、アプリタイプ、エクステンション)
- テスト期待値が明確(何をテストし、どうテストを実行するか)
- 既知の問題が文書化されている(Claude Codeが同じ壁にぶつかるのを防ぐ)
- 環境変数が列挙されている(実際の値は含まない)
- 機密データがない(APIキー、トークン、パスワードなし)
CLAUDE.mdはバージョン管理にコミットされる通常のファイルです。APIキー、アクセストークン、データベースパスワード、その他の機密資格情報を含めないでください。変数名(例: SHOPIFY_API_KEY)はリストアップしますが、値は含めません。
CLAUDE.mdの進化
CLAUDE.mdはプロジェクトとともに進化させるべきです。以下の場合に更新してください:
- Shopify APIバージョンをアップグレードした時
- 新しいエクステンションやWebhookを追加した時
- アーキテクチャパターンを変更した時
- 時間を無駄にする新しい「落とし穴」を発見した時
- 開発コマンドを追加または変更した時
- チームのコーディング標準が進化した時
古くなったCLAUDE.mdはCLAUDE.mdがないより悪い状態です。Claude Codeに自信を持って間違ったコンテキストを与えてしまうためです。最新に保ち、簡潔に保ち、プロジェクトの実際の状態に正直に保ってください。
次のステップ
CLAUDE.mdを配置したら、MCPの基礎を探索して、Model Context ProtocolがShopify開発のためにClaude Codeの機能をさらにどのように拡張できるかを学ぶ準備ができています。