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
kian
kian2y ago
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.
sks
sks2y ago
I see. are there any such global, but bound to the session? This is the starting point of my worker:
export async function onRequest(context)
export async function onRequest(context)
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 ?
kian
kian2y ago
context.data is there for arbitrary data
sks
sks2y ago
Can you provide me the link to the documentation for that. I think that should solve my problem.
kian
kian2y ago
API Reference · Cloudflare Pages docs
Learn about the APIs used within Pages Functions.
sks
sks2y ago
is the context.data empty? or can it have data when the worker is called ? Hello ?
JustinNoel
JustinNoel2y ago
You can put whatever your want in context.data and then access it wherever your have access to context.
sks
sks2y ago
I understand thank you
sakuta96
sakuta962y ago
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!
sks
sks2y ago
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 )
Want results from more Discord servers?
Add your server