Node module for encrypted cookies, can be used as middleware for express/socket.io or manually.

Downloads in past


021.1.54 years ago4 years agoMinified + gzip package size for encrypt-cookie in KB


npm npm code style: prettier TypeScript

Easy to use cookie encryption middleware for express and socket.io


npm install --save encrypt-cookie
yarn add encrypt-cookie


  • Strong encryption AES 256 GCM
  • Derive unique encryption key for each cookie from master
  • Node.js middleware
  • Socket.io middleware

Node Express middleware

The express middleware automatically encrypts and decrypts the cookies.
import express from 'express';
import cookieParser from 'cookie-parser';
import { encryptCookieNodeMiddleware } from 'encrypt-cookie';

const expressApp = express();

// Set new cookie as usual
response.cookie(cookieName, cookieValue, cookieOptions);

Socket.io middleware

The middleware for socket.io just parses and decrypts the cookies. Since there exist no HTTP response you can not set any headers to submit new cookie values to the browser. The socket handshake includes the cookie values that exist when the handshake is created. To include newer cookies, you need to reset the socket connection. (Any workaround?)
import socketIO from 'socket.io';
import { decryptCookieSocketMiddleware } from 'encrypt-cookie';

this.httpServer = http.createServer(this.expressApp);
this.socketServer = socketIO(this.httpServer); // often defined as `io`
this.socketServer.use(decryptCookieSocketMiddleware(signatureSecret, encryptionSecret));

Set cookie with socket.io

The new cookie value only remains in the current handshake. It will not be submitted to the browsers cookie cache. The value will be deleted when the handshake is recreated.
cookieOptions will be mostly ignored, because the socked does not include any meta information about the cookies. Currently the only noticed value for cookieOptions is {sign: true} to sign the cookie.
import { setSocketCookie } from 'encrypt-cookie';

const cookieOptions = {sign: true};
setSocketCookie(socket: SocketIO.Socket, signaturePassword: string, cookieName: string, cookieValue: any, cookieOptions: express.CookieOptions): void

Encryption/Decryption methods

You can access the encryption methods to use it anywhere
import { decryptAesGcm, encryptAesGcm } from 'encrypt-cookie';

type Password = string | Buffer | NodeJS.TypedArray | DataView;

decryptAesGcm(cipherText: string, password: Password): string | undefined
encryptAesGcm(plainText: string | object, password: Password): string | undefined