#Global Variable
4 messages · Page 1 of 1 (latest)
Hi @dull jungle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro doesn't directly support global variables that can be accessed from any component. However, there are a few ways you can pass data around:
- Passing Variables as Props: You can pass variables as props from one component to another. This is useful when you have a parent-child relationship between components. For example, in the case of Markdoc, variables can be passed as props via the
Contentcomponent. source (https://docs.astro.build/en/guides/integrations-guide/markdoc/)
<!--Pass the `abTest` param as a variable-->
<Content abTestGroup={Astro.params.abTestGroup} />
- Using
define:varsDirective: Thedefine:varsdirective can pass server-side variables from your component frontmatter into the client<script>or<style>tags. Any JSON-serializable frontmatter variable is supported, includingpropspassed to your component throughAstro.props. source (https://docs.astro.build/en/reference/directives-reference/)
---const foregroundColor = "rgb(221 243 228)";const backgroundColor = "rgb(24 121 78)";const message = "Astro is awesome!";---
<style define:vars={{ textColor: foregroundColor, backgroundColor }}> h1 { background-color: var(--backgroundColor); color: var(--textColor); }</style>
<script define:vars={{ message }}> alert(message);</script>
- Environment Variables: You can use environment variables to store data that can be accessed from any part of your application. You can use
process.envin a configuration file to access environment variables. source (https://docs.astro.build/en/guides/configuring-astro/)
import { loadEnv } from "vite";
const { SECRET_PASSWORD } = loadEnv(process.env.NODE_ENV, process.cwd(), "");