Set-Cookie response header doesn't set a cookie (GTM server-side implementation)

151 views Asked by At

I'm trying to set a cookie with the response from my server-side GTM container.

My setup:

  1. Custom HTML tag on client-side GTM:
<script>
  fetch('{{sst address}}', {
    method: 'POST',
    headers: {
      'content-type': 'application/json; charset=utf-8',
      'x-gtm-server-preview': '{{sst preview}}'
    },
    body: JSON.stringify({
      "events": [{  
        "event_name": "{{Event}}"
      }]
    })
  });
</script>

  1. Two requests are being sent:
  1. Server-Side container set up on the same domain (sing.eventless.org) handles CORS headers + adds 'Set-Cookie' in the response: Response Headers screenshot

  2. The cookie is visible in the Request explorer but not in the Application tab (also in Safari the cookie is no being created):

  1. For the comparison, I set up also a regular Google Tag for GA4 which also sets cookie and then it sets correctly doing exactly the same (Set-Cookie in the response header): cookie set correctly with the GA4 request screenshot

You can replicate it on your side at eventless.org using Chrome dev tools.

Why the cookie is not being set?

I tried:

  • Sending the same request from Postman - It works there...
  • Changing name/value of the cookie
  • Manipulating the SameSite, Domain, Expiration and HttpOnly parameters
  • Chaning URLs and paths
  • Disabling / enabling cashing
1

There are 1 answers

0
Mariusz Brucki On

I found a solution. In the first tag - from the client-side GTM, there should be added credentials:

<script>
  fetch('{{sst address}}', {
    method: 'POST',
    headers: {
      'content-type': 'application/json; charset=utf-8',
      'x-gtm-server-preview': '{{sst preview}}'
    },
    credentials: 'include',
    body: JSON.stringify({
      "events": [{  
        "event_name": "{{Event}}"
      }]
    })
  });
</script>