@tanstack/db assumes crypto.randomUUID exists in non-secure browser contexts #1541
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.tsfor mutation IDs on insert/update/deletepackages/db/src/transactions.tsfor transaction IDspackages/db/src/local-only.tsfor local-only collection IDspackages/db/src/collection/index.tswhen 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:
crypto.randomUUID()is secure-context-only: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUIDcrypto.getRandomValues()is available in insecure contexts: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
why haven’t yhe team fixed this yet?
KyleAMathews closed this
Sign in to join this conversation.
the same issue exists in
db-sqlite-persistence-corewhich is consumed byexpo-db-sqlite-persistencewherecrypto.randomUUIDisn't available.