Cloudflare Workers KV Migrate Between Accounts / KV Namespaces
I recently had to move a Cloudflare KV Namespace from one environment to another, you could use this also to migrate Keys between accounts. To do this, I created a new API Key in the Cloudflare Dashboard with a Read-Only scope of my Workers and KV Namespaces, then I created a new Worker where I wanted to store the entries. This should be the Worker where you want to migrate to.
You should publish the new Worker and create the new KV Namespace for it. The following script sample does the following things:
- being executed from the new Worker
- calls the Cloudflare REST API to retrieve KV keys and values from the OLD Worker
- iterates through the keys
- fetches the name and value
- puts them into the new KV
This script should just be some guidance, and probably needs to be updated for each use-case. In my use-case, I used KV metadata as well to store the content-type of a file, so I’m migrating this also.
I stored the API Key of the old environment in a secret with the name oldApiKey, like so:
wrangler secret put oldApiKey
The Account ID and Namespace ID can be retrieved from the Cloudflare Dashboard and need to be put manually into the Worker. For me, this was a one-off Task, and I’m not running this continuously. Also, if you have a lot of keys, you might need some paginating in the migration script as well, the maximum number of keys the API returns is limited to 1000