Ad code & integration

How to add Google AdSense to an Astro site (with or without view transitions)

Last updated Published By the editorial team6 min5 sources

Key takeaways

  • In Astro, a script tag with any attribute other than src is not processed or bundled, so the AdSense code with async and crossorigin is output exactly as written.
  • Put the AdSense code in the shared layout head, between head tags, as Google instructs for every page.
  • With Astro's ClientRouter, bundled module scripts run only once and the body is replaced on navigation, so new ad slots must be pushed again from an astro:page-load listener.
  • Files in Astro's public directory are copied to the build output untouched, which makes public/ads.txt the simplest way to serve ads.txt at the site root.
  • import.meta.env.PROD is true only in production builds, which lets you keep ad requests out of local development.
HTML, PHP and Java source code displayed on a computer monitor
Image: Html php java source code (38891650224),Markus Spiske from Forchheim, Bavaria Upper Franconia,CC0,via Wikimedia Commons.

To add AdSense to Astro, render the AdSense code unprocessed in your shared layout’s <head>, create a small component that outputs the <ins> ad unit plus its push call, and serve ads.txt from public/. If you use Astro’s <ClientRouter /> for view transitions, push new slots on the astro:page-load event, because the body is swapped without a full page load.

What do you need before you start?

  • An AdSense account with your site added, and your publisher ID (ca-pub-...).
  • For manual placements, an ad unit created on the Ads page and its slot ID.
  • An Astro project with a shared layout (for example src/layouts/Base.astro).

The snippets below use ca-pub-0000000000000000 and slot 1234567890 as placeholders.

How do I add the AdSense code to the Astro head?

Google asks you to paste the AdSense code between <head> and </head>, on every page (Where to place AdSense code in your HTML). In Astro, that means the layout every page uses.

Astro bundles and transforms <script> tags by default (TypeScript, imports, type="module", deduplication). The Astro scripts guide states that “Astro will not process a <script> tag if it has any attribute other than src”, and that is:inline opts out explicitly. Third-party ad code must stay exactly as Google provides it, so use is:inline:

---
// src/layouts/Base.astro
const { title } = Astro.props;
const showAds = import.meta.env.PROD;
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{title}</title>
    {showAds && (
      <script
        is:inline
        async
        src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-0000000000000000"
        crossorigin="anonymous"
      ></script>
    )}
  </head>
  <body>
    <slot />
  </body>
</html>

import.meta.env.PROD is true in production builds and false in astro dev, per Astro’s environment variables guide. Keeping ad requests out of development avoids filling your reports with your own test impressions. If a preview deployment is built in production mode, guard it with your own variable (for example a PUBLIC_ADS_ENABLED flag) instead.

This head snippet is all Auto ads need. Turn on Auto ads for the site in AdSense and you are done; the rest of this guide is for manual units.

How do I build a reusable ad unit component?

Create a component that renders the <ins> element and the push call. Because the push script carries is:inline, Astro renders it once per component instance, which is exactly what you need: one push per slot.

