In Cloudflare Durable Objects, what is the difference between idFromName() and newUniqueId(), and when would you choose each?
answer
- deterministic versus random
- who remembers the ID
- toString() and idFromString()
- first-access worldwide check
- ctx.id.name inside the object
basics
~10 sidFromName() hashes a string into the same Durable Object ID everywhere, so one name always reaches one object worldwide; newUniqueId() mints a random ID you must store (as toString()) and rebuild later with idFromString().
solid answer
~50 sBoth return a `DurableObjectId`, a 64-digit hex identifier for one instance of a class. `idFromName("doc-42")` is deterministic: every Worker, in every location, gets the same ID for the same name in the same namespace, so a document editor can route each document ID straight to its object without a lookup. `getByName()` folds that into one call and returns the stub. `newUniqueId()` returns a random ID that nobody can re-derive, so you persist `id.toString()` somewhere (a database row, a cookie, another object) and rebuild it with `idFromString()`, which throws on a malformed string or one from another namespace. The trade: a named object's first access runs a worldwide check that nobody else created it at the same moment (up to a few hundred milliseconds), which a unique ID skips. Inside the object, `ctx.id.name` holds the name when the caller used a name.
code
javascript · 26 linesimport { DurableObject } from "cloudflare:workers";
export class DocumentRoom extends DurableObject {
async whoAmI() {
return { id: this.ctx.id.toString(), name: this.ctx.id.name ?? null };
}
}
export default {
async fetch(request, env) {
const a = env.DOCUMENT.idFromName("doc-42");
const b = env.DOCUMENT.idFromName("doc-42");
const draft = env.DOCUMENT.newUniqueId();
const saved = draft.toString();
const restored = env.DOCUMENT.idFromString(saved);
return Response.json({
sameName: a.equals(b),
idLength: a.toString().length,
draftName: draft.name ?? null,
restoredEqual: restored.equals(draft),
byName: await env.DOCUMENT.getByName("doc-42").whoAmI(),
byUniqueId: await env.DOCUMENT.get(restored).whoAmI(),
});
},
};go deeper
Recall the two calls: idFromName() for a name you already have, newUniqueId() for a fresh random ID, and that both are only addresses until a stub is used.
Explain why a unique ID must be saved with toString() and rebuilt with idFromString(), and why that call throws for a string from another namespace.
Show you know the first-access global uniqueness check, why ctx.id.name can be undefined, and how a careless name choice funnels traffic onto one instance.
Frame the name as the unit of coordination: choosing what string identifies an object decides isolation, throughput and data residency for the whole design.
## What a Durable Object ID is A **Durable Object** is one instance of a class you export from a Cloudflare Worker, with its own storage and a single thread of execution. Every instance is identified by a **`DurableObjectId`**: a 64-digit hexadecimal value (not every 64-digit hex string is valid). You never build one by hand. You ask the **namespace binding** (for example `env.DOCUMENT`, declared under `durable_objects.bindings` in the Wrangler file) to make one, then turn it into a **stub** with `get(id)`. Creating an ID does not create the object. The object comes into existence lazily, when the first call through a stub reaches it. That is why an application can address billions of objects without ever provisioning them. ## The two ways to make an ID | | `idFromName(name)` | `newUniqueId()` | |---|---|---| | Input | any string you choose | none (optionally `{ jurisdiction }`) | | Same result twice? | yes, in the same namespace | never | | How you find it again | call `idFromName()` with the same name | store `id.toString()`, rebuild with `idFromString()` | | `id.name` / `ctx.id.name` | the name | `undefined` | | First access | runs a worldwide uniqueness check | skips that check | | Typical key | a business identifier you already have | a new thing with no natural key yet | **`idFromName()`** is the common case. The name is hashed into the ID, so a Worker in Sydney and a Worker in Frankfurt that both call `env.DOCUMENT.idFromName("doc-42")` get equal IDs (`a.equals(b)` is `true`) and reach the same single instance. In a collaborative document editor, the document's primary key from your own database is the natural name: every edit for that document funnels into one object, which is exactly what makes concurrent editing coordinate. **`getByName(name)`** is shorthand for `get(idFromName(name))`. It returns the stub directly and, like `get()`, accepts an optional `{ locationHint }`. **`newUniqueId()`** returns a random ID. Use it when the thing you are creating has no natural, collision-free name yet, for example a fresh anonymous editing session or a scratch draft that the server mints before a user names it. Because nobody can re-derive the ID, you must persist it: 1. Call `const id = env.DOCUMENT.newUniqueId()`. 2. Store `id.toString()` (64 hex characters) wherever you keep the mapping: a database row, a cookie, or the parent object that owns the child. 3. Later, call `env.DOCUMENT.idFromString(saved)` and `get()` that ID. `idFromString()` throws if the string is not a valid ID or was created by a different namespace, so a tampered or mixed-up value fails loudly instead of silently reaching an unrelated object. ## Why a unique ID is faster on first use When a named object is reached for the first time, the platform cannot rule out that a Worker on the other side of the world is reaching the same name at the same moment. To guarantee only one instance, it checks globally before creating it, and that round-the-world check can take up to a few hundred milliseconds. A random ID cannot collide, so `newUniqueId()` skips the check. After the first use the object's location is cached, so later lookups are fast either way. This is a first-access cost only. It should not drive the choice for long-lived objects such as documents; correctness of routing should. ## Knowing your own name inside the object Inside the class, `this.ctx.id` is the object's ID. Since March 2026, `ctx.id.name` holds the name when the caller used `idFromName()` or `getByName()`, which is useful in code with no caller to pass it, such as an alarm handler. It is `undefined` when: - the object was created with `newUniqueId()`; - the caller reached it through `idFromString()`, even if the ID originally came from a name; - the name is longer than 1,024 bytes. If an object must always know its business identity, persist it on first use rather than relying on how the caller happened to address it. ## Choosing in practice - **The entity already has a stable key** (document ID, tenant ID, room code): use `idFromName()` or `getByName()`. No lookup table, no extra read. - **The entity is being born and has no key yet**: `newUniqueId()`, then store the string with whatever will look it up later. - **The name comes from user input**: validate or normalise it first. Any string maps to some object, so `doc-42` and `Doc-42` are two different objects. - **The data must stay in one region**: create the ID from a jurisdiction-restricted subnamespace, `env.DOCUMENT.jurisdiction("eu")`, because the same name gives a different ID there. One design point follows from all of this: whatever string you choose as the name *is* your unit of coordination. Naming every document's object after one shared constant collapses the whole application onto a single instance.
- What happens if you call idFromString() with an ID string created by a different Durable Object namespace?It throws. An ID is only valid in the namespace that created it, so a string copied from another class's namespace, or a malformed string that is not 64 hex digits, is rejected instead of quietly addressing some other object. Treat a stored ID string as untrusted input and catch that error at the boundary.
- Is idFromName() itself a network call?No. Deriving the ID from the name happens in the calling Worker and returns immediately, as does creating the stub. The cost appears when the first request reaches a never-before-used named object: the platform then checks worldwide that no other instance with that ID was just created, which can take up to a few hundred milliseconds once.
- Your document editor stores each document's object ID string in a table. Is that needed?Not if the document already has a stable primary key. idFromName(documentId) re-derives the same ID on every request, so the table adds a read and a place to get out of sync. Storing the string is needed only for IDs from newUniqueId(), which no one can re-derive.
- idFromName() gives each data center its own copy of the object
- Calling newUniqueId() again with the same arguments returns the same ID
- Creating an ID or a stub instantiates the object immediately
- You must store idFromName() IDs in a table to find them again
- ctx.id.name is always set, whichever way the caller reached the object
Assumes Cloudflare's platform as of 2026-10-10: getByName() was added in August 2025 and ctx.id.name is populated inside the object since March 2026.