Exclude Out-of-Stock Variants from DSA via Shopify GraphQL

Learn how to exclude out-of-stock variants from Dynamic Search Ads using headless Shopify GraphQL feeds. Step-by-step setup, custom scripts, and best practices.

By AdTurbo Team · 2026-10-12

Dynamic Search Ads (DSA) are one of the most effective tools for capturing long-tail query volume without manually managing thousands of keywords. However, for e-commerce brands operating on a modern headless commerce architecture—such as Next.js, Remix, or Hydrogen paired with Shopify—DSA can quickly become a budget drain.

When a customer clicks a Dynamic Search Ad that points directly to a product page where their specific size, color, or variant is sold out, bounce rates skyrocket. Even worse, if an entire product has zero inventory across all variants but remains published in your storefront catalog, Google continues serving ads to that dead-end URL until your crawlers detect a 404 or an out-of-stock schema tag. By that time, you have already burned hundreds of dollars in wasted ad spend.

Traditional Shopify stores solve this by injecting liquid tags or relying on monolithic app plugins. In a headless setup, your storefront frontend is completely decoupled from the Shopify backend. Native page indexing crawlers often struggle to reconcile dynamic JavaScript states with real-time stock levels.

The technical solution is to build an automated data pipeline using the Shopify GraphQL Admin API and Storefront API. By generating a high-frequency, inventory-aware Google Ads Page Feed, you can programmatically pass custom labels to Google Ads, allowing your DSA campaigns to target only available inventory while instantly suppressing out-of-stock variants and products.

Here is a comprehensive, production-ready guide to building a headless Shopify DSA page feed setup that eliminates ad waste on out-of-stock inventory.

---

The Architecture of Out-of-Stock Waste in Headless Dynamic Search Ads

Dynamic Search Ads function by crawling your website pages or parsing an uploaded spreadsheet known as a Page Feed. When a user's search query matches indexed page content, Google automatically generates an ad headline and points the user to the destination URL.

In standard DSA setups without feeds, Google's crawler evaluates the rendered DOM. On headless storefronts, this model breaks down for three structural reasons:

1. Client-Side Rendering (CSR) Latency: Many headless setups render variant selectors via client-side JavaScript. Googlebot crawls the raw HTML, sees an "Add to Cart" container, and assumes the item is ready to ship, completely missing that all child variant selectors are disabled.

2. Canonical URL Flattening: Headless architectures typically map all variant permutations (e.g., /products/classic-tee?variant=481029) to a single canonical URL (/products/classic-tee). If sizes Small, Medium, and Large are out of stock, but XXL is available, Google's standard crawl treats the entire page as 100% available.

3. Crawl Frequency Disconnect: Googlebot visits individual product pages once every few days or weeks. If a viral run depletes your inventory on Tuesday afternoon, Google Ads may continue driving paid traffic to that depleted product through the weekend.

[Shopify Backend Inventory]

│

▼ (GraphQL Admin API Polling / Webhooks)

[Feed Worker Node / Cloudflare Worker]

│

▼ (Generates Filtered CSV Feed)

[Public / Authenticated Cloud Endpoint]

│

▼ (Daily / Hourly Schedule Fetch)

[Google Ads Business Data: Page Feed]

│

▼ (Custom Label: instock)

[Dynamic Search Ad Group: Target only instock]

By implementing an automated pipeline that queries Shopify's GraphQL API and serves a dynamically updated Google Ads Page Feed, you regain deterministic control over which URLs Google is allowed to serve.

---

Querying Shopify GraphQL: Core Filtering Parameters Reference

To construct an accurate page feed, you must query your inventory data without hitting API rate limits or retrieving unnecessary data blocks. While REST endpoints often return sprawling JSON blobs that cause timeout issues on stores with 10,000+ SKUs, GraphQL allows precise field projection.

Querying Variants and Inventory Levels

