The Astro script tag lets you add client-side JavaScript to any .astro component without React, Svelte or Vue. Write a plain <script> in the component, and Astro bundles it with Vite, processes TypeScript and npm imports, and includes it once per page no matter how many times the component is used.
That covers most interactive needs on a content site: menus, toggles, tabs, copy buttons, form validation. This guide shows how processed and inline scripts differ, how to pass server data into a script, and how to keep scripts working across view transitions.
Key Takeaways
- A plain
<script>in an.astrofile is processed: bundled, minified, TypeScript-aware,type="module", and deduplicated.- Adding
is:inlineor any attribute other thansrcturns processing off. The script is printed exactly as written.- Frontmatter variables don’t exist in the browser. Pass values through
data-*attributes ordefine:vars.- Wrapping behavior in a custom element scopes it to each instance and runs it automatically for every copy.
- With
<ClientRouter />, rerun setup code on theastro:page-loadevent.
How the Astro script tag is processed
By default, Astro treats a <script> inside a component as a module that belongs in the client bundle:
---
// src/components/Greeting.astro
---
<button type="button" class="greet">Say hello</button>
<script>
const buttons = document.querySelectorAll<HTMLButtonElement>('.greet');
buttons.forEach((button) => {
button.addEventListener('click', () => alert('Hello from Astro'));
});
</script>
When you build the site, Astro and Vite do the following with that script:
- Compile TypeScript, so the generic
querySelectorAll<HTMLButtonElement>above is fine. - Resolve imports, including npm packages and files in
src/. - Bundle and minify it, and output it as
type="module". - Include it once per page, even if
<Greeting />appears ten times.
Because it is a module, the script is deferred automatically. It runs after the HTML is parsed, so document.querySelectorAll finds the elements without a DOMContentLoaded listener.
Since Astro 5, processed scripts render where you place them rather than being hoisted into the <head>. That rarely matters for module scripts, which run after parsing anyway, but it explains why you see them in the body of the built HTML.
Inline scripts with is:inline
Sometimes you need the script exactly as written: a third-party snippet, a theme-flash fix that must run before paint, or JSON-LD. Add is:inline:
---
// src/components/ThemeInit.astro
---
<script is:inline>
const stored = localStorage.getItem('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.dataset.theme = stored ?? (prefersDark ? 'dark' : 'light');
</script>
An inline script is not bundled, not deduplicated and not transformed. It can’t use TypeScript or import npm packages. It runs where it sits in the HTML, and if the component renders five times, the script appears five times.
Watch for one rule that surprises people: any attribute other than src makes a script inline. <script type="module">, <script async> and <script data-id="x"> all skip processing, as if you’d written is:inline. If your TypeScript suddenly stops compiling, look for a stray attribute.
| Script | Bundled | TypeScript | npm imports | Deduplicated |
|---|---|---|---|---|
<script> |
yes | yes | yes | yes |
<script src="./local.ts"> |
yes | yes | yes | yes |
<script is:inline> |
no | no | no | no |
<script type="module"> |
no | no | no | no |
<script define:vars={...}> |
no | no | no | no |
Passing data from frontmatter to a script
Frontmatter runs on the server at build time. A processed script runs in the browser. Variables don’t cross that line, so this fails:
---
// src/components/Broken.astro
const message = 'Hi';
---
<script>
console.log(message); // ReferenceError: message is not defined
</script>
The clean fix is a data-* attribute. Render the value into HTML on the server, then read it in the browser:
---
// src/components/Countdown.astro
interface Props {
target: string; // ISO date, e.g. "2026-12-31T23:59:59Z"
}
const { target } = Astro.props;
---
<p class="countdown" data-target={target}>Loading...</p>
<script>
document.querySelectorAll<HTMLElement>('.countdown').forEach((el) => {
const target = new Date(el.dataset.target!).getTime();
const tick = () => {
const seconds = Math.max(0, Math.floor((target - Date.now()) / 1000));
el.textContent = `${seconds.toLocaleString()} seconds to go`;
};
tick();
setInterval(tick, 1000);
});
</script>
Each instance carries its own data-target, and the single bundled script handles all of them. For objects, use data-config={JSON.stringify(config)} and JSON.parse it in the script.
The other option is define:vars, which injects variables directly but makes the script inline, with every limitation from the table above. It suits a one-off snippet. The define:vars tip shows when it’s worth that trade.
Scoping scripts with custom elements
Selecting elements by class works, but it gets fragile when components nest or you need per-instance state. A custom element gives each instance its own scope and runs automatically whenever the tag appears in the DOM:
---
// src/components/Disclosure.astro
interface Props {
label: string;
}
const { label } = Astro.props;
---
<ui-disclosure>
<button type="button" aria-expanded="false">{label}</button>
<div hidden><slot /></div>
</ui-disclosure>
<script>
class UiDisclosure extends HTMLElement {
connectedCallback() {
const button = this.querySelector('button')!;
const panel = this.querySelector('div')!;
button.addEventListener('click', () => {
const open = button.getAttribute('aria-expanded') === 'true';
button.setAttribute('aria-expanded', String(!open));
panel.hidden = open;
});
}
}
if (!customElements.get('ui-disclosure')) {
customElements.define('ui-disclosure', UiDisclosure);
}
</script>
The browser calls connectedCallback for every <ui-disclosure> on the page, including ones added later. No framework runtime, no hydration step, and this.querySelector only searches inside that instance. Many accessible components in production Astro themes are written this way. The accordion component walkthrough builds a fuller version.
Importing npm packages in a script
Processed scripts can import from node_modules, and Vite bundles only what you use:
npm install canvas-confetti
---
// src/components/Celebrate.astro
---
<button type="button" id="celebrate">Celebrate</button>
<script>
import confetti from 'canvas-confetti';
document.getElementById('celebrate')?.addEventListener('click', () => {
confetti({ particleCount: 120, spread: 70 });
});
</script>
For heavy libraries that most visitors never trigger, use a dynamic import() inside the handler. Vite splits it into its own chunk, which downloads only on first click:
// inside a <script> in an .astro component
document.getElementById('open-chart')?.addEventListener('click', async () => {
const { renderChart } = await import('../lib/chart');
renderChart(document.getElementById('chart')!);
});
You can also keep larger scripts in their own file and reference them with src. A relative src is still processed:
<script src="../scripts/menu.ts"></script>
Scripts and view transitions
If you add <ClientRouter /> from astro:transitions, navigation swaps the page content without a full reload. Bundled module scripts run only once, on the first page, so listeners attached to elements on that page are gone after navigation.
Run your setup on the astro:page-load event, which fires on the first load and after every client-side navigation:
<script>
function setupMenu() {
const toggle = document.querySelector<HTMLButtonElement>('[data-menu-toggle]');
const menu = document.querySelector<HTMLElement>('[data-menu]');
toggle?.addEventListener('click', () => {
const open = toggle.getAttribute('aria-expanded') === 'true';
toggle.setAttribute('aria-expanded', String(!open));
menu?.toggleAttribute('hidden', open);
});
}
document.addEventListener('astro:page-load', setupMenu);
</script>
Custom elements avoid this problem entirely, because the browser calls connectedCallback again for elements in the newly swapped content. The view transitions docs list the full lifecycle events.
When a script tag is enough and when to use an island
A script tag is the right tool when the interaction is local and event-driven: open, close, copy, validate, animate. It ships only your code, with no framework runtime and no hydration step.
Move to a framework island (client:visible and friends) when the UI is driven by state that re-renders many elements: filtering a list of 200 products, a multi-step form with branching, a live search with results. At that point a framework saves code rather than adding it. The island or script guide has a checklist, and the Astro components guide covers where scripts sit in the component model. For where these files live in a project, see the folder structure docs.
FAQ
Why is my Astro script not running?
The most common causes are an attribute that made the script inline (so TypeScript or imports fail), referencing a frontmatter variable that doesn’t exist in the browser, or view transitions replacing the page after your listeners were attached. Check the browser console first, then move setup code into an astro:page-load listener if you use <ClientRouter />.
Does Astro hoist script tags to the head?
Not anymore. Since Astro 5, processed scripts render where you place them in the component. They are still type="module", so they run after the HTML is parsed regardless of position.
How do I pass a variable from frontmatter to a script in Astro?
Render it into a data-* attribute on an element and read it with element.dataset in the script. For a quick one-off you can use define:vars, but that makes the script inline, so it loses bundling, TypeScript and imports.
What does is:inline do in Astro?
is:inline tells Astro to leave the script untouched. It is printed exactly as written, isn’t bundled or deduplicated, and runs at that point in the HTML. Use it for snippets that must run before paint or third-party code that expects to be inline.
Can I use TypeScript in an Astro script tag?
Yes, in processed scripts. A plain <script> or <script src="./file.ts"> is compiled by Vite, so type annotations and generics work. Inline scripts are not compiled, so they must be plain JavaScript.