Global in Workers?
I am creating a Cloudflare workers script, and I have too many scripts, I am having to pass the objects from one to another, and write a lot of complex stuff to just pass the objects, so that they are accessible where ever required.
I was wondering if it is possible to use global objects, such as in the browser we have the window object. Are there any such global object in the context of workers ?
10 Replies
globalThis
is the equivalent in Workers but it is used by any other concurrent requests going to that Worker, so you don't really want to put anything in there that isn't static.I see. are there any such global, but bound to the session?
This is the starting point of my worker:
it is a pages function.
Maybe I was thinking to append my variables to the context object, and just pass the context object only.
Or is there any other better way to go about this ?
context.data
is there for arbitrary dataCan you provide me the link to the documentation for that. I think that should solve my problem.
Doesn't seem like there really is any anymore - https://developers.cloudflare.com/pages/platform/functions/api-reference/#data
API Reference · Cloudflare Pages docs
Learn about the APIs used within Pages Functions.
is the context.data empty? or can it have data when the worker is called ?
Hello ?
You can put whatever your want in
context.data
and then access it wherever your have access to context
.I understand thank you
probably not the best way of doing things, but you could get the cloudflare ray id, the ip address and request url, then you would've a pretty damn unique id to use for extending the
globalThis
safely :)
the chance of another request having the same cf ray id, ip and request url is pretty low.
for even a higher guarantee of uniqueness, you could e.g. use the geo headers and/or user agent in addition!context.data is more suitable.
But I guess a global object store imported into each file is more better. (Kinda like the store for frontend frameworks like react / vue / svelte )