Skip to content

Instantly share code, notes, and snippets.

@MarcosSantosDev
Last active February 2, 2023 15:52
Show Gist options
  • Save MarcosSantosDev/c0cf7466171cf3c6928029b4944ca79f to your computer and use it in GitHub Desktop.
Save MarcosSantosDev/c0cf7466171cf3c6928029b4944ca79f to your computer and use it in GitHub Desktop.
Hook to use encrypted local storage
/**
* Encryption methods and encryption removal
*/
# const encryptData = <T = unknown>(secretPass: string, data: T) => ...
# const decryptData = <T = unknown>(secretPass: string, encryptedData: string): T => ...
/**
* Secret key to use for encryption and decryption
*/
# const SECRET_PASS_LOCAL_STORAGE = '...'
const hasWindowObject = typeof window !== 'undefined';
const manageStorageCriptoContractor = {
getStorage: <T>(storageKey: string): T | null => {
if (hasWindowObject) {
const storageEncryptedData = localStorage.getItem(storageKey);
if (storageEncryptedData) {
const dencryptedData = decryptData<T>(
SECRET_PASS_LOCAL_STORAGE,
storageEncryptedData,
);
return dencryptedData;
}
}
return null;
},
setStorage: <T>(storageKey: string, data: T) => {
if (hasWindowObject) {
const encryptedData = encryptData<T>(SECRET_PASS_LOCAL_STORAGE, data);
localStorage.setItem(storageKey, encryptedData);
}
},
removeStorage: (storageKey: string) => {
if (hasWindowObject) {
localStorage.removeItem(storageKey);
}
},
};
export const useEncryptedLocalStorage = <T>(key: string) => {
return {
getStorageData: (initialData: T) => {
return manageStorageCriptoContractor.getStorage<T>(key) || initialData;
},
setStorageData: (data: T) => {
return manageStorageCriptoContractor.setStorage(key, data);
},
removeStorageData: () => manageStorageCriptoContractor.removeStorage(key),
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment