---
title: Use market metafields
description: >-
  Learn how to store custom data on markets with market metafields, and how
  Shopify resolves market metafield values for each buyer across Liquid, the
  Storefront API, and Shopify Functions.
source_url:
  html: 'https://shopify.dev/docs/apps/build/markets/market-metafields'
  md: 'https://shopify.dev/docs/apps/build/markets/market-metafields.md'
---

# Use market metafields

A market metafield is a [metafield](https://shopify.dev/docs/apps/build/metafields) that stores your app's custom data on a market. For each buyer, Shopify returns the values from the markets that the buyer matches, based on conditions such as the buyer's region or company location. A [child market](https://shopify.dev/docs/apps/build/markets/market-inheritance) uses its parent market's metafield values unless it sets its own.

In this guide, you'll learn how to create, read, and delete market metafields, how Shopify resolves them for a buyer, and how to retrieve the resolved values so your app can show a custom experience to different buyers.

***

## Requirements

* Your app can make [authenticated requests](https://shopify.dev/docs/api/admin-graphql/latest#authentication) to the GraphQL Admin API.
* Your app has the [`read_markets`](https://shopify.dev/docs/api/usage/access-scopes#read_markets) access scope, and either the [`write_market_metafields`](https://shopify.dev/docs/api/usage/access-scopes#write_market_metafields) or the [`write_markets`](https://shopify.dev/docs/api/usage/access-scopes#write_markets) access scope. Learn how to [configure your access scopes using Shopify CLI](https://shopify.dev/docs/apps/build/cli-for-apps/app-configuration).

**Note:**

If your app is migrating from deprecated single-market endpoints, then Shopify will help backfill the market metafield access scopes for your app. Learn how to [migrate to market metafields](https://shopify.dev/docs/apps/build/markets/migrate-to-market-metafields).

***

## Limitations

* Each app that's installed on a shop can create up to 256 market metafield definitions in its [reserved namespace](#use-the-app-reserved-namespace).
* A shop can have up to 256 merchant-owned market metafield definitions, which use namespaces that aren't app-reserved. This limit is separate from each app's limit, and it includes the merchant-owned definitions that apps create.

Learn more about [metafield limits](https://shopify.dev/docs/apps/build/metafields/metafield-limits).

***

## Create metafields on markets

To store custom data on a market, create a metafield definition with the `MARKET` owner type, and then set a metafield value on a market.

### Step 1: Create a market metafield definition

Use the [`metafieldDefinitionCreate`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/metafieldDefinitionCreate) mutation to create a definition with the `MARKET` owner type. The following example creates a definition for a discount percentage, an integer, in the app-reserved `$app` namespace. The `PUBLIC_READ` storefront access makes the values available to the Storefront API:

## POST https://{shop}.myshopify.com/admin/api/{api\_version}/graphql.json

## GraphQL mutation

```graphql
mutation CreateMarketMetafieldDefinition($definition: MetafieldDefinitionInput!) {
  metafieldDefinitionCreate(definition: $definition) {
    createdDefinition {
      id
      name
      namespace
      key
      ownerType
    }
    userErrors {
      field
      message
    }
  }
}
```

## Variables

```json
{
  "definition": {
    "name": "Discount percent",
    "description": "The discount percentage for buyers in a market.",
    "namespace": "$app",
    "key": "discount_percent",
    "ownerType": "MARKET",
    "type": "number_integer",
    "access": {
      "storefront": "PUBLIC_READ"
    }
  }
}
```

## JSON response

```json
{
  "data": {
    "metafieldDefinitionCreate": {
      "createdDefinition": {
        "id": "gid://shopify/MetafieldDefinition/1",
        "name": "Discount percent",
        "namespace": "app--123",
        "key": "discount_percent",
        "ownerType": "MARKET"
      },
      "userErrors": []
    }
  }
}
```

You can also declare app-owned metafield definitions in your app's `shopify.app.toml` file. Learn more about [creating metafield definitions with TOML](https://shopify.dev/docs/apps/build/metafields/definitions#toml-app-owned-example).

### Step 2: Set a metafield on a market

Use the [`metafieldsSet`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/metafieldsSet) mutation to set the metafield value on a market. Pass the market's ID as the `ownerId`:

## POST https://{shop}.myshopify.com/admin/api/{api\_version}/graphql.json

## GraphQL mutation

```graphql
mutation SetMarketMetafield($metafields: [MetafieldsSetInput!]!) {
  metafieldsSet(metafields: $metafields) {
    metafields {
      id
      namespace
      key
      value
      ownerType
    }
    userErrors {
      field
      message
    }
  }
}
```

## Variables

```json
{
  "metafields": [
    {
      "ownerId": "gid://shopify/Market/1",
      "namespace": "$app",
      "key": "discount_percent",
      "type": "number_integer",
      "value": "10"
    }
  ]
}
```

## JSON response

```json
{
  "data": {
    "metafieldsSet": {
      "metafields": [
        {
          "id": "gid://shopify/Metafield/1",
          "namespace": "app--123",
          "key": "discount_percent",
          "value": "10",
          "ownerType": "MARKET"
        }
      ],
      "userErrors": []
    }
  }
}
```

***

## Read metafields on markets

Use the GraphQL Admin API to read the metafields that are set directly on a market. These queries return the value that's stored on each market, not the value that Shopify resolves for a buyer. To get the resolved value, refer to [Retrieve resolved market metafields](#retrieve-resolved-market-metafields).

To read a metafield on one market, use the [`market`](https://shopify.dev/docs/api/admin-graphql/latest/queries/market) query:

## POST https://{shop}.myshopify.com/admin/api/{api\_version}/graphql.json

## GraphQL query

```graphql
query MarketMetafield {
  market(id: "gid://shopify/Market/1") {
    metafield(namespace: "$app", key: "discount_percent") {
      value
      type
    }
  }
}
```

## JSON response

```json
{
  "data": {
    "market": {
      "metafield": {
        "value": "10",
        "type": "number_integer"
      }
    }
  }
}
```

To read a metafield on many markets, use the [`markets`](https://shopify.dev/docs/api/admin-graphql/latest/queries/markets) query. A market that doesn't have the metafield returns `null`:

## POST https://{shop}.myshopify.com/admin/api/{api\_version}/graphql.json

## GraphQL query

```graphql
query MarketsMetafield {
  markets(first: 50) {
    nodes {
      id
      metafield(namespace: "$app", key: "discount_percent") {
        value
        type
      }
    }
  }
}
```

## JSON response

```json
{
  "data": {
    "markets": {
      "nodes": [
        {
          "id": "gid://shopify/Market/1",
          "metafield": {
            "value": "10",
            "type": "number_integer"
          }
        },
        {
          "id": "gid://shopify/Market/2",
          "metafield": null
        }
      ]
    }
  }
}
```

***

## Delete metafields on markets

Use the [`metafieldsDelete`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/metafieldsDelete) mutation to delete a metafield from a market:

## POST https://{shop}.myshopify.com/admin/api/{api\_version}/graphql.json

## GraphQL mutation

```graphql
mutation DeleteMarketMetafield($metafields: [MetafieldIdentifierInput!]!) {
  metafieldsDelete(metafields: $metafields) {
    deletedMetafields {
      ownerId
      namespace
      key
    }
    userErrors {
      field
      message
    }
  }
}
```

## Variables

```json
{
  "metafields": [
    {
      "ownerId": "gid://shopify/Market/1",
      "namespace": "$app",
      "key": "discount_percent"
    }
  ]
}
```

## JSON response

```json
{
  "data": {
    "metafieldsDelete": {
      "deletedMetafields": [
        {
          "ownerId": "gid://shopify/Market/1",
          "namespace": "app--123",
          "key": "discount_percent"
        }
      ],
      "userErrors": []
    }
  }
}
```

***

## How market metafields resolve

A metafield identifier is a namespace and a key. Shopify evaluates the markets that a buyer matches, and resolves each market metafield identifier to a single value based on market specificity. Specificity is the [market precedence](https://shopify.dev/docs/apps/build/markets/market-inheritance#market-precedence-stack) and the market's position in the market hierarchy. For example, a B2B market is more specific than a region market, and a child market is more specific than its parent.

To find the parent-child relationships between a shop's markets, use the [`marketRelationships`](https://shopify.dev/docs/api/admin-graphql/latest/queries/marketRelationships) query. Learn more about [market inheritance](https://shopify.dev/docs/apps/build/markets/market-inheritance).

### Resolution rules

Shopify resolves each metafield identifier separately, so different metafields can resolve from different markets:

* If the buyer matches no market that has a metafield with the identifier, then no value is returned for the identifier.
* If the buyer matches one market that has a metafield with the identifier, then that market's value is returned.
* If the buyer matches more than one market that has a metafield with the identifier, then the value from the most specific market is returned.
* If two markets with equal specificity have a metafield with the identifier, then Shopify breaks the tie. Learn more about [tie-breaking](#tie-breaking).

### Inheritance

A metafield value that's set on a parent market applies to all of its child markets. For example, you set an app-owned metafield with the key `discount_percent` and the value `10` on the North America market. A query for the `discount_percent` key for a buyer in Canada returns `10`, even though no metafield is set on the Canada market.

### Override

A child market can set its own value for the same metafield identifier to override the inherited value. For example, you also set the `discount_percent` key to `15` on the Canada market. A query for the `discount_percent` key for a buyer in Canada now returns `15`, instead of the value `10` from the North America market.

### Tie-breaking

If two markets with the same specificity set the same metafield identifier, then Shopify uses the value from the market whose handle is first in alphabetical order. While this behavior rolls out, some stores use the value that was updated most recently instead.

For example, a store has the following markets, which have the same specificity:

| Market name | Market handle | Metafield |
| - | - | - |
| Canada and United States | `ca_us` | `namespace: "$app"`, `key: "discount_percent"`, `value: 10` |
| Canada and Mexico | `ca_mx` | `namespace: "$app"`, `key: "discount_percent"`, `value: 15` |

A buyer in Canada matches both markets. The `discount_percent` key resolves to `15` from the Canada and Mexico market, because the handle `ca_mx` is before `ca_us` in alphabetical order.

***

## Retrieve resolved market metafields

Each buyer-facing surface returns the market metafield values that Shopify resolves for the current buyer.

### Liquid

Use [`localization.market.metafields`](https://shopify.dev/docs/api/liquid/objects/market#market-metafields) to access the resolved market metafields for the buyer. In a theme app extension, use the `$app` reserved prefix for your app's namespace. The store's own theme code uses the full namespace, `app--{your_app_id}`:

## Liquid

```liquid
{%- assign discount_percent = localization.market.metafields["$app"].discount_percent.value -%}
{%- if discount_percent -%}
  <p class="market-discount">Save {{ discount_percent }}% on your order.</p>
{%- endif -%}
```

### Storefront API

The Storefront API returns resolved market metafields through the [`marketsMetafield`](https://shopify.dev/docs/api/storefront/unstable/objects/Localization#field-Localization.fields.marketsMetafield) and [`marketsMetafields`](https://shopify.dev/docs/api/storefront/unstable/objects/Localization#field-Localization.fields.marketsMetafields) fields on the [`Localization`](https://shopify.dev/docs/api/storefront/unstable/objects/Localization) object. These fields are available in the `unstable` version of the Storefront API.

You need the following to query market metafields with the Storefront API:

* A valid [Storefront API access token](https://shopify.dev/docs/api/storefront/latest#token-based-authentication).
* The [storefront access](https://shopify.dev/docs/apps/build/metafields#storefront-permissions) of the metafield definition set to `PUBLIC_READ`.

**Note:**

The `$app` namespace resolves to your app's reserved namespace, such as `app--123`, based on the access token that makes the request. If the request uses a merchant's own Storefront API access token, then use the full namespace, such as `app--123`, instead of `$app`.

Use the [`@inContext`](https://shopify.dev/docs/storefronts/headless/building-with-the-storefront-api/in-context#using-the-incontext-directive) directive to set the buyer's country, and then query the market metafields through `localization.marketsMetafields`:

## POST https://{shop}.myshopify.com/api/unstable/graphql.json

## GraphQL query

```graphql
query MarketsMetafields($identifiers: [HasMetafieldsIdentifier!]!) @inContext(country: CA) {
  localization {
    marketsMetafields(identifiers: $identifiers) {
      namespace
      key
      value
    }
  }
}
```

## Variables

```json
{
  "identifiers": [
    {
      "namespace": "app--123",
      "key": "discount_percent"
    }
  ]
}
```

## JSON response

```json
{
  "data": {
    "localization": {
      "marketsMetafields": [
        {
          "namespace": "app--123",
          "key": "discount_percent",
          "value": "10"
        }
      ]
    }
  }
}
```

To resolve market metafields for a logged-in B2B customer, pass the `buyer` argument to the `@inContext` directive. The `buyer` argument requires a customer access token that you get through the [Customer Account API authentication flow](https://shopify.dev/docs/storefronts/headless/building-with-the-customer-account-api/getting-started):

## POST https://{shop}.myshopify.com/api/unstable/graphql.json

## GraphQL query

```graphql
query MarketsMetafields($identifiers: [HasMetafieldsIdentifier!]!, $buyer: BuyerInput!) @inContext(buyer: $buyer) {
  localization {
    marketsMetafields(identifiers: $identifiers) {
      namespace
      key
      value
    }
  }
}
```

## Variables

```json
{
  "identifiers": [
    {
      "namespace": "app--123",
      "key": "discount_percent"
    }
  ],
  "buyer": {
    "customerAccessToken": "{customer_access_token}",
    "companyLocationId": "gid://shopify/CompanyLocation/1"
  }
}
```

Learn more about [B2B on headless storefronts](https://shopify.dev/docs/storefronts/headless/bring-your-own-stack/b2b).

### Shopify Functions

Shopify Functions read resolved market metafields through the `localization.marketsMetafield` field of the input query. This field is available in the `unstable` version of the Function APIs, for example in the [Discount Function API](https://shopify.dev/docs/api/functions/unstable/discount#Input.fields.localization.marketsMetafield).

Use an [input query variable](https://shopify.dev/docs/apps/build/functions/input-queries/use-variables-input-queries) for the metafield key, so that each function owner, such as a discount, can read a different market metafield:

1. Define the input query with a variable for the metafield key:

   ## src/cart\_lines\_discounts\_generate\_run.graphql

   ```graphql
   query Input($marketMetafieldKey: String!) {
     localization {
       marketsMetafield(namespace: "$app", key: $marketMetafieldKey) {
         value
       }
     }
   }
   ```

2. In your function's `shopify.extension.toml` file, set `input_variables` on the target. It names the metafield that holds the variable values. That metafield is on the [function owner](https://shopify.dev/docs/apps/build/functions/input-queries/metafields-for-input-queries#how-it-works), the resource that the function is attached to, such as a discount:

   ## shopify.extension.toml

   ```toml
   [[extensions.targeting]]
   target = "cart.lines.discounts.generate.run"
   input_query = "src/cart_lines_discounts_generate_run.graphql"
   input_variables = { namespace = "$app", key = "function_variables" }
   export = "cart-lines-discounts-generate-run"
   ```

3. Use the [`metafieldsSet`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/metafieldsSet) mutation to set the JSON metafield that `input_variables` names, with the namespace `$app` and the key `function_variables`, on the function owner, such as the discount. Each property of the metafield's value sets the input query variable with the same name. The following value sets `$marketMetafieldKey`, so the function reads the market metafield with the key `discount_percent`:

   ## Metafield value

   ```json
   {
     "marketMetafieldKey": "discount_percent"
   }
   ```

4. Read the resolved value in your function code. The `marketsMetafield` field is `null` when no market that the buyer matches has the metafield:

   ## src/cart\_lines\_discounts\_generate\_run.js

   ```javascript
   const discountPercent = Number(input.localization.marketsMetafield?.value ?? 0);
   ```

### GraphQL Admin API

The GraphQL Admin API returns the metafields that are set on each market. To read them, refer to [Read metafields on markets](#read-metafields-on-markets).

To find out which market metafield value applies to a buyer, query the [Storefront API](#storefront-api) with the buyer's context.

**Note:**

The Storefront API doesn't immediately reflect the changes that a merchant makes to their store's configuration. Use the Storefront API to find what applies to a buyer, not to manage the store's current configuration in the Shopify admin.

### Customer Account API

To find out which market metafield value applies to a logged-in customer, query the [Storefront API](#storefront-api) with the `buyer` argument of the `@inContext` directive.

***

## Best practices

The following practices help you keep market metafields safe from other apps, and easy for your app and merchants to manage.

### Use the app-reserved namespace

Use an app-owned [reserved prefix](https://shopify.dev/docs/apps/build/metafields#metafield-ownership), such as `$app`, in your metafield namespace, so that other apps can't use your metafields.

### Use JSON metafields for complex configurations

Metafields support many [data types](https://shopify.dev/docs/apps/build/metafields/list-of-data-types), but app configurations often require nested or repeated data structures. A single JSON metafield can make your configuration easier to manage and query.

If you need larger and more structured data, then you can use a metafield with [metaobject references](https://shopify.dev/docs/apps/build/metafields/list-of-data-types#reference-types).

### Store related settings in one metafield

Your app might have settings that belong together, such as the products in a promotion and their discounts. If you store them in one metafield, then a market inherits or overrides all of them together, instead of each one separately. For example, the North America market gets promotions on products A and B, and the Canada market gets promotions on products A and C, but not on product B.

Use a JSON metafield with the same key, such as `promo_config`, to store the settings on each market:

## Values of the promo\_config metafield

##### North America market

```json
{
  "products": [
    { "name": "UltraWide Monitor", "discount_percent": 15 },
    { "name": "Mechanical Keyboard", "discount_percent": 10 }
  ]
}
```

##### Canada market

```json
{
  "products": [
    { "name": "UltraWide Monitor", "discount_percent": 20 },
    { "name": "Ergonomic Mouse", "discount_percent": 12 }
  ]
}
```

Your app can then manage and query related settings together, in one metafield.

Shopify resolves each metafield key, not each setting in the metafield. A buyer in Canada gets all of the Canada market's settings, which override the settings of the North America market. Your app must write all of the settings on each child market where the settings are different from its parent's.

### Reference configurations by name

Merchants can see market metafields on the markets in the Shopify admin. Instead of a complex configuration, you can store the name that the merchant gave the configuration. For example, a merchant understands "Summer sale" better than a JSON object.

Your app can use the name to find the full configuration, which it stores in a separate metafield, a metaobject, or the app's database.

***

## Next steps

* Learn how to [migrate your app from deprecated single-market endpoints to market metafields](https://shopify.dev/docs/apps/build/markets/migrate-to-market-metafields).
* Learn how [market inheritance](https://shopify.dev/docs/apps/build/markets/market-inheritance) ranks the markets that a buyer matches.
* Learn more about [metafields](https://shopify.dev/docs/apps/build/metafields).

***
