npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@codecorn/empty-session-reaper

v1.0.0

Published

Clean up & inspect zombie sessions in Express: prunes cookie-only sessions to keep Prisma/Redis stores lean.

Readme

@codecorn/empty-session-reaper

Tiny middleware to prune or debug empty sessions (cookie-only + your rules) and keep Prisma/Redis stores lean.
Agnostic core — no app-specific keys inside. Bring your own policy via options.


Features

  • 🧹 Prune sessions that are “empty” under your rules.
  • 🔎 Debug with dry-run + logger; optional session mutation logger.
  • 🧩 Agnostic: pass allowlists, predicates, denylists — no hardcoded keys.
  • 🧪 Store-agnostic: Prisma/SQL, Redis, etc.
  • ⚙️ Composable predicates (emptyObject, equals, oneOf, and, or, flashEmptyOrOneOf).
  • 🧰 Optional preset: cookieFlash() — beginner-friendly.
  • 🧯 Safe by design: no env access, tiny footprint.

Install

npm i @codecorn/empty-session-reaper

Import styles

// ✅ CommonJS (require)
const {
  wireEmptySessionReaper,
  predicates,
  buildAllowedKeys,
  wireSessionMutationLogger, // optional: logs added/removed keys
} = require("@codecorn/empty-session-reaper");
const { cookieFlash } = require("@codecorn/empty-session-reaper/presets");
// ✅ ESM / TypeScript
import {
  wireEmptySessionReaper,
  predicates as P,
  buildAllowedKeys,
  wireSessionMutationLogger, // optional
} from "@codecorn/empty-session-reaper";
import { cookieFlash } from "@codecorn/empty-session-reaper/presets";

Usage A — minimal “cookie + empty flash”

// Meaning of buildAllowedKeys(input, expandBase, base):
// - base: starting list (default: ['cookie'])
// - input: extra keys to allow (e.g., ['flash'])
// - expandBase:
//     true  => merge base + input  (e.g., ['cookie'] + ['flash'] -> ['cookie','flash'])
//     false => use input only      (e.g., ['flash'])
wireEmptySessionReaper(app, {
  logger: (m, meta) => console.debug(m, meta),

  allowedKeys: buildAllowedKeys(["flash"], true, ["cookie"]),
  // ↑ allowlist = merge base ['cookie'] + ['flash'] → ['cookie','flash']
  maxKeys: 2,

  keyPredicates: {
    // flash is harmless if it's an empty object {}
    flash: P.emptyObject,
  },
});

Usage B — advanced custom policy (full control)

const isLoginFlash = (flash: any) => {
  if (!flash || typeof flash !== "object") return false;
  const ks = Object.keys(flash);
  if (ks.length !== 1) return false;
  const arr = Array.isArray((flash as any)[ks[0]]) ? (flash as any)[ks[0]] : [];
  return arr.length === 1 && /^please sign in\.?$/i.test(String(arr[0] || ""));
};

wireEmptySessionReaper(app, {
  logger: (m, meta) => console.debug(m, meta),

  allowedKeys: ["cookie", "flash", "url", "flag"],
  maxKeys: 4,

  disallowedKeyPatterns: [/^csrf/i, /^token/i, /^user/i],

  keyPredicates: {
    flash: (v) => P.emptyObject(v) || isLoginFlash(v),
    url: (v) => ["/", "/login", "/signin"].includes(String(v || "")),
    flag: P.oneOf([false, "auto"]),
  },

  isSessionPrunable: (s) => {
    const url = String((s as any).url || "");
    return !(/\.(env|git)\b/i.test(url) || /\/upload\/\./i.test(url));
  },
});

Usage C — optional preset cookieFlash

const preset = cookieFlash({
  // flashKey: 'flash',
  // flashField: 'error',
  // loginMessages: [/^please sign in\.?$/i, /^access denied$/i],
  // extraAllowedKeys: ['url'],
  // maxKeys: 3,
  // disallowedKeyPatterns: [/^csrf/i, /^token/i],
  // extraPredicates: { url: (v) => ['/', '/login'].includes(String(v || '')) },
  // finalCheck: (s) => !/\.env\b/i.test(String((s as any).url || '')),
});
wireEmptySessionReaper(app, { logger: console.debug, ...preset });

Bonus: Session mutation logger (discover origins)

// Place AFTER session(...) and BEFORE the reaper:
wireSessionMutationLogger(app, {
  logger: (label, meta) => console.debug(label, meta),
  includeValues: false, // true to also log shallow values (use redact to mask)
  redact: (k, v) => (/(token|secret|pass)/i.test(k) ? "[redacted]" : v),
  label: "session mutation",
});

Logs { path, added: [...], removed: [...] } on each response where the session keys changed.


API (core)

createEmptySessionReaper(opts) -> (req, res, next) => void
  Create the middleware with your pruning policy.

wireEmptySessionReaper(app, opts) -> middleware
  Mounts the middleware on the app and returns it.

buildAllowedKeys(input?: string[], expandBase?: boolean, base?: string[]) -> string[]
  Helper to compose allowlists.
  - base: starting list (default: ["cookie"])
  - input: extra allowed keys (e.g., ["flash"])
  - expandBase:
      true  -> merge base + input
      false -> use input only

predicates:
  - emptyObject(v)
  - equals(x)
  - oneOf([a,b,c])
  - and(p1,p2,...)
  - or(p1,p2,...)
  - flashEmptyOrOneOf(field='error', messages=[/^please sign in\.?$/i])

createSessionMutationLogger(opts) -> middleware
wireSessionMutationLogger(app, opts) -> middleware
lookUpSessMutation(app, opts) -> alias of wireSessionMutationLogger

📝 License

MIT © CodeCorn™

Distributed under the MIT license.

Credits

  • Cousìn (co-author & review)PYTORCHIA FOR LIFE
  • Federico Girolami (CodeCorn) — Maintainer

👤 Maintainer


🤝 Contribute

Pull requests are welcome. For major changes, please open an issue first to discuss what you’d like to change.

Powered by CodeCorn™ 🚀