---
title: Compute input query variables at runtime
description: Learn how to use a prepare target to compute a function's input query variables from the current cart.
source_url:
  html: https://shopify.dev/docs/apps/build/functions/input-queries/prepare-input-query-variables
  md: https://shopify.dev/docs/apps/build/functions/input-queries/prepare-input-query-variables.md
---

# Compute input query variables at runtime

Use [input query variables](https://shopify.dev/docs/apps/build/functions/input-queries/use-variables-input-queries) 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](https://shopify.dev/docs/apps/build/metaobjects#app-owned-metaobjects) entry that holds the quantity limit for that country.

***

## How it works

When a function has a prepare target, Shopify does the following for each function run:

1. Takes the `variables` object that the prepare target returns. Each key is the name of a variable that the run target's input query declares.
2. 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.

***

## Requirements

* Create a function that uses the [Cart and Checkout Validation Function API](https://shopify.dev/docs/api/functions/2027-01/cart-and-checkout-validation).
* Use API version `2027-01` or later for your function.
* Learn how to [use input query variables](https://shopify.dev/docs/apps/build/functions/input-queries/use-variables-input-queries).
* If you're using Rust, then use version 2.3.0 or higher of the [`shopify_function`](https://crates.io/crates/shopify_function) crate.

***

## Step 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

```toml
[[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

```toml
[[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

```terminal
shopify app function schema
```

***

## Step 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

```graphql
query CartValidationsGeneratePrepareInput {
  localization {
    country {
      isoCode
    }
  }
}
```

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

```terminal
shopify app function typegen
```

***

## Step 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

```js
// @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

```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`](https://shopify.dev/docs/apps/build/functions/monitoring-and-errors#list-of-errors). 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

```js
export * from './cart_validations_generate_prepare';
export * from './cart_validations_generate_run';
```

##### Rust

```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();
}
```

***

## Step 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

```graphql
query CartValidationsGenerateRunInput($ruleSetHandle: String!) {
  cart {
    lines {
      quantity
    }
  }
  shop {
    ruleSet: metaobject(handle: {type: "$app:validation_rule_set", handle: $ruleSetHandle}) {
      maxQuantity: field(key: "max_quantity") {
        jsonValue
      }
    }
  }
}
```

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`](https://shopify.dev/docs/apps/build/functions/monitoring-and-errors#list-of-errors).

If you're using JavaScript, then regenerate types for the updated query:

## Terminal

```terminal
shopify app function typegen
```

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

```js
// @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

```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 },
        )],
    })
}
```

***

## Step 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

```toml
[metaobjects.app.validation_rule_set]
name = "Validation rule set"


[metaobjects.app.validation_rule_set.fields.max_quantity]
name = "Max quantity"
type = "number_integer"
```

Deploy your app. The deploy includes the function and the metaobject definition:

## Terminal

```terminal
shopify app deploy
```

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`](https://shopify.dev/docs/apps/build/apis/graphql-admin/api-exploration/admin-cli-app-execute), which authenticates as your app. For example, the following command creates an entry that limits carts in Canada to five items:

## Terminal

```bash
shopify app execute --query 'mutation {
  metaobjectCreate(metaobject: {
    type: "$app:validation_rule_set"
    handle: "ca"
    fields: [{ key: "max_quantity", value: "5" }]
  }) {
    userErrors {
      field
      message
    }
  }
}'
```

When your function runs on a store, the **Logs** section of your [Dev Dashboard](https://shopify.dev/docs/apps/build/functions/monitoring-and-errors#debug-a-function) 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**.

***

## Next steps

* Learn how to use [app-owned metaobjects in Shopify Functions](https://shopify.dev/docs/apps/build/metaobjects#use-in-shopify-functions).
* Learn how to [test and debug Shopify Functions](https://shopify.dev/docs/apps/build/functions/test-debug-functions).
* Learn about the [errors that a function run can return](https://shopify.dev/docs/apps/build/functions/monitoring-and-errors#list-of-errors).
* Consult the [API references for Shopify Functions](https://shopify.dev/docs/api/functions).

***