google publisher tag migrate to setconfig
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, e
Documentation & Preview
--- name: google-publisher-tag-migrate-to-setconfig description: >- 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. metadata: version: "1.0.0" publisher: google category: GoogleAds
---
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_modulesexists, 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.pushcallback 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 acrosscmd.pushblocks
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:
Setting | Separate calls | Clear one entry | Clear everything :------------------------------- | :---------------------------------------------- | :---------------- | :--------------- targeting, adsenseAttributes | Merge keys | { [key]: null } | null categoryExclusion | Append unique non-empty labels; [] is a no-op | Not supported | null
- Merge adjacent
setCategoryExclusioncalls or loops into one array. - When legacy code clears and then re-adds, clear with
nullin 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()andsetSafeFrameConfig()become onesafeFrame
object. Drop useUniqueDomain, which GPT ignores. Drop sandbox: false, because sandbox accepts only true or null.
enableVideoAds()andsetVideoContent()become onevideoAdsobject.
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
configmay beundefined, default it to{}. - In wrappers where
configisnull, keep itnullto clear the lazy-load
setting.
- Replace
-1withnullinfetchMarginPercent,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()supportsadsenseAttributes,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 returnedstring[], 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()anddefineOutOfPageSlot()returnSlot | null. Check the
slot before calling slot.setConfig().
- Keep the keys of existing
setConfig()calls when merging in new settings. - Rename deprecated `adYiel