workers-sdk icon indicating copy to clipboard operation
workers-sdk copied to clipboard

🚀 Feature Request: Support for ENV vars in Pages Functions(beta)

Open s1mple opened this issue 3 years ago • 4 comments

Describe the solution

It would be really nice to be able to configure environment variables inside of pages functions using a wrangler.toml configuration file, similar to the workflow used for workers.

Here an idea of what the pages functions environment variable documentation could be after this feature is rolled out:

Adding environment variables locally

You can set environment variables for your project by adding env var bindings to a wrangler.toml file in the root of your pages functions project, and preview different env vars locally for development by adding --binding ENV_NAME="ENV_VALUE" to your wrangler commands.

For global values, use a [vars] section in your wrangler.toml file:

[vars]
COLOR = "ORANGE"

For separate bindings for each environment, with cascading overwrites of global [vars], use env-specific bindings:

[env.preview.vars]
COLOR = "RED"

[env.production.vars]
COLOR = "BLUE"

For previewing a different value during development, add the binding to your Wrangler commands using npx wrangler pages dev dist --binding ENV_NAME="ENV_VALUE". All of these methods allow you to then access the environment value in your component by using env.ENV_NAME.

For example, you can run npx wrangler pages dev dist --binding COLOR="BLUE" and then:

export async function onRequest({ env }) {
  return new Response(env.COLOR);
}

Note: env vars set inside of the Cloudflare Pages project control panel will always take precedence over those set in a project wrangler.toml file when the project has been deployed.

s1mple avatar Jun 03 '22 18:06 s1mple

This would be great!

kristianfreeman avatar Jun 15 '22 11:06 kristianfreeman

You may be interested in #898 which is actively in progress and will hopefully be released soon.

We're still very much in the discussions stage about how we want to do config for Pages projects. It might be a wranger.toml, or something else entirely.

GregBrimble avatar Jun 25 '22 11:06 GregBrimble

We recently added support for a .dev.vars file. Documentation is in progress, but it works like any .env file. This doesn't address the general .toml request, but may help with specific vars request.

https://github.com/cloudflare/wrangler2/pull/1274

nprogers avatar Sep 07 '22 15:09 nprogers

Thank you, this is very helpful!

Please feel free to close this issue since this effectively addresses the development process gap I was experiencing when I first opened this ticket.

I will leave this open for now, just in case there are additional features around pages ENV vars you're still working on, but after looking at the new docs at https://developers.cloudflare.com/pages/platform/functions/#adding-environment-variables-locally I like where this is going :)

s1mple avatar Sep 14 '22 18:09 s1mple