Accessing Cloudflare Pages functions environment variables

I’m building a site with a contact form using Cloudflare Pages. To implement the contact form I’m using Cloudflare workers with a functions folder by following the documentation here: Functions · Cloudflare Pages docs

Now I need to set some environment variables such as API keys (secrets don’t seem to be supported yet) in order to send emails. However, setting any environment variables in the Cloudflare dashboard doesn’t seem to work - none of the environment variables are set.

For example, I have set MY_ENV_VAR like so:

Then I have a script in functions/contact.js which always crashes when calling it:

export async function onRequest({request}) {
  return new Response('Variable: ' + MY_ENV_VAR)
}

The documentation doesn’t seem to include anything on how to access these variables (Functions · Cloudflare Pages docs). Looking through the regular worker documentation I only find examples on how to access them directly as in my example (Environment variables · Cloudflare Workers docs).

What is the current approach to access environment variables? Is there support for secrets or have I missed it as well? How could I set environment variables (and secrets if its supported) locally using wrangler?

Having the same issue. Is there any way to access environment variables in Functions?

Hey, yes you can do this through the env property in the passed context

Example:

export async function onRequest({ request, env }) {
  return new Response('Variable: ' + env.MY_ENV_VAR)
}

And advanced example (_worker.js):

export default {
  fetch(req, env) {
    return new Response('Variable: ' + env.MY_ENV_VAR)
  }
}
1 Like

Thanks for your answer.

I am getting an error in my VS Code though:

Property 'STRIPE_SECRET_KEY' does not exist on type '{ ASSETS: { fetch: { (input: RequestInfo, init?: RequestInit | undefined): Promise<Response>; (request: string | Request, requestInitr?: Request | ... 1 more ... | undefined): Promise<...>; }; }; }'.ts(2339)

Do you know where I could set the global types?

Did you find a solution? I have the problem…

I believe something like this should fix your typing issue for the environment variables:

interface Env {
   KV: KVNamespace;
  TEST_KEY:string;
}
export const onRequest: PagesFunction<Env> = async (context) => {
...
}