0

Question:

I'm trying to add Google Analytics to my website built with the Astro Starlight theme. However, the theme doesn't have a layouts or components folder, which is where most tutorials suggest placing the tracking code.

Here are the steps I've taken so far:

Obtained my Google Analytics tracking ID (e.g., UA-XXXXX-Y). Tried to locate files in the theme where I can insert the tracking code. The structure of the Astro Starlight theme is different from what I'm used to, and I'm not sure where to add the Google Analytics tracking script.

Can anyone guide me on how to properly integrate Google Analytics with the Astro Starlight theme?

Additional Information:

I'm using the latest version of the Astro Starlight theme. The theme doesn't have obvious layouts or components directories. I need a way to include the tracking code in a way that works with this specific theme structure. Thanks in advance for your help!

2 Answers 2

0

The Starlight docs have this example of the head config field. Put the following into astro.config.mjs:

import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
  integrations: [
    starlight({
      head: [
        // Example: add Fathom analytics script tag.
        {
          tag: 'script',
          attrs: {
            src: 'https://cdn.usefathom.com/script.js',
            'data-site': 'MY-FATHOM-ID',
            defer: true,
          },
        },
      ],
    }),
  ],
});

which will put the following HTML in the document's <head>:

<script
  src="https://cdn.usefathom.com/script.js" 
  data-site="MY-FATHOM-ID"
  defer
  >
</script>

Adjust accordingly for Google Analytics.

0
0

I added the following but couldnt get it to work.

head: [
                // Add Google Analytics script tag.
                {
                  tag: 'script',
                  attrs: {
                    async: true,
                    src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX',
                  },
                },
                {
                  tag: 'script',
                  children: `
                    window.dataLayer = window.dataLayer || [];
                    function gtag(){dataLayer.push(arguments);}
                    gtag('js', new Date());
                    gtag('config', 'G-XXXXXXXX');
                  `,
                },
                // end of Google Analytics script tag.
1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jun 23 at 18:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.