building-storefronts

作成者: medusajs

Medusaストアフロント向けのSDKファーストなフロントエンド統合で、React Queryパターンと重要なAPI呼び出しルールを備えています。すべてのAPIリクエストには常にMedusa JS SDKを使用し、通常のfetch()は使用しないでください。必要なヘッダー(ストアルート用の公開可能APIキー、管理ルート用の認証)が欠落するためです。SDKメソッドにはプレーンなJavaScriptオブジェクトを渡し、ボディパラメータにJSON.stringify()を使用しないでください。SDKが自動的にシリアライズを処理します。GETリクエストにはuseQueryを、POST/DELETEリクエストにはuseMutationを使用してください。

npx skills add https://github.com/medusajs/medusa-agent-skills --skill building-storefronts

Medusa Storefront Development

Frontend integration guide for building storefronts with Medusa. Covers SDK usage, React Query patterns, and calling custom API routes.

When to Apply

Load this skill for ANY storefront development task, including:

  • Calling custom Medusa API routes from the storefront
  • Integrating Medusa SDK in frontend applications
  • Using React Query for data fetching
  • Implementing mutations with optimistic updates
  • Error handling and cache invalidation

Also load building-with-medusa when: Building the backend API routes that the storefront calls

CRITICAL: Load Reference Files When Needed

The quick reference below is NOT sufficient for implementation. You MUST load the reference file before writing storefront integration code.

Load this reference when implementing storefront features:

  • Calling API routes? → MUST load references/frontend-integration.md first
  • Using SDK? → MUST load references/frontend-integration.md first
  • Implementing React Query? → MUST load references/frontend-integration.md first

Rule Categories by Priority

PriorityCategoryImpactPrefix
1SDK UsageCRITICALsdk-
2React Query PatternsHIGHquery-
3Data DisplayHIGH (includes CRITICAL price rule)display-
4Error HandlingMEDIUMerror-

Quick Reference

1. SDK Usage (CRITICAL)

  • sdk-always-use - ALWAYS use the Medusa JS SDK for ALL API requests - NEVER use regular fetch()
  • sdk-existing-methods - For built-in endpoints, use existing SDK methods (sdk.store.product.list(), sdk.admin.order.retrieve())
  • sdk-client-fetch - For custom API routes, use sdk.client.fetch()
  • sdk-required-headers - SDK automatically adds required headers (publishable API key for store, auth for admin) - regular fetch() missing these headers causes errors
  • sdk-no-json-stringify - NEVER use JSON.stringify() on body - SDK handles serialization automatically
  • sdk-plain-objects - Pass plain JavaScript objects to body, not strings
  • sdk-locate-first - Always locate where SDK is instantiated in the project before using it

2. React Query Patterns (HIGH)

  • query-use-query - Use useQuery for GET requests (data fetching)
  • query-use-mutation - Use useMutation for POST/DELETE requests (mutations)
  • query-invalidate - Invalidate queries in onSuccess to refresh data after mutations
  • query-keys-hierarchical - Structure query keys hierarchically for effective cache management
  • query-loading-states - Always handle isLoading, isPending, isError states

3. Data Display (HIGH)

  • display-price-format - CRITICAL: Prices from Medusa are stored as-is ($49.99 = 49.99, NOT in cents). Display them directly - NEVER divide by 100

4. Error Handling (MEDIUM)

  • error-on-error - Implement onError callback in mutations to handle failures
  • error-display - Show error messages to users when mutations fail
  • error-rollback - Use optimistic updates with rollback on error for better UX

Critical SDK Pattern

ALWAYS pass plain objects to the SDK - NEVER use JSON.stringify():

// ✅ CORRECT - Plain object
await sdk.client.fetch("/store/reviews", {
  method: "POST",
  body: {
    product_id: "prod_123",
    rating: 5,
  }
})

// ❌ WRONG - JSON.stringify breaks the request
await sdk.client.fetch("/store/reviews", {
  method: "POST",
  body: JSON.stringify({  // ❌ DON'T DO THIS!
    product_id: "prod_123",
    rating: 5,
  })
})

Why this matters:

  • The SDK handles JSON serialization automatically
  • Using JSON.stringify() will double-serialize and break the request
  • The server won't be able to parse the body

Common Mistakes Checklist

Before implementing, verify you're NOT doing these:

SDK Usage:

  • Using regular fetch() instead of the Medusa JS SDK (causes missing header errors)
  • Not using existing SDK methods for built-in endpoints (e.g., using sdk.client.fetch("/store/products") instead of sdk.store.product.list())
  • Using JSON.stringify() on the body parameter
  • Manually setting Content-Type headers (SDK adds them)
  • Hardcoding SDK import paths (locate in project first)
  • Not using sdk.client.fetch() for custom routes

React Query:

  • Not invalidating queries after mutations
  • Using flat query keys instead of hierarchical
  • Not handling loading and error states
  • Forgetting to disable buttons during mutations (isPending)

Data Display:

  • CRITICAL: Dividing prices by 100 when displaying (prices are stored as-is: $49.99 = 49.99, NOT in cents)

Error Handling:

  • Not implementing onError callbacks
  • Not showing error messages to users
  • Not handling network failures gracefully

How to Use

