How to inject environment variables into webpack?

I am sorry to disturb you all. (bows deeply)
Victoria can you point me to some materials on how to inject those wrangler variables into my webpack?
Can’t get my head around this problem.

Environment variables (and secrets environment variables) are now a first-party feature of Workers and Wrangler.

But how can I consume those variables in my react app?

Let’s say I have a config file looking like this:

type = "webpack"
name = "worker-name"
account_id = "some-id"
workers_dev = true

[site]
  bucket = "./public"
  entry-point = "./workers-site"

[env.production]
  name = "website"
  myVar = "test"

and in workers-site/index.js I want to pass it down to my React app.

Question 1: How do I access the myVar in the worker’s index.js file, non of what I already tried seems to work
Question 2: Once I have that variable how do I expose it to React runtime, or React context?

Env vars are exposed to the worker as global variables. if you have the env var SECRET_TOKEN, you access it just the same in your script. If you’re using typescript, you should have a definition file (eg. types.d.ts) with your global env vars in it:

declare global {
    const SECRET_TOKEN: string
}

But if you’re not using typescript, you don’t need to do any preparation and can access it like any other global variable.

Once a text variable is uploaded via wrangler or in the UI, the string is exposed on the global namespace as type String.

If you’re taking about obtaining a variable in the browser, you can either pass it via a prop or via an extra API request to your worker where the API just returns the value of the worker; there’s no built-in functionality for obtaining env vars via Workers Sites.

For those who are seeing this, more context can be provided int he cf worker-types GitHub:

Using bindings

It’s recommended that you create an ambient type file for any bindings your Worker uses. Create a > file named bindings.d.ts in your src directory:

bindings.d.ts

export {}; declare global { const MY_ENV_VAR: string const MY_SECRET: string const myKVNamespace: KVNamespace }

Hey all, I’m doing all of the things as described here and I still don’t get the environment variable injected to my worker. Am I missing any special build / webpack config, or is Cloudflare supposed to take care of the magic? I can see the correct environment variable / value when I look at the worker in the dashboard.

wrangler.toml

[env.dev]
name = “mywebsite-website-dev”
route = “dev.mywebsite.com/*
vars = { REACT_APP_API_BASE_URL = “https://api-website-dev.mywebsite.com/” }

src\bindings.d.ts

export {};

declare global {
const REACT_APP_API_BASE_URL: string
}

react snippet

export const transferApi = createApi({
reducerPath: ‘transferApi’,
baseQuery: fetchBaseQuery({
baseUrl: REACT_APP_API_BASE_URL,
prepareHeaders: (headers, { getState }) => {

Runtime

Uncaught ReferenceError: REACT_APP_API_BASE_URL is not defined