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

@unikvs/session-storage

Usage of SessionStorage in @unikvs/session-storage, a storage that keeps strings in sessionStorage.

Overview

@unikvs/session-storage Browser only Usage of SessionStorage in @unikvs/session-storage, a storage that keeps strings in sessionStorage.

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

Install with:

npm install @unikvs/session-storage
pnpm add @unikvs/session-storage
yarn add @unikvs/session-storage
bun add @unikvs/session-storage
nub add @unikvs/session-storage
aube add @unikvs/session-storage

Usage

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

import { SessionStorage } from "@unikvs/session-storage";

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.sessionStorage when omitted.

TypeStorage | undefined

The following example stores a string and reads it back.

import { SessionStorage } from "@unikvs/session-storage";
import * as unikvs from "unikvs";

const kvs = new unikvs.Builder<{
  greeting: unikvs.PlainValue<string>;
}>()
  .persist(new SessionStorage())
  .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/session-storage";

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 sessionStorage.

How to fix

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

SessionStorageNotAvailableError

Meaning

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

How to fix

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

Was this page helpful?