javascripttypescriptastrojs

Sharing Global Constants/Variables in Astro


I have an Astro site that I'm working on, and I find that I'll be reusing constant values across all of my pages, for instance, a link to a social media account like https://x.com/someuser. This value won't change at runtime, but should be easily referenceable across the entire site, and should live in a single place so that if I need to modify it, everything that uses it will be automatically updated without having to find all of the individual usages.

I've searched the documentation and the internet, and I've been having trouble finding out how to do this. Is there a way to centrally store and globally use a constant/variable across layouts/pages?


Solution

  • You can just create a JavaScript/TypeScript file and export constants from there, then import those contents in the frontmatter and use them in the template.

    Example:

    ./src/constants.ts

    export const MY_CONSTANT = "some value";
    

    ./src/pages/index.astro

    ---
    import { MY_CONSTANT } from "../constants";
    ---
    
    <h1>hi {MY_CONSTANT}</h1>
    

    ./src/pages/another.astro

    ---
    import { MY_CONSTANT } from "../constants";
    ---
    
    <h1>hi again {MY_CONSTANT}</h1>
    

    You can export an object containing a bunch of properties instead of individual variables, if you prefer. The imports don't have to be in pages themselves, they can be in whatever page/component/layout you want, just make sure the import path is correct.