#Access environment variables during build time

3 messages · Page 1 of 1 (latest)

dim relic
#

how do I access environment variables during build time if the deployment is using Cloudflare

gloomy idolBOT
#

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:


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

Astro Documentation

Learn how to use environment variables in an Astro project.

Astro Documentation

How to deploy your Astro site to the web using Cloudflare Pages.