In Shopify's GraphQL Admin API (version 2024-01 or later), inventory data is nested under the ProductVariant entity. To determine whether an item should be eligible for DSA indexing, you must inspect two primary fields: inventoryQuantity and availableForSale.

Here is the foundational GraphQL query structure to retrieve active products with variant-level stock checks:

graphql

query GetActiveProductsWithInventory($cursor: String) {

products(first: 50, after: $cursor, query: "status:ACTIVE") {

pageInfo {

hasNextPage

endCursor

}

edges {

node {

id

title

handle

onlineStoreUrl

totalInventory

tracksInventory

variants(first: 100) {

edges {

node {

id

title

sku

availableForSale

inventoryQuantity

selectedOptions {

name

value

}

}

}

}

}

}

}

}

Field Projection: Using the Columns Parameter to Minimize Payload

When pulling data for ad operations, never request non-essential fields like descriptionHtml, metafields, or historical image assets. Notice in the query above that we limit our field projection strictly to the attributes required to validate commercial eligibility:

• totalInventory: A fast top-level number field used to discard completely depleted products without iterating through child variants.

• availableForSale: A boolean field returning whether a buyer can check out. This accounts for backorders and whether "Continue selling when out of stock" is enabled.

• inventoryQuantity: A number field displaying the raw physical units available across all assigned locations.

By maintaining a minimal payload footprint, you prevent memory leak exceptions in serverless environments like AWS Lambda or Cloudflare Workers.

---

Handling Complex Data Types and API Data Filtering Operators

Building an enterprise-ready filter requires handling edge cases in product configurations. If your store contains variable options (sizes, colors, materials), you cannot rely on a simple binary check at the parent product level.

Filtering Operators Across Data Types

When parsing the GraphQL response in your ingestion script, you will evaluate multiple data types to construct your target criteria:

| Data Type | Target Field | Evaluation Logic | DSA Page Feed Impact |

| :--- | :--- | :--- | :--- |

| Boolean | availableForSale | Must strictly evaluate to true | If false, strip URL or assign customlabel = outofstock |

| Number | inventoryQuantity | Compare against threshold (e.g., = 3) | Buffer against race conditions where cart reserves deplete final units |

| Number | totalInventory | Top-level integer validation | Instantly excludes dead parent products before processing variant arrays |

| Array | variants.edges | Calculate ratio: instockvariants / totalvariants | Exclude products with severe size breaks (e.g., only XS remaining) |

| String | handle | Concatenate with headless domain URL | Builds the exact Page URL column for Google Ads ingestion |

| Date | updatedAt | Compare against feed build timestamp | Enables incremental compilation rather than full rebuilds |

The "Continue Selling When Out of Stock" Edge Case

Shopify allows merchants to enable inventory overselling via the setting inventoryPolicy: CONTINUE.

If a merchant enables this, availableForSale will return true even when inventoryQuantity is zero or negative. For luxury items or made-to-order goods, this is acceptable. For fast-fashion or commodity goods, running DSA traffic to backordered items often yields poor conversion rates and inflated Customer Acquisition Cost (CAC).

If you want to understand how run-away acquisition costs impact your overall account efficiency, review our analysis on why Google Ads is so expensive. In your GraphQL feed processing script, make sure you evaluate both parameters:

javascript

function isVariantEligible(variant, policyThreshold = 0) {

// If merchant allows overselling, verify business intent

if (variant.inventoryPolicy === 'CONTINUE') {

return true; // Or set to false if you do not want to advertise backorders

}

// Strict inventory quantity buffer check

return variant.availableForSale && variant.inventoryQuantity policyThreshold;

}

Size-Break Filtering (Ratio Logic)

One common reason DSA efficiency collapses is what e-commerce merchandisers call "broken size runs." If a pair of running shoes is available only in men's size 6 and size 14, 90% of searchers clicking that ad will immediately bounce because common sizes (9 through 11) are missing.

Using an array aggregation check in your node middleware, you can calculate the availability percentage:

