Google Publisher Tag Migrate To Setconfig

google/skills/skills/ads/google-publisher-tag-migrate-to-setconfig

by google35474caa2b668a8b6900fedb2049e613955efe56No license25K starsListed Dec 1, 2026Updated Dec 1, 2026Repository updated today

Migrates web publisher JavaScript and TypeScript code from deprecated Google Publisher Tag (GPT) setter and getter methods on googletag.pubads() and googletag.Slot to setConfig() and getConfig(). Use when auditing, updating, or refactoring GPT or googletag code in web scripts, ad wrappers, or frontend components to replace deprecated configuration APIs (such as setTargeting, clearTargeting, updateTargetingFromMap, collapseEmptyDivs, setCollapseEmptyDiv, enableSingleRequest, disableInitialLoad, enableLazyLoad, setSafeFrameConfig, setForceSafeFrame, setCategoryExclusion, clearCategoryExclusions, setVideoContent, setLocation, setCookieOptions, setRequestNonPersonalizedAds, or getTargeting). Don't use for non-GPT ad server integrations.

FeaturedInstructions onlySoftware Development
AI-generated overview

Migrates Google Publisher Tag code from deprecated pubads and Slot setters and getters to setConfig and getConfig.

What it does
Provides a reference workflow and mapping tables for replacing deprecated Google Publisher Tag (GPT) methods on googletag.pubads() and googletag.Slot with setConfig() and getConfig(). It covers page-level and slot-level setters and getters, merging and clearing collections, SafeFrame, video ads, lazy loading, dynamic targeting, privacy settings and removed APIs. It also lists APIs that must stay unchanged and validation steps such as node --check and reading GPT console warnings.
When to use it
Use when auditing, updating or refactoring GPT or googletag code in web scripts, ad wrappers or frontend components to replace deprecated configuration APIs. Not intended for non-GPT ad server integrations.
Requirements
Instructions only, no bundled scripts. TypeScript projects should update @types/google-publisher-tag and local googletag or Slot interfaces; validation may use the project's existing checks, node --check, or browser/E2E tests that load gpt.js.

How AI overviews are written and checked

Migrate Google Publisher Tag configuration to setConfig and getConfig

Replace deprecated Google Publisher Tag (GPT) setters and getters on googletag.pubads() and googletag.Slot with setConfig() and getConfig() without changing ad request behavior. This skill is the complete reference for GPT setConfig and getConfig mappings and validation rules, so you don't need to search the web.

Workflow

Batch edits per file and validate once at the end.

  • 1. Update TypeScript types in TypeScript projects. Update @types/google-publisher-tag to the latest release in package.json, and update local googletag or Slot interfaces to declare setConfig and getConfig. Run a package-manager install only if node_modules already exists, because sandboxed environments are often offline.
  • 2. Inventory GPT calls in a single pass. Read named files directly. For a directory, search for googletag to find entry points, then follow where Slot and PubAdsService objects are passed. Sort what you find into deprecated setters and getters, existing setConfig calls whose keys must be preserved, privacy and removed APIs, and APIs to keep unchanged.
  • 3. Migrate page-level setters. Use the page-level setters and privacy and removed APIs tables with the migration rules.
  • 4. Migrate slot-level setters. Use the slot-level setters table with the migration rules.
  • 5. Migrate getters and feature checks. Use the page-level getters and slot-level getters tables. Remove legacy fallback branches and change feature checks to test for getConfig.
  • 6. Validate.
    • If node_modules exists, run the project's existing checks. For standalone files without a test suite, run node --check {file_path} and review your diff instead of writing ad-hoc test scripts.
    • When browser or E2E tests run live gpt.js, read the console output. Invalid setConfig and getConfig properties don't throw. GPT logs a warning and ignores them.
    • If a check fails or logs GPT console warnings, fix the code and run it again.

Migration rules

Page settings: one call on googletag

Page-level setConfig and getConfig exist only on googletag. PubAdsService has no setConfig, so googletag.pubads().setConfig() throws a TypeError, including through an alias such as const pubadsService = googletag.pubads().

  • Merge page settings from the same googletag.cmd.push callback or function into one googletag.setConfig() call before googletag.enableServices(), even when other calls such as defineSlot sit between them.
  • Don't merge across separate <script> tags, or across cmd.push blocks split by async header-bidding calls. They run at different times.
  • Replace detached method references too, such as const clear = pubads.clearTargeting or labels.forEach(pubads.setCategoryExclusion).
