この記事は現在英語版のみです。翻訳は近日公開予定です。
Shopify Functions Complete Guide: Customize Business Logic at Scale
Shopify Functions allow developers to customize core commerce logic that runs within Shopify's infrastructure rather than on external servers. This means custom discount calculations, payment method filtering, shipping rate modifications, and cart validation execute in milliseconds without network latency. Functions replaced the Script Editor (Shopify Scripts) and represent the future of backend customization on the platform. This guide covers every function type, development workflow, and deployment pattern.
Key Takeaways
- Shopify Functions execute in a WebAssembly sandbox within Shopify's infrastructure, ensuring sub-5ms execution times
- Five function APIs are available: discounts, payment customization, delivery customization, cart validation, and order routing
- Functions are written in Rust, JavaScript, or any language that compiles to WebAssembly
- Each function receives input via GraphQL query results and returns structured output that Shopify applies to the operation
- Functions deploy as part of Shopify apps and can be configured by merchants through the admin
What Are Shopify Functions?
Shopify Functions are lightweight programs that customize specific commerce operations at predefined extension points. Unlike webhooks (which send data to external servers), Functions run inside Shopify's infrastructure as WebAssembly modules, guaranteeing:
- Speed: Sub-5ms execution (no network latency)
- Reliability: No external server dependencies
- Scale: Handles any traffic volume without capacity planning
- Security: Sandboxed execution with no filesystem or network access
Function APIs
| API | Purpose | Replaces |
|---|---|---|
| Discounts | Custom discount logic (BOGO, tiered, conditional) | Shopify Scripts (line item discounts) |
| Payment Customization | Show/hide/reorder payment methods at checkout | Payment method conditional logic |
| Delivery Customization | Modify shipping rates, names, and availability | Shipping rate scripts |
| Cart Validation | Validate cart contents and block invalid combinations | Cart attribute validation |
| Order Routing | Customize fulfillment location selection | Default location routing |
Development Environment
Prerequisites
- Shopify CLI (latest version)
- Node.js 18+
- A Shopify Partner account and development store
- Rust toolchain (for Rust-based functions) or JavaScript runtime
Creating a Function
Scaffold a new function using the Shopify CLI:
Run npx shopify app generate extension and select the function type. The CLI generates:
| File | Purpose |
|---|---|
src/run.js (or run.rs) | The function logic |
input.graphql | GraphQL query defining the input data |
shopify.extension.toml | Configuration and metadata |
schema.graphql | The Shopify API schema (auto-generated) |
Development Workflow
- Define input query: Write the GraphQL query in
input.graphqlthat fetches the data your function needs - Implement logic: Write the function in
src/run.jsthat transforms input into output - Test locally: Run unit tests with
npx shopify app function test - Deploy: Push to Shopify with
npx shopify app deploy - Configure: Merchants configure function parameters through the app's UI
Discount Functions
How Discount Functions Work
A discount function receives cart data (line items, customer info, discount codes) and returns discount operations to apply. The function runs every time the cart is evaluated---on page load, item add/remove, and checkout entry.
Common Discount Patterns
Buy X Get Y: When the cart contains product X, apply a percentage or fixed discount to product Y.
Tiered discounts: Apply increasing discounts based on cart total (10% over 100 USD, 15% over 200 USD, 20% over 500 USD).
Customer-specific pricing: Check customer tags or metafields and apply segment-specific discounts (wholesale, VIP, employee).
Bundle discounts: When specific product combinations are in the cart, apply a bundle discount (buy all three, save 25%).
Volume discounts: Apply per-unit discounts based on quantity (1-9 units at full price, 10-24 at 10% off, 25+ at 20% off).
Input Query Example
The discount function's input query typically requests:
- Cart line items with product IDs, variant IDs, quantities, and prices
- Customer information (ID, tags, metafields) if using customer segmentation
- Discount code if validating a code-based discount
- Product metafields for product-specific discount rules
Output Structure
The function returns an array of discount operations:
| Operation | Description |
|---|---|
productDiscount | Apply discount to specific products/variants |
orderDiscount | Apply discount to the order total |
freeShipping | Remove shipping charges |
Each operation includes the discount value (percentage or fixed amount), a message displayed to the customer, and the conditions under which it applies.
Payment Customization Functions
Use Cases
- Hide payment methods: Hide "Cash on Delivery" for orders above a threshold
- Reorder methods: Show the most popular payment method first based on customer location
- Rename methods: Display localized payment method names
- Add messaging: Show additional information next to specific payment methods
Implementation Pattern
The function receives the cart details and available payment methods. It returns operations that modify the payment method list:
| Operation | Effect |
|---|---|
hide | Remove a payment method from the checkout |
rename | Change the display name of a payment method |
move | Reorder payment methods |
Delivery Customization Functions
Use Cases
- Rename shipping options: Display "Express Delivery (2-3 days)" instead of carrier rate names
- Hide options: Remove ground shipping for perishable products
- Reorder options: Show the fastest option first for urgent orders
- Add messaging: Display estimated delivery dates next to each option
Implementation
The function receives shipping rates from configured carriers and returns modifications. The input includes cart line items (to check product types), shipping address (for location-based rules), and available delivery options.
Cart Validation Functions
Use Cases
- Quantity limits: Maximum 5 units of limited-edition products
- Combination restrictions: Product A and Product B cannot be in the same cart (incompatible)
- Minimum requirements: Wholesale accounts must order minimum 100 USD
- Geographic restrictions: Block certain products from shipping to restricted regions
Validation Output
When validation fails, the function returns an error with:
- Target: Which cart line or the cart itself
- Message: Customer-facing error message
- Severity: Error (blocks checkout) or warning (allows but notifies)
Testing Functions
Unit Testing
Test functions locally without deploying:
- Create test fixtures with sample input data
- Run the function against the fixtures
- Assert the output matches expected results
The Shopify CLI generates test boilerplate:
| Test Scenario | What to Verify |
|---|---|
| Empty cart | Function returns no operations |
| Qualifying cart | Correct discount/modification applied |
| Edge cases | Boundary values, maximum quantities |
| Error handling | Invalid input handled gracefully |
| Performance | Execution completes under 5ms |
Preview Mode
Test functions in a development store before publishing:
- Deploy the function to your development store
- Configure it through the app admin
- Add products to cart and verify behavior
- Check the function execution logs in the Shopify CLI output
Performance Considerations
Execution Limits
| Limit | Value |
|---|---|
| Execution time | 5ms maximum |
| Memory | 12 MB |
| Input size | 64 KB |
| Output size | 64 KB |
| Instructions | 1 million Wasm instructions |
Optimization Tips
- Minimize the input query to only the fields your logic needs
- Avoid complex nested loops---use hash maps for lookups
- Pre-compute values in app configuration rather than in the function
- Use Rust for performance-critical functions (2-3x faster than JavaScript)
- Profile function execution using the Shopify CLI performance tools
Merchant Configuration
App Configuration UI
Functions are configured through your app's UI, not directly in the Shopify admin. Build a configuration page that:
- Displays the function's purpose and current settings
- Allows merchants to set parameters (thresholds, product selections, percentages)
- Stores configuration as metafields that the function reads at runtime
- Validates inputs before saving
Configuration Storage
Store function configuration using app metafields:
- Metafields on the discount: Threshold amounts, percentage values, product IDs
- App data storage: Complex configuration like tiered rules, customer segments
- Function configuration: Passed as part of the function's input via the input query
ECOSIRE Function Development Services
Custom Shopify Functions require both commerce domain expertise and WebAssembly development skills. ECOSIRE's Shopify app development services include function design, implementation, testing, and deployment. Our team builds discount engines, payment customizations, and validation logic tailored to your business rules. For ongoing needs, our support services maintain and evolve your custom functions as Shopify's platform progresses.
Related Reading
- Shopify Checkout Extensibility
- Shopify App Development Guide
- Shopify API Integration Guide
- Shopify Flow Automation
- Shopify Plus Enterprise Guide
Do Shopify Functions replace Shopify Scripts?
Yes. Shopify Scripts are deprecated and Functions are the replacement. The key differences: Functions run as WebAssembly (not Ruby), deploy through apps (not the Script Editor), and support more extension points. Existing Scripts continue to work but Shopify recommends migrating to Functions.
Can non-developers create Shopify Functions?
Not directly. Functions require programming knowledge (JavaScript or Rust). However, developers can build apps with configuration UIs that let merchants customize function behavior without coding. Many apps on the Shopify App Store use Functions internally while presenting a merchant-friendly interface.
Is there a limit to how many Functions can run on a single store?
Shopify does not impose a hard limit on the number of installed Functions. However, each checkout evaluation runs all applicable Functions sequentially, so performance considerations apply. The 5ms per-function limit ensures individual Functions cannot slow the checkout, but having dozens of Functions could theoretically impact total checkout evaluation time.
執筆者
ECOSIRE Research and Development Team
ECOSIREでエンタープライズグレードのデジタル製品を開発。Odoo統合、eコマース自動化、AI搭載ビジネスソリューションに関するインサイトを共有しています。
関連記事
e コマース向け AI パーソナライゼーション: コンバージョンをもたらす個別化されたエクスペリエンス
製品レコメンデーション、動的コンテンツ、パーソナライズされた検索、カスタマー ジャーニーの最適化により、e コマース向け AI パーソナライゼーションを導入し、コンバージョン率を 15 ~ 30% 高めます。
水素を使用したヘッドレス Shopify: 高性能のカスタム ストアフロントを構築
Remix、Storefront API、Oxygen ホスティング、パフォーマンスの最適化をカバーする、Hydrogen フレームワークを使用してヘッドレス Shopify ストアフロントを構築するための完全なガイドです。
モバイルファーストの Shopify ストアの構築: 完全な最適化ガイド
コンバージョンにつながるモバイルファーストの Shopify ストアを構築します。テーマの選択、モバイル UX、チェックアウトの最適化、アプリのパフォーマンス、Shopify 固有のモバイル戦略について説明します。