Feature Request: Hook into worker script shutdown


#1

I would like to be able to run some code when the worker script is shutting down, and the data stored in the global JavaScript variables are about to be cleared. This would allow me to store information in global JavaScript variables that would persist between worker requests, and before shutdown sends that information to an external API for logging.

For my purposes, this would be useful for creating custom analytics beyond what Cloudflare provides in the dashboard.

Thanks!


#2

Awesome! This is a common use case of event.waitUntil and asynchronous requests. Workers doesn’t generally support an ‘unload’ hook, although we have not ruled it out. In general though, Workers are restarted so infrequently that customers find they only ‘lose’ the tiniest fraction of data. For sites which get a moderate amount of traffic, your Worker will most likely only be restarted a single time per week, making the data very accurate even given the negligible losses.


#3

You could alternatively provide a method to push those data periodically (Once a day? Once per hour?). That could also run before restart. It could be counted as a request, per billing purposes.


#4

I didn’t realize that the Worker scripts would persist for so long. That should work for my use-case.

I suppose this function could still be useful if someone were making frequent updates to their Worker script. Then the script could have a chance to do any necessary shutdown operations before it started the new version.