// Before
googletag.cmd.push(() => {
  const pubads = googletag.pubads();
  pubads.enableSingleRequest();
  googletag.defineSlot('/1234/banner', [728, 90], 'banner')
      ?.addService(pubads);
  pubads.collapseEmptyDivs();
  ['politics', 'gambling'].forEach(pubads.setCategoryExclusion);
  googletag.enableServices();
});

// After
googletag.cmd.push(() => {
  googletag.setConfig({
    singleRequest: true,
    collapseDiv: 'ON_NO_FILL',
    categoryExclusion: ['politics', 'gambling'],
  });
  googletag.defineSlot('/1234/banner', [728, 90], 'banner')
      ?.addService(googletag.pubads());
  googletag.enableServices();
});

Merging and clearing collections

Separate setConfig calls update collection settings instead of replacing them:

SettingSeparate callsClear one entryClear everything
targeting, adsenseAttributesMerge keys{ [key]: null }null
categoryExclusionAppend unique non-empty labels; [] is a no-opNot supportednull
  • Merge adjacent setCategoryExclusion calls or loops into one array.
  • When legacy code clears and then re-adds, clear with null in its own call first. Otherwise stale keys and labels survive. This applies to clearTargeting() followed by setTargeting() or updateTargetingFromMap(), and to clearCategoryExclusions() followed by setCategoryExclusion().
// Before
slot.clearTargeting();
slot.updateTargetingFromMap({ pos: 'top', section: 'news' });
slot.clearCategoryExclusions();
labels.forEach((label) => slot.setCategoryExclusion(label));

// After
slot.setConfig({ targeting: null });
slot.setConfig({ targeting: { pos: 'top', section: 'news' } });
slot.setConfig({ categoryExclusion: null });
if (labels.length > 0) {
  slot.setConfig({ categoryExclusion: labels });
}

SafeFrame and video ads

Merge related legacy calls on the same page or slot into one sub-object.

  • setForceSafeFrame() and setSafeFrameConfig() become one safeFrame object. Drop useUniqueDomain, which GPT ignores. Drop sandbox: false, because sandbox accepts only true or null.
  • enableVideoAds() and setVideoContent() become one videoAds object. Always include enableVideoAds: true, even for a standalone setVideoContent() call, because VideoAdsConfig requires it.
// Before
pubads.setForceSafeFrame(true);
pubads.setSafeFrameConfig({
  allowOverlayExpansion: false,
  useUniqueDomain: true,
  sandbox: false,
});
pubads.setVideoContent('content-id', 'cms-id');

// After
googletag.setConfig({
  safeFrame: { forceSafeFrame: true, allowOverlayExpansion: false },
  videoAds: {
    enableVideoAds: true,
    videoContentId: 'content-id',
    videoCmsId: 'cms-id',
  },
});

Collapsing empty divs

The legacy boolean means different things at page and slot level:

  • Page-level collapseEmptyDivs(false) still collapses on no fill, so it maps to 'ON_NO_FILL', never 'DISABLED'.
  • Slot-level setCollapseEmptyDiv(false) turns collapsing off, so it maps to 'DISABLED'.

The setter tables list every form. When a slot call is conditional, keep the condition and don't add an else branch that sets 'DISABLED'. The slot then inherits the page setting:

// Before
if (collapseBeforeFetch) slot.setCollapseEmptyDiv(true, true);

// After: no 'DISABLED' fallback branch
if (collapseBeforeFetch) slot.setConfig({ collapseDiv: 'BEFORE_FETCH' });

Lazy loading

setConfig rejects top-level properties set to undefined, and legacy lazy-load configs used -1 to mean "unset".

  • In wrappers where config may be undefined, default it to {}.
  • In wrappers where config is null, keep it null to clear the lazy-load setting.
  • Replace -1 with null in fetchMarginPercent, renderMarginPercent, and mobileScaling directly at call sites instead of adding a runtime helper.
// Before
googletag.pubads().enableLazyLoad({
  fetchMarginPercent: 300,
  renderMarginPercent: -1,
});
googletag.pubads().enableLazyLoad(config);

// After
googletag.setConfig({
  lazyLoad: {
    fetchMarginPercent: 300,
    renderMarginPercent: null,
  },
});
googletag.setConfig({ lazyLoad: config === undefined ? {} : config });

Dynamic targeting

setConfig validates targeting as Record<string, string | string[] | null> | null. It rejects empty or whitespace keys, undefined, numbers, booleans, and nested arrays.

