Vaultrice SDK - v1.1.1
    Preparing search index...

    Class NonLocalStorage

    Provides a persistent, optionally encrypted, remote key-value store. Supports atomic operations, TTL, and presence via websockets.

    Use this class to interact with the Vaultrice API for storing and retrieving data.

    Hierarchy

    • default
      • NonLocalStorage
    Index

    Constructors

    Properties

    id: string

    Unique instance identifier

    ttl: undefined | number
    isConnected: boolean = false

    Indicates if the WebSocket connection is currently established. True if connected, false otherwise. Only relevant/appropriate if having some listeners attached (i.e. nls.on('message')) If not using any WebSocket feature, it will always return false.

    connectionId?: string

    Connection ID assigned by the server for the WebSocket connection.

    Methods

    • Retrieves an access token for a given project using API credentials.

      Parameters

      • projectId: string

        The unique identifier of the project.

      • apiKey: string

        The API key associated with the project.

      • apiSecret: string

        The API secret associated with the project.

      • Optionaloptions: { origin?: string }

        Optional settings for token retrieval.

        • Optionalorigin?: string

          (Optional) The browser origin to use if the API key has configured an origin restriction. Pass this when minting a token from a backend for use in a browser. Example: { origin: req.headers.origin }

      Returns Promise<string>

      A promise that resolves to the access token as a string.

      const token = await NonLocalStorage.retrieveAccessToken('projectId', 'apiKey', 'apiSecret');
      // When there is an origin restriction:
      const token = await NonLocalStorage.retrieveAccessToken('projectId', 'apiKey', 'apiSecret', { origin: req.headers.origin });
    • Sets the access token to be used for authentication.

      Parameters

      • accessToken: string

        The access token string to set.

      Returns number

      token expiration in milliseconds from now

      When using the token provider authentication method, you typically don't need to call this directly - the SDK handles it automatically.

    • Registers a handler function to be called when the access token is about to expire.

      Parameters

      • handler: () => void

        A callback function that will be invoked before the access token expires.

      Returns void

    • Removes a previously registered handler for the access token expiring event.

      Parameters

      • handler: () => void

        The callback function to remove from the access token expiring handlers list.

      Returns void

    • Retrieve or initialize encryption settings for end-to-end encryption.

      Parameters

      • OptionalsaltLength: number

        Optional salt length in bytes (default: 16).

      Returns Promise<EncryptionSettingsInfos>

      Promise resolving to encryption settings information.

      Error if called without encryption configuration.

      This method is mandatory when using end-to-end encryption. It fetches the encryption salt and key version from the server, then initializes the encryption handler.

    • Rotate encryption keys to enhance security.

      Parameters

      • OptionalsaltLength: number

        Optional salt length in bytes (default: 16).

      Returns Promise<EncryptionSettingsInfos>

      Promise resolving to new encryption settings information.

      Error if called without encryption configuration.

      This generates new encryption settings while preserving access to data encrypted with previous keys. Useful for periodic security rotation.

    • Store a value by key.

      Parameters

      • name: string

        The key name.

      • value: ValueType

        The value to store.

      • Optionaloptions: { ttl?: number; ifAbsent?: boolean; updatedAt?: number }

        Optional overrides.

        • Optionalttl?: number

          Time-to-live in milliseconds for this item.

        • OptionalifAbsent?: boolean

          If true only set if item absent.

        • OptionalupdatedAt?: number

          If provided, the operation will only succeed if the remote item's updatedAt timestamp matches this value.

      Returns Promise<undefined | ItemType>

      Metadata about the stored item.

      3600000 (1 hour)
      
      false
      
      undefined
      
    • Store multiple values at once.

      Parameters

      • items: Record<
            string,
            { value: ValueType; ttl?: number; ifAbsent?: boolean; updatedAt?: number },
        >

        Object of key/value pairs. Example: { key1: { value: 'foo' }, key2: { value: 'bar', ttl: 3600000 }, key2: { value: 'zip', ifAbsent: true } } ttl is time-to-live in milliseconds for each item.

      Returns Promise<undefined | ItemsType>

      Metadata for each stored item.

      3600000 (1 hour) ifAbsent if true only set if item absent - for each item.

      false updatedAt If provided, the operation will only succeed if the remote item's updatedAt timestamp matches this value.

      undefined
      
    • Retrieve multiple values by key.

      Parameters

      • names: string[]

        Array of key names.

      Returns Promise<undefined | ItemsType>

      Object of items found.

    • Retrieve all items, optionally filtered by prefix.

      Parameters

      • Optionaloptions: { prefix?: string }

        Optional prefix filter.

      Returns Promise<undefined | ItemsType>

      Object of all items.

    • Get all keys, optionally filtered by prefix.

      Parameters

      • Optionaloptions: { prefix?: string }

        Optional prefix filter.

      Returns Promise<undefined | string[]>

      Array of key names.

    • Remove a value by key.

      Parameters

      • name: string

        The key name.

      Returns Promise<undefined>

    • Remove multiple values by key.

      Parameters

      • names: string[]

        Array of key names.

      Returns Promise<undefined>

    • Atomically increment a numeric value.

      Parameters

      • name: string

        The key name.

      • value: number = 1

        Amount to increment by (default 1).

      • Optionaloptions: { ttl?: number; updatedAt?: number }

        Optional overrides.

        • Optionalttl?: number

          Time-to-live in milliseconds for this item.

        • OptionalupdatedAt?: number

          If provided, the operation will only succeed if the remote item's updatedAt timestamp matches this value.

      Returns Promise<ItemType>

      The updated item.

      3600000 (1 hour)
      
      undefined
      
    • Atomically decrement a numeric value.

      Parameters

      • name: string

        The key name.

      • value: number = 1

        Amount to decrement by (default 1).

      • Optionaloptions: { ttl?: number; updatedAt?: number }

        Optional overrides.

        • Optionalttl?: number

          Time-to-live in milliseconds for this item.

        • OptionalupdatedAt?: number

          If provided, the operation will only succeed if the remote item's updatedAt timestamp matches this value.

      Returns Promise<ItemType>

      The updated item.

      3600000 (1 hour)
      
      undefined
      
    • Atomically adds an element to an item that is an array. If the item does not exist, it will be created as a new array.

      Parameters

      • name: string

        The key of the array item.

      • element: ValueType

        The element to push to the array.

      • Optionaloptions: { ttl?: number; updatedAt?: number }

        Optional overrides.

        • Optionalttl?: number

          Time-to-live in milliseconds for this item.

        • OptionalupdatedAt?: number

          If provided, the operation will only succeed if the remote item's updatedAt timestamp matches this value.

      Returns Promise<ItemType>

      The updated item metadata.

      3600000 (1 hour)
      
      undefined
      
    • Atomically modifies an array item using splice semantics.

      Parameters

      • name: string

        The key of the array item.

      • startIndex: number

        The index to start changing the array.

      • deleteCount: number

        The number of elements to remove.

      • Optionalitems: ValueType[]

        Optional array of elements to add.

      • Optionaloptions: { ttl?: number; updatedAt?: number }

        Optional overrides.

        • Optionalttl?: number

          Time-to-live in milliseconds for this item.

        • OptionalupdatedAt?: number

          If provided, the operation will only succeed if the remote item's updatedAt timestamp matches this value.

      Returns Promise<ItemType>

      The updated item metadata.

      3600000 (1 hour)
      
      undefined
      
    • Atomically merges fields from a given object into an existing JSON object. If the item does not exist, it will be created.

      Parameters

      • name: string

        The key of the object item.

      • objectToMerge: ValueType

        The object containing fields to merge.

      • Optionaloptions: { ttl?: number; updatedAt?: number }

        Optional overrides.

        • Optionalttl?: number

          Time-to-live in milliseconds for this item.

        • OptionalupdatedAt?: number

          If provided, the operation will only succeed if the remote item's updatedAt timestamp matches this value.

      Returns Promise<ItemType>

      The updated item metadata.

      3600000 (1 hour)
      
      undefined
      
    • Atomically sets a value deep within a nested JSON object using a path.

      Parameters

      • name: string

        The key of the object item.

      • path: string | string[]

        A dot notation string (e.g., "user.profile.name") or an array of keys.

      • value: ValueType

        The value to set at the specified path.

      • Optionaloptions: { ttl?: number; updatedAt?: number }

        Optional overrides.

        • Optionalttl?: number

          Time-to-live in milliseconds for this item.

        • OptionalupdatedAt?: number

          If provided, the operation will only succeed if the remote item's updatedAt timestamp matches this value.

      Returns Promise<ItemType>

      The updated item metadata.

      3600000 (1 hour)
      
      undefined
      
    • Remove all items for this instance.

      Returns Promise<undefined>

    • Send a message to the server or other clients.

      Parameters

      • msg: JSONObj

        The message object to send.

      • options: {
            transport?: "ws" | "http";
            auth?: { userIdSignature?: string; identityToken?: string };
        } = ...

        Transport and authentication options.

        • Optionaltransport?: "ws" | "http"

          Transport method: 'ws' (WebSocket) or 'http'. Defaults to 'ws'.

        • Optionalauth?: { userIdSignature?: string; identityToken?: string }

          Optional authentication credentials for user verification.

          • OptionaluserIdSignature?: string

            The signature for Mode 3 user verification.

          • OptionalidentityToken?: string

            The JWT token for Mode 2 user verification.

      Returns Promise<undefined>

      Error if encryption is configured but getEncryptionSettings() not called.

      • If transport: 'ws' (WebSocket), the message is delivered to other clients but not echoed back to the sender. The sender will not receive their own message via on('message').
      • If transport: 'http', the message is delivered to all clients including the sender. The sender will receive their own message via on('message').
      • Messages are automatically encrypted if encryption is configured.
      • WebSocket transport is preferred for real-time delivery, but HTTP can be used as fallback.
      • User ID signature verification will not work with encrypted payloads or non-string payloads.
      • When using userIdSignature, the userId should also be provided for proper verification.
      // Message sent via WebSocket (not received by sender)
      await instance.send({ type: 'chat', message: 'Hello!' });

      // Message sent via HTTP (received by sender)
      await instance.send({ type: 'chat', message: 'Hello!' }, { transport: 'http' });

      // Send with Mode 2 user authentication
      await instance.send(
      { type: 'chat', message: 'Hello!', userId: '1234 },
      {
      transport: 'ws',
      auth: { identityToken: 'jwt-token-here' }
      }
      );

      // Send with Mode 3 user authentication
      await instance.send(
      { type: 'chat', message: 'Hello!', userId: '1234 },
      {
      transport: 'ws',
      auth: {
      userIdSignature: 'signature123'
      }
      }
      );
    • Register an event handler for WebSocket connection events.

      Parameters

      • event: "connect"

        The 'connect' event name.

      • handler: () => void

        Function to call when connected.

      Returns any

    • Register an event handler for WebSocket disconnection events.

      Parameters

      • event: "disconnect"

        The 'disconnect' event name.

      • handler: () => void

        Function to call when disconnected.

      Returns any

    • Register an event handler for presence join events.

      Parameters

      • event: "presence:join"

        The 'presence:join' event name.

      • handler: (joinedConnection: JoinedConnection) => void

        Function to call when a connection joins.

      Returns any

    • Register an event handler for presence leave events.

      Parameters

      • event: "presence:leave"

        The 'presence:leave' event name.

      • handler: (leavedConnection: LeavedConnection) => void

        Function to call when a connection leaves.

      Returns any

    • Register an event handler for incoming messages.

      Parameters

      • event: "message"

        The 'message' event name.

      • handler: (data: JSONObj) => void

        Function to call when a message is received.

      Returns any

    • Register an event handler for WebSocket errors.

      Parameters

      • event: "error"

        The 'error' event name.

      • handler: (error: Error) => void

        Function to call when an error occurs.

      Returns any

    • Register an event handler for all setItem events.

      Parameters

      • event: "setItem"

        The 'setItem' event name.

      • handler: (item: ItemType & { prop: string }) => void

        Function to call when any item is set.

      Returns any

    • Register an event handler for specific setItem events.

      Parameters

      • event: "setItem"

        The 'setItem' event name.

      • name: string

        The specific item name to listen for.

      • handler: (item: ItemType & { prop: string }) => void

        Function to call when the named item is set.

      Returns any

    • Register an event handler for all removeItem events.

      Parameters

      • event: "removeItem"

        The 'removeItem' event name.

      • handler: (item: { prop: string }) => void

        Function to call when any item is removed.

      Returns any

    • Register an event handler for specific removeItem events.

      Parameters

      • event: "removeItem"

        The 'removeItem' event name.

      • name: string

        The specific item name to listen for.

      • handler: (item: { prop: string }) => void

        Function to call when the named item is removed.

      Returns any

    • Remove an event handler for WebSocket connection events.

      Parameters

      • event: "connect"

        The 'connect' event name.

      • handler: () => void

        Function to remove.

      Returns any

    • Remove an event handler for WebSocket disconnection events.

      Parameters

      • event: "disconnect"

        The 'disconnect' event name.

      • handler: () => void

        Function to remove.

      Returns any

    • Remove an event handler for presence join events.

      Parameters

      • event: "presence:join"

        The 'presence:join' event name.

      • handler: (joinedConnection: JoinedConnection) => void

        Function to remove.

      Returns any

    • Remove an event handler for presence leave events.

      Parameters

      • event: "presence:leave"

        The 'presence:leave' event name.

      • handler: (leavedConnection: LeavedConnection) => void

        Function to remove.

      Returns any

    • Remove an event handler for incoming messages.

      Parameters

      • event: "message"

        The 'message' event name.

      • handler: (data: JSONObj) => void

        Function to remove.

      Returns any

    • Remove an event handler for WebSocket errors.

      Parameters

      • event: "error"

        The 'error' event name.

      • handler: (error: Error) => void

        Function to remove.

      Returns any

    • Remove an event handler for all setItem events.

      Parameters

      • event: "setItem"

        The 'setItem' event name.

      • handler: (item: ItemType & { prop: string }) => void

        Function to remove.

      Returns any

    • Remove an event handler for specific setItem events.

      Parameters

      • event: "setItem"

        The 'setItem' event name.

      • name: string

        The specific item name.

      • handler: (item: ItemType & { prop: string }) => void

        Function to remove.

      Returns any

    • Remove an event handler for all removeItem events.

      Parameters

      • event: "removeItem"

        The 'removeItem' event name.

      • handler: (item: { prop: string }) => void

        Function to remove.

      Returns any

    • Remove an event handler for specific removeItem events.

      Parameters

      • event: "removeItem"

        The 'removeItem' event name.

      • name: string

        The specific item name.

      • handler: (item: { prop: string }) => void

        Function to remove.

      Returns any

    • Opens the WebSocket connection.

      Returns Promise<void>

      Does usually not need to be used, since the WebSocke connection is automatically established on WS feature usage.

    • Close the WebSocket connection and clean up resources.

      Returns Promise<void>

      If the instance has joined the presence channel, it will automatically leave before disconnecting. This ensures proper cleanup and notifies other clients of the departure. All event handlers are also cleaned up.

    • Join the presence channel to announce this connection to others.

      Parameters

      • data: JSONObj

        Optional data to associate with this connection.

      • Optionalauth: { userIdSignature?: string; identityToken?: string }

        Optional object containing authentication credentials.

        • OptionaluserIdSignature?: string

          The signature for Mode 3 verification.

        • OptionalidentityToken?: string

          The JWT for Mode 2 verification.

      Returns Promise<undefined>

      Error if encryption is configured but getEncryptionSettings() not called.

      After joining, this connection will:

      • Appear in getJoinedConnections() results for other clients
      • Trigger 'presence:join' events for other connected clients
      • Automatically send 'presence:leave' when disconnecting
      await instance.join({
      username: 'Alice',
      status: 'online',
      avatar: 'avatar1.png'
      });
    • Leave the presence channel.

      Returns Promise<undefined>

      Notifies other connected clients that this connection has left. This is automatically called when disconnecting if the connection had previously joined.

    • Get a list of all currently connected clients in the presence channel.

      Returns Promise<JoinedConnections>

      Promise resolving to an array of connected clients with their data.

      Error if encryption is configured but getEncryptionSettings() not called.

      Each connection object includes:

      • connectionId: Unique identifier for the connection
      • joinedAt: Timestamp when the connection joined
      • data: Custom data provided when joining (automatically decrypted)

      Your own connection always appears first in the list for convenience.

      const connections = await instance.getJoinedConnections();
      console.log(`${connections.length} users online`);
      const myConnection = connections[0]; // Always your connection
      const otherUsers = connections.slice(1); // All other users
      connections.forEach(conn => {
      console.log(`User: ${conn.data.username}, joined: ${new Date(conn.joinedAt)}`);
      });