Skip to content

@tanstack/db assumes crypto.randomUUID exists in non-secure browser contexts #1541

Description

@m3ridian-zero

Describe the bug

In browser contexts served over non-localhost HTTP, such as a dev server accessed from another machine via a LAN IP address, crypto.randomUUID can be unavailable because it is a secure-context-only API. crypto.getRandomValues remains available in insecure contexts.

@tanstack/db calls crypto.randomUUID() directly in collection, transaction, and mutation paths. That causes collection writes to throw before application code can handle it.

Version

  • @tanstack/db: 0.6.5
  • Browser: Chromium/Chrome behavior consistent with the Web Crypto secure-context restriction

Reproduction

Serve a browser app over non-localhost HTTP, for example:

http://<LAN-IP>:<port>

In DevTools on that page:

window.isSecureContext // false
typeof crypto.randomUUID // "undefined"
typeof crypto.getRandomValues // "function"

Then run code equivalent to:

import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'

const collection = createCollection(
  localOnlyCollectionOptions({
    id: 'items',
    getKey: (item) => item.id,
  }),
)

collection.insert({ id: '1' })

Expected behavior

The collection write succeeds, or @tanstack/db falls back to UUID generation via crypto.getRandomValues() when crypto.randomUUID() is not present.

Actual behavior

The write throws:

TypeError: crypto.randomUUID is not a function

Affected code paths

Current source has direct crypto.randomUUID() calls in several places, including:

  • packages/db/src/collection/mutations.ts for mutation IDs on insert/update/delete
  • packages/db/src/transactions.ts for transaction IDs
  • packages/db/src/local-only.ts for local-only collection IDs
  • packages/db/src/collection/index.ts when a collection ID is omitted

Suggested fix

Centralize UUID generation and use native crypto.randomUUID() when present. Otherwise, generate an RFC 4122 version 4 UUID using crypto.getRandomValues() when available.

If neither API is available, throw an explicit error explaining that UUID generation requires Web Crypto / a secure-enough browser environment.

Relevant docs:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions