Skip to main content

Function: getDONamespaceFromPathSegment()

getDONamespaceFromPathSegment(pathSegment, env): undefined | { bindingName: string; namespace: any; }

Defined in: packages/utils/src/get-do-namespace-from-path-segment.ts:188

Find a Durable Object namespace from a path segment with intelligent case conversion.

This function bridges the gap between URL path segments (typically kebab-case) and TypeScript/Cloudflare environment binding names (various case conventions).

Smart Matching Rule: Only applies case conversion for kebab-case-with-only-lowercase-and-digits (e.g., my-do, api-v2, room-123). Any path segment with uppercase letters, underscores, or other characters matches exactly as-is.

Smart Matching Examples (kebab-case):

  • my-doMY_DO, MyDO, MyDo, myDo, my-do
  • user-sessionUSER_SESSION, UserSession, userSession, user-session
  • api-v2API_V2, ApiV2, apiV2, api-v2
  • my-d-oMY_D_O, MyDO, myDO, my-d-o

Exact Matching Examples (non-kebab-case):

  • MY_DOMY_DO only
  • MyDOMyDO only
  • my_domy_do only

Return Behavior:

  • Returns { bindingName, namespace } if exactly one match is found
  • Returns undefined if no matching binding is found (no-match scenario)
  • Throws MultipleBindingsFoundError if multiple bindings match (configuration error)

Parameters

pathSegment

string

The path segment that should match a DO binding

env

Record<string, any>

The Cloudflare Workers environment object containing DO bindings

Returns

undefined | { bindingName: string; namespace: any; }

Object with bindingName and namespace, or undefined if no match

Throws

If multiple bindings match the path segment (genuine error)

Example

// Kebab-case to SCREAMING_SNAKE_CASE
// URL: /my-do/instance → Binding: MY_DO
const result = getDONamespaceFromPathSegment('my-do', { MY_DO: myDoNamespace });
// → { bindingName: 'MY_DO', namespace: myDoNamespace }

// camelCase to PascalCase
// URL: /userSession/abc → Binding: UserSession
const result = getDONamespaceFromPathSegment('userSession', { UserSession: userNamespace });
// → { bindingName: 'UserSession', namespace: userNamespace }

// Handles acronyms intelligently
// URL: /chat-d-o/room → Binding: ChatDO
const result = getDONamespaceFromPathSegment('chat-d-o', { ChatDO: chatNamespace });
// → { bindingName: 'ChatDO', namespace: chatNamespace }

// No match cases return undefined
const result = getDONamespaceFromPathSegment('unknown', env);
// → undefined

// Multiple matches throw error
try {
const result = getDONamespaceFromPathSegment('ambiguous', {
AMBIGUOUS: ns1,
Ambiguous: ns2
});
} catch (error) {
if (error instanceof MultipleBindingsFoundError) {
console.log('Matched bindings:', error.matchedBindings);
}
}