{"id":11041,"library":"hono-sessions","title":"Hono Sessions Middleware","description":"hono-sessions is a middleware library designed for the Hono web framework, providing robust cookie-based session management. Currently at version 0.8.1, the library is actively maintained with a focus on stability and features like `autoExtendExpiration` and improved type safety. It differentiates itself by supporting a wide array of runtimes, including Node.js (v20+), Deno, Bun, Cloudflare Workers, and Cloudflare Pages, leveraging the Web Crypto API for secure, encrypted cookies via `iron-webcrypto`. Key features include support for 'flash messages' (data deleted after one read), built-in Memory and Cookie storage drivers, extensible architecture for custom drivers (like Bun SQLite), and strong TypeScript typing for session variables. It offers a flexible approach to user session management, particularly powerful in serverless and edge environments where persistent server-side state might be impractical.","status":"active","version":"0.8.1","language":"javascript","source_language":"en","source_url":"https://github.com/jcs224/hono_sessions","tags":["javascript","typescript"],"install":[{"cmd":"npm install hono-sessions","lang":"bash","label":"npm"},{"cmd":"yarn add hono-sessions","lang":"bash","label":"yarn"},{"cmd":"pnpm add hono-sessions","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency required for integration with the Hono web framework.","package":"hono","optional":false}],"imports":[{"note":"The primary middleware function. 'hono-sessions' is an ESM-first package. Deno users can import from 'jsr:@jcs224/hono-sessions' or 'npm:hono-sessions'.","wrong":"const { sessionMiddleware } = require('hono-sessions')","symbol":"sessionMiddleware","correct":"import { sessionMiddleware } from 'hono-sessions'"},{"note":"A common built-in storage driver for cookie-based sessions. All storage drivers are named exports.","wrong":"import CookieStore from 'hono-sessions/CookieStore'","symbol":"CookieStore","correct":"import { CookieStore } from 'hono-sessions'"},{"note":"This type is crucial for providing strong typing for the session object within your Hono context, improving developer experience and preventing runtime errors related to session data access.","wrong":null,"symbol":"Session","correct":"import { Session } from 'hono-sessions'"}],"quickstart":{"code":"import { Hono } from 'hono'\nimport {\n  Session,\n  sessionMiddleware,\n  CookieStore\n} from 'hono-sessions'\n\n// Add types to your session data for improved safety and autocomplete\ntype SessionDataTypes = {\n  'counter': number,\n  'flashMessage'?: string\n}\n\n// Set up your Hono instance with session types\nconst app = new Hono<{\n  Variables: {\n    session: Session<SessionDataTypes>,\n    session_key_rotation: boolean // Type for internal middleware variable\n  }\n}>()\n\nconst store = new CookieStore()\n\napp.use('*', sessionMiddleware({\n  store,\n  // IMPORTANT: encryptionKey must be at least 32 characters long for CookieStore\n  encryptionKey: process.env.SESSION_ENCRYPTION_KEY ?? 'super-secret-key-that-is-at-least-thirty-two-characters-long',\n  expireAfterSeconds: 900, // Session expires after 15 minutes of inactivity\n  autoExtendExpiration: true, // Automatically extends session on activity (default: true)\n  cookieOptions: {\n    sameSite: 'Lax', // Recommended for basic CSRF protection\n    path: '/', // Required for the library to function correctly\n    httpOnly: true, // Recommended to prevent client-side script access\n    secure: process.env.NODE_ENV === 'production' // Use 'Secure' in production\n  },\n}))\n\napp.get('/', async (c) => {\n  const session = c.get('session')\n\n  const currentCounter = session.get('counter') || 0;\n  session.set('counter', currentCounter + 1);\n\n  const flash = session.getFlash('flashMessage');\n  if (flash) {\n    console.log(`Flash message: ${flash}`);\n  }\n\n  return c.html(`\n    <h1>You have visited this page ${session.get('counter')} times</h1>\n    ${flash ? `<p style=\"color: green;\">${flash}</p>` : ''}\n    <p><a href=\"/set-flash\">Set a flash message</a></p>\n    <p><a href=\"/read\">Read counter (and touch session)</a></p>\n  `)\n})\n\napp.get('/set-flash', async (c) => {\n  const session = c.get('session');\n  session.setFlash('flashMessage', 'This is a one-time message!');\n  return c.redirect('/');\n});\n\napp.get('/read', (c) => {\n  const session = c.get('session')\n  session.touch() // Explicitly update the session expiration time\n  return c.json({\n    counter: session.get('counter'),\n    flash: session.getFlash('flashMessage') // This will be undefined after first read\n  })\n})\n\n// For Bun, Cloudflare Workers, etc.\n// export default {\n//   port: 3000,\n//   fetch: app.fetch\n// }\n\n// For Deno\n// Deno.serve(app.fetch)\n\n// For Node.js (via Hono adapter)\n// import { serve } from '@hono/node-server';\n// serve({ fetch: app.fetch, port: 3000 });\n","lang":"typescript","description":"This quickstart demonstrates basic session usage with `hono-sessions`, including setting and retrieving data, handling flash messages, and explicitly touching the session to extend its expiration. It configures `CookieStore` with essential options like `encryptionKey` and `cookieOptions`, and incorporates TypeScript types for session data."},"warnings":[{"fix":"Update your 'hono' package to version '^4.0.0' or newer: `npm install hono@^4.0.0` or `deno add hono@^4.0.0`.","message":"Hono v4.0.0 or higher is required as a peer dependency. Ensure your 'hono' package meets this requirement to prevent type mismatches and runtime errors.","severity":"breaking","affected_versions":">=0.8.1"},{"fix":"Provide a strong, sufficiently long (>=32 chars) `encryptionKey` in the `sessionMiddleware` options. Consider using an environment variable for this: `encryptionKey: process.env.SESSION_SECRET ?? 'your-very-long-secret-key-here'`.","message":"The `encryptionKey` option is mandatory when using `CookieStore` and highly recommended for other storage drivers to ensure session data integrity and confidentiality. It must be at least 32 characters long.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Verify that your runtime environment satisfies the Web Crypto API requirement. For Node.js, this means using version 20 or newer. Check your environment's documentation for Web Crypto API support.","message":"The Web Crypto API is a required runtime dependency for `hono-sessions` due to its use of `iron-webcrypto` for encryption. Ensure your chosen runtime environment (e.g., Node.js v20+, Deno, Bun, Cloudflare Workers) supports this API.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Always include `path: '/'` within the `cookieOptions` object passed to `sessionMiddleware`.","message":"The `cookieOptions.path` property must be set to `'/'` for `hono-sessions` to function correctly across all routes. If omitted or set incorrectly, sessions might not persist as expected.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Be aware that `session_key_rotation` will be ignored when `CookieStore` is active. This is expected behavior; no specific fix is required unless you're migrating to a stateful store where key rotation would become relevant.","message":"The `session_key_rotation` feature is explicitly stated to have no effect when using the `CookieStore` because cookie-only sessions lack server-side state that would benefit from key rotation.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you are using ESM `import { sessionMiddleware } from 'hono-sessions'` and that your environment supports ESM.","cause":"Attempting to use CommonJS `require` syntax or incorrect named import for an ESM-only package.","error":"TypeError: sessionMiddleware is not a function"},{"fix":"Add a `encryptionKey` string (at least 32 characters long) to the `sessionMiddleware` configuration.","cause":"The `encryptionKey` was not provided in the `sessionMiddleware` options when using `CookieStore`.","error":"Error: encryptionKey is required."},{"fix":"Upgrade your Node.js version to 20 or higher, or ensure you are running in an environment with Web Crypto API support (e.g., Deno, Bun, Cloudflare Workers).","cause":"The runtime environment does not support the Web Crypto API, or the Node.js version is too old (<v20).","error":"ReferenceError: crypto is not defined (or similar Web Crypto API error)"},{"fix":"Verify that `app.use('*', sessionMiddleware(...))` is correctly placed before any routes accessing `c.get('session')`. Also, ensure your 'hono' peer dependency is `^4.0.0` or newer.","cause":"This typically indicates that the Hono `c` context does not have the `session` variable, likely due to the `sessionMiddleware` not being applied or a mismatch in Hono versions preventing context augmentation.","error":"TypeError: c.get is not a function"}],"ecosystem":"npm"}