Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

renameSessionStorageKey

Renames a key in sessionStorage while preserving its value.

TypeScript
Copied!
1/**
2 * Renames a key in sessionStorage while preserving its value.
3 *
4 * @param oldKey - The existing key to rename.
5 * @param newKey - The new key name.
6 * @throws If the old key does not exist or the new key already exists.
7 */
8export function renameSessionStorageKey(oldKey: string, newKey: string): void {
9  if (!sessionStorage.getItem(oldKey)) {
10    throw new Error(`Key "${oldKey}" does not exist in sessionStorage`);
11  }
12  if (sessionStorage.getItem(newKey)) {
13    throw new Error(`Key "${newKey}" already exists in sessionStorage`);
14  }
15
16  const value = sessionStorage.getItem(oldKey);
17  sessionStorage.setItem(newKey, value!);
18  sessionStorage.removeItem(oldKey);
19}
  • Preserves Data Integrity

    Ensures the value is transferred without alteration when renaming a key, maintaining session data consistency.

  • Prevents Accidental Overwrites

    Explicitly checks that the new key does not already exist, avoiding unintentional data loss.

  • Error Feedback

    Provides informative error messages for both missing keys and collisions, aiding debugging and robustness.

  • Simple and Focused Utility

    Offers a minimal, single-responsibility helper that abstracts a common but error-prone storage manipulation task.

Tests | Examples

TypeScript
Copied!
1beforeEach(() => {
2  sessionStorage.clear();
3});
4
5test('renames a key while preserving its value', () => {
6  sessionStorage.setItem('oldKey', JSON.stringify('value'));
7
8  renameSessionStorageKey('oldKey', 'newKey');
9
10  expect(sessionStorage.getItem('oldKey')).toBeNull();
11  expect(sessionStorage.getItem('newKey')).toBe(JSON.stringify('value'));
12});
13
14test('throws if old key does not exist', () => {
15  expect(() => renameSessionStorageKey('missingKey', 'newKey')).toThrow(
16    'Key "missingKey" does not exist in sessionStorage'
17  );
18});
19
20test('throws if new key already exists', () => {
21  sessionStorage.setItem('oldKey', 'a');
22  sessionStorage.setItem('newKey', 'b');
23
24  expect(() => renameSessionStorageKey('oldKey', 'newKey')).toThrow(
25    'Key "newKey" already exists in sessionStorage'
26  );
27});

Common Use Cases

  • Key Schema Migration

    Transition existing sessionStorage keys to a new naming convention without data loss.

  • Namespacing Adjustments

    Prefix or restructure keys to group session data by module or context.

  • Feature Refactoring

    Change the name of a storage key when modifying feature logic or scope.

  • Conflict Resolution

    Move session data from a deprecated key to a new one while preserving the old value temporarily.

Codebase: Utilities -> Storage -> renameSessionStorageKey | Yevhen Klymentiev