Astro Partytown support comes from the official @astrojs/partytown integration. Run npx astro add partytown, change a third-party script’s type to text/partytown, and that script runs in a web worker instead of on the main thread, which keeps analytics and tag managers from slowing down clicks and taps.
It works well for scripts that mostly collect and send data. It works badly, or not at all, for scripts that need to change the page immediately. This guide covers both, with the configuration for the common cases.
Key Takeaways
npx astro add partytowninstalls the integration; then settype="text/partytown"on each script you want moved.- Scripts that call globals like
dataLayer.pushorgtagfrom your page need those names in theforwardoption.- Partytown fetches scripts from inside a worker, so third-party hosts without CORS headers need a proxy via
resolveUrl.- Good fits: analytics, tag managers, pixels. Poor fits: chat widgets, A/B testing, consent banners, anything that edits the DOM on load.
- Measure INP before and after. If nothing changes, the script wasn’t your problem.
What Partytown does
A normal <script src="..."> runs on the browser’s main thread, the same thread that handles input and paints the page. A tag manager that loads several vendors can occupy that thread for hundreds of milliseconds, and any tap that happens during that time waits. That wait is what Interaction to Next Paint (INP) measures.
Partytown is an open-source library that runs those scripts inside a web worker. The worker has no direct access to the DOM, so Partytown gives it proxies for window, document and friends. When a script in the worker reads document.title or sets a cookie, Partytown relays the call to the main thread and returns the result synchronously, using either a service worker or Atomics when the page is cross-origin isolated.
The result: the expensive part of the script, parsing and running its code, happens off the main thread. The small DOM reads and writes still cross over, which is why scripts that touch the DOM heavily don’t benefit much.
Install the Astro Partytown integration
npx astro add partytown
That installs @astrojs/partytown and adds it to your config:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import partytown from '@astrojs/partytown';
export default defineConfig({
integrations: [partytown()],
});
The integration does three things. It injects the small Partytown loader inline into the head of every page. It serves the Partytown library files from /~partytown/ in development. And at build time it copies those files into dist/~partytown/ so your host serves them from your own domain. If you set base in your config, the path follows it.
Move a script into the worker
Change type on any script you want Partytown to run. Nothing else in the tag changes:
---
// src/components/Analytics.astro
---
<script
type="text/partytown"
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"
></script>
<script type="text/partytown">
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-XXXXXXX');
</script>
The browser ignores scripts with an unknown type, so these don’t run on the main thread at all. Partytown’s loader finds them and executes them in the worker.
Notice there’s no is:inline here. Astro treats any script with an attribute other than src as inline, so it won’t try to bundle a text/partytown script. Add is:inline anyway if you want the intent to be obvious to the next person reading the file.
Include the component in your base layout’s <head>, after the integration’s injected loader (which Astro places for you).
Forward calls from the main thread
Your own page code still runs on the main thread. If it calls gtag('event', ...) on a button click, that call has to reach the copy of gtag living in the worker. The forward option creates main-thread stubs that queue calls and pass them across:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import partytown from '@astrojs/partytown';
export default defineConfig({
integrations: [
partytown({
config: {
forward: ['dataLayer.push', 'gtag'],
},
}),
],
});
Common forward values:
| Script | Forward |
|---|---|
| Google Tag Manager | dataLayer.push |
| Google Analytics 4 (gtag.js) | dataLayer.push, gtag |
| Meta Pixel | fbq |
| Many other pixels | the global function name from the vendor’s snippet |
Anything not forwarded is invisible to the worker. If events fire in the console but never reach your analytics dashboard, a missing forward entry is the first thing to check.
Debugging Partytown in Astro
The integration turns Partytown’s debug mode on automatically in astro dev and off for builds. In debug mode, Partytown loads unminified files and logs every proxied DOM access in the console, which shows you exactly what a script is trying to do.
To keep debug output in a production build while you test:
// astro.config.mjs
partytown({
config: {
debug: true,
forward: ['dataLayer.push'],
},
});
Turn it back off before you ship. Debug mode loads larger files and logs a lot.
Useful checks when something doesn’t work:
- Open DevTools and confirm
/~partytown/partytown.jsand the worker files load with status 200. - In the Network panel, look for the third-party script request. If it’s blocked by CORS, see the next section.
- Check the console for Partytown logs mentioning the global your page calls.
- Run
npm run build && npm run previewand test the production output, since the dev server behaves differently.
Fixing CORS errors
A normal script tag can load from any origin. A web worker fetches scripts with fetch(), and that requires the third-party server to send Access-Control-Allow-Origin. Google’s tag scripts generally do; many smaller vendors don’t.
When a vendor doesn’t, route the request through a proxy you control using resolveUrl:
// astro.config.mjs
partytown({
config: {
forward: ['dataLayer.push'],
resolveUrl: (url, location, type) => {
if (type === 'script' && url.hostname === 'cdn.vendor-example.com') {
const proxy = new URL('/proxy/', location.origin);
proxy.searchParams.set('url', url.href);
return proxy;
}
return url;
},
},
});
The /proxy/ path has to exist on your host and return the script with CORS headers. On Cloudflare, Netlify or Vercel that’s a small edge function or a rewrite rule. On a purely static host with no functions, you can’t proxy, so a vendor without CORS headers can’t run in Partytown there.
Note that resolveUrl is serialized into the inline loader, so it must be self-contained: no imports or variables from outside the function.
Partytown and view transitions
If you use <ClientRouter /> for view transitions, the page body is swapped on navigation instead of reloaded. The Astro integration handles this by moving Partytown’s hidden iframe into the new document on the astro:before-swap event, so the worker survives navigation.
Your analytics script won’t send a new page view on its own, though, because from its point of view the page never reloaded. Send one yourself after each navigation:
<script>
// Runs on the main thread; gtag is forwarded to the worker
document.addEventListener('astro:page-load', () => {
(window as any).gtag?.('event', 'page_view', {
page_location: location.href,
page_title: document.title,
});
});
</script>
Check your analytics configuration so the first load isn’t counted twice.
When Partytown is the wrong tool
Partytown is a good fit for scripts that observe the page and send data out. It’s a poor fit when a script needs the DOM synchronously and often:
- Chat widgets that inject a launcher and react to every scroll and resize.
- A/B testing tools that must change content before first paint to avoid flicker. In a worker they run later, so users see the original first.
- Consent banners that need to block other scripts until the user chooses.
- Video players and maps that render complex UI.
- Scripts that rely on
document.write.
For these, the better options are, in order:
- Remove the script or replace it with a lighter one. A privacy-friendly analytics tool under a few kilobytes often removes the need for Partytown entirely. See privacy-friendly analytics for Astro.
- Load on interaction. Show a static “Chat with us” button and only load the widget when it’s clicked.
- Load late with
deferor after theloadevent, so at least it doesn’t compete with first paint.
Here’s the load-on-interaction pattern for a chat widget:
---
// src/components/ChatButton.astro
---
<button type="button" data-chat>Chat with us</button>
<script>
const button = document.querySelector('[data-chat]');
button?.addEventListener('click', () => {
const s = document.createElement('script');
s.src = 'https://widget.chat-example.com/loader.js';
s.async = true;
document.head.append(s);
button.remove();
}, { once: true });
</script>
Measure before and after
Partytown changes where work happens, not how much there is. Measure before you commit to it:
- Run Lighthouse on the production build and note Total Blocking Time.
- In the Performance panel, record a load and check how much main-thread time belongs to the third-party script.
- Move the script to Partytown, rebuild and repeat.
If Total Blocking Time drops and the script still works, keep it. If the script’s share of main-thread time was small to begin with, Partytown adds a dependency without a visible gain. The Astro Core Web Vitals guide explains how to confirm the change with field data, and the broader Astro performance guide covers the other main-thread costs.
Komal themes ship without third-party scripts, so whatever you add is the only thing on the main thread. If you’re starting a new site, you can browse Astro themes and add analytics your own way. The official Astro Partytown integration docs list every config option, and the Astro config docs cover where integrations go.
FAQ
Does Partytown work with Google Tag Manager in Astro?
Yes, in most setups. Load the GTM script with type="text/partytown" and add dataLayer.push to the forward option. Tags inside GTM that manipulate the page heavily, such as some heatmap or testing tags, may still need to run on the main thread.
Is Partytown still maintained?
The library moved to the @qwik.dev/partytown package, which is what @astrojs/partytown uses today. Check the project’s GitHub releases before a large rollout to confirm it supports the scripts you plan to move.
Why do my analytics events not show up with Partytown?
The most common cause is a missing forward entry. Calls made from main-thread code to a global like gtag or fbq are lost unless that name is forwarded. The second most common cause is a CORS error when the worker fetches the script.
Does Partytown improve Lighthouse scores?
It can lower Total Blocking Time, which Lighthouse uses as a lab stand-in for INP, when a third-party script was taking significant main-thread time. It doesn’t change LCP or CLS much, and it won’t help if the script was already light.
Can I use Partytown on a static Astro site?
Yes. The integration works with static output and copies its files into dist/~partytown/. The only static-hosting limit is proxying: if a vendor’s script lacks CORS headers, you need a function or rewrite on the host to proxy it.