null also changes meaning. Legacy setTargeting(key, null) was ignored, but { [key]: null } deletes the key, and String(null) sends 'null'.

When slot.updateTargetingFromMap(map) receives a map that already holds valid string, string[], or null values, pass it straight to slot.setConfig({ targeting: map }). Don't wrap it in a sanitizer. Maps that the caller builds and controls fit this case, such as header-bidding targeting maps and { [key]: null } maps that reset keys on purpose.

// Before
slot.updateTargetingFromMap(bidTargeting);
slot.updateTargetingFromMap({ pos: null, section: null });

// After
slot.setConfig({ targeting: bidTargeting });
slot.setConfig({ targeting: { pos: null, section: null } });

Sanitize only when the source can hold numbers, booleans, undefined, or nested arrays. That usually means setTargeting() calls with variable keys or values, including loops over Object.entries or Object.keys. Build a clean object instead of passing the source through:

// Before
for (const [key, value] of Object.entries(params)) {
  googletag.pubads().setTargeting(key, value);
}

// After
const targeting: Record<string, string | string[]> = {};
for (const [key, value] of Object.entries(params)) {
  if (!key.trim() || value == null) continue; // Skip, don't delete.
  if (Array.isArray(value)) {
    const values = value.flat(Infinity).filter((v) => v != null).map(String);
    if (values.length > 0) targeting[key] = values;
  } else {
    targeting[key] = String(value);
  }
}
if (Object.keys(targeting).length > 0) {
  googletag.setConfig({ targeting });
}

To clean an untyped updateTargetingFromMap map, use the same loop, but copy explicit null values through unchanged instead of skipping them. That way, intentional resets still delete their keys.

Reading settings with getConfig

  • googletag.getConfig() supports adsenseAttributes, disableInitialLoad, and targeting. slot.getConfig() supports adsenseAttributes, categoryExclusion, and targeting. Every other setting is write-only.
  • getConfig() returns a deeply frozen object keyed by setting name, never a flat map, so don't mutate it. getConfig('targeting') returns { targeting: { ... } }, which replaces loops over getTargetingKeys() and getTargeting(key).
  • Legacy getTargeting(key) always returned string[], or [] when unset. getConfig('targeting').targeting?.[key] is typed as string | string[] | null | undefined, so normalize it before calling array methods such as .includes(), .map(), or .length:
function toArray(value: string | string[] | null | undefined): string[] {
  if (Array.isArray(value)) return value;
  return value == null ? [] : [value];
}

const sections = toArray(slot.getConfig('targeting').targeting?.['section']);

Slot null checks and existing config

  • defineSlot() and defineOutOfPageSlot() return Slot | null. Check the slot before calling slot.setConfig().
  • Keep the keys of existing setConfig() calls when merging in new settings.
  • Rename deprecated adYield to threadYield if it appears in googletag.setConfig().

Page-level mapping

Use these tables to replace deprecated googletag.pubads() setters and getters with googletag.setConfig() and googletag.getConfig().

googletag.setConfig(config: googletag.config.PageSettingsConfig): void;
googletag.getConfig(keys: string | string[]): Readonly<
  Pick<
    googletag.config.PageSettingsConfig,
    'adsenseAttributes' | 'disableInitialLoad' | 'targeting'
  >
>;

Page-level setters

FeatureLegacy googletag.pubads() callReplacement
AdSense attributesset(key, value)googletag.setConfig({ adsenseAttributes: { [key]: value } })
Category exclusion (add)setCategoryExclusion(label)googletag.setConfig({ categoryExclusion: [label] })
Category exclusion (clear)clearCategoryExclusions()googletag.setConfig({ categoryExclusion: null })
CenteringsetCentering(isCentered)googletag.setConfig({ centering: isCentered })
Collapse empty divs (on no fill)collapseEmptyDivs() or collapseEmptyDivs(false)googletag.setConfig({ collapseDiv: 'ON_NO_FILL' })
Collapse empty divs (before fetch)collapseEmptyDivs(true)googletag.setConfig({ collapseDiv: 'BEFORE_FETCH' })
Initial loaddisableInitialLoad()googletag.setConfig({ disableInitialLoad: true })
Single Request ArchitectureenableSingleRequest()googletag.setConfig({ singleRequest: true })
Lazy loading (defaults)enableLazyLoad()googletag.setConfig({ lazyLoad: {} })
Lazy loading (custom)enableLazyLoad(config)googletag.setConfig({ lazyLoad: config === undefined ? {} : config })
Geographic locationsetLocation(address)googletag.setConfig({ location: address })
SafeFrame (force)setForceSafeFrame(force)googletag.setConfig({ safeFrame: { forceSafeFrame: force } })
SafeFrame (config)setSafeFrameConfig(config)googletag.setConfig({ safeFrame: config })
Targeting (set)setTargeting(key, value)googletag.setConfig({ targeting: { [key]: value } })
Targeting (clear one key)clearTargeting(key)googletag.setConfig({ targeting: { [key]: null } })
Targeting (clear all)clearTargeting()googletag.setConfig({ targeting: null })
Video ads (enable)enableVideoAds()googletag.setConfig({ videoAds: { enableVideoAds: true } })
Video ads (content)setVideoContent(contentId, cmsId)googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: contentId, videoCmsId: cmsId } })

