Shopify Functions Complete Guide: Customize Business Logic at Scale

Master Shopify Functions for custom discounts, payment method filtering, shipping rate manipulation, and cart validation with this complete development guide.

E
ECOSIRE Research and Development Team
|March 16, 20267 min read1.6k Words|

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

APIPurposeReplaces
DiscountsCustom discount logic (BOGO, tiered, conditional)Shopify Scripts (line item discounts)
Payment CustomizationShow/hide/reorder payment methods at checkoutPayment method conditional logic
Delivery CustomizationModify shipping rates, names, and availabilityShipping rate scripts
Cart ValidationValidate cart contents and block invalid combinationsCart attribute validation
Order RoutingCustomize fulfillment location selectionDefault 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:

FilePurpose
src/run.js (or run.rs)The function logic
input.graphqlGraphQL query defining the input data
shopify.extension.tomlConfiguration and metadata
schema.graphqlThe Shopify API schema (auto-generated)

Development Workflow

  1. Define input query: Write the GraphQL query in input.graphql that fetches the data your function needs
  2. Implement logic: Write the function in src/run.js that transforms input into output
  3. Test locally: Run unit tests with npx shopify app function test
  4. Deploy: Push to Shopify with npx shopify app deploy
  5. 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:

OperationDescription
productDiscountApply discount to specific products/variants
orderDiscountApply discount to the order total
freeShippingRemove 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:

OperationEffect
hideRemove a payment method from the checkout
renameChange the display name of a payment method
moveReorder 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:

  1. Create test fixtures with sample input data
  2. Run the function against the fixtures
  3. Assert the output matches expected results

The Shopify CLI generates test boilerplate:

Test ScenarioWhat to Verify
Empty cartFunction returns no operations
Qualifying cartCorrect discount/modification applied
Edge casesBoundary values, maximum quantities
Error handlingInvalid input handled gracefully
PerformanceExecution completes under 5ms

Preview Mode

Test functions in a development store before publishing:

  1. Deploy the function to your development store
  2. Configure it through the app admin
  3. Add products to cart and verify behavior
  4. Check the function execution logs in the Shopify CLI output

Performance Considerations

Execution Limits

LimitValue
Execution time5ms maximum
Memory12 MB
Input size64 KB
Output size64 KB
Instructions1 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:

  1. Displays the function's purpose and current settings
  2. Allows merchants to set parameters (thresholds, product selections, percentages)
  3. Stores configuration as metafields that the function reads at runtime
  4. 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.

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.

E

Written by

ECOSIRE Research and Development Team

Building enterprise-grade digital products at ECOSIRE. Sharing insights on Odoo integrations, e-commerce automation, and AI-powered business solutions.

Chat on WhatsApp