Set metafields on a cart returns null

I’m trying to save metafields on a Shopify cart using the cartMetafieldsSet mutation from the Storefront API (2024-10), but I’m facing an issue where the operation seems to succeed yet returns null for the metafields in the response.

What I’m trying to do:

I need to store recently viewed product references as metafields on the cart to later retrieve them.

My code:

mutation cartMetafieldsSet($metafields: [CartMetafieldsSetInput!]!) {
  cartMetafieldsSet(metafields: $metafields) {
    metafields {
      id
      key
      value
    }
    userErrors {
      field
      message
    }
  }
}

With input:

{
  "metafields": [
    {
      "key": "views",
      "type": "single_line_text_field", 
      "ownerId": "gid://shopify/Cart/Z2NwLXVzLWVhc3QxOjAxSlJFWTBWUThZM1ZaSEVFSE1LUjdHRU1O",
      "value": "my_value"
    }
  ]
}

Response I’m getting:

{
  "cartMetafieldsSet": {
    "__typename": "CartMetafieldsSetPayload",
    "metafields": null,
    "userErrors": []
  }
}

Questions:

  1. Why does the mutation return null for metafields even though there are no errors?
  2. Why is namespace not requires when setting metafields, what is my namespace?
  3. Is the cart token required when reading metafield tokens?

I’ve tried both with and without namespace (namespace: “custom”, key: “productviews” vs key: “custom.productviews”) and get the same result. When attempting to retrieve the metafields afterward using cart queries, they don’t appear to exist.

Any help would be greatly appreciated!

Solved. The analytics library provides the cart.id without the secret key. You have to fetch that from another source before you can write a metafield.