October 04, 2021

POST requests with fetch() in a GTM Custom Template

by Justus

Custom Tag Templates in your client side Google Tag Manager are super versatile. The sandboxed JavaScript they offer is usually enough for most usecases, even for things like outgoing HTTP requests with sendPixel.
Unfortunately sendPixel only supports GET requests which doesn’t cut it if your data recipient requires a POST request.

There’s also no dedicated function for POST request listed in the Templates API docs.

Doesn’t work: callInWindow('fetch', …)

The easiest way would be to simply call window.fetch through the callInWindow function. But it’s the Permissions setting that doesn’t allow for access to predefined window attributes.
If you try and save the template, you’ll get an error:

A screenshot of the Permissions tab in the Template editor that reads 'The value must not start with any key predefined on global scope (i.e. in Window), or any JavaScript keywords.'

Workaround: Supply a fetch reference through a GTM JavaScript Variable

To start off, create a Google Tag Manager Variable of the type JavaScript Variable (not to be confused with Custom JavaScript Variables):

A screenshot of a GTM variable of type 'JavaScript Variable' with the name 'js.fetch'

That’s our reference to window.fetch which we now just have to get into the instance of the Custom Tag Template.
On your template, create a new field of the type Text Input. I called it fetchReference:

A screenshot of the Custom Tag Template editor with a field named 'fetchReference'

Inside your Tag Template’s code you can then use fetch through data.fetchReference like you normally would:

const JSON = require('JSON');
const fetch = data.fetchReference;
const myData = { someKey: "someValue" };

fetch("//", {
  method: "POST",
  body: JSON.stringify(myData)
.then(() => {
  // Call data.gtmOnSuccess when the tag is finished.

Lastly, make sure the tag that’s based on your tag template references the js.fetch variable and you’re good to go:

A screenshot of a tag instance

Did this article help you?

Then follow me on twitter
so you won't miss new articles here and for Web Analytics and Marketing technology updates in general :)