#Access environment variables during build time
3 messages · Page 1 of 1 (latest)
Hi @dim relic. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To access environment variables during build time when deploying on Cloudflare, you can use import.meta.env in your Astro components or API routes. For server-side code, all environment variables are available, while only those prefixed with PUBLIC_ are available in client-side code for security purposes.
Here's an example of how to access environment variables:
// When import.meta.env.SSR === true
const data = await db(import.meta.env.DB_PASSWORD);
// When import.meta.env.SSR === false
const data = fetch(`${import.meta.env.PUBLIC_POKEAPI}/pokemon/squirtle`);
When deploying on Cloudflare Pages, make sure to set the environment variables in the Cloudflare dashboard under the build settings. For example, add an environment variable with a Variable name of NODE_VERSION and a Value of v16.13.0 or higher to tell Cloudflare to use a compatible Node version.
For more information, refer to the following extracts:
- Using environment variables (https://docs.astro.build/en/guides/environment-variables)
- How to deploy a site with Git (https://docs.astro.build/en/guides/deploy/cloudflare#how-to-deploy-a-site-with-git)