$\text{Availability Ratio} = \frac{\sum \text{Eligible Variants}},{\text{Total Active Variants}}$

If the ratio falls below a defined threshold (such as 0.25 or 25%), your script should flag the product as customlabel = brokeninventory rather than instock. This prevents DSA from serving ads to landing pages with low conversion probabilities.

---

Handling Large Datasets: Pagination and Cursors

Shopify limits REST API responses via standard page and limit parameters, but the GraphQL Admin API relies exclusively on Cursor-based Pagination via the pageInfo object. Attempting to run offset-based queries will fail or result in data timeouts.

Cursor-Based Pagination Implementation

To pull your catalog reliably, implement a recursive or looping cursor fetch function. This snippet illustrates production-grade fetching with cursor assignment:

javascript

import { createAdminApiClient } from '@shopify/admin-api-client';

const client = createAdminApiClient({

storeDomain: process.env.SHOPIFYSTOREDOMAIN,

apiVersion: '2024-01',

accessToken: process.env.SHOPIFYADMINACCESSTOKEN,

});

async function fetchAllCatalogProducts() {

let hasNextPage = true;

let cursor = null;

const allProducts = [];

while (hasNextPage) {

const response = await client.request(GetActiveProductsWithInventory, {

variables: { cursor },

});

if (response.errors) {

console.error('GraphQL Query Errors:', response.errors);

throw new Error('Failed to fetch catalog from Shopify GraphQL API');

}

const { edges, pageInfo } = response.data.products;

for (const edge of edges) {

allProducts.push(edge.node);

}

hasNextPage = pageInfo.hasNextPage;

cursor = pageInfo.endCursor;

// Implement throttle awareness based on API cost tracking

await preventRateLimiting(response.extensions);

}

return allProducts;

}

Handling API Rate Limits and Query Complexity

Every Shopify GraphQL query carries a calculated complexity cost. Shopify allows a leaky bucket replenishment rate of 50 to 100 cost points per second depending on your plan tier (Shopify Plus grants 200 points per second).

Inspect the extensions.cost object returned in every response:

json

{

"extensions": {

"cost": {

"requestedQueryCost": 52,

"actualQueryCost": 32,

"throttleStatus": {

"maximumAvailable": 2000,

"currentlyAvailable": 1968,

"restoreRate": 100

}

}

}

}

If currentlyAvailable drops below 200 points, force your feed generation script to execute a sleep delay of (200 - currentlyAvailable) / restoreRate 1000 milliseconds before making the next cursor call. This keeps your feed running smoothly without throwing THROTTLED errors.

For growing teams who don't have engineering cycles to maintain custom data pipelines, leveraging dedicated ppc management software can bridge the gap between storefront inventory and ad campaign delivery.

---

Normalizing and Generating the Google Ads DSA Page Feed

Google Ads Dynamic Search Ads require Page Feeds to adhere to a strict two-column CSV format (with an optional third column for targets):

1. Page URL (Required): The target landing page URL.

2. Custom label (Required): Semi-colon delimited strings used to group pages into specific DSA ad groups.

csv

Page URL,Custom label

https://example.com/products/leather-jacket,instock;apparel;highmargin

https://example.com/products/denim-shirt,instock;apparel;sale

https://example.com/products/wool-beanie,outofstock;accessories

Step-by-Step Feed Generator Script

Here is a complete Node.js script that compiles Shopify GraphQL data into a compliant Google Ads Page Feed CSV:

javascript

import fs from 'fs';

import { Parser } from 'json2csv';

const HEADLESSBASEURL = 'https://www.yourheadlessstore.com';

export async function generateDSAPageFeed(products) {

const feedRows = [];

for (const product of products) {

const activeVariants = product.variants.edges.map(e = e.node);

// Calculate available inventory metrics

const totalEligibleVariants = activeVariants.filter(v =

v.availableForSale && v.inventoryQuantity 0

).length;

const variantAvailabilityRatio = activeVariants.length 0

? (totalEligibleVariants / activeVariants.length)

: 0;

const destinationUrl = ${HEADLESSBASEURL}/products/${product.handle};

let statusLabel = 'outofstock';

// Criteria: Must have at least 1 variant available AND pass 20% size run availability

if (totalEligibleVariants 0 && variantAvailabilityRatio = 0.20) {

statusLabel = 'instock';

} else if (totalEligibleVariants 0 && variantAvailabilityRatio < 0.20) {

statusLabel = 'brokensizes';

}

feedRows.push({

'Page URL': destinationUrl,

'Custom label': ${statusLabel};${product.tracksInventory ? 'tracked' : 'untracked'}

});

}

const fields = ['Page URL', 'Custom label'];

const json2csvParser = new Parser({ fields });

const csvData = json2csvParser.parse(feedRows);

fs.writeFileSync('./public/feeds/dsa-google-feed.csv', csvData);

console.log('DSA Page Feed successfully compiled and saved to disk.');

}

When writing custom logic, avoid sending Google Ads 404 URLs or entirely excluding dead links from your feed if they previously existed. Why? If you simply delete a URL from your feed, Google will fall back to using domain-wide crawler data if your DSA target allows it. Instead, explicitly include the URL with Custom label = outofstock, then configure Google Ads to target only instock.

---

Configuring Google Ads DSA Campaigns to Exclude Out-of-Stock URLs

Once your endpoint serves a live, auto-updating CSV file (e.g., hosted on an Amazon S3 bucket, Cloudflare R2 bucket, or your Next.js /api/feeds/dsa route), you must connect it to Google Ads.

Step 1: Upload the Page Feed to Business Data

1. Sign in to your Google Ads account.

2. Navigate to Tools and Settings (wrench icon) Shared Library Business Data.

3. Click the blue plus button (+) and select Page feed.

4. Name your feed (e.g., ShopifyHeadlessCatalogDSA).

5. Select your source: choose Schedule and provide the public HTTPS URL where your headless feed is hosted.

6. Set the fetch frequency to Daily or Every 6 Hours (depending on catalog churn).

