Injecting Environment Variables Dynamically in Cloudflare Pages
LaunchFast Logo LaunchFast

Injecting Environment Variables Dynamically in Cloudflare Pages

Rishi Raj Jain
Injecting Environment Variables Dynamically in Cloudflare Pages

In this guide, you will learn how to inject environment variables dynamically in a Cloudflare Pages application.

High Quality Starter Kits with built-in authentication flow (Auth.js), object uploads (AWS, Clouflare R2, Firebase Storage, Supabase Storage), integrated payments (Stripe, LemonSqueezy), email verification flow (Resend, Postmark, Sendgrid), and much more. Compatible with any database (Redis, Postgres, MongoDB, SQLite, Firestore).
Next.js Starter Kit
SvelteKit Starter Kit

Prerequisites

You’ll need the following:

Dynamic Environment Variables via wrangler.toml

As Cloudflare Pages configuration via wrangler.toml is now in open beta, you can use this file as your environment variable manager (apart from the Environment Variables defined in the Cloudflare Pages Settings of your project).

As denoted in the example wrangler.toml file, all the variables in the [vars] are deployed to Cloudflare Pages.

You get the idea - dynamically insert your environment variables into the [vars] as key value pair. This becomes handy when you’re trying to provision something in your CI/CD pipeline and then you require the generated values to be used as environment variables.

A simple script to do the same would be as follows:

Terminal window
echo "[vars]" >> wrangler.toml
echo "MY_ENV_NAME=MY_ENV_VALUE" >> wrangler.toml

But that’s not all, there’s one more gotcha with using wrangler.toml with Cloudflare Pages during deployment. You need to use the latest CLI instead of their outdated GitHub Action.

Deploy to Cloudflare Pages

You will need to use the Wrangler CLI to deploy your application to Cloudflare Pages. Run the following command to deploy (after, if your application has a build step):

Terminal window
npx wrangler@latest pages deploy --project-name="<name>"

(Make sure that you are using the latest version of Wrangler CLI to deploy to Cloudflare Pages)

Conclusion

In this guide, you learned how to inject environment variables dynamically in Cloudflare Pages.

If you have any questions or comments, feel free to reach out to me on Twitter.

Learn More Query Cloud Firestore with Astro on Cloudflare Workers
Query Cloud Firestore with Astro on Cloudflare Workers April 25, 2025
Query Redis with Astro on Cloudflare Workers
Query Redis with Astro on Cloudflare Workers April 25, 2025
How to Generate Pre-signed URLs for Firebase Storage with Astro on Cloudflare Workers
How to Generate Pre-signed URLs for Firebase Storage with Astro on Cloudflare Workers April 24, 2025