Can you access _cfduid in a Cloudflare worker?

Is there a way to access _cfduid (or some other “client id”) in a Cloudflare worker? Has it been set by the time the worker runs?

I want to send requests to Google Analytics from the worker, since that will better protect a user’s privacy than loading the JS on the page, but they require a Client ID. I was thinking of using the _cfduid but I’m not sure how to access that from the worker. Any ideas?

If a client doesn’t send the cookie yet along, you won’t get it. Once it is set you should be able to access it via the standard methods of request.headers.

Ah. I see that it is there. Is there a way to get it while it is being set (i.e. on the initial request)? or does that happen after the worker is run?

That is most likely going to be added once the script returns.

Welp… it would be nice if there was a way to get that on the initial request (maybe a property on the FetchEvent or something?)

If you want a unique id on each request then I believe you can use ‘cf-request-id’ header and if you want to have unique id per session then you can do something with ‘x-real-ip’