惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
月光博客
月光博客
雷峰网
雷峰网
WordPress大学
WordPress大学
博客园 - 司徒正美
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security @ Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
爱范儿
爱范儿
W
WeLiveSecurity
J
Java Code Geeks
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
T
Threatpost
The Cloudflare Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
Latest news
Latest news
V2EX - 技术
V2EX - 技术
小众软件
小众软件
T
The Blog of Author Tim Ferriss
A
Arctic Wolf
B
Blog RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
C
Check Point Blog
N
News | PayPal Newsroom
Cyberwarzone
Cyberwarzone
V
V2EX
TaoSecurity Blog
TaoSecurity Blog
P
Privacy & Cybersecurity Law Blog
Microsoft Security Blog
Microsoft Security Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
K
Kaspersky official blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google DeepMind News
Google DeepMind News
C
CXSECURITY Database RSS Feed - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Stop Storing Plaintext in Browser Cookies — Use AES-GCM Encryption Instead
Abdullah Al Fahim · 2026-05-31 · via DEV Community

If any of them look like this:

{"userId":42,"role":"admin","email":"user@example.com","plan":"pro"}

You have a problem.

Anyone who can access that browser — a shared computer, a browser extension, a shoulder-surfer, an XSS payload — can read everything you stored. No hacking required. It's just... there.

Today I'm going to show you how to fix it in under 5 minutes using js-cookie-encrypt — the only actively maintained, zero-dependency, client-side encrypted cookie library built on the browser's native SubtleCrypto API.


The Problem With Cookies Today

Browser cookies are the backbone of web sessions. Nearly every framework uses them to track authentication state, user preferences, feature flags, and shopping carts. They're fast, they work across tabs, they survive page reloads.

But they have one glaring flaw: they're stored in plaintext by default.

The most popular cookie library, js-cookie, has 23 million weekly downloads. It's excellent. But it does zero encryption. Same story for universal-cookie (1.8M weekly downloads) and every other client-side cookie manager I've found.

The server-side world has secure-cookie and cookie-encrypter — but those are Express middleware. They don't help you in a React SPA, a Next.js client component, or a Vue app.

crypto-js has encryption algorithms — but it's been abandoned by its maintainers and carries 300KB+ of algorithms you'll never use.

So developers are left with three bad options:

  1. Store plaintext (everyone does this)
  2. Roll their own encryption (error-prone, usually wrong)
  3. Use an abandoned library (crypto-js)

There's a fourth option now.


Introducing js-cookie-encrypt

js-cookie-encrypt fills the gap that's existed in the frontend ecosystem for years: a lightweight, actively maintained, client-side encrypted cookie library built on the browser's native Web Cryptography API.

npm install js-cookie-encrypt

Here's what your cookies look like after:

gcm:aGVsbG8td29ybGQtdGhpcy1pcy1lbmNyeXB0ZWQtd2l0aC1hZXMtZ2NtLTI1Ni1iaXQ...

Unreadable. Authenticated. Tamper-proof.


Why Native SubtleCrypto Instead of crypto-js?

Most encrypted cookie libraries reach for crypto-js. Don't.

The browser has had a built-in cryptography API since 2013 — window.crypto.subtle. It:

  • Ships in every modern browser with zero bundle cost
  • Runs in a separate thread (non-blocking)
  • Uses hardware acceleration where available
  • Is maintained by browser vendors, not abandoned npm packages
  • Implements AES-GCM with authenticated encryption (tamper detection built in)

js-cookie-encrypt uses SubtleCrypto directly. No crypto library dependency. Zero dependencies total.


Getting Started

Installation

npm install js-cookie-encrypt
# yarn add js-cookie-encrypt
# pnpm add js-cookie-encrypt

CDN:

<script src="https://cdn.jsdelivr.net/npm/js-cookie-encrypt/dist/js-cookie-encrypt.min.js"></script>

Basic Usage

import JsCookieEncrypt from 'js-cookie-encrypt';

const store = new JsCookieEncrypt({
  storageKey: 'session',
  cryptoConfig: {
    privateKey: 'your-secret-key',
    algorithm: 'aes-gcm',
  }
});

// Write encrypted
await store.setAsync({
  userId: 42,
  role: 'admin',
  email: 'user@example.com'
});

// Read decrypted
const session = await store.getAsync();
console.log(session?.role); // 'admin'

That's it. Everything in the cookie is now AES-GCM 256-bit encrypted. The data in DevTools is an unreadable ciphertext blob.


TypeScript-First Design

Every API is fully generic. You get autocomplete, type checking, and compile-time errors — not just any.

interface UserSession {
  userId: number;
  role: 'admin' | 'user' | 'guest';
  preferences: {
    theme: 'dark' | 'light';
    language: string;
  };
}

const session = new JsCookieEncrypt<UserSession>({
  storageKey: 'session',
  cryptoConfig: { privateKey: 'secret', algorithm: 'aes-gcm' }
});

// TypeScript knows the shape of everything
const role = await session.getAsync('role'); // typed as 'admin' | 'user' | 'guest'
const theme = await session.getByPathAsync('preferences.theme'); // typed as 'dark' | 'light'

// This is a compile error — 'superadmin' is not valid
await session.setAsync({ role: 'superadmin' }); // ❌ Type error

The deep path API uses TypeScript's template literal types to infer the exact return type at every dot-notation path. getByPathAsync('preferences.theme') returns 'dark' | 'light' — not any.


Deep Path Operations

Working with nested objects doesn't require reading, cloning, and re-writing the entire cookie. The path API handles it:

interface AppState {
  user: {
    name: string;
    address: { city: string; country: string };
    preferences: { theme: 'dark' | 'light'; notifications: boolean };
  };
  cart: { items: number[]; total: number };
}

const store = new JsCookieEncrypt<AppState>({
  storageKey: 'app',
  cryptoConfig: { privateKey: 'secret', algorithm: 'aes-gcm' }
});

// Initialize
await store.setAsync({
  user: { name: 'Alice', address: { city: 'London', country: 'UK' }, preferences: { theme: 'dark', notifications: true } },
  cart: { items: [], total: 0 }
});

// Get nested value — typed as string
const city = await store.getByPathAsync('user.address.city');
// 'London'

// Update one nested field without touching the rest
await store.setByPathAsync('user.address.city', 'Paris');

// Deep merge a nested object
await store.updateByPathAsync('user.preferences', { theme: 'light' });

// Delete a nested field
await store.deleteByPathAsync('user.address.country');

// Check existence
const hasCity = await store.hasAsync('user.address.city'); // true

All of these read → decrypt → mutate → encrypt → write under the hood. You work with clean data.


Real-Time Change Subscriptions

Subscribe to cookie changes across your application. Perfect for keeping UI state in sync without prop drilling or a global store.

const unsubscribe = store.subscribe((event) => {
  switch (event.type) {
    case 'set':
      console.log('Cookie created:', event.newValue);
      break;
    case 'update':
      console.log('Changed:', event.oldValue, '', event.newValue);
      break;
    case 'delete':
      console.log('Fields deleted, cookie is now:', event.newValue);
      break;
    case 'clear':
      console.log('Cookie cleared. Was:', event.oldValue);
      break;
  }
});

// Each method fires the correct event type
await store.setAsync({ items: [] });           // fires 'set'
await store.updateAsync({ items: [1, 2, 3] }); // fires 'update'
await store.deleteFieldsAsync(['cart']);         // fires 'delete'
await store.clearAsync();                       // fires 'clear'

// Clean up
unsubscribe();


Enterprise Key Rotation

Rotating encryption keys in production is painful when users have existing encrypted cookies — they break the moment you deploy a new key.

js-cookie-encrypt solves this with zero downtime key rotation. Pass an array of keys: the first is the active encryption key, the rest are fallbacks for decrypting old cookies.

const store = new JsCookieEncrypt({
  storageKey: 'session',
  cryptoConfig: {
    // New key at index 0. Old keys at index 1, 2...
    privateKey: ['new-key-2026', 'old-key-2025', 'older-key-2024'],
    algorithm: 'aes-gcm',
  }
});

// Automatically:
// 1. Tries to decrypt with 'new-key-2026'
// 2. Falls back to 'old-key-2025' if that fails
// 3. Falls back to 'older-key-2024' if that fails
// 4. Re-encrypts with 'new-key-2026' and saves
const session = await store.getAsync();

Users who have cookies encrypted with old keys get transparently migrated on their next request. No session invalidation. No support tickets.


SSR-Safe (Next.js, Nuxt, Remix)

The most common Next.js cookie bug: calling document.cookie on the server crashes with ReferenceError: document is not defined.

js-cookie-encrypt detects when document.cookie is unavailable and silently falls back to an in-memory Map. Your code works identically on server and client.

// lib/session.ts — safe to import anywhere in Next.js
import JsCookieEncrypt from 'js-cookie-encrypt';

interface Session {
  userId: number;
  role: string;
}

export const sessionStore = new JsCookieEncrypt<Session>({
  storageKey: 'session',
  cryptoConfig: {
    privateKey: process.env.NEXT_PUBLIC_COOKIE_KEY!,
    algorithm: 'aes-gcm',
  },
  defaultOptions: {
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: '/',
  }
});

// app/page.tsx — works in server components too
import { sessionStore } from '@/lib/session';

export default async function Page() {
  const session = await sessionStore.getAsync();
  // session is null server-side (no document.cookie)
  // session is populated client-side after hydration
}


React Hook Example

Here's a production-ready React hook that keeps state in sync with the encrypted cookie:

import { useEffect, useState, useCallback } from 'react';
import JsCookieEncrypt from 'js-cookie-encrypt';

interface UserPrefs {
  theme: 'dark' | 'light';
  language: string;
  notifications: boolean;
}

const prefStore = new JsCookieEncrypt<UserPrefs>({
  storageKey: 'prefs',
  cryptoConfig: { privateKey: 'secret', algorithm: 'aes-gcm' },
  defaultOptions: { sameSite: 'lax', path: '/' }
});

export function usePreferences() {
  const [prefs, setPrefs] = useState<UserPrefs | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    prefStore.getAsync().then(data => {
      setPrefs(data as UserPrefs | null);
      setLoading(false);
    });

    // Stay in sync with external changes
    const unsubscribe = prefStore.subscribe(event => {
      if (event.type === 'set' || event.type === 'update') {
        setPrefs(event.newValue as UserPrefs);
      }
      if (event.type === 'clear') {
        setPrefs(null);
      }
    });

    return unsubscribe;
  }, []);

  const update = useCallback(
    (updates: Partial<UserPrefs>) => prefStore.updateAsync(updates),
    []
  );

  const clear = useCallback(() => prefStore.clearAsync(), []);

  return { prefs, loading, update, clear };
}

// In your component
function SettingsPage() {
  const { prefs, loading, update } = usePreferences();

  if (loading) return <Spinner />;

  return (
    <button onClick={() => update({ theme: prefs?.theme === 'dark' ? 'light' : 'dark' })}>
      Toggle Theme (currently: {prefs?.theme})
    </button>
  );
}


How the Encryption Actually Works

For the curious — here's what happens under the hood when you call setAsync():

Encryption:

  1. Your data object is serialized to JSON: {"userId":42,"role":"admin"}
  2. A random 12-byte IV (initialization vector) is generated using crypto.getRandomValues()
  3. Your private key is hashed with SHA-256 to produce a consistent 256-bit AES key
  4. The JSON string is encrypted using AES-GCM with the IV
  5. The IV (12 bytes) is prepended to the ciphertext
  6. The combined bytes are base64-encoded and prefixed with gcm:
  7. The result is written to document.cookie

Decryption:

  1. The cookie is read and the gcm: prefix stripped
  2. The base64 string is decoded back to bytes
  3. The first 12 bytes are extracted as the IV
  4. The remaining bytes are decrypted using AES-GCM (this also verifies the authentication tag — if the data was tampered with, decryption fails)
  5. The decrypted bytes are decoded from UTF-8 to a string
  6. The JSON string is parsed and returned as your typed object

AES-GCM is authenticated encryption — it doesn't just encrypt, it also produces an authentication tag that detects any tampering with the ciphertext. If someone modifies your encrypted cookie, decryption throws rather than returning corrupted data.


Comparison With Alternatives

js-cookie universal-cookie crypto-js js-cookie-encrypt
Browser cookies
AES-GCM 256-bit
Native Web Crypto
Zero dependencies
TypeScript generics
Key rotation
Deep path API
Change events
SSR / Next.js safe ⚠️
Actively maintained ❌ abandoned
Weekly downloads 23M 1.8M 15M growing

Security Considerations (Be Honest With Your Users)

I want to be transparent about what this library does and doesn't protect against.

What it protects:

  • Casual reading of cookie values in DevTools
  • Cookie values visible in log files, analytics tools, error trackers
  • Network-level interception of cookie values (combined with secure: true)
  • Shoulder surfing
  • Automated scraping of cookie values

What it does NOT protect against:

  • An attacker with JavaScript execution on your page. The encryption key is accessible to JS — if your site has XSS vulnerabilities, those need to be fixed first.
  • Browser extensions with full page access
  • Physical access to the machine (cookies are stored on disk)

This library is best described as defense in depth — it makes cookie values meaningless to anyone who isn't running your application code. For sessions that need true server-side security, use HttpOnly cookies set by your server (no JS library can do this — it's a server responsibility).


Production Configuration Checklist

const store = new JsCookieEncrypt({
  storageKey: 'session',
  cryptoConfig: {
    privateKey: process.env.NEXT_PUBLIC_COOKIE_SECRET!, // ✅ env var, not hardcoded
    algorithm: 'aes-gcm',                               // ✅ strong cipher
  },
  defaultOptions: {
    secure: process.env.NODE_ENV === 'production',       // ✅ HTTPS only in prod
    sameSite: 'lax',                                     // ✅ CSRF protection
    path: '/',                                           // ✅ available site-wide
    // expires: 7 * 24 * 60 * 60 * 1000,               // optional: 7 days in ms
  }
});


Install and Try It Now

npm install js-cookie-encrypt

If you find it useful, a ⭐ on GitHub goes a long way. Issues and PRs welcome.


Wrapping Up

The frontend ecosystem has had a gap for years: no maintained, client-side, encrypted cookie library. Every option was either plaintext, abandoned, server-only, or required a 300KB dependency.

js-cookie-encrypt fills that gap. It's:

  • Built on native browser APIs (no dependency risk)
  • AES-GCM 256-bit (authenticated encryption, not just obfuscation)
  • TypeScript-first with full generic type inference
  • Ready for production with key rotation and SSR support

Your users' data deserves better than plaintext cookies. It takes five minutes to fix.