Skip to content
ReferenceVersion 6.0.2

Storage and Legacy Encryption ​

Interactive example ​

View example source
tsx
import { useI18n } from '@/hooks'
import { getStorage, hasStorage, removeStorage, setStorage } from '@/utils'
import {
  NButton,
  NCard,
  NFlex,
  NFormItem,
  NInput,
  NRadioButton,
  NRadioGroup,
} from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'

export default defineComponent({
  name: 'CacheDemo',
  setup() {
    const { t } = useI18n('demoDetails')
    const value = ref('Ray')
    const scope = ref<'sessionStorage' | 'localStorage'>('sessionStorage')
    const suffix = ref('name')
    const selectedKey = computed(() => `ray:showcase:${suffix.value.trim()}`)
    const current = ref<string | null>(null)
    const operation = ref('cache.read')
    const keyId = useId()
    const valueId = useId()

    const read = () => {
      current.value = hasStorage(selectedKey.value, scope.value)
        ? getStorage<string>(selectedKey.value, scope.value)
        : null
    }

    watch([selectedKey, scope], read, { immediate: true })

    return () => (
      <DemoPage title={t('cache.title')} description={t('cache.intro')}>
        <div class="r-demo-grid">
          <NCard title={t('cache.write')}>
            <div class="r-demo-card-stack">
              <NRadioGroup
                v-model:value={scope.value}
                aria-label={t('cache.scope')}
              >
                <NRadioButton value="sessionStorage">
                  sessionStorage
                </NRadioButton>
                <NRadioButton value="localStorage">localStorage</NRadioButton>
              </NRadioGroup>
              <NFormItem
                label={t('cache.key')}
                labelProps={{ for: keyId }}
                showFeedback={false}
              >
                <NInput
                  inputProps={{ id: keyId }}
                  v-model:value={suffix.value}
                  maxlength={32}
                />
              </NFormItem>
              <NFormItem
                label={t('cache.value')}
                labelProps={{ for: valueId }}
                showFeedback={false}
              >
                <NInput
                  inputProps={{ id: valueId }}
                  v-model:value={value.value}
                />
              </NFormItem>
              <NFlex>
                <NButton
                  type="primary"
                  disabled={!suffix.value.trim()}
                  onClick={() => {
                    setStorage(selectedKey.value, value.value, scope.value)
                    operation.value = 'cache.write'
                    read()
                  }}
                >
                  {t('cache.write')}
                </NButton>
                <NButton
                  onClick={() => {
                    operation.value = 'cache.read'
                    read()
                  }}
                >
                  {t('cache.read')}
                </NButton>
                <NButton
                  onClick={() => {
                    removeStorage(selectedKey.value, scope.value)
                    operation.value = 'cache.remove'
                    read()
                  }}
                >
                  {t('cache.remove')}
                </NButton>
              </NFlex>
            </div>
          </NCard>
          <NCard title={t('result')}>
            <DemoResult label={t(operation.value)}>
              <pre>{selectedKey.value}</pre>
              <pre>
                {current.value === null
                  ? t('cache.missing')
                  : JSON.stringify(current.value)}
              </pre>
            </DemoResult>
          </NCard>
        </div>
      </DemoPage>
    )
  },
})

Web Storage ​

The default is sessionStorage, scoped to the current tab session. Pass 'localStorage' for persistence beyond that session. Values use JSON serialization. Type parameters affect compile-time typing. Validate the stored shape when needed.

APIBehavior
setStorage(key, value, storageType?, options?)Writes a serializable value. Empty keys, circular references, and denied writes log an error.
getStorage<T>(key, storageType?, options?)Returns options.defaultValue or null when missing, malformed, or unreadable. An explicit JSON null stays null.
hasStorage(key, storageType?, options?)Checks for a key and returns false if storage is inaccessible. JSON content is not validated.
removeStorage(key, storageType?, options?)Removes a key. __all__, __all_sessionStorage__, and __all_localStorage__ perform bulk removal.
prefixCacheKey(key, { customPrefix }?)Prepends the custom prefix or APP_CATCH_KEY_PREFIX. Include any separator in the prefix.

