Generate code for each item in the order in the metafield ?

Topic summary

Goal: Automatically generate a unique alphanumeric code for each item in a customer’s order and store these codes in the order’s metafields for later email distribution (e.g., for a raffle).

Current issue: The provided ADDCODES.JS script runs on purchase but the order metafields remain empty after testing. The code attempts to loop over line items, create codes, and save them as metafields.

Key questions/clarifications: A respondent asks where the ADDCODES.JS file is located and whether a custom app is being used. Placement and execution context are unclear.

Suggested approach: Use a backend service (e.g., a Node.js server) to listen to Shopify’s orders/create webhook. Upon order creation, generate per-item codes and persist them to the order via the Admin API, then send the codes by email to customers.

Definitions: Metafields are custom data fields attached to resources like orders. Webhooks notify an external app when events occur.

Status: No confirmation of implementation details yet. Discussion remains open without a confirmed fix.

Summarized with AI on January 19. AI used: gpt-5.

Hello,Could you help me? I’m trying to create a function that, every time a customer makes a purchase in my store, generates an alphanumeric code for each item in their order.

For example:

Customer bought: 3x shoes and 3x dress shirt

Total = 6 items

Generated codes:

CODE1 = ABC5415

CODE2 = ABC5420

CODE3 = ABC5430
CODE4 = ABC5440

CODE5 = ABC5450

CODE6 = ABC5460

And save the generated code in the order’s metafield.

I created a file called ADDCODES.JS with this script:

// GENERATE RANDOM CODES
function generateRandomCode(length) { // ...code omitted }

// ADD CODES TO ORDERS
function addCodesToOrders(order) { const codes = []; for (let i = 1; i <= order.line_items.length; i++) { const namespace = custom.code${i}; const code = generateRandomCode(6); codes.push({ namespace, key: CODE${i}, value: code, value_type: 'string' }); }

// Add metafields to the order
shopify.order.addMetafields(order.id, codes); }

// EXECUTE
{% if order %} {% include 'addcodes' %} {% endif %}

However, when performing a test purchase, the metafields remain empty.

I will conduct a draw among customers who have purchased a specific item, and each of these items in the order entitles them to a number to enter the draw. Later, I will send these codes to the customers send by e-mail . Could you help me?

Hi Esdrasvlogs,

This sounds like a great idea! Where exactly is the ADDCODES.JS file located? Are you creating a custom app to achieve this? One option could be to use a backend service (eg: Node.js server) to listen for new orders using Shopify’s webhook for order creation. When a new order is detected, your app could generate the codes and save them as metafields using the Admin API, then those could be sent via email to your customers.