Page-level getters

toArray() is defined in Reading settings with getConfig.

Legacy googletag.pubads() callReplacement
get(key)googletag.getConfig('adsenseAttributes').adsenseAttributes?.[key] ?? null
getAttributeKeys()Object.keys(googletag.getConfig('adsenseAttributes').adsenseAttributes ?? {})
isInitialLoadDisabled()Boolean(googletag.getConfig('disableInitialLoad').disableInitialLoad)
getTargeting(key)toArray(googletag.getConfig('targeting').targeting?.[key])
getTargetingKeys()Object.keys(googletag.getConfig('targeting').targeting ?? {})

Slot-level mapping

Use these tables to replace deprecated googletag.Slot setters and getters with slot.setConfig() and slot.getConfig().

slot.setConfig(config: googletag.config.SlotSettingsConfig): googletag.Slot;
slot.getConfig(keys: string | string[]): Readonly<
  Pick<
    googletag.config.SlotSettingsConfig,
    'adsenseAttributes' | 'categoryExclusion' | 'targeting'
  >
>;

Slot-level setters

FeatureLegacy Slot callReplacement
AdSense attributesslot.set(key, value)slot.setConfig({ adsenseAttributes: { [key]: value } })
Category exclusion (add)slot.setCategoryExclusion(label)slot.setConfig({ categoryExclusion: [label] })
Category exclusion (clear)slot.clearCategoryExclusions()slot.setConfig({ categoryExclusion: null })
Click URL (non-SRA only)slot.setClickUrl(url)slot.setConfig({ clickUrl: url })
Collapse empty div (disabled)slot.setCollapseEmptyDiv(false) or slot.setCollapseEmptyDiv(false, true)slot.setConfig({ collapseDiv: 'DISABLED' })
Collapse empty div (on no fill)slot.setCollapseEmptyDiv(true) or slot.setCollapseEmptyDiv(true, false)slot.setConfig({ collapseDiv: 'ON_NO_FILL' })
Collapse empty div (before fetch)slot.setCollapseEmptyDiv(true, true)slot.setConfig({ collapseDiv: 'BEFORE_FETCH' })
SafeFrame (force)slot.setForceSafeFrame(force)slot.setConfig({ safeFrame: { forceSafeFrame: force } })
SafeFrame (config)slot.setSafeFrameConfig(config)slot.setConfig({ safeFrame: config })
Targeting (set)slot.setTargeting(key, value)slot.setConfig({ targeting: { [key]: value } })
Targeting (bulk map)slot.updateTargetingFromMap(map)slot.setConfig({ targeting: map })
Targeting (clear one key)slot.clearTargeting(key)slot.setConfig({ targeting: { [key]: null } })
Targeting (clear all)slot.clearTargeting()slot.setConfig({ targeting: null })

Slot-level getters

Legacy Slot callReplacement
slot.get(key)slot.getConfig('adsenseAttributes').adsenseAttributes?.[key] ?? null
slot.getAttributeKeys()Object.keys(slot.getConfig('adsenseAttributes').adsenseAttributes ?? {})
slot.getCategoryExclusions()slot.getConfig('categoryExclusion').categoryExclusion ?? []
slot.getTargeting(key)toArray(slot.getConfig('targeting').targeting?.[key])
slot.getTargetingKeys()Object.keys(slot.getConfig('targeting').targeting ?? {})
slot.getTargetingMap()slot.getConfig('targeting').targeting ?? {}

Privacy and removed APIs

Move legacy privacy setters to googletag.pubads().setPrivacySettings(), never to setConfig(). Delete calls that GPT has removed.

