UuidThe Uuid class provides universally unique identifiers (UUIDs) with support for UUID v4 (random) and UUID v7 (time-ordered) generation.
Import:
import { Uuid } from 'surrealdb' ; Source: value/uuid.ts
Constructor new Uuid(value)Create a UUID from an existing value.
new Uuid ( uuid ) // Clone existing new Uuid ( string ) // Parse from string new Uuid ( bytes ) // From binary representation Parameters Parameter Type Description value Uuid | string | ArrayBuffer | Uint8ArrayValue to create UUID from.
Examples // Parse from string const uuid = new Uuid ( '550e8400-e29b-41d4-a716-446655440000' ) ; // From binary const bytes = new Uint8Array ( [ /* 16 bytes */ ] ) ; const uuid = new Uuid ( bytes ) ; // Clone existing const copy = new Uuid ( uuid ) ; Static Methods Uuid.v4()Generate a random UUID v4.
Returns Uuid - Random UUID v4
Example const randomId = Uuid . v4 ( ) ; console . log ( randomId . toString ( ) ) ; // '550e8400-e29b-41d4-a716-446655440000' // Use as record ID const userId = new RecordId ( 'users' , Uuid . v4 ( ) ) ; await db . create ( userId ) . content ( userData ) ;
Uuid.v7()Generate a time-ordered UUID v7.
Returns Uuid - Time-ordered UUID v7
UUID v7 includes a timestamp component, making it sortable by creation time. This is useful for time-series data and maintaining chronological order.
Example const timeOrderedId = Uuid . v7 ( ) ; // Sequential v7 UUIDs are sortable const id1 = Uuid . v7 ( ) ; // ... time passes ... const id2 = Uuid . v7 ( ) ; // id1 < id2 (lexicographically)
Uuid.parse(string)Parse a UUID from its string representation.
Parameters Parameter Type Description str stringUUID string in standard format.
Returns Uuid - Parsed UUID
Example const uuid = Uuid . parse ( '550e8400-e29b-41d4-a716-446655440000' ) ; Instance Methods .toString()Convert to string representation.
Returns string - UUID string in standard format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
Example const uuid = Uuid . v4 ( ) ; console . log ( uuid . toString ( ) ) ; // '550e8400-e29b-41d4-a716-446655440000'
.toJSON()Serialize for JSON.
Returns string - UUID string
.toUint8Array()Get the binary representation as Uint8Array.
Returns Uint8Array - 16-byte binary representation
Example const uuid = Uuid . v4 ( ) ; const bytes = uuid . toUint8Array ( ) ; console . log ( bytes . length ) ; // 16
.toBuffer()Get the binary representation as ArrayBuffer.
Returns ArrayBufferLike - Binary representation
.equals(other)Check if two UUIDs are equal.
Returns boolean - True if equal
Complete Examples Session Management import { Surreal , Uuid , RecordId , DateTime , Duration , Table } from 'surrealdb' ; const db = new Surreal ( ) ; await db . connect ( 'ws://localhost:8000' ) ; // Create session with UUID const sessionId = Uuid . v4 ( ) ; const session = await db . create ( new RecordId ( 'sessions' , sessionId ) ) . content ( { user : userId , created_at : DateTime . now ( ) , expires_at : DateTime . now ( ) . plus ( Duration . parse ( '24h' ) ) , ip_address : '192.168.1.1' } ) ; console . log ( 'Session ID:' , sessionId . toString ( ) ) ; Time-Ordered Records // Use v7 for time-series data const events = [ ] ; for ( let i = 0 ; i < 100 ; i ++ ) { const eventId = Uuid . v7 ( ) ; await db . create ( new RecordId ( 'events' , eventId ) ) . content ( { type : 'user_action' , timestamp : DateTime . now ( ) , data : { action : 'click' , target : 'button' } } ) ; events . push ( eventId ) ; } // Events are naturally sorted by creation time Unique Identifiers // Generate unique IDs for various purposes const requestId = Uuid . v4 ( ) ; const correlationId = Uuid . v4 ( ) ; const traceId = Uuid . v7 ( ) ; // Time-ordered for distributed tracing await db . create ( new Table ( 'requests' ) ) . content ( { id : requestId , correlation_id : correlationId , trace_id : traceId , timestamp : DateTime . now ( ) } ) ; API Keys // Generate API keys function generateApiKey ( ) : string { return `api_ ${ Uuid . v4 ( ) . toString ( ) . replace ( /-/g , '' ) } ` ; } const apiKey = generateApiKey ( ) ; console . log ( apiKey ) ; // 'api_550e8400e29b41d4a716446655440000' await db . create ( new Table ( 'api_keys' ) ) . content ( { key : apiKey , user : userId , created_at : DateTime . now ( ) } ) ; Distributed System IDs // Use UUID v7 for distributed systems (sortable) class IdGenerator { static generateOrderId ( ) : Uuid { return Uuid . v7 ( ) ; // Time-ordered } static generateTransactionId ( ) : Uuid { return Uuid . v7 ( ) ; // Time-ordered } static generateRandomId ( ) : Uuid { return Uuid . v4 ( ) ; // Random } } const orderId = IdGenerator . generateOrderId ( ) ; const txnId = IdGenerator . generateTransactionId ( ) ; File Upload Tracking // Track file uploads with UUIDs async function uploadFile ( file : File ) : Promise < string > { const uploadId = Uuid . v4 ( ) ; await db . create ( new RecordId ( 'uploads' , uploadId ) ) . content ( { filename : file . name , size : file . size , mime_type : file . type , uploaded_at : DateTime . now ( ) , status : 'processing' } ) ; return uploadId . toString ( ) ; } Parsing and Validation // Parse UUID from user input function validateUuid ( input : string ) : Uuid | null { try { return Uuid . parse ( input ) ; } catch ( error ) { console . error ( 'Invalid UUID format' ) ; return null ; } } const userInput = '550e8400-e29b-41d4-a716-446655440000' ; const uuid = validateUuid ( userInput ) ; if ( uuid ) { const record = await db . select ( new RecordId ( 'items' , uuid ) ) ; } Batch ID Generation // Generate multiple UUIDs function generateBatchIds ( count : number , useV7 = false ) : Uuid [ ] { const ids : Uuid [ ] = [ ] ; for ( let i = 0 ; i < count ; i ++ ) { ids . push ( useV7 ? Uuid . v7 ( ) : Uuid . v4 ( ) ) ; } return ids ; } const randomIds = generateBatchIds ( 100 ) ; // 100 random UUIDs const sortableIds = generateBatchIds ( 100 , true ) ; // 100 time-ordered UUIDs UUID v4 vs UUID v7 UUID v4 (Random) Pros: Truly random, no predictability
Cons: Not sortable, no time information
Use when: You need unpredictable, secure IDs
const randomId = Uuid . v4 ( ) ; UUID v7 (Time-ordered) Pros: Sortable, includes timestamp, better for database indexes
Cons: Slightly predictable (timestamp component)
Use when: You need sortable IDs or time-series data
const timeOrderedId = Uuid . v7 ( ) ; Best Practices 1. Choose the Right Version // Good: v7 for time-series and events const eventId = Uuid . v7 ( ) ; // Good: v4 for security tokens const token = Uuid . v4 ( ) ; 2. Use with RecordId // Good: UUID as record ID const userId = new RecordId ( 'users' , Uuid . v7 ( ) ) ; // Good: Provides uniqueness and sortability await db . create ( userId ) . content ( userData ) ; // Good: Validate before use try { const uuid = Uuid . parse ( userInput ) ; await processUuid ( uuid ) ; } catch ( error ) { return { error : 'Invalid UUID format' } ; } 4. Store as UUID Type // Good: Store as UUID await db . create ( table ) . content ( { session_id : Uuid . v4 ( ) } ) ; // Avoid: Store as string await db . create ( table ) . content ( { session_id : Uuid . v4 ( ) . toString ( ) } ) ; See Also