1
---
2
name: google-publisher-tag-migrate-to-setconfig
3
description: >-
4
Migrates web publisher JavaScript and TypeScript code from deprecated Google
5
Publisher Tag (GPT) setter and getter methods on googletag.pubads() and
6
googletag.Slot to setConfig() and getConfig(). Use when auditing, updating, or
7
refactoring GPT or googletag code in web scripts, ad wrappers, or frontend
8
components to replace deprecated configuration APIs (such as setTargeting,
9
clearTargeting, updateTargetingFromMap, collapseEmptyDivs,
10
setCollapseEmptyDiv, enableSingleRequest, disableInitialLoad, enableLazyLoad,
11
setSafeFrameConfig, setForceSafeFrame, setCategoryExclusion,
12
clearCategoryExclusions, setVideoContent, setLocation, setCookieOptions,
13
setRequestNonPersonalizedAds, or getTargeting). Don't use for non-GPT ad
14
server integrations.
15
metadata:
16
version: "1.0.0"
17
publisher: google
18
category: GoogleAds
19
---
20
21
# Migrate Google Publisher Tag configuration to setConfig and getConfig
22
23
Replace deprecated Google Publisher Tag (GPT) setters and getters on
24
`googletag.pubads()` and `googletag.Slot` with `setConfig()` and `getConfig()`
25
without changing ad request behavior. This skill is the complete reference for
26
GPT `setConfig` and `getConfig` mappings and validation rules, so you don't
27
need to search the web.
28
29
## Workflow
30
31
Batch edits per file and validate once at the end.
32
33
- [ ] **1. Update TypeScript types in TypeScript projects.** Update
34
`@types/google-publisher-tag` to the latest release in `package.json`, and
35
update local `googletag` or `Slot` interfaces to declare `setConfig` and
36
`getConfig`. Run a package-manager install only if `node_modules` already
37
exists, because sandboxed environments are often offline.
38
- [ ] **2. Inventory GPT calls in a single pass.** Read named files directly.
39
For a directory, search for `googletag` to find entry points, then follow
40
where `Slot` and `PubAdsService` objects are passed. Sort what you find into
41
deprecated setters and getters, existing `setConfig` calls whose keys must
42
be preserved, [privacy and removed APIs](#privacy-and-removed-apis), and
43
[APIs to keep unchanged](#apis-to-keep-unchanged).
44
- [ ] **3. Migrate page-level setters.** Use the
45
[page-level setters](#page-level-setters) and
46
[privacy and removed APIs](#privacy-and-removed-apis) tables with the
47
[migration rules](#migration-rules).
48
- [ ] **4. Migrate slot-level setters.** Use the
49
[slot-level setters](#slot-level-setters) table with the
50
[migration rules](#migration-rules).
51
- [ ] **5. Migrate getters and feature checks.** Use the
52
[page-level getters](#page-level-getters) and
53
[slot-level getters](#slot-level-getters) tables. Remove legacy fallback
54
branches and change feature checks to test for `getConfig`.
55
- [ ] **6. Validate.**
56
- If `node_modules` exists, run the project's existing checks. For
57
standalone files without a test suite, run `node --check {file_path}`
58
and review your diff instead of writing ad-hoc test scripts.
59
- When browser or E2E tests run live `gpt.js`, read the console output.
60
Invalid `setConfig` and `getConfig` properties don't throw. GPT logs a
61
warning and ignores them.
62
- If a check fails or logs GPT console warnings, fix the code and run it
63
again.
64
65
## Migration rules
66
67
### Page settings: one call on googletag
68
69
Page-level `setConfig` and `getConfig` exist only on `googletag`.
70
`PubAdsService` has no `setConfig`, so `googletag.pubads().setConfig()` throws a
71
`TypeError`, including through an alias such as
72
`const pubadsService = googletag.pubads()`.
73
74
- Merge page settings from the same `googletag.cmd.push` callback or function
75
into one `googletag.setConfig()` call before `googletag.enableServices()`,
76
even when other calls such as `defineSlot` sit between them.
77
- Don't merge across separate `<script>` tags, or across `cmd.push` blocks
78
split by async header-bidding calls. They run at different times.
79
- Replace detached method references too, such as
80
`const clear = pubads.clearTargeting` or
81
`labels.forEach(pubads.setCategoryExclusion)`.
82
83
```js
84
// Before
85
googletag.cmd.push(() => {
86
const pubads = googletag.pubads();
87
pubads.enableSingleRequest();
88
googletag.defineSlot('/1234/banner', [728, 90], 'banner')
89
?.addService(pubads);
90
pubads.collapseEmptyDivs();
91
['politics', 'gambling'].forEach(pubads.setCategoryExclusion);
92
googletag.enableServices();
93
});
94
95
// After
96
googletag.cmd.push(() => {
97
googletag.setConfig({
98
singleRequest: true,
99
collapseDiv: 'ON_NO_FILL',
100
categoryExclusion: ['politics', 'gambling'],
101
});
102
googletag.defineSlot('/1234/banner', [728, 90], 'banner')
103
?.addService(googletag.pubads());
104
googletag.enableServices();
105
});
106
```
107
108
### Merging and clearing collections
109
110
Separate `setConfig` calls update collection settings instead of replacing them:
111
112
Setting | Separate calls | Clear one entry | Clear everything
113
:------------------------------- | :---------------------------------------------- | :---------------- | :---------------
114
`targeting`, `adsenseAttributes` | Merge keys | `{ [key]: null }` | `null`
115
`categoryExclusion` | Append unique non-empty labels; `[]` is a no-op | Not supported | `null`
116
117
- Merge adjacent `setCategoryExclusion` calls or loops into one array.
118
- When legacy code clears and then re-adds, clear with `null` in its own call
119
first. Otherwise stale keys and labels survive. This applies to
120
`clearTargeting()` followed by `setTargeting()` or
121
`updateTargetingFromMap()`, and to `clearCategoryExclusions()` followed by
122
`setCategoryExclusion()`.
123
124
```js
125
// Before
126
slot.clearTargeting();
127
slot.updateTargetingFromMap({ pos: 'top', section: 'news' });
128
slot.clearCategoryExclusions();
129
labels.forEach((label) => slot.setCategoryExclusion(label));
130
131
// After
132
slot.setConfig({ targeting: null });
133
slot.setConfig({ targeting: { pos: 'top', section: 'news' } });
134
slot.setConfig({ categoryExclusion: null });
135
if (labels.length > 0) {
136
slot.setConfig({ categoryExclusion: labels });
137
}
138
```
139
140
### SafeFrame and video ads
141
142
Merge related legacy calls on the same page or slot into one sub-object.
143
144
- `setForceSafeFrame()` and `setSafeFrameConfig()` become one `safeFrame`
145
object. Drop `useUniqueDomain`, which GPT ignores. Drop `sandbox: false`,
146
because `sandbox` accepts only `true` or `null`.
147
- `enableVideoAds()` and `setVideoContent()` become one `videoAds` object.
148
Always include `enableVideoAds: true`, even for a standalone
149
`setVideoContent()` call, because `VideoAdsConfig` requires it.
150
151
```js
152
// Before
153
pubads.setForceSafeFrame(true);
154
pubads.setSafeFrameConfig({
155
allowOverlayExpansion: false,
156
useUniqueDomain: true,
157
sandbox: false,
158
});
159
pubads.setVideoContent('content-id', 'cms-id');
160
161
// After
162
googletag.setConfig({
163
safeFrame: { forceSafeFrame: true, allowOverlayExpansion: false },
164
videoAds: {
165
enableVideoAds: true,
166
videoContentId: 'content-id',
167
videoCmsId: 'cms-id',
168
},
169
});
170
```
171
172
### Collapsing empty divs
173
174
The legacy boolean means different things at page and slot level:
175
176
- Page-level `collapseEmptyDivs(false)` still collapses on no fill, so it maps
177
to `'ON_NO_FILL'`, never `'DISABLED'`.
178
- Slot-level `setCollapseEmptyDiv(false)` turns collapsing off, so it maps to
179
`'DISABLED'`.
180
181
The setter tables list every form. When a slot call is conditional, keep the
182
condition and don't add an `else` branch that sets `'DISABLED'`. The slot then
183
inherits the page setting:
184
185
```js
186
// Before
187
if (collapseBeforeFetch) slot.setCollapseEmptyDiv(true, true);
188
189
// After: no 'DISABLED' fallback branch
190
if (collapseBeforeFetch) slot.setConfig({ collapseDiv: 'BEFORE_FETCH' });
191
```
192
193
### Lazy loading
194
195
`setConfig` rejects top-level properties set to `undefined`, and legacy
196
lazy-load configs used `-1` to mean "unset".
197
198
- In wrappers where `config` may be `undefined`, default it to `{}`.
199
- In wrappers where `config` is `null`, keep it `null` to clear the lazy-load
200
setting.
201
- Replace `-1` with `null` in `fetchMarginPercent`, `renderMarginPercent`, and
202
`mobileScaling` directly at call sites instead of adding a runtime helper.
203
204
```js
205
// Before
206
googletag.pubads().enableLazyLoad({
207
fetchMarginPercent: 300,
208
renderMarginPercent: -1,
209
});
210
googletag.pubads().enableLazyLoad(config);
211
212
// After
213
googletag.setConfig({
214
lazyLoad: {
215
fetchMarginPercent: 300,
216
renderMarginPercent: null,
217
},
218
});
219
googletag.setConfig({ lazyLoad: config === undefined ? {} : config });
220
```
221
222
### Dynamic targeting
223
224
`setConfig` validates `targeting` as
225
`Record<string, string | string[] | null> | null`. It rejects empty or
226
whitespace keys, `undefined`, numbers, booleans, and nested arrays.
227
228
`null` also changes meaning. Legacy `setTargeting(key, null)` was ignored, but
229
`{ [key]: null }` deletes the key, and `String(null)` sends `'null'`.
230
231
When `slot.updateTargetingFromMap(map)` receives a map that already holds valid
232
`string`, `string[]`, or `null` values, pass it straight to
233
`slot.setConfig({ targeting: map })`. Don't wrap it in a sanitizer. Maps that
234
the caller builds and controls fit this case, such as header-bidding targeting
235
maps and `{ [key]: null }` maps that reset keys on purpose.
236
237
```js
238
// Before
239
slot.updateTargetingFromMap(bidTargeting);
240
slot.updateTargetingFromMap({ pos: null, section: null });
241
242
// After
243
slot.setConfig({ targeting: bidTargeting });
244
slot.setConfig({ targeting: { pos: null, section: null } });
245
```
246
247
Sanitize only when the source can hold numbers, booleans, `undefined`, or
248
nested arrays. That usually means `setTargeting()` calls with variable keys or
249
values, including loops over `Object.entries` or `Object.keys`. Build a clean
250
object instead of passing the source through:
251
252
```ts
253
// Before
254
for (const [key, value] of Object.entries(params)) {
255
googletag.pubads().setTargeting(key, value);
256
}
257
258
// After
259
const targeting: Record<string, string | string[]> = {};
260
for (const [key, value] of Object.entries(params)) {
261
if (!key.trim() || value == null) continue; // Skip, don't delete.
262
if (Array.isArray(value)) {
263
const values = value.flat(Infinity).filter((v) => v != null).map(String);
264
if (values.length > 0) targeting[key] = values;
265
} else {
266
targeting[key] = String(value);
267
}
268
}
269
if (Object.keys(targeting).length > 0) {
270
googletag.setConfig({ targeting });
271
}
272
```
273
274
To clean an untyped `updateTargetingFromMap` map, use the same loop, but copy
275
explicit `null` values through unchanged instead of skipping them. That way,
276
intentional resets still delete their keys.
277
278
### Reading settings with getConfig
279
280
- `googletag.getConfig()` supports `adsenseAttributes`, `disableInitialLoad`,
281
and `targeting`. `slot.getConfig()` supports `adsenseAttributes`,
282
`categoryExclusion`, and `targeting`. Every other setting is write-only.
283
- `getConfig()` returns a deeply frozen object keyed by setting name, never a
284
flat map, so don't mutate it. `getConfig('targeting')` returns
285
`{ targeting: { ... } }`, which replaces loops over `getTargetingKeys()`
286
and `getTargeting(key)`.
287
- Legacy `getTargeting(key)` always returned `string[]`, or `[]` when unset.
288
`getConfig('targeting').targeting?.[key]` is typed as
289
`string | string[] | null | undefined`, so normalize it before calling array
290
methods such as `.includes()`, `.map()`, or `.length`:
291
292
```ts
293
function toArray(value: string | string[] | null | undefined): string[] {
294
if (Array.isArray(value)) return value;
295
return value == null ? [] : [value];
296
}
297
298
const sections = toArray(slot.getConfig('targeting').targeting?.['section']);
299
```
300
301
### Slot null checks and existing config
302
303
- `defineSlot()` and `defineOutOfPageSlot()` return `Slot | null`. Check the
304
slot before calling `slot.setConfig()`.
305
- Keep the keys of existing `setConfig()` calls when merging in new settings.
306
- Rename deprecated `adYield` to `threadYield` if it appears in
307
`googletag.setConfig()`.
308
309
## Page-level mapping
310
311
Use these tables to replace deprecated `googletag.pubads()` setters and getters
312
with `googletag.setConfig()` and `googletag.getConfig()`.
313
314
```ts
315
googletag.setConfig(config: googletag.config.PageSettingsConfig): void;
316
googletag.getConfig(keys: string | string[]): Readonly<
317
Pick<
318
googletag.config.PageSettingsConfig,
319
'adsenseAttributes' | 'disableInitialLoad' | 'targeting'
320
>
321
>;
322
```
323
324
### Page-level setters
325
326
Feature | Legacy `googletag.pubads()` call | Replacement
327
:--------------------------------- | :-------------------------------------------------- | :----------
328
AdSense attributes | `set(key, value)` | `googletag.setConfig({ adsenseAttributes: { [key]: value } })`
329
Category exclusion (add) | `setCategoryExclusion(label)` | `googletag.setConfig({ categoryExclusion: [label] })`
330
Category exclusion (clear) | `clearCategoryExclusions()` | `googletag.setConfig({ categoryExclusion: null })`
331
Centering | `setCentering(isCentered)` | `googletag.setConfig({ centering: isCentered })`
332
Collapse empty divs (on no fill) | `collapseEmptyDivs()` or `collapseEmptyDivs(false)` | `googletag.setConfig({ collapseDiv: 'ON_NO_FILL' })`
333
Collapse empty divs (before fetch) | `collapseEmptyDivs(true)` | `googletag.setConfig({ collapseDiv: 'BEFORE_FETCH' })`
334
Initial load | `disableInitialLoad()` | `googletag.setConfig({ disableInitialLoad: true })`
335
Single Request Architecture | `enableSingleRequest()` | `googletag.setConfig({ singleRequest: true })`
336
Lazy loading (defaults) | `enableLazyLoad()` | `googletag.setConfig({ lazyLoad: {} })`
337
Lazy loading (custom) | `enableLazyLoad(config)` | `googletag.setConfig({ lazyLoad: config === undefined ? {} : config })`
338
Geographic location | `setLocation(address)` | `googletag.setConfig({ location: address })`
339
SafeFrame (force) | `setForceSafeFrame(force)` | `googletag.setConfig({ safeFrame: { forceSafeFrame: force } })`
340
SafeFrame (config) | `setSafeFrameConfig(config)` | `googletag.setConfig({ safeFrame: config })`
341
Targeting (set) | `setTargeting(key, value)` | `googletag.setConfig({ targeting: { [key]: value } })`
342
Targeting (clear one key) | `clearTargeting(key)` | `googletag.setConfig({ targeting: { [key]: null } })`
343
Targeting (clear all) | `clearTargeting()` | `googletag.setConfig({ targeting: null })`
344
Video ads (enable) | `enableVideoAds()` | `googletag.setConfig({ videoAds: { enableVideoAds: true } })`
345
Video ads (content) | `setVideoContent(contentId, cmsId)` | `googletag.setConfig({ videoAds: { enableVideoAds: true, videoContentId: contentId, videoCmsId: cmsId } })`
346
347
### Page-level getters
348
349
`toArray()` is defined in
350
[Reading settings with getConfig](#reading-settings-with-getconfig).
351
352
Legacy `googletag.pubads()` call | Replacement
353
:------------------------------- | :----------
354
`get(key)` | `googletag.getConfig('adsenseAttributes').adsenseAttributes?.[key] ?? null`
355
`getAttributeKeys()` | `Object.keys(googletag.getConfig('adsenseAttributes').adsenseAttributes ?? {})`
356
`isInitialLoadDisabled()` | `Boolean(googletag.getConfig('disableInitialLoad').disableInitialLoad)`
357
`getTargeting(key)` | `toArray(googletag.getConfig('targeting').targeting?.[key])`
358
`getTargetingKeys()` | `Object.keys(googletag.getConfig('targeting').targeting ?? {})`
359
360
## Slot-level mapping
361
362
Use these tables to replace deprecated `googletag.Slot` setters and getters with
363
`slot.setConfig()` and `slot.getConfig()`.
364
365
```ts
366
slot.setConfig(config: googletag.config.SlotSettingsConfig): googletag.Slot;
367
slot.getConfig(keys: string | string[]): Readonly<
368
Pick<
369
googletag.config.SlotSettingsConfig,
370
'adsenseAttributes' | 'categoryExclusion' | 'targeting'
371
>
372
>;
373
```
374
375
### Slot-level setters
376
377
Feature | Legacy `Slot` call | Replacement
378
:-------------------------------- | :--------------------------------------------------------------------------- | :----------
379
AdSense attributes | `slot.set(key, value)` | `slot.setConfig({ adsenseAttributes: { [key]: value } })`
380
Category exclusion (add) | `slot.setCategoryExclusion(label)` | `slot.setConfig({ categoryExclusion: [label] })`
381
Category exclusion (clear) | `slot.clearCategoryExclusions()` | `slot.setConfig({ categoryExclusion: null })`
382
Click URL (non-SRA only) | `slot.setClickUrl(url)` | `slot.setConfig({ clickUrl: url })`
383
Collapse empty div (disabled) | `slot.setCollapseEmptyDiv(false)` or `slot.setCollapseEmptyDiv(false, true)` | `slot.setConfig({ collapseDiv: 'DISABLED' })`
384
Collapse empty div (on no fill) | `slot.setCollapseEmptyDiv(true)` or `slot.setCollapseEmptyDiv(true, false)` | `slot.setConfig({ collapseDiv: 'ON_NO_FILL' })`
385
Collapse empty div (before fetch) | `slot.setCollapseEmptyDiv(true, true)` | `slot.setConfig({ collapseDiv: 'BEFORE_FETCH' })`
386
SafeFrame (force) | `slot.setForceSafeFrame(force)` | `slot.setConfig({ safeFrame: { forceSafeFrame: force } })`
387
SafeFrame (config) | `slot.setSafeFrameConfig(config)` | `slot.setConfig({ safeFrame: config })`
388
Targeting (set) | `slot.setTargeting(key, value)` | `slot.setConfig({ targeting: { [key]: value } })`
389
Targeting (bulk map) | `slot.updateTargetingFromMap(map)` | `slot.setConfig({ targeting: map })`
390
Targeting (clear one key) | `slot.clearTargeting(key)` | `slot.setConfig({ targeting: { [key]: null } })`
391
Targeting (clear all) | `slot.clearTargeting()` | `slot.setConfig({ targeting: null })`
392
393
### Slot-level getters
394
395
Legacy `Slot` call | Replacement
396
:----------------------------- | :----------
397
`slot.get(key)` | `slot.getConfig('adsenseAttributes').adsenseAttributes?.[key] ?? null`
398
`slot.getAttributeKeys()` | `Object.keys(slot.getConfig('adsenseAttributes').adsenseAttributes ?? {})`
399
`slot.getCategoryExclusions()` | `slot.getConfig('categoryExclusion').categoryExclusion ?? []`
400
`slot.getTargeting(key)` | `toArray(slot.getConfig('targeting').targeting?.[key])`
401
`slot.getTargetingKeys()` | `Object.keys(slot.getConfig('targeting').targeting ?? {})`
402
`slot.getTargetingMap()` | `slot.getConfig('targeting').targeting ?? {}`
403
404
## Privacy and removed APIs
405
406
Move legacy privacy setters to `googletag.pubads().setPrivacySettings()`, never
407
to `setConfig()`. Delete calls that GPT has removed.
408
409
Legacy `googletag.pubads()` call | Replacement
410
:------------------------------------------ | :----------
411
`setRequestNonPersonalizedAds(0 \| 1)` | `googletag.pubads().setPrivacySettings({ nonPersonalizedAds: true \| false })`
412
`setTagForChildDirectedTreatment(0 \| 1)` | `googletag.pubads().setPrivacySettings({ childDirectedTreatment: true \| false })`
413
`clearTagForChildDirectedTreatment()` | `googletag.pubads().setPrivacySettings({ childDirectedTreatment: null })`
414
`setTagForUnderAgeOfConsent(0 \| 1 \| -1)` | `googletag.pubads().setPrivacySettings({ underAgeOfConsent: true \| false \| null })`
415
`setCookieOptions(options)` | Removed from GPT. Delete the call without setting `cookieOptions` in `setConfig` or `setPrivacySettings`.
416
`setLocation(latitude, longitude, radius?)` | Removed from GPT. Delete the call. `location` accepts only an address string, such as `'10001,US'`, or `null`.
417
418
Numeric flags map `1` to `true`, `0` to `false`, and `-1` or a missing value to
419
`null`. `nonPersonalizedAds` accepts only a boolean, so use `Boolean(value)`.
420
For wrappers that forward a numeric flag:
421
422
```js
423
function toPrivacyFlag(value) {
424
if (value === 1) return true;
425
if (value === 0) return false;
426
return null; // -1 or omitted
427
}
428
429
// Before: googletag.pubads().setTagForUnderAgeOfConsent(value);
430
googletag.pubads().setPrivacySettings({
431
underAgeOfConsent: toPrivacyFlag(value),
432
});
433
```
434
435
## APIs to keep unchanged
436
437
Migrate only the deprecated methods listed in the mapping tables above. Leave
438
all other GPT and third-party calls unchanged, especially these common
439
look-alikes:
440
441
- `googletag.pubads().setPrivacySettings(...)`: Keep on `googletag.pubads()`.
442
`googletag.setConfig({ privacyTreatments })` doesn't replace it.
443
- `googletag.pubads().setPublisherProvidedId(ppid)`: Keep on
444
`googletag.pubads()`. Don't move it to `googletag.setConfig()`.
445
- `googletag.setAdIframeTitle(title)`: Keep on `googletag`.
446
- Third-party header bidding and non-GPT helpers: Leave calls such as
447
`pbjs.setConfig()` and `apstag.fetchBids()` untouched, even when called
448
through an alias.
449