Using this API in a worker you can convert a string name into an ID to get the DO stub object:
let id = OBJECT_NAMESPACE.idFromName(name);
But when my DO is running, how do I get
name from itself?
The API here only returns the hex ID:
Is there an API or env var?
Getting the name of the Durable Object is important as external systems index the data associated with the Durable Object by name, not by the non-human-readable hex ID. The name needs to be read from inside the Durable Object so that when sending the data to another system (central database/for backups) it can be indexed by Durable Object name.
state.id.name from the durable object can access the name
state.id.name will always be undefined inside a durable object. If you need access to the name inside a DO, pass it in the fetch request to the DO
PR to update docs here: state.id.name is not defined in a Durable Object by koeninger · Pull Request #8786 · cloudflare/cloudflare-docs · GitHub
It seems to be set when I run the durable object locally with:
wrangler dev src/index.ts --experimental-local
Will it not be set in production?
The interface also says
name may be set, but in which cases?
It will not be set in production.
A DurableObjectId contains a name only in the case it is obtained from
i.e. in the worker calling the durable object, not in the durable object itself.