Skip to content
UniKVS
Esc
↑↓navigate↵open⌘Jpreview
On this page

@unikvs/localstorage

Usage of LocalStorage in @unikvs/localstorage, a storage that keeps strings in localStorage.

Overview

@unikvs/localstorage Browser only Usage of LocalStorage in @unikvs/localstorage, a storage that keeps strings in localStorage.

  • name is LocalStorage.
  • isOpen is always true. open checks availability; close does nothing.
  • Logical keys are stored with keyPrefix prepended.

Install with:

npm install @unikvs/localstorage
pnpm add @unikvs/localstorage
yarn add @unikvs/localstorage
bun add @unikvs/localstorage
nub add @unikvs/localstorage
aube add @unikvs/localstorage

Usage

LocalStorage implements IStorage. Pass it to UniKvs with persist().

import { LocalStorage } from "@unikvs/localstorage";

Constructor arguments:

PropType
keyPrefix?string | undefined

Prefix attached to every key.

Typestring | undefined
Default"unikvs:"
allowClearWithoutPrefix?boolean | undefined

Whether to allow clear with an empty prefix.

Typeboolean | undefined
Defaultfalse
storage?Storage | undefined

The Storage to use. Uses globalThis.localStorage when omitted.

TypeStorage | undefined

The following example stores a string and reads it back.

import { LocalStorage } from "@unikvs/localstorage";
import * as unikvs from "unikvs";

const kvs = new unikvs.Builder<{
  greeting: unikvs.PlainValue<string>;
}>()
  .persist(new LocalStorage())
  .build();

await kvs.open();
await kvs.set("greeting", "hello");

const value = await kvs.get("greeting");
console.log(value); // "hello"

await kvs.close();

Data types

Operation Supported data type
write / read Strings
  • Stores strings only.
  • Convert objects and other values to strings before passing them.
  • Streams (getWritable / getReadable) are not supported.

Errors

KeyNotFoundError

Meaning

Thrown when the specified key does not exist. A shared error from @unikvs/core.

How to fix

Check with exists before reading.

Example

The following example catches KeyNotFoundError.

import { KeyNotFoundError } from "@unikvs/localstorage";

try {
  await kvs.get("missing-key");
} catch (ex) {
  if (ex instanceof KeyNotFoundError) {
    console.log("Key not found");
  } else {
    throw ex;
  }
}

ClearWithoutPrefixNotAllowedError

Meaning

Thrown when clear is called with an empty keyPrefix while allowClearWithoutPrefix is still false. This guard prevents wiping the whole localStorage.

How to fix

Set a non-empty keyPrefix or pass allowClearWithoutPrefix: true.

LocalStorageNotAvailableError

Meaning

Thrown when operating in an environment without localStorage. No storage was injected and the runtime has no localStorage.

How to fix

Inject a Storage via options.storage or run in a supported browser.

Was this page helpful?