Skip to content

Improved inline script support #1447

Open

Description

@delucis

Summary

  • Overhaul Astro’s <script> handling to allow for improved inline script DX and UX, including transpilation of authored TypeScript syntax and shipping smaller, CSP-compatible inline scripts to users.
  • Remove support for define:vars on scripts (styles will continue to support it).

Background & Motivation

Adding inline script processing

Astro has an is:inline directive for script tags that disables bundling and hoisting. Currently, the contents of an inline script are not processed at all and shipped verbatim to the browser.

One common use case for inline scripts is to ensure some code executes at a specific point in the page load lifecycle. The classic example is colour theme preference: an inline script should execute and set a dark/light mode preference as early as possible to avoid a flash of the incorrect colour theme.

Astro’s current behaviour means you are forced to write inline scripts in plain JavaScript and (ideally) author it in a fairly terse way, because all comments etc. will be shipped to users as is. This makes for a less good authoring/maintenance experience, but also for a worse end-user experience if they have to download larger than necessary script tags.

As an example, Starlight has multiple places where it uses inline scripts to control page behaviour during the page load lifecycle and each of these needs to be authored carefully and in a less maintainable way to avoid shipping overly verbose inline code.

Removing define:vars

The define:vars directive has long been a source of user confusion and something of a footgun. It would be technically be possible to continue supporting it and only implement the first part of this proposal, but I think it makes sense to tackle both at once. See #1246 for more details, and “Breaking changes” for the migration path.

Goals

  • Support TypeScript syntax in is:inline scripts
  • Ship minified JavaScript for scripts authored using is:inline
  • Support Content Security Policy (CSP) hashes on is:inline scripts the same way we do for hoisted scripts
  • Remove support for the define:vars attribute on scripts in favour of web platform alternatives (support for styles won’t change)
  • Clarify the is:inline vs is:raw directive distinction

Non-Goals

  • Non-goal: inline script bundling. Processing should only include transpilation and minification, not an import-aware bundling step.

  • Out-of-scope: configurable minification. In theory, users could provide options to tweak what kind of minification happens. For now at least, we should choose safe defaults that won’t break user scripts and not offer configuration.

  • Non-goal: varying processing based on attributes like type. In theory, we could treat type="module" scripts differently from other inline scripts, e.g. mangling top-level variables. Given attributes are sometimes only known at render time, we shouldn’t try to do this.

Detailed Design

Today, is:inline and is:raw are equivalent on scripts. This proposal changes that so we will have three distinct cases:

hoisted bundled optimized
1. <script> ✅ ✅ ✅
2. <script is:inline> ❌ ❌ ✅
3. <script is:raw> ❌ ❌ ❌

Implementation

After discussion with @Princesseuh, we believe this can primarily take place in the compiler, with Astro core responsible for the CSP component.

Compiler

When compiling a <script> element there are three distinct cases, only one of which is impacted by this proposal:

  1. Unchanged: the current rules for hoisted scripts. <script> (and <script src=""> with a local file path src attribute) are hoisted and bundled as currently.

  2. As currently, a script with other attributes is treated as is:inline by default, but users are encouraged to set the directive explicitly with a warning if it isn’t already.

    Changes:

    • If an inline script uses set:text, set:html, or src attributes, no processing takes place, and the script is treated as currently (equivalent to is:raw, no change from today).
    • Otherwise, instead of leaving the script content in place as-is, the compiler now passes the content through a pipeline to transpile TypeScript syntax and minify with oxc, using safe options appropriate for an inline script (i.e. no top-level mangling). This transpiled, minified content replaces the authored content in the compiler output.
    • The transpiled, minified content is also exposed as a string in metadata, so that Astro can use it to compute hashes for the purposes of CSP, similar to how hoisted scripts are exposed.
    • The define:vars directive is no longer supported. The compiler will no longer wrap script content in an IIFE and using define:vars will result in an error, see “Breaking changes” below.
  3. Unchanged: the current rules for scripts with the is:raw directive. Attributes and script content are all passed through as-is.

Astro core

When calculating hashes for CSP, Astro will use the minified inline scripts passed from the compiler to allow the inline scripts to run even when a strict CSP is enabled. This can follow the same approach as used currently for hoisted scripts, minus the Vite bundling step.

Language tools

This change also influences editor diagnostics and astro check. For example, we could highlight incorrect use of is:inline. I haven’t investigated the impacts in this area yet.

Docs

Currently, we document scripts as “processed” and “unprocessed” in our “Scripts and event handling” guide. We will need to update documentation to align the meaning more with directive naming and clarify that there are three cases. Similarly the “Template directives reference” entries will need updating to reflect the new reality.

This might seem “more complex” than the current docs, because we mostly skip over is:raw in our script docs (it’s not even mentioned in the main guide), but I think in reality this complexity is already present for users, just hidden in the docs.

