Public browser variables

Expose public configuration to browser code with Astro

← Back to Astro

Astro exposes variables prefixed with PUBLIC_ to browser code. Only use this prefix for values anyone can see, such as a site name or public API URL. Encryption protects the file in git; it does not make a browser variable private.

Add a public value

Add an encrypted value to .env:


$ npx dotenvx set PUBLIC_SITE_NAME "My site"

Read it in an Astro page's browser script:


<script>
  document.title = import.meta.env.PUBLIC_SITE_NAME;
</script>

Restart npm run dev after changing your environment file.

Build for production

Add PUBLIC_SITE_NAME to .env.production with the same set command and the -f .env.production flag. Commit the encrypted file.

Public variables are included at build time. Update your build script:


{
  "scripts": {
    "build": "dotenvx run -f .env.production --strict -- astro build"
  }
}

Give your build environment access to the production key. With an Enclaved Key, select the resource that runs the build when encrypting. Then run npm run build there.

Changing a public value requires a new build. The main guide's start script continues to load server secrets at runtime.

See Astro's environment variable documentation for more.

markdown