renameLocalStorageKey
Renames a key in localStorage while preserving its value.
1/**
2 * Renames a key in localStorage 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 renameLocalStorageKey(oldKey: string, newKey: string): void {
9 if (!localStorage.getItem(oldKey)) {
10 throw new Error(`Key "${oldKey}" does not exist in localStorage`);
11 }
12 if (localStorage.getItem(newKey)) {
13 throw new Error(`Key "${newKey}" already exists in localStorage`);
14 }
15
16 const value = localStorage.getItem(oldKey);
17 localStorage.setItem(newKey, value!);
18 localStorage.removeItem(oldKey);
19}
Safe Key Renaming
Ensures data integrity by checking both existence of the old key and absence of the new key before proceeding.
Preserves Original Value
Transfers the value as-is with no transformation or parsing involved.
Atomic Operation
Executes in a single synchronous flow - no intermediate states are visible to other scripts.
Useful for Schema Evolution
Facilitates seamless transitions when localStorage keys need to be updated as app logic evolves.
Tests | Examples
1beforeEach(() => {
2 localStorage.clear();
3});
4
5test('renames a key while preserving its value', () => {
6 localStorage.setItem('oldKey', JSON.stringify('value'));
7
8 renameLocalStorageKey('oldKey', 'newKey');
9
10 expect(localStorage.getItem('oldKey')).toBeNull();
11 expect(localStorage.getItem('newKey')).toBe(JSON.stringify('value'));
12});
13
14test('throws if old key does not exist', () => {
15 expect(() => renameLocalStorageKey('missingKey', 'newKey')).toThrow(
16 'Key "missingKey" does not exist in localStorage'
17 );
18});
19
20test('throws if new key already exists', () => {
21 localStorage.setItem('oldKey', 'a');
22 localStorage.setItem('newKey', 'b');
23
24 expect(() => renameLocalStorageKey('oldKey', 'newKey')).toThrow(
25 'Key "newKey" already exists in localStorage'
26 );
27});
Common Use Cases
Data Migration on App Update
Rename keys to match updated naming conventions or storage schemas during version upgrades.
Namespace Refactoring
Change key prefixes (e.g.
user_
→account_
) without losing stored data.Conflict Resolution
Avoid collisions by renaming a key before introducing a new one with the same name.
User Preference Management
Transition user settings under new keys while preserving legacy preferences.
Testing Key Behavior
Simulate or test how different storage keys affect app functionality without deleting values.