Skip to main content

Prompt Engineering for Shopify Development

The difference between a frustrating Claude Code session and a productive one often comes down to how you write your prompts. This guide provides battle-tested prompt templates and techniques specifically tuned for Shopify development.

Principles of Effective Shopify Prompts

Before diving into templates, understand the four principles that make prompts effective:

  1. Be specific about Shopify context: Mention API versions, app type (Remix, custom), theme version (OS 2.0), and relevant Shopify concepts
  2. Include constraints: Specify what not to do as much as what to do -- "Use Polaris, not custom UI components"
  3. Provide examples of expected output: Show a snippet of what you want when the format matters
  4. State the "why": Claude Code makes better decisions when it understands the business logic
The CLAUDE.md Advantage

Many of these prompts become shorter when your CLAUDE.md file already contains project context. If your CLAUDE.md specifies "API version: 2025-01" and "UI: Polaris," you don't need to repeat those in every prompt. The templates below include full context for standalone use -- trim them based on what your CLAUDE.md already covers.

Ready-to-Use Prompt Templates

App Extensions

1. Build a 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. Build a 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. Build an 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 Queries and Mutations

4. Write a Paginated Query

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. Write a Complex 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. Write a Bulk Operation Query

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 and Theme Development

7. Create a 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. Create a 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. Build a Dynamic Cart Drawer

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. Generate a Discount Function in Rust

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. Generate a 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 Handlers

12. Debug a Webhook Handler

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. Create a Webhook Handler with Retry Logic

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

Testing

14. Generate a Comprehensive Test Suite

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. Generate Playwright E2E Tests

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

Code Generation and Refactoring

16. Generate a Polaris CRUD Interface

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. Refactor to 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. Generate API Rate Limiting Middleware

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. Generate a Shopify App OAuth Flow

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. Create a Multi-Location Inventory Sync

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

Bonus Prompts

21. Generate Metafield Definitions

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. Build a Custom Storefront with 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

Iterative Prompting Techniques

Single prompts are powerful, but iterative prompting is where Claude Code truly shines for complex Shopify projects.

The Build-Test-Refine Loop

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 Enhancement

Start simple and layer on complexity:

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
Why Iterative Beats Monolithic

A single massive prompt asking for all features at once often produces code that's harder to debug when something goes wrong. Building iteratively means each layer works before the next is added. It also keeps Claude Code's responses focused and manageable.

Multi-File Project Prompting

When your task spans multiple files, be explicit about the scope:

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.

Session Management Commands

/compact -- Reclaim Context

Use /compact when you've been working for a while and context is getting large:

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

When to use: After completing a feature, before starting the next one in the same session.

/clear -- Fresh Start

Use /clear when switching to a completely different task:

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

When to use: Switching between unrelated tasks (e.g., theme development to app backend work).

/cost -- Monitor Spending

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

When to use: Every 30-60 minutes during active development, or before starting a large task.

Context Window Limits

If Claude Code's responses start losing coherence or it "forgets" earlier decisions, you've likely filled the context window. Use /compact immediately. If that doesn't help, /clear and restart with a focused prompt and good CLAUDE.md context.

Anti-Patterns to Avoid

Anti-PatternWhy It FailsBetter Approach
"Build my entire app"Too vague, too largeBreak into feature-level prompts
"Make it better"No specific direction"Improve performance by adding pagination"
"Fix the bug" (no context)Claude Code needs error detailsPaste the error message and relevant code
Repeating context every promptWastes tokensPut stable context in CLAUDE.md
Never using /compactContext overflowCompact after each completed feature

Next Steps

With these prompt templates in your toolkit, proceed to the CLAUDE.md Template for a complete, copy-paste-ready project configuration file optimized for Shopify development.