---
// src/components/AdUnit.astro
interface Props {
  adSlot: string;
  format?: string;
  fullWidth?: boolean;
}
const { adSlot, format = "auto", fullWidth = true } = Astro.props;
const showAds = import.meta.env.PROD;
---
{showAds && (
  <div class="ad-slot">
    <ins
      class="adsbygoogle"
      style="display:block"
      data-ad-client="ca-pub-0000000000000000"
      data-ad-slot={adSlot}
      data-ad-format={format}
      data-full-width-responsive={fullWidth ? "true" : "false"}
    ></ins>
    <script is:inline>
      (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
  </div>
)}

<style>
  .ad-slot { min-height: 280px; }
</style>

Use it in a page or another layout:

---
import Base from "../layouts/Base.astro";
import AdUnit from "../components/AdUnit.astro";
---
<Base title="My article">
  <article>
    <p>Intro paragraph...</p>
    <AdUnit adSlot="1234567890" />
    <p>More content...</p>
  </article>
</Base>

Notes on this component:

  • The attribute values (data-ad-format, data-full-width-responsive) are the ones Google documents for responsive units. See responsive ad units for the allowed values.
  • The min-height on the wrapper reserves space so the ad does not push content down when it loads. Pick a value that matches the size you expect on your layout; reserving space for ads explains the trade-offs.
  • Astro scopes the <style> to the component, so .ad-slot will not leak into other elements.
  • Do not set display:none on the <ins> to hide it conditionally. Google’s code modification policy lists hiding ad units at any time as not permitted, with a separate exception for responsive units hidden through media queries.

How do AdSense ads behave with Astro view transitions?

By default, Astro uses normal full-page navigation, and the setup above works unchanged. Things change when you add <ClientRouter /> from astro:transitions, which turns the site into a client-side routed app. The view transitions docs describe what happens on navigation:

  • The <head> is swapped, but scripts that exist on the new page are left in place. The AdSense library is therefore not loaded twice.
  • The <body> is completely replaced by the new page’s body. Your old ad slots are gone and the new page arrives with new, empty <ins> elements.
  • Bundled module scripts “are only ever executed once”. Inline scripts may or may not run again, depending on the page history.
  • astro:page-load fires “both on initial page navigation for a pre-rendered page and on any subsequent navigation”.

The robust pattern is to stop relying on per-slot inline scripts and push from one listener. Remove the inline <script> from AdUnit.astro and add this bundled script to the layout:

<script>
  document.addEventListener("astro:page-load", () => {
    const slots = document.querySelectorAll(
      "ins.adsbygoogle:not([data-adsbygoogle-status])"
    );
    slots.forEach(() => {
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    });
  });
</script>

data-adsbygoogle-status is the attribute the ad code sets on slots it has processed (Google’s data-ad-status article mentions it as used “for ads processing purposes”), so the selector counts only new slots. Each push({}) fills the next empty <ins>.

If you prefer to keep inline scripts, Astro also offers data-astro-rerun to force an inline script to run after every transition. It works, but one listener is easier to reason about than many inline scripts.

What about Auto ads with ClientRouter?

Google does not document how Auto ads react to client-side navigation in a framework router. Auto ads analyze a page when it loads. With ClientRouter, the browser never loads a new document, so do not assume Auto ads re-scan each swapped page. If Auto ads matter more to you than animations, the simplest options are to skip <ClientRouter />, use browser-native cross-document view transitions (which Astro’s docs note do not alter how an MPA loads scripts), or force full navigation on specific links with data-astro-reload. The single-page apps guide covers the same issue for React, Vue and Svelte.

How do I serve ads.txt from Astro?

Put the file at public/ads.txt:

google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0

Astro’s project structure docs say files in public/ “will be copied into the build folder untouched”, which is what makes it suitable for robots.txt and similar root files. After deploying, open https://your-domain/ads.txt and confirm you get the plain text line, not an HTML page. Host-specific caveats (redirects, trailing slashes, caching) are in ads.txt on static hosts and CDNs.

Troubleshooting

Symptom Likely cause Fix
Script tag appears with type="module" or a hashed file name Astro processed it Add is:inline and keep the original attributes
Ads show on first page, blank after clicking a link ClientRouter swapped the body, nobody pushed the new slots Use the astro:page-load listener above
Console: “adsbygoogle.push() error: All ‘ins’ elements in the DOM with class=adsbygoogle already have ads in them.” More push() calls than empty slots, often an inline push script running again Push only for unprocessed slots, or remove duplicate inline scripts
Console: “No slot size for availableWidth=0” The slot’s container has no width when the push runs (hidden, collapsed, inside a closed tab) Make sure the container is visible and has a width when you push
Ads in astro dev but not in production, or the reverse Environment guard Check import.meta.env.PROD and any custom flag
/ads.txt returns your 404 page File not in public/, or a host rewrite Move it to public/ads.txt and check host redirects

Is this approach policy-safe?

Yes, as long as you keep the code as Google provides it. The snippets above only move the AdSense code into a layout, wrap the <ins> in a container and use the same push call Google generates. The code modification policy allows changes needed for a clean user experience and responsive sizing via CSS; it forbids changes that artificially inflate ad performance, hiding units, and covering content. For a site-wide view of approval on static builds, read AdSense on static and Jamstack sites.

Frequently asked questions

Do I need is:inline on the AdSense script in Astro?

Not strictly. Astro's docs say it does not process a script tag that has any attribute other than src, and the AdSense code already has async and crossorigin. Adding is:inline makes the intent explicit and protects you if someone later strips attributes. Either way, the tag is rendered exactly as written, which is what you want for third-party ad code.

Why do my AdSense ads disappear after navigating with view transitions?

With Astro's ClientRouter, the body is replaced on each navigation and bundled scripts run only once. The new page contains fresh ins elements that nobody has pushed. Listen for the astro:page-load event, which fires on the first load and after every navigation, and call adsbygoogle.push once for each ins element that the ad library has not processed yet.

Where do I put ads.txt in an Astro project?

Put it in the public folder as public/ads.txt. Astro copies everything in public to the build output untouched, so the file is served at /ads.txt on your domain. Check it after deploy by opening https://yourdomain/ads.txt in a browser and confirming it returns the plain text line, not your 404 page.

Can I wrap the AdSense script in an Astro component or bundle it?

You can render it from a component, but do not bundle or rewrite the library. Load adsbygoogle.js from Google's URL exactly as provided. AdSense's code modification policy forbids changes that artificially inflate ad performance, so keep the provided attributes and only make changes Google documents, such as CSS sizing for responsive units.

Sources

  1. Scripts and event handling · Astro Docs
  2. View transitions · Astro Docs
  3. Project structure · Astro Docs
  4. Where to place AdSense code in your HTML · Google AdSense Help
  5. Modifications of AdSense ad code · Google AdSense Help