Storage Migration in JavaScript
Migrate stored data in JavaScript: rename keys, track versions, back up first and run step-by-step localStorage migrations. Explanation and output.
Run this in the browser console or a page script. localStorage and sessionStorage are browser features, so plain Node will not have them.
1// Method 1: Simple migration2function migrateStorage() {3 const oldData = localStorage.getItem('oldKey');4 if (oldData) {5 // Migrate to new format6 const newData = {7 version: 2,8 data: JSON.parse(oldData)9 };10 localStorage.setItem('newKey', JSON.stringify(newData));11 localStorage.removeItem('oldKey');12 console.log('Migration complete');13 }14}1516// Method 2: Version-based migration17const STORAGE_VERSION = 2;1819function checkAndMigrate() {20 const currentVersion = localStorage.getItem('storageVersion');2122 if (!currentVersion || parseInt(currentVersion) < STORAGE_VERSION) {23 console.log('Migration needed');24 migrateToVersion(parseInt(currentVersion) || 1);25 localStorage.setItem('storageVersion', STORAGE_VERSION.toString());26 }27}2829function migrateToVersion(fromVersion) {30 if (fromVersion === 1) {31 // Migrate from v1 to v232 const v1Data = localStorage.getItem('userData');33 if (v1Data) {34 const data = JSON.parse(v1Data);35 const v2Data = {36 ...data,37 metadata: {38 createdAt: new Date().toISOString(),39 version: 240 }41 };42 localStorage.setItem('userData', JSON.stringify(v2Data));43 }44 }45}4647checkAndMigrate();4849// Method 3: Migration with backup50function migrateWithBackup() {51 // Create backup52 const backup = {};53 for (let i = 0; i < localStorage.length; i++) {54 const key = localStorage.key(i);55 backup[key] = localStorage.getItem(key);56 }57 localStorage.setItem('backup_' + Date.now(), JSON.stringify(backup));5859 // Perform migration60 try {61 migrateStorage();62 console.log('Migration successful');63 } catch (e) {64 console.error('Migration failed, restoring backup');65 // Restore from backup66 restoreBackup(backup);67 }68}6970function restoreBackup(backup) {71 localStorage.clear();72 Object.keys(backup).forEach(key => {73 localStorage.setItem(key, backup[key]);74 });75}7677// Method 4: Progressive migration78function progressiveMigration() {79 const migrationSteps = [80 () => migrateStep1(),81 () => migrateStep2(),82 () => migrateStep3()83 ];8485 migrationSteps.forEach((step, index) => {86 try {87 step();88 console.log(`Step ${index + 1} complete`);89 } catch (e) {90 console.error(`Step ${index + 1} failed:`, e);91 throw e;92 }93 });94}9596function migrateStep1() {97 // Step 1 logic98}99100function migrateStep2() {101 // Step 2 logic102}103104function migrateStep3() {105 // Step 3 logic106}107108// Method 5: Data transformation109function transformData(oldFormat) {110 // Transform old format to new format111 return {112 id: oldFormat.userId,113 name: oldFormat.fullName,114 email: oldFormat.emailAddress,115 settings: {116 theme: oldFormat.theme || 'light',117 notifications: oldFormat.notify ?? true118 }119 };120}121122function migrateUserData() {123 const oldData = localStorage.getItem('oldUserData');124 if (oldData) {125 const parsed = JSON.parse(oldData);126 const newData = transformData(parsed);127 localStorage.setItem('userData', JSON.stringify(newData));128 localStorage.removeItem('oldUserData');129 }130}
Sample Output
Migration needed
On a fresh browser there is no storageVersion, so the migration runs once. Run it again and nothing prints.
In this one
- Why stored data needs migrations
- How a version number makes migrations run once
- How to back up and restore before changing data
- How to transform old fields into a new shape
How it works
- 1
migrateStorage is defined to move oldKey to newKey.
- 2
checkAndMigrate finds no version and runs the v1 to v2 step.
- 3
The version is saved as 2.
- 4
migrateWithBackup and progressiveMigration are ready to call.
- 5
transformData maps old fields to new ones.
Edge cases
Running twice
Without a version check, a migration may wrap data twice.
Save the new version number right after migrating.
False values lost
oldFormat.notify || true turns false into true.
Use ?? so only missing values get the default.
Backup too big
Saving a full backup can hit the storage quota.
Catch the error, or back up only the keys you change.
What's going on
Apps change. Version 1 of a student portal might store a user as { userId, fullName }, while version 2 wants { id, name, settings }. A storage migration updates old saved data to the new format so returning users do not see errors or lose data.
Method 1 is a simple migration. If oldKey exists, it wraps the data in a new shape with a version number, saves it under newKey, and removes the old key.
Method 2 is version-based. The app stores storageVersion. If it is missing or lower than STORAGE_VERSION, the app runs migrateToVersion and then saves the new version number. That way each migration runs once. On a fresh browser there is no version yet, so it prints "Migration needed" and treats the data as version 1.
Method 3 makes a backup first. It copies every key into an object, saves it under a backup key with a timestamp, and then migrates. If anything throws, restoreBackup clears storage and puts the old values back. Always back up before you change user data.
Method 4 is progressive. The migration is split into small steps. Each step runs in order, logs when it completes, and stops the whole process if one fails by re-throwing the error.
Method 5 transforms data. transformData maps old field names to new ones and fills defaults. One fix was made here: notify used || true, which turned a saved false into true. It now uses ??, the nullish operator, which only uses the default when the value is null or undefined.
Only checkAndMigrate is called in this file. The other methods are defined for you to call when needed. Best practices: check the version, create backups, test migrations, handle failures and document each change. Use cases include schema changes, format updates, data restructuring and version upgrades.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the value of false ?? true?
Pick an answer to check it.
Question 2
Why store a version number?
Pick an answer to check it.
Questions people ask
Why does only "Migration needed" print?
Only checkAndMigrate is called. The other methods are examples to call yourself.
What does ?? do?
It uses the right side only when the left is null or undefined.
Should I delete the old key?
Yes, after the new data is saved and checked.