SyntaxStudy
Sign Up
JavaScript Private Storage with Encryption
JavaScript Advanced 7 min read

Private Storage with Encryption

Encrypted Storage

For mildly sensitive data that must be client-side, encrypt before storing using the Web Crypto API or a library.

Example
// Simple encryption with Web Crypto API
async function encrypt(text, password) {
  const key = await deriveKey(password);
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const encoded = new TextEncoder().encode(text);
  const buf = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, encoded);
  return JSON.stringify({ iv: [...iv], data: [...new Uint8Array(buf)] });
}

// Store encrypted
const encrypted = await encrypt(sensitiveData, userPassword);
localStorage.setItem("secure", encrypted);

// Note: the password must come from the user — never hardcode it!
Pro Tip

Client-side encryption is only as strong as the key management — if the key is also stored in localStorage, it adds no real security.