How to dynamically create and delete namespaces in Cloudflare Workers KV

534 views Asked by At

I am trying to create a mini database that may have to be dynamic in workers. I have a workers backend going and a couple kv namespaces. When the app is live I would like the ability to create a new space and then populate it or delete a namespace and its items. I know how to add, read and delete kv-pairs in existing namespaces within the script using NAMESPACE.get and so on. However I do not know how to create or delete a namespace within the script. I know I can go onto the workers dashboard or do it from wrangler CLI but I really need the application to make its own namespaces when its live.

How can I do this?

Was told to post here from webmaster.stackexchange.

https://webmasters.stackexchange.com/questions/139465/how-to-dynamically-create-and-delete-namespaces-in-cloudflare-workers-kv

1

There are 1 answers

0
Brett On

You can manage Workers KV namespaces via the API: https://api.cloudflare.com/#workers-kv-namespace-create-a-namespace

Workers bindings can't be dynamically managed from within a Worker, though. You'd need to redeploy your worker itself to add or remove KV bindings to use the namespace efficiently from your Worker.

I wouldn't recommend doing anything above.

I would make an abstraction using a single KV namespace. Add your own prefix to each key access, depending on what "namespace" you want to access.