[Google Ads Business Data] ──(Pulls every 6 hours)── [https://store.com/api/feeds/dsa]

Step 2: Link the Feed to Your DSA Campaign

1. Open your Dynamic Search Ads campaign settings.

2. Scroll down to Dynamic Search Ads setting.

3. Under Select a targeting source, change the option from Use Google's index of my website to:

• Use URLs from my page feed only (Recommended for total control).

• Or: Use URLs from both Google's index of my website and my page feed.

4. Attach your newly linked ShopifyHeadlessCatalogDSA feed.

5. Click Save.

Step 3: Configure Ad Groups to Target instock Exclusively

Now configure your ad group dynamic targets:

1. Go to your DSA Campaign Dynamic Ad Targets tab.

2. Add a new dynamic target.

3. Select Custom label.

4. Enter instock.

5. Save this target.

6. Next, navigate to Negative dynamic ad targets.

7. Add a negative target for custom labels outofstock and brokensizes.

By layering both an inclusion target (instock) and an explicit negative dynamic ad target (outofstock), you build a fail-safe boundary preventing your ad budget from reaching unavailable product pages.

If you find your campaign performance still lags after fixing your inventory exclusions, run through our comprehensive guide on Google Ads not working to rule out conversion tracking discrepancies or quality score bottlenecks.

---

Developer Best Practices for Production Data Access

Deploying a custom programmatic data feed to production requires continuous monitoring and operational guardrails. A failed pipeline can either cut off traffic entirely or permit out-of-stock products to resume spending.

1. Implement Webhook-Driven Incremental Invalidation

Instead of repeatedly running exhaustive full-catalog sweeps through Shopify's GraphQL API every hour, combine scheduled bulk generation with real-time webhooks. Subscribe to the following Shopify event topics:

• inventorylevels/update

• products/update

• products/delete

When inventory hits zero for a critical variant, push an immediate partial update to your Page Feed CSV file via an automated Cloudflare Worker or AWS S3 SDK script. This reduces the latency between a warehouse sell-out and Google Ads auction suppression from hours down to minutes.

2. Multi-Dimensional Sorting: Using the Sort Parameter for Prioritization

If your catalog exceeds 50,000 SKUs, generation runtime can become an issue. Optimize your GraphQL pipeline by sorting items by update frequency or commercial priority:

graphql

query GetPrioritizedProducts($cursor: String) {

products(first: 50, after: $cursor, sortKey: UPDATEDAT, reverse: true) {

edges {

node {

id

handle

updatedAt

totalInventory

}

}

}

}

Processing the most recently modified records first ensures that any recent catalog changes are prioritized during long-running feed compiles.

3. Graceful Degradation on API Failure

If Shopify encounters a platform service disruption or returns HTTP 500/503 errors during your cron execution, ensure your feed service serves the last successfully cached CSV file alongside an HTTP 304 Not Modified header.

Never allow your server endpoint to return an empty 200 OK document or a raw JSON error trace to Google Ads. If Google Ads crawls an empty page feed, it will unassign all dynamic targets, instantly pausing your DSA campaigns across the entire catalog.

4. Continuous Negative Keyword Scrubbing

Even with an inventory-filtered page feed, searchers may still use out-of-stock modifier phrases (e.g., "clearance leather jacket size medium") that Google Ads attempts to match against related in-stock items. Regularly analyze your search term data to catch queries searching for missing sizes or discontinued product styles.

For a structured walk-through on keeping non-converting search queries out of your campaigns, read our guide on how to find negative keywords in Google Ads.

---

Automating E-Commerce PPC with Modern Tooling

Maintaining headless pipelines, custom GraphQL webhooks, and manual CSV feeds requires sustained engineering support. For growing e-commerce teams that need automated account protection without allocating full-time developers, modern automation platforms can streamline these workflows.

AdTurbo is an AI-powered Google Ads management tool ($149/mo with a 7-day trial; credit card required to start) designed to handle operational PPC tasks automatically. By monitoring account metrics, search query trends, and campaign delivery in real time, AdTurbo helps teams identify wasted ad spend, negative search patterns, and bid inefficiencies across their search and performance campaigns.

To discover how modern AI automation fits alongside your campaign architecture, review our deep dive into what is a Google Ads AI manager.

---

Related Guides

• How to Use the Google Ads Search Terms Report to Cut Wasted Spend

• Google Ads Optimization Checklist: 15 Things to Check Every Week

• PPC Audit Checklist: 12 Steps to Fix a Leaking Google Ads Account

---

Frequently Asked Questions

How often does Google Ads refresh its Dynamic Search Ads page feed?

Google Ads allows you to set automated feed schedules that fetch your hosted CSV daily, weekly, or at specific hourly intervals. In business data settings, the most frequent native schedule available is every 6 to 12 hours. If your catalog inventory fluctuates faster than this window, rely on API-based batch uploads or direct Google Ads Script pushes.

Why can't I just use Google Merchant Center inventory data for Dynamic Search Ads?

Google Merchant Center feeds are designed for Shopping and Performance Max campaigns, not native Search text ads. While Performance Max can dynamically construct landing pages, standard Dynamic Search Ads campaigns require either on-page DOM crawling or dedicated Google Ads Business Data Page Feeds formatted with custom URL labels.

What happens if all variants are out of stock but the page returns a 200 OK status?

If your page remains live with a 200 status code and you lack an inventory-filtered page feed, Googlebot will continue matching user search queries to that URL. This leads to wasted ad clicks where shoppers immediately bounce upon seeing an out-of-stock notice. Implementing a GraphQL-driven page feed with an outofstock custom label allows you to explicitly exclude these URLs without relying on Googlebot to re-crawl your headless frontend.