Worker Environment

When request comes into the worker you have two objects (context and environment). Is environment scoped to the specific reqeust like context or is shared across the requests? Example if I set some unique value on environment, will it stay in that request or it can leak into other requests. Afaik context is scoped to the request and is not leaking (like global scope) across requests in the same worker, but I am not sure if the same is for environment
4 Replies
tadhglewis
tadhglewis3mo ago
Afaik there's no good reason to set variables on the environment object. Just create a new variable environment is just used for this like bindings to R2 and secrets. It's not some request object that you modify
nejc
nejcOP3mo ago
@Lewis thank you for the reply. My question is more about how local/global scope and memory works with this variables
tadhglewis
tadhglewis3mo ago
You should not use global scope in Workers, everything should be scoped within the fetch function. If you have a code example I can guide you more on a more specific example. Generally speaking everything is isolated within Workers except #durable-objects or calls to bindings etc
mallets
mallets3mo ago
You shouldn't use it but there is no way around it sometimes. I use global variables to set a "first run" flag and fetch some (read-only) data only once per worker instantiation. Would be terribly slow if I keep fetching that piece of data every request. And don't say use KV or other offerings, trying to avoid unnecessary dependencies.
Want results from more Discord servers?
Add your server