Storage methods call the prefix helper only with options.prefix: true. prefixKey overrides the default. A nonempty prefix limits bulk removal to matching keys. With an empty prefix, removal clears the corresponding storage area. Use the same prefix options for reads, writes, and removal. Pinia has its own persistence settings, so changing this utility prefix leaves old Pinia data in place.

ts
import { getStorage, removeStorage, setStorage } from '@/utils'

const options = { prefix: true, prefixKey: 'inventory:' }
export function saveOrderFilter(status: string) {
  setStorage('order-filter', { status }, 'sessionStorage', options)
}
export const readOrderFilter = () =>
  getStorage<{ status: string }>('order-filter', 'sessionStorage', options)
export const clearOrderFilter = () =>
  removeStorage('order-filter', 'sessionStorage', options)

The shared package's createStorage(storage, prefix?) builds get, set, and remove on a host-provided synchronous store. It uses the same JSON format. Failed reads return null and failed writes or removals are contained. Unserializable values such as undefined, functions, and circular objects leave existing data intact. The prefix is concatenated directly with the key.

Legacy AES JSON ​

This example compares cache key prefixes and uses a sample passphrase to encrypt and recover JSON.

View example source
tsx
import { useI18n } from '@/hooks'
import { decrypt, encrypt, prefixCacheKey } from '@/utils'
import { NButton, NFlex, NInput } from 'naive-ui'
import DemoPage from './components/DemoPage'
import DemoResult from './components/DemoResult'

export default defineComponent({
  name: 'DocsStorageUtils',
  setup() {
    const { t } = useI18n('docsExamples')
    const text = (key: string) => t<string>(key)
    const key = ref('order-filter')
    const prefix = ref('orders:')
    const input = ref(text('storage.initial'))
    const ciphertext = ref('')
    const restored = ref('')
    const passphrase = 'ray-template-example-only'
    const cacheKey = computed(() =>
      prefixCacheKey(key.value, { customPrefix: prefix.value }),
    )

    return () => (
      <DemoPage
        title={text('storage.title')}
        description={text('storage.intro')}
      >
        <NFlex>
          <NInput
            v-model:value={prefix.value}
            aria-label={text('storage.prefix')}
          />
          <NInput v-model:value={key.value} aria-label={text('storage.key')} />
        </NFlex>
        <DemoResult label={text('storage.resultKey')}>
          <code>{cacheKey.value}</code>
        </DemoResult>
        <NInput
          v-model:value={input.value}
          aria-label={text('storage.plainText')}
        />
        <NFlex>
          <NButton
            onClick={() => {
              ciphertext.value = encrypt({ status: input.value }, passphrase)
              restored.value = ''
            }}
          >
            {text('storage.encrypt')}
          </NButton>
          <NButton
            disabled={!ciphertext.value}
            onClick={() => {
              restored.value = JSON.stringify(
                decrypt(ciphertext.value, passphrase),
              )
            }}
          >
            {text('storage.decrypt')}
          </NButton>
        </NFlex>
        <DemoResult label={text('storage.ciphertext')}>
          <code>{ciphertext.value}</code>
        </DemoResult>
        <DemoResult label={text('storage.restored')}>
          <code>{restored.value}</code>
        </DemoResult>
      </DemoPage>
    )
  },
})

encrypt(data, key?) returns serialized JSON ciphertext and decrypt(ciphertext, key?) decodes it. Use a passphrase string or CryptoJS WordArray. Encryption and decryption require the same key type and contents. Passphrases use the OpenSSL-compatible format. Raw keys use a random IV and serialize to IV:ciphertext. An invalid ciphertext or key logs an error and returns undefined. Unserializable input throws during encryption.

CRYPTO_KEY is a public compatibility constant for existing local data, such as the demo lock screen. Protect server credentials and sessions with server-side mechanisms. Preserve reads of legacy ciphertext when migrating formats.

Storage implementation · Encryption · Decryption