Skip to content

Commit f294024

Browse files
committed
Add documentation for importable env from cloudflare:workers
Document the import { env } from 'cloudflare:workers' API across Workers documentation pages that discuss environment variables, secrets, and bindings access patterns. Updates: - environment-variables.mdx: Add section on importing env globally - secrets.mdx: Show importable env as an access method with example - process.mdx: Add alternative to process.env using cloudflare:workers - fetch.mdx: Cross-reference importable env in env parameter docs - migrate-to-module-workers.mdx: Show importable env for ES modules
1 parent c00265d commit f294024

File tree

5 files changed

+94
-25
lines changed

5 files changed

+94
-25
lines changed

src/content/docs/workers/configuration/environment-variables.mdx

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ head: []
55
description: You can add environment variables, which are a type of binding, to attach text strings or JSON values to your Worker.
66
---
77

8-
import { Render, TabItem, Tabs, WranglerConfig, DashButton } from "~/components";
8+
import { Render, TabItem, Tabs, TypeScriptExample, WranglerConfig, DashButton } from "~/components";
99

1010
## Background
1111

@@ -47,6 +47,34 @@ export default {
4747

4848
</TabItem> </Tabs>
4949

50+
### Import `env` for global access
51+
52+
You can also import `env` from [`cloudflare:workers`](/workers/runtime-apis/bindings/#importing-env-as-a-global) to access environment variables from anywhere in your code, including outside of request handlers:
53+
54+
<TypeScriptExample>
55+
56+
```ts
57+
import { env } from "cloudflare:workers";
58+
59+
// Access environment variables at the top level
60+
const apiHost = env.API_HOST;
61+
62+
export default {
63+
async fetch(request: Request): Promise<Response> {
64+
return new Response(`API host: ${apiHost}`);
65+
},
66+
};
67+
```
68+
69+
</TypeScriptExample>
70+
71+
This approach is useful when you need to:
72+
73+
- Initialize configuration or API clients at the top level of your Worker.
74+
- Access environment variables from deeply nested functions without passing `env` through every function call.
75+
76+
For more details, refer to [Importing `env` as a global](/workers/runtime-apis/bindings/#importing-env-as-a-global).
77+
5078
### Configuring different environments in Wrangler
5179

5280
[Environments in Wrangler](/workers/wrangler/environments) let you specify different configurations for the same Worker, including different values for `vars` in each environment.
@@ -102,13 +130,7 @@ Select the **Secret** type if your environment variable is a [secret](/workers/c
102130

103131
## Environment variables and Node.js compatibility
104132

105-
When you enable both the [`nodejs_compat`](/workers/runtime-apis/nodejs/) and
106-
[`nodejs_compat_populate_process_env`](/workers/configuration/compatibility-flags/#nodejs_compat_populate_process_env)
107-
compatibility flags, and the `disallow_importable_env` compatibility flag is
108-
not set, environment variables will also be available via the global
109-
`process.env`. Note that the `nodejs_compat_populate_process_env` flag is
110-
enabled automatically when `nodejs_compat` is used with a compatibility date
111-
on or after April 1st, 2025.
133+
When you enable [`nodejs_compat`](/workers/runtime-apis/nodejs/) and the [`nodejs_compat_populate_process_env`](/workers/configuration/compatibility-flags/#nodejs_compat_populate_process_env) compatibility flag (enabled by default for compatibility dates on or after 2025-04-01), environment variables are available via the global `process.env`.
112134

113135
The `process.env` will be populated lazily the first time that `process` is accessed
114136
in the worker.

src/content/docs/workers/configuration/secrets.mdx

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,21 @@ head: []
55
description: Store sensitive information, like API keys and auth tokens, in your Worker.
66
---
77

8-
import { Render,DashButton } from "~/components";
8+
import { Render, DashButton, TypeScriptExample } from "~/components";
99

1010
## Background
1111

12-
Secrets are a type of binding that allow you to attach encrypted text values to your Worker. Secrets are used for storing sensitive information like API keys and auth tokens. Secrets are programmatically available on the [`env` parameter](/workers/runtime-apis/handlers/fetch/#parameters) passed to your Worker's [`fetch` event handler](/workers/runtime-apis/handlers/fetch/), and may also be accessible via [`process.env`](/workers/configuration/environment-variables) in Workers that support Node.js compatibility.
12+
Secrets are a type of binding that allow you to attach encrypted text values to your Worker. Secrets are used for storing sensitive information like API keys and auth tokens.
13+
14+
You can access secrets in your Worker code through:
15+
16+
- The [`env` parameter](/workers/runtime-apis/handlers/fetch/#parameters) passed to your Worker's [`fetch` event handler](/workers/runtime-apis/handlers/fetch/).
17+
- Importing `env` from [`cloudflare:workers`](/workers/runtime-apis/bindings/#importing-env-as-a-global) to access secrets from anywhere in your code.
18+
- [`process.env`](/workers/configuration/environment-variables) in Workers that have [Node.js compatibility](/workers/runtime-apis/nodejs/) enabled.
1319

1420
## Access your secrets with Workers
1521

16-
Secrets can be accessed from Workers as you would any other [environment variables](/workers/configuration/environment-variables/). For instance, given a `DB_CONNECTION_STRING` secret, you can access it in your Worker code:
22+
Secrets can be accessed from Workers as you would any other [environment variables](/workers/configuration/environment-variables/). For instance, given a `DB_CONNECTION_STRING` secret, you can access it in your Worker code through the `env` parameter:
1723

1824
```js title="index.js"
1925
import postgres from "postgres";
@@ -31,6 +37,32 @@ export default {
3137
};
3238
```
3339

40+
You can also import `env` from `cloudflare:workers` to access secrets from anywhere in your code, including outside of request handlers:
41+
42+
<TypeScriptExample>
43+
44+
```ts
45+
import { env } from "cloudflare:workers";
46+
import postgres from "postgres";
47+
48+
// Initialize the database client at the top level using a secret
49+
const sql = postgres(env.DB_CONNECTION_STRING);
50+
51+
export default {
52+
async fetch(request: Request): Promise<Response> {
53+
const result = await sql`SELECT * FROM products;`;
54+
55+
return new Response(JSON.stringify(result), {
56+
headers: { "Content-Type": "application/json" },
57+
});
58+
},
59+
};
60+
```
61+
62+
</TypeScriptExample>
63+
64+
For more details on accessing `env` globally, refer to [Importing `env` as a global](/workers/runtime-apis/bindings/#importing-env-as-a-global).
65+
3466
:::note[Secrets Store (beta)]
3567
Secrets described on this page are defined and managed on a per-Worker level. If you want to use account-level secrets, refer to [Secrets Store](/secrets-store/). Account-level secrets are configured on your Worker as a [Secrets Store binding](/secrets-store/integrations/workers/).
3668
:::

src/content/docs/workers/reference/migrate-to-module-workers.mdx

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ description: Write your Worker code in ES modules syntax for an optimized experi
66

77
---
88

9-
import { WranglerConfig } from "~/components";
9+
import { WranglerConfig, TypeScriptExample } from "~/components";
1010

1111
This guide will show you how to migrate your Workers from the [Service Worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) format to the [ES modules](https://blog.cloudflare.com/workers-javascript-modules/) format.
1212

@@ -177,7 +177,7 @@ addEventListener("fetch", async (event) => {
177177

178178
### Environment variables in ES modules format
179179

180-
In ES modules format, environment variables are only available inside the `env` parameter that is provided at the entrypoint to your Worker application.
180+
In ES modules format, environment variables are available through the `env` parameter provided at the entrypoint to your Worker application:
181181

182182
```js
183183
export default {
@@ -188,6 +188,28 @@ export default {
188188
};
189189
```
190190

191+
You can also import `env` from `cloudflare:workers` to access environment variables from anywhere in your code, including the top-level scope:
192+
193+
<TypeScriptExample>
194+
195+
```ts
196+
import { env } from "cloudflare:workers";
197+
198+
// Access environment variables at the top level
199+
const accountId = env.API_ACCOUNT_ID;
200+
201+
export default {
202+
async fetch(request: Request): Promise<Response> {
203+
console.log(accountId) // Logs "<EXAMPLE-ACCOUNT-ID>"
204+
return new Response("Hello, world!")
205+
},
206+
};
207+
```
208+
209+
</TypeScriptExample>
210+
211+
This approach is useful for initializing configuration or accessing environment variables from deeply nested functions without passing `env` through every function call. For more details, refer to [Importing `env` as a global](/workers/runtime-apis/bindings/#importing-env-as-a-global).
212+
191213
## Cron Triggers
192214

193215
To handle a [Cron Trigger](/workers/configuration/cron-triggers/) event in a Worker written with ES modules syntax, implement a [`scheduled()` event handler](/workers/runtime-apis/handlers/scheduled/#syntax), which is the equivalent of listening for a `scheduled` event in Service Worker syntax.

src/content/docs/workers/runtime-apis/handlers/fetch.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ The Workers runtime does not support `XMLHttpRequest` (XHR). Learn the differenc
3434

3535
* `env` object
3636

37-
* The [bindings](/workers/configuration/environment-variables/) available to the Worker. As long as the [environment](/workers/wrangler/environments/) has not changed, the same object (equal by identity) may be passed to multiple requests.
37+
* The [bindings](/workers/runtime-apis/bindings/) available to the Worker. As long as the [environment](/workers/wrangler/environments/) has not changed, the same object (equal by identity) may be passed to multiple requests. You can also [import `env` from `cloudflare:workers`](/workers/runtime-apis/bindings/#importing-env-as-a-global) to access bindings from anywhere in your code.
3838

3939
* <code>ctx.waitUntil(promisePromise)</code> : void
4040

src/content/docs/workers/runtime-apis/nodejs/process.mdx

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,14 @@ Workers-specific implementation details apply when adapting Node.js process supp
2020

2121
In the Node.js implementation of `process.env`, the `env` object is a copy of the environment variables at the time the process was started. In the Workers implementation, there is no process-level environment, so by default `env` is an empty object. You can still set and get values from `env`, and those will be globally persistent for all Workers running in the same isolate and context (for example, the same Workers entry point).
2222

23-
When [Node.js compatibility](/workers/runtime-apis/nodejs/) is turned on and the [`nodejs_compat_populate_process_env`](/workers/configuration/compatibility-flags/#enable-auto-populating-processenv) compatibility flag is set, `process.env` will contain any [environment variables](/workers/configuration/environment-variables/),
23+
When [Node.js compatibility](/workers/runtime-apis/nodejs/) is enabled and the [`nodejs_compat_populate_process_env`](/workers/configuration/compatibility-flags/#enable-auto-populating-processenv) compatibility flag is set (enabled by default for compatibility dates on or after 2025-04-01), `process.env` will contain any [environment variables](/workers/configuration/environment-variables/),
2424
[secrets](/workers/configuration/secrets/), or [version metadata](/workers/runtime-apis/bindings/version-metadata/) metadata that has been configured on your Worker.
2525

26-
### Relationship to per-request `env` argument in `fetch()` handlers
27-
28-
Workers have a concept of [environment variables](/workers/configuration/environment-variables/) that are applied on a per-Worker and per-request basis.
26+
Setting any value on `process.env` will coerce that value into a string.
2927

30-
By default, these are not accessible via the `process.env` API.
31-
To automatically populate environment variables and secrets on `process.env`, enable
32-
the [`nodejs_compat_populate_process_env`](/workers/configuration/compatibility-flags/#nodejs_compat_populate_process_env)
33-
compatibility flag and disable the `disallow_importable_env` compatibility flag.
34-
It is also possible to manually copy these values into `process.env` if
35-
necessary -- but only within the context of a request.
28+
### Alternative: Import `env` from `cloudflare:workers`
3629

37-
Setting any value on `process.env` will coerce that value into a string.
30+
Instead of using `process.env`, you can [import `env` from `cloudflare:workers`](/workers/runtime-apis/bindings/#importing-env-as-a-global) to access environment variables and all other bindings from anywhere in your code.
3831

3932
```js
4033
import * as process from "node:process";

0 commit comments

Comments
 (0)