For detailed patterns and examples, load reference file:

references/frontend-integration.md - SDK usage, React Query patterns, API integration

The reference file contains:

  • Step-by-step SDK integration patterns
  • Complete React Query examples
  • Correct vs incorrect code examples
  • Query key best practices
  • Optimistic update patterns
  • Error handling strategies

When to Use MedusaDocs MCP Server

Use this skill for (PRIMARY SOURCE):

  • How to call custom API routes from storefront
  • SDK usage patterns (sdk.client.fetch)
  • React Query integration patterns
  • Common mistakes and anti-patterns

Use MedusaDocs MCP server for (SECONDARY SOURCE):

  • Built-in SDK methods (sdk.admin., sdk.store.)
  • Official Medusa SDK API reference
  • Framework-specific configuration options

Why skills come first:

  • Skills contain critical patterns like "don't use JSON.stringify" that MCP doesn't emphasize
  • Skills show correct vs incorrect patterns; MCP shows what's possible
  • Planning requires understanding patterns, not just API reference

Integration with Backend

⚠️ CRITICAL: ALWAYS use the Medusa JS SDK - NEVER use regular fetch()

When building features that span backend and frontend:

  1. Backend (building-with-medusa skill): Module → Workflow → API Route
  2. Storefront (this skill): SDK → React Query → UI Components
  3. Connection:
    • Built-in endpoints: Use existing SDK methods (sdk.store.product.list())
    • Custom API routes: Use sdk.client.fetch("/store/my-route")
    • NEVER use regular fetch() - missing publishable API key causes errors

Why the SDK is required:

  • Store routes need x-publishable-api-key header
  • Admin routes need Authorization and session headers
  • SDK handles all required headers automatically
  • Regular fetch() without headers → authentication/authorization errors

See building-with-medusa for backend API route patterns.

medusajsのその他のスキル

mcloud-variables
medusajs
mcloud variablesコマンドを実行して、Cloud環境の環境変数を一覧表示および取得します。環境変数を検査、読み取り、またはエクスポートする際に使用します。
official
building-admin-dashboard-customizations
medusajs
Medusa Adminダッシュボード向けのカスタムUI拡張機能。Admin SDKとMedusa UIコンポーネントを使用。管理UIの作業(計画、実装、調査)では、このスキルを最初に読み込むこと。MCPサーバーはAPIリファレンスのみを提供し、デザインパターンやデータ読み込み戦略は提供しない。重要:すべてのAPIリクエストにはMedusa JS SDKを使用すること(通常のfetchは不可)。表示クエリとモーダルクエリを分離し、ミューテーション後は表示データを無効化すること。既存ページにウィジェットを実装するか、カスタムUIルートを作成すること。...
official
learning-medusa
medusajs
対話形式で段階的に進むMedusa開発ブートキャンプ。ブランド機能を構築しながらアーキテクチャパターンを学びます。モジュール、ワークフロー、APIルート、モジュールリンク、ワークフローフック、管理UIのカスタマイズをカバーする3つのレッスン(合計2~3時間)を用意。各主要コンポーネント完了後のチェックポイント検証では、概念理解、コード品質、機能性を確認してから次に進みます。エラーを学習の機会として捉え、診断的な質問と根本原因の分析を通じて一緒にデバッグします。
official
db-migrate
medusajs
保留保留中のMedusaデータベースマイグレーションを実行し、結果を報告します。Bash経由でnpx medusa db:migrateを実行し、保留中のすべてのマイグレーションをMedusaデータベースに適用します。適用されたマイグレーションの数、発生したエラー、成功確認を含むマイグレーション結果を報告します。標準のnpm/npxセットアップを使用したMedusaプロジェクト向けに設計されています。
official
mcloud-environments
medusajs
mcloud environments コマンドを実行して、Cloud環境の一覧表示、取得、作成、削除、再デプロイ、またはビルドのトリガーを行います。環境のライフサイクル管理時に使用します。
official
db-generate
medusajs
単一のコマンドでMedusaモジュールのデータベースマイグレーションを生成します。npx medusa db:generate CLIコマンドをラップして、指定されたMedusaモジュールのマイグレーションファイルを作成します。モジュール名を引数として受け取り、マイグレーションファイルの場所、エラー、次のステップを報告します。生成後にnpx medusa db:migrateを実行してマイグレーションを適用することを自動的に提案します。
official
mcloud-deployments
medusajs
mcloud deploymentsコマンドを実行して、デプロイメントの一覧表示、デプロイメント詳細の取得、ビルドログの取得を行います。デプロイメントの一覧表示時やデプロイメントの確認時に使用します…
official
building-with-medusa
medusajs
Medusaバックエンドアーキテクチャ、ワークフロー、および重要な実装ルールに関する包括的なガイド。6つのルールカテゴリ(アーキテクチャ、型安全性、ビジネスロジックの配置、インポート、データアクセス、ファイル構成)をカバーし、具体的なアンチパターンと実施チェックを含む。厳格なレイヤー分離を強制:Module → Workflow → API Route → Frontend。すべてのミューテーションにワークフローが必要で、GET/POST/DELETEのHTTPメソッドのみ許可。重要なデータ処理ルールを含む:価格はそのまま保存...
official