encrypt-storage
encrypt-storage copied to clipboard
JSON strings don't survive `setItem`/`getItem` roundtrip
Describe the bug
When saving a string that is valid JSON with setItem, then loading it with getItem, the returned value isn't the original string, but the value obtained by parsing it as JSON.
To Reproduce Run the following test:
const storage = new EncryptStorage('verysecret');
const value = '{}';
storage.setItem('foo', value);
expect(storage.getItem('foo')).toEqual(value);
The test fails, also with other JSON values such as 42, "a string", true, [] and null.
Expected behavior
getItem should reproduce the original string saved using setItem.
Desktop:
- OS: Windows
- Browser: Chrome
- Version:
124.0.6367.119
Additional context
This behavior occurs because values with a type different from object (e.g. string) aren't JSON.stringify'd by setItem, but saved as is. getItem then tries to parse those values as JSON and returns the original string only if parsing fails. Now if the original string happens to be valid JSON, this roundtrip doesn't work.
I guess it would make sense to always JSON.stringify in setItem, even for primitive values.