Testing Strategy

  • Compiler unit tests should show users’ inline scripts being minified and check that top-level variable names remain unchanged.
  • Astro’s CSP tests should check that inline script hashes are included on pages that have them.

Drawbacks

  • This is a breaking change in some cases and may be disruptive to some users. Hopefully a period of experimental status and clear migration steps (see “Adoption strategy”) should smooth that over.
  • This change introduces a slight difference between <script> and <style> elements. <style is:inline> would remain like is:raw, while <script is:inline> would now be processed.

Alternatives

Alternatives include introducing a new API to achieve something similar to this proposal without breaking changes.

For example, a new directive could make this opt-in at the <script> level:

<script is:inline-optimized>
</script>

Or a Vite plugin could allow for importing external script files as inline script components:

---
import Script from './my-script.ts?inline-script';
---

<Script />

I believe these would only confuse users more about how scripts behave and what to use.

  • Both of these would put the onus on users to remember to optimize their scripts, which goes against the “pit of success” where the optimal path should be the default/easy path.
  • The Vite plugin approach is also less ergonomic and would be harder to make CSP compatible.

Alternatives to removing define:vars

Instead of removing define:vars, we could continue supporting and meet the RFC goal of CSP support if we changed how define:vars works.

Currently a define:vars script ends up compiled something like the following:

<script>
	(function () {
		// properties passed to `define:vars` converted to top-level variables
		const foo = 'fooValue';
		// --- user-authored script starts ---
		console.log(foo);
	})();
</script>

Because define:vars values are only known at runtime, this is incompatible with CSP.

We could switch so that define:vars uses the same dataset approach we are recommending to users. This would make the script content consistent across renders with only the data attribute changing at runtime. However, this would also require users to update their scripts to read values from a single object (e.g. vars):

<script data-vars='{"foo": "fooValue"}'>
	(function () {
		let vars = {};
		try {
			vars = JSON.parse(document.currentScript.dataset.vars || '{}');
		} catch {}
		// --- user-authored script starts ---
		console.log(vars.foo);
	})();
</script>

Given all of the issues with define:vars, I don’t believe it is valuable to try to migrate people to something like this instead of just removing it. Users who absolutely need it, should migrate as shown below.

Adoption strategy

Initially, this should be released behind an experimental flag. Users would opt in as usual in the Astro config:

export default defineConfig({
	experimental: {
		optimizedInlineScripts: true,
	},
});

We can then switch over to the new behaviour by default in a future major version of Astro (v8?).

Most existing uses of is:inline should be able to migrate seamlessly, benefiting from smaller script sizes with the same functionality. The only exceptions are uses of specific types of attribute, see below.

Breaking changes

The compiler should be able to provide diagnostics guiding users to update their code in the following circumstances.

  • define:vars will no longer be available. Users should migrate to web platform alternatives, for example:

    - <script define:vars={{ foo: "bar", baz: 10 }}>
    + <script data-vars={JSON.stringify({ foo: "bar", baz: 10 })}>
    + 		const { foo, baz } = JSON.parse(document.currentScript.dataset.vars);
      		console.log(foo, baz);
      </script>

    We should provide errors that show this migration path. It should be possible to show a user exactly the code changes they need to make.

  • Some script types will have to be migrated to is:raw instead of is:inline, for example:

      <!-- Speculation Rules declaration -->
    - <script is:inline type="speculationrules">
    + <script is:raw type="speculationrules">
      	{...}
      </script>
    
      <!-- JSON-LD data object -->
    - <script is:inline type="application/ld+json">
    + <script is:raw type="application/ld+json">
      	{...}
      </script>

    While it is theoretically possible to automatically treat these cases as raw, we should avoid trying to sniff stuff based on attribute values (which may only be known at runtime) and instead require users to explicitly set is:raw.

    When detected, we should provide errors to guide users to switch from is:inline to is:raw for cases such as these.

Activity

  1. saimonsays199128 commented on Nov 19, 2026

    @saimonsays199128

    Supporting data point from production: across 9 sites on Astro 7 (Wix-managed headless) we have about 20 <script define:vars> uses, mostly passing a few IDs and strings to tracking and cart scripts. The data-vars + document.currentScript.dataset migration in the proposal covers every one of them, and we're moving to it now.

    Two requests from that experience:

    1. The compiler error with the exact replacement, as proposed. Several of ours sit on cart and product pages, where each change has to be checked by hand, so a precise diff per script saves real time.
    2. A way to read the computed hashes outside the <meta> CSP, e.g. in the build manifest or an API. Our CSP is a response header set in middleware, because the host injects its own scripts at request time, so Astro's meta-tag CSP can't be used as is. With the hashes exposed we could add them to the header and drop 'unsafe-inline'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    • Status
      Stage 2: Accepted Proposals, No RFC

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions