Compute input query variables at runtime
Use input query variables to pass arguments into a function's input query. Their values come from a metafield on the function owner. Every function run reads the same values, so the input query can't select data based on the current cart.
A prepare target removes that limit. It runs just before the run target, reads data from the cart, and returns the values for the run target's input query variables.
In this guide, you'll add a prepare target to a cart and checkout validation function. The prepare target reads the buyer's country, and the run target uses it to load the one app-owned metaobject entry that holds the quantity limit for that country.
Anchor to How it worksHow it works
When a function has a prepare target, Shopify does the following for each function run:
- Takes the
variablesobject that the prepare target returns. Each key is the name of a variable that the run target's input query declares. - Runs the run target's input query with those variables and passes the result to the run target as its input.
The prepare target's input query can request the same fields as the run target's input query, except the fields that only run targets can request, such as fetchResult. It can't declare variables. If the prepare target fails, then the run target doesn't execute and the function run fails.
Anchor to RequirementsRequirements
- Create a function that uses the Cart and Checkout Validation Function API.
- Use API version
2027-01or later for your function. - Learn how to use input query variables.
- If you're using Rust, then use version 2.3.0 or higher of the
shopify_functioncrate.
Anchor to Step 1: Add the prepare target to your configurationStep 1: Add the prepare target to your configuration
In your function's shopify.extension.toml file, add a [[extensions.targeting]] section for the prepare target, next to the section for the run target. The prepare target needs its own input query file and export:
shopify.extension.toml
shopify.extension.toml
JavaScript
[[extensions.targeting]]
target = "cart.validations.generate.prepare"
input_query = "src/cart_validations_generate_prepare.graphql"
export = "cart-validations-generate-prepare"
[[extensions.targeting]]
target = "cart.validations.generate.run"
input_query = "src/cart_validations_generate_run.graphql"
export = "cart-validations-generate-run"Rust
[[extensions.targeting]]
target = "cart.validations.generate.prepare"
input_query = "src/cart_validations_generate_prepare.graphql"
export = "cart_validations_generate_prepare"
[[extensions.targeting]]
target = "cart.validations.generate.run"
input_query = "src/cart_validations_generate_run.graphql"
export = "cart_validations_generate_run"The prepare target supplies the run target's variables, so don't set input_variables on the prepare target or the run target. If your configuration has an [extensions.input.variables] section, then remove it. Shopify rejects a deploy that configures variables in either place. Other targets of your function can keep their own input_variables. A run target can have a fetch target or a prepare target before it, but not both.
Then, download the latest schema so that code generation includes the prepare target:
Terminal
Anchor to Step 2: Write the prepare input queryStep 2: Write the prepare input query
Create the src/cart_validations_generate_prepare.graphql file. This query reads the buyer's country:
src/cart_validations_generate_prepare.graphql
The prepare target's input query can't declare variables. If a field in this query takes arguments, then write their values directly in the query.
If you're using JavaScript, then regenerate types for the new query:
Terminal
Anchor to Step 3: Return the run target's variablesStep 3: Return the run target's variables
Create the prepare function. It returns the buyer's country code in lowercase as the ruleSetHandle variable:
Prepare function
src/cart_validations_generate_prepare.js
JavaScript
// @ts-check
/**
* @typedef {import("../generated/api").CartValidationsGeneratePrepareInput} CartValidationsGeneratePrepareInput
* @typedef {import("../generated/api").CartValidationsGeneratePrepareResult} CartValidationsGeneratePrepareResult
*/
/**
* @param {CartValidationsGeneratePrepareInput} input
* @returns {CartValidationsGeneratePrepareResult}
*/
export function cartValidationsGeneratePrepare(input) {
return {
variables: {
ruleSetHandle: input.localization.country.isoCode.toLowerCase(),
},
};
}Rust
use crate::schema;
use shopify_function::prelude::*;
use shopify_function::Result;
#[shopify_function]
fn cart_validations_generate_prepare(
input: schema::prepare::CartValidationsGeneratePrepareInput,
) -> Result<schema::CartValidationsGeneratePrepareResult> {
Ok(schema::CartValidationsGeneratePrepareResult {
variables: schema::run::CartValidationsGenerateRunInputVariables {
rule_set_handle: input.localization().country().iso_code().to_lowercase(),
},
})
}The value of variables must be a JSON object. If the prepare target returns any other value, then the function run fails with an InvalidOutputError. The object needs a key for each required variable of the run target's input query. A required variable has a non-null type, such as String!, and no default value. The object can leave out an optional variable.
In Rust, variables is the CartValidationsGenerateRunInputVariables struct, which the shopify_function crate generates from the variables that the run target's input query declares. You declare $ruleSetHandle in that query in the next step. If you later add, remove, rename, or change the type of a variable in the run target's input query, then the prepare function doesn't compile until you update it.
Export the prepare function alongside the run function. In Rust, the custom_scalar_overrides option of typegen sets the type of the prepare result's variables field to the run target's variables struct:
Entry points
src/index.js
JavaScript
export * from './cart_validations_generate_prepare';
export * from './cart_validations_generate_run';Rust
use shopify_function::prelude::*;
use std::process;
pub mod cart_validations_generate_prepare;
pub mod cart_validations_generate_run;
#[typegen("./schema.graphql", custom_scalar_overrides = {
"CartValidationsGeneratePrepareResult.variables" => run::CartValidationsGenerateRunInputVariables,
})]
pub mod schema {
#[query("src/cart_validations_generate_prepare.graphql")]
pub mod prepare {}
#[query("src/cart_validations_generate_run.graphql")]
pub mod run {}
}
fn main() {
log!("Please invoke a named export.");
process::abort();
}Anchor to Step 4: Use the variables in the run input queryStep 4: Use the variables in the run input query
Declare the variable in the run target's input query, and use it as a field argument. This query loads the metaobject entry whose handle matches ruleSetHandle. You create the metaobject entries in step 5.
src/cart_validations_generate_run.graphql
Shopify checks the variables that the prepare target returns against this query. If a value has the wrong type, a required variable is missing, or the prepare target returns a variable that this query doesn't declare, then the function run fails with an InvalidVariableValueError.
If you're using JavaScript, then regenerate types for the updated query:
Terminal
Update the run function to read the limit from the metaobject entry. If no entry has a matching handle, then ruleSet is null and the function doesn't apply a limit:
Run function
src/cart_validations_generate_run.js
JavaScript
// @ts-check
/**
* @typedef {import("../generated/api").CartValidationsGenerateRunInput} CartValidationsGenerateRunInput
* @typedef {import("../generated/api").CartValidationsGenerateRunResult} CartValidationsGenerateRunResult
*/
/**
* @param {CartValidationsGenerateRunInput} input
* @returns {CartValidationsGenerateRunResult}
*/
export function cartValidationsGenerateRun(input) {
const errors = [];
const maxQuantity = input.shop.ruleSet?.maxQuantity?.jsonValue;
if (typeof maxQuantity === 'number') {
const totalQuantity = input.cart.lines.reduce(
(total, line) => total + line.quantity,
0,
);
if (totalQuantity > maxQuantity) {
errors.push({
message: `You can't order more than ${maxQuantity} items.`,
target: '$.cart',
});
}
}
return {operations: [{validationAdd: {errors}}]};
}Rust
use crate::schema;
use shopify_function::prelude::*;
use shopify_function::scalars::JsonValue;
use shopify_function::Result;
#[shopify_function]
fn cart_validations_generate_run(
input: schema::run::CartValidationsGenerateRunInput,
) -> Result<schema::CartValidationsGenerateRunResult> {
let mut errors = Vec::new();
let max_quantity = input
.shop()
.rule_set()
.and_then(|rule_set| rule_set.max_quantity())
.and_then(|field| match field.json_value() {
Some(JsonValue::Number(max)) => Some(*max as i32),
_ => None,
});
if let Some(max_quantity) = max_quantity {
let total_quantity: i32 = input.cart().lines().iter().map(|line| *line.quantity()).sum();
if total_quantity > max_quantity {
errors.push(schema::ValidationError {
message: format!("You can't order more than {max_quantity} items."),
target: "$.cart".to_string(),
});
}
}
Ok(schema::CartValidationsGenerateRunResult {
operations: vec![schema::Operation::ValidationAdd(
schema::ValidationAddOperation { errors },
)],
})
}Anchor to Step 5: Deploy the function and create the rule setsStep 5: Deploy the function and create the rule sets
The run target reads its quantity limit from an app-owned metaobject entry. In your app's shopify.app.toml file, create a metaobject definition with an integer field for the limit:
shopify.app.toml
Deploy your app. The deploy includes the function and the metaobject definition:
Terminal
Shopify rejects the deploy if the configuration breaks a prepare target rule. For example, the prepare target's input query can't declare variables, and the run target's input query must declare at least one variable. The deploy can't check which variables the prepare target returns, so Shopify checks them when the function runs.
After the deploy succeeds, create an entry of the type $app:validation_rule_set for each country that has its own limit. Each entry's handle is the country's two-letter code in lowercase, which is the value that the prepare target returns.
The $app prefix refers to the app that makes the request, so create the entries as your app. In a dev store, you can use shopify app execute, which authenticates as your app. For example, the following command creates an entry that limits carts in Canada to five items:
Terminal
When your function runs on a store, the Logs section of your Dev Dashboard shows one entry for the prepare target and one entry for the run target. The prepare target's entry has the earlier time, and its Output shows the variables object. The run target's entry shows the same values under Input query variables. In each entry, the Related runs row links to the other entry, with the text Prepare log or Run log.
Anchor to Next stepsNext steps
- Learn how to use app-owned metaobjects in Shopify Functions.
- Learn how to test and debug Shopify Functions.
- Learn about the errors that a function run can return.
- Consult the API references for Shopify Functions.