How to retrieve current product identifier using Shopify JavaScript API

I’m working on a Shopify application that integrates with an external image processing service. For this integration to work properly, I need to capture the product identifier that the user is currently viewing.

My current approach involves modifying the product.liquid template file to include a hidden element containing the product ID. Then I can use JavaScript to grab this value and pass it to my API endpoint.

Here’s what I’m thinking:

// Get product ID from hidden element
const productId = document.getElementById('hidden-product-id').value;

// Make API call with product data
fetch('/api/process-product', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({id: productId})
});

Is there a more reliable method to access the current product information on every product page? I want to make sure this works consistently across different themes. Any suggestions would be helpful!

why not just use window.ShopifyAnalytics.meta.product.id? most themes have this already loaded so u dont need to mess with hidden elements or worry about theme compatibility issues. just check if its available first tho

Just use the global meta object that Shopify injects into product pages. You can grab the product ID with window.meta.product.id - works on pretty much every modern theme. No template changes needed and it stays consistent across different themes. I’ve used this on several client projects and it’s rock solid. Just wrap your code in a DOM ready check so the meta object loads first. Way better than relying on hidden elements that might disappear when themes get updated.

Hit this exact issue last month building a product customizer. Best solution I found: use window.ShopifyAnalytics.meta.page.resourceId - grabs the product ID directly without touching any templates. Works across all themes since it’s built into Shopify’s analytics. You can also pull variant info and other product data from window.ShopifyAnalytics.meta.product. Just wrap your code in a timeout or check if the object exists first - sometimes takes a sec to load on slower connections.