In Cloudflare Workers, what does `import { env } from "cloudflare:workers"` let module-level code do, and which binding calls still fail there?
answer
- env outside the handler
- global scope forbids I/O
- values yes, calls no
- withEnv for overrides
basics
~20 sIt exposes the Worker's bindings at module level and in nested functions without passing env along. Top-level code may read vars and secrets, but I/O such as a KV get or a service binding call throws outside a handler.
solid answer
~50 s`import { env } from "cloudflare:workers"` gives any module the bindings the handler receives. Two uses follow: top-level setup that reads a var or secret before any request, such as configuring a client, and deeply nested helpers that read `env.PROVIDER_API_KEY` without threading `env` through every call. The limit is the runtime's rule that global scope allows no asynchronous I/O. Reading values works, and so does `env.NAMESPACE.get(id)` to obtain a Durable Object stub, but a KV call, a call on that stub or a service binding call throws `Disallowed operation called within global scope`; uncaught at top level, that stops the Worker from starting. Inside a handler the imported `env` works for every binding. `withEnv()` from the same module runs a callback with overridden values, which helps tests, and passing `env` as a parameter remains the plainer pattern for dependency injection.
code
javascript · 22 linesimport { env } from "cloudflare:workers";
// Allowed at top level: reading a var or a secret.
const PROVIDER_REGION = env.PROVIDER.region;
// Not allowed at top level: this KV call would throw.
// const cursor = await env.WEBHOOK_STATE.get("cursor");
function providerHeaders() {
return { Authorization: `Bearer ${env.PROVIDER_API_KEY}` };
}
export default {
async fetch(request) {
const cursor = await env.WEBHOOK_STATE.get("cursor");
return Response.json({
region: PROVIDER_REGION,
cursor,
hasAuth: "Authorization" in providerHeaders(),
});
},
};go deeper
Recall that env can be imported from cloudflare:workers and read anywhere, including in helper functions far from the handler.
Explain which operations global scope allows: reading vars and secrets and getting a stub, but no KV, stub or service binding calls.
Show why values derived in module scope can go stale after a bindings-only deploy, and how withEnv keeps code that reads the imported env testable.
Weigh an ambient env against explicit parameters for testability and clarity, and settle one convention for the team's codebase.
## Three ways to reach `env` A Worker's bindings (vars, secrets, KV namespaces, R2 buckets and the rest) live on an object called `env`. The runtime offers it in three places: - as an **argument to entrypoint handlers**, as in `fetch(request, env, ctx)`; - as **`this.env`** on classes that extend `WorkerEntrypoint`, `DurableObject` or `WorkflowEntrypoint`; - as an **import**: `import { env } from "cloudflare:workers"`, usable from any module, including at the top level. The import solves two problems. Setup code can configure something once at module load (a log level read from a var, an API client configured from a secret), and helper functions several calls deep can read a binding without every function in between taking an `env` parameter. ## What module-level code may do Workers do not allow I/O outside a request context, and the imported `env` does not change that rule. It changes only *where you can see* the bindings. | Operation | At module top level | Inside a handler | |---|---|---| | Read a var or secret, `env.PROVIDER.region` | Works | Works | | Get a Durable Object stub, `env.NAMESPACE.get(id)` | Works | Works | | Call a method on that stub | Fails | Works | | KV call, `env.WEBHOOK_STATE.get("cursor")` | Fails | Works | | Call another Worker through a service binding | Fails | Works | A failing call throws synchronously while the module is being evaluated, with the runtime's global-scope error: ```plaintext Uncaught Error: Disallowed operation called within global scope. Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values are not allowed within global scope. To fix this error, perform this operation within a handler. ``` Because the error is raised during module evaluation, an uncaught one means the Worker's script cannot load at all. A top-level `await` does not help: it does not defer the call into a request, it just evaluates the forbidden call at load time. ## A worked example Take a payments-webhook Worker with a JSON var `PROVIDER` (holding the provider's region), a secret `PROVIDER_API_KEY` and a KV namespace bound as `WEBHOOK_STATE`: 1. When an isolate loads the module, the top-level line `const PROVIDER_REGION = env.PROVIDER.region;` reads the var. No I/O happens, so this is allowed. 2. A helper `providerHeaders()` reads `env.PROVIDER_API_KEY` from the imported `env`. It takes no parameters, yet it is called only from inside the handler, so it always runs during a request. 3. The handler performs the KV read `await env.WEBHOOK_STATE.get("cursor")`. The same line moved to the top of the module would stop the script from loading. Inside a handler, the imported `env` and the handler's own `env` parameter expose the same bindings, so code can mix the two styles while a codebase migrates from one to the other. ## Caveats that come with an ambient `env` 1. **Derived values are computed once per isolate.** A client or parsed configuration built at the top level is built when the isolate loads the module. Cloudflare may reuse running isolates when a deploy changes only bindings, so such an object can keep an old secret after the secret changes. Anything that must track the current value belongs inside the handler. 2. **Dependencies become invisible.** A function that reads the imported `env` has an input its signature does not show. `withEnv(overrides, callback)`, also exported from `cloudflare:workers`, runs the callback with the imported `env` showing overridden values and restores the originals afterwards. Cloudflare's docs still note that passing `env` as an argument is a helpful pattern for dependency injection and testing. 3. **It can be switched off.** The compatibility flag `disallow_importable_env` removes the importable `env`, together with the importable `exports`. ## In practice - Use the import for configuration that is safe to compute once, and for helpers deep in a call tree. - Keep every KV, R2, D1, Durable Object or service binding call inside a handler, even when the `env` used is the imported one. - Do not cache objects derived from secrets at module level without a way to notice that the secret changed. - In tests, wrap calls in `withEnv()` or prefer an explicit `env` parameter for code you want to unit-test in isolation.
- Why may top-level code get a Durable Object stub from `env` but not call it?Cloudflare's docs allow `env.NAMESPACE.get(id)` at module level: it returns a stub, a handle to the object. Calling a method on the stub sends a request to the object, which is I/O, and global scope forbids I/O. Get the stub wherever is convenient, but make the call inside a handler.
- How do you test a helper that reads the imported `env`?Wrap the call in `withEnv({ PROVIDER_API_KEY: "test-key" }, () => helper())`: inside the callback the imported `env` shows the overridden values, and after it the configured ones return. Many teams still prefer to pass `env` as a parameter, which makes the dependency visible in the signature.
- Calling env.WEBHOOK_STATE.get() at module level to warm a cache before requests.
- Believing the imported env, like the handler parameter, exists only during a request.
- Assuming a top-level client built from a secret updates when the secret changes.
- Thinking withEnv changes the deployed Worker's bindings until the next deploy.
- Treating a top-level await on a binding call as a way around the global-scope rule.