How to Protect Data in the Browser Using Web Crypto API

Have you ever wanted to cache data in the browser but worried about privacy? For example, when building multi-step forms and you wanted to save user input without leaving sensitive data exposed in localStorage. Especially in Germany, this topic is very sensitive due to GDPR.

Enter the Web Crypto API

A built-in browser tool that lets you encrypt and decrypt data with AES, Salt and IV locally, keeping it secure without relying on external servers.

Playground Example

Here you could find a playground to test it out: https://codepen.io/artursopelnik/pen/WbQmyvz

Integrating with State Management

In my current project, we use Zustand to persist global state in the browser. We’ve implemented a middleware that encrypts all data before saving it and decrypts it when reading it, ensuring everything stored remains secure.

Additionally, we apply a Base64 transformation before saving objects to the store. This prevents issues with directly reading/writing complex objects in localStorage, keeping everything smooth and reliable.

When initializing the store, we use a client-side secret from sessionStorage that exists only for the duration of the session. Once the session expires, decryption will fail, and in that case, the data is automatically deleted to prevent unauthorized access.

“Stealing data online? Easy. Securing it so no one can ever decrypt it? That’s real art.”