Legacy googletag.pubads() callReplacement
setRequestNonPersonalizedAds(0 | 1)googletag.pubads().setPrivacySettings({ nonPersonalizedAds: true | false })
setTagForChildDirectedTreatment(0 | 1)googletag.pubads().setPrivacySettings({ childDirectedTreatment: true | false })
clearTagForChildDirectedTreatment()googletag.pubads().setPrivacySettings({ childDirectedTreatment: null })
setTagForUnderAgeOfConsent(0 | 1 | -1)googletag.pubads().setPrivacySettings({ underAgeOfConsent: true | false | null })
setCookieOptions(options)Removed from GPT. Delete the call without setting cookieOptions in setConfig or setPrivacySettings.
setLocation(latitude, longitude, radius?)Removed from GPT. Delete the call. location accepts only an address string, such as '10001,US', or null.

Numeric flags map 1 to true, 0 to false, and -1 or a missing value to null. nonPersonalizedAds accepts only a boolean, so use Boolean(value). For wrappers that forward a numeric flag:

function toPrivacyFlag(value) {
  if (value === 1) return true;
  if (value === 0) return false;
  return null; // -1 or omitted
}

// Before: googletag.pubads().setTagForUnderAgeOfConsent(value);
googletag.pubads().setPrivacySettings({
  underAgeOfConsent: toPrivacyFlag(value),
});

APIs to keep unchanged

Migrate only the deprecated methods listed in the mapping tables above. Leave all other GPT and third-party calls unchanged, especially these common look-alikes:

  • googletag.pubads().setPrivacySettings(...): Keep on googletag.pubads(). googletag.setConfig({ privacyTreatments }) doesn't replace it.
  • googletag.pubads().setPublisherProvidedId(ppid): Keep on googletag.pubads(). Don't move it to googletag.setConfig().
  • googletag.setAdIframeTitle(title): Keep on googletag.
  • Third-party header bidding and non-GPT helpers: Leave calls such as pbjs.setConfig() and apstag.fetchBids() untouched, even when called through an alias.

Source and attribution

Source:google/skillsinskills/ads/google-publisher-tag-migrate-to-setconfigat commit35474ca

License: No license

Content belongs to its original authors. SourceWeft indexes it from a public repository.

Add a badge to your README

Show readers this skill is listed on SourceWeft. The badge links to this page.

Preview of the “Listed on SourceWeft” badge
[![Listed on SourceWeft](https://sourceweft.com/badge/skills/gh-google-skills-google-publisher-tag-migrate-to-setconfig-skills-ads-google-publisher-tag-migrate-to-setconfig-7771aa9da26090c4.svg)](https://sourceweft.com/skills/gh-google-skills-google-publisher-tag-migrate-to-setconfig-skills-ads-google-publisher-tag-migrate-to-setconfig-7771aa9da26090c4?utm_source=readme&utm_medium=badge)

Report or request removal

More from google/skills

Google Cloud Solution Telco Dtwin Readiness

google

Featured

Assesses telco network digital twin data readiness on Google Cloud using SDO domain alignment and a 7-pillar rubric.

Includes scripts
Data & Analytics25Kupdated today

Compute Log Troubleshooting

google

Featured

Diagnoses Google Compute Engine VM guest issues using Cloud Logging, serial console output, Cloud Monitoring and gcloud.

DevOps & Cloud25Kupdated today

Secops Siem Data Architecture

google

Featured

Designs Google SecOps SIEM data architectures: Bindplane/OTel dual replication, OTTL pipelines, retention tiering and compliance logging.

Includes scripts
Security25Kupdated today

Secops Logging Best Practices

google

Featured

Guides configuration and auditing of threat-driven event logging and priority SIEM ingestion baselines for Google SecOps.

Security25Kupdated today

Cloud Operator Admin Setup

google

Featured

Guides organization administrators through enabling, configuring and granting access to Google Cloud operator for a whole organization.

DevOps & Cloud25Kupdated today

Finding Google Skills

google

Featured

Google platform decision and setup guidance, loaded on demand from Google's skill catalog. Use when a developer is choosing or setting up part of their stack, such as where to run a service, a database, storage, messaging, authentication, analytics, ads, or AI model serving, and a Google product is a reasonable candidate - whether or not a vendor is named - or when a request names a Google product or API. Brings in the matching Google skill so the answer can weigh Google options, their trade-offs, and when they are not the right fit. Skip when the stack is already settled on another provider and no Google product is named, or the task involves no platform choice.

Awaiting classification25Kupdated today