#how to access astro variable inside <script> tag

3 messages · Page 1 of 1 (latest)

neat valve
#

how to access astro variable inside <script> tag?

blissful flameBOT
#

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

#

To access Astro variables inside a <script> tag, you can use the define:vars directive to pass server-side variables from your component frontmatter into the client <script> tag. Here's an example:

---
const message = "Astro is awesome!";
---
<script define:vars={{ message }}>
 alert(message);
</script>

Keep in mind that using define:vars on a <script> tag implies the is:inline directive, which means your scripts won't be bundled and will be inlined directly into the HTML.

Source: Astro Directives Reference (https://docs.astro.build/en/reference/directives-reference#definevars)

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

Astro Documentation

Build faster websites with less client-side JavaScript.