Partytown Implementation Not Working Correctly in Astro.js Project

368 views Asked by At

I'm encountering issues with Partytown integration in my Astro.js project hosted on Vercel. The setup involves proxying requests to Google Analytics and Google Tag Manager. However, the integration doesn't seem to work as expected, and Google Tag Assistant shows "0 tags found."

Steps Taken:

  • Followed the official Astro.js Partytown integration guide.
  • Due to CORS errors, I implemented a proxy following the guidelines from partytown.builder.io.
  • Incorporated Partytown in my astro.config.js with the defined resolveUrl for proxying Google Analytics and Google Tag Manager requests.

Code Snippet (GoogleAnalytics.astro):

<script
  type="text/partytown"
  src="https://www.googletagmanager.com/gtag/js?id=G-ID"></script>

<script type="text/partytown">
window.dataLayer = window.dataLayer || []

function gtag() {
  dataLayer.push(arguments)
}

gtag('js', new Date())
gtag('config', 'G-ID', {
  page_path: window.location.pathname
})
</script>

Astro Configuration (astro.config.js):

import { defineConfig } from 'astro/config'
import partytown from '@astrojs/partytown'

// Other configurations...

export default defineConfig({
  output: 'server',
  integrations: [
    // ... Other integrations ...
    partytown({
      config: {
        forward: ['dataLayer.push'],
        resolveUrl: (url) => {
          const siteUrl = 'https://site-url/proxytown'

          if (url.hostname === 'www.googletagmanager.com') {
            const proxyUrl = new URL(`${siteUrl}/gtm`)
            const gtmId = new URL(url).searchParams.get('id')
            if (gtmId) {
              proxyUrl.searchParams.append('id', gtmId)
            }
            return proxyUrl
          } else if (url.hostname === 'www.google-analytics.com') {
            const proxyUrl = new URL(`${siteUrl}/ga`)
            return proxyUrl
          }

          return url
        }
      }
    }),
  ],
  // Other configurations...
})

Vercel Configuration (vercel.json):

{
  "rewrites": [
    {
      "source": "/proxytown/gtm",
      "destination": "https://www.googletagmanager.com/gtag/js"
    },
    {
      "source": "/proxytown/ga",
      "destination": "https://www.google-analytics.com/analytics.js"
    }
  ]
}

Note: Without using the type="text/partytown" attribute in the script tag, the integration works as expected. This suggests that the issue might be related to how Partytown is configured in my Astro.js project.

Any help, advice, or insights on resolving this issue would be highly appreciated. Thanks.

0

There are 0 answers