#How to let a script execute before every client component hydrates?

3 messages · Page 1 of 1 (latest)

worthy temple
#

As titled

magic spokeBOT
#

Hi @worthy temple. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To execute a script before every client component hydrates in Astro, you can use an integration with the injectScript() option using the "before-hydration" stage.

Using injectScript()

When building an Astro integration, the astro:config:setup hook provides an injectScript callback. Setting the stage to "before-hydration" ensures the JavaScript is imported client-side before any hydration scripts run. This script will be optimized and resolved by Vite [Astro Integration API].

Example integration:

export default function myIntegration() {
  return {
    name: 'my-integration',
    hooks: {
      'astro:config:setup': ({ injectScript }) => {
        injectScript(
          'before-hydration',
          `console.log("This runs before hydration!");`
        );
      },
    },
  };
}

Considerations for View Transitions

If your site uses View Transitions, keep in mind that bundled scripts (including those injected via integrations) typically only execute once per site visit. If you need logic to run specifically after every page navigation but before new content is fully interactive, you may also need to listen for lifecycle events like astro:page-load or astro:after-swap [Script re-execution].

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: