{"id":13600796,"url":"https://github.com/koajs/session","last_synced_at":"2025-05-13T20:22:38.060Z","repository":{"id":11677538,"uuid":"14187683","full_name":"koajs/session","owner":"koajs","description":"Simple session middleware for koa","archived":false,"fork":false,"pushed_at":"2025-04-06T22:00:42.000Z","size":289,"stargazers_count":901,"open_issues_count":52,"forks_count":113,"subscribers_count":12,"default_branch":"master","last_synced_at":"2025-05-07T18:04:42.613Z","etag":null,"topics":["koa","koa-session","session"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/koajs.png","metadata":{"files":{"readme":"Readme.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2013-11-06T22:33:49.000Z","updated_at":"2025-05-03T04:55:30.000Z","dependencies_parsed_at":"2025-04-11T12:57:07.851Z","dependency_job_id":"c4e2a446-01cb-47f5-aa0e-836382a00cdc","html_url":"https://github.com/koajs/session","commit_stats":{"total_commits":181,"total_committers":39,"mean_commits":4.641025641025641,"dds":0.5359116022099448,"last_synced_commit":"98630aaf6587b199969490f8503641554aeee917"},"previous_names":[],"tags_count":59,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koajs%2Fsession","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koajs%2Fsession/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koajs%2Fsession/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koajs%2Fsession/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/koajs","download_url":"https://codeload.github.com/koajs/session/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253736154,"owners_count":21955799,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["koa","koa-session","session"],"created_at":"2024-08-01T18:00:48.782Z","updated_at":"2025-05-13T20:22:38.008Z","avatar_url":"https://github.com/koajs.png","language":"TypeScript","readme":"# koa-session\n\n[![NPM version][npm-image]][npm-url]\n[![Node.js CI](https://github.com/koajs/session/actions/workflows/nodejs.yml/badge.svg)](https://github.com/koajs/session/actions/workflows/nodejs.yml)\n[![Test coverage][codecov-image]][codecov-url]\n[![Known Vulnerabilities][snyk-image]][snyk-url]\n[![npm download][download-image]][download-url]\n[![Node.js Version](https://img.shields.io/node/v/koajs/session.svg?style=flat)](https://nodejs.org/en/download/)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)\n\n[npm-image]: https://img.shields.io/npm/v/koa-session.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/koa-session\n[codecov-image]: https://codecov.io/gh/koajs/session/branch/master/graph/badge.svg\n[codecov-url]: https://codecov.io/gh/koajs/session\n[snyk-image]: https://snyk.io/test/npm/koa-session/badge.svg?style=flat-square\n[snyk-url]: https://snyk.io/test/npm/koa-session\n[download-image]: https://img.shields.io/npm/dm/koa-session.svg?style=flat-square\n[download-url]: https://npmjs.org/package/koa-session\n\nSimple session middleware for Koa. Defaults to cookie-based sessions and supports external stores.\n\n## Installation\n\n```bash\nnpm install koa-session\n```\n\n## Notice\n\n7.x has a breaking change: drop Node.js \u003c 18.19.0 support. And it support CommonJS and ESM both.\n\n6.x changed the default cookie key from `koa:sess` to `koa.sess` to ensure `set-cookie` value valid with HTTP spec.\n[See issue](https://github.com/koajs/session/issues/28).\nIf you want to be compatible with the previous version, you can manually set `config.key` to `koa:sess`.\n\n## Example\n\nView counter example:\n\n```js\nimport Koa from 'koa';\nimport session from 'koa-session';\n\nconst app = new Koa();\n\napp.keys = ['some secret hurr'];\n\nconst CONFIG = {\n  key: 'koa.sess', /** (string) cookie key (default is koa.sess) */\n  /** (number || 'session') maxAge in ms (default is 1 days) */\n  /** 'session' will result in a cookie that expires when session/browser is closed */\n  /** Warning: If a session cookie is stolen, this cookie will never expire */\n  maxAge: 86400000,\n  autoCommit: true, /** (boolean) automatically commit headers (default true) */\n  overwrite: true, /** (boolean) can overwrite or not (default true) */\n  httpOnly: true, /** (boolean) httpOnly or not (default true) */\n  signed: true, /** (boolean) signed or not (default true) */\n  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */\n  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/\n  secure: true, /** (boolean) secure cookie*/\n  sameSite: null, /** (string) session cookie sameSite options (default null, do not provide this key if you are not restricting sameSite) */\n};\n\napp.use(session(CONFIG, app));\n// or if you prefer all default config, just use =\u003e app.use(session(app));\n\napp.use(ctx =\u003e {\n  // ignore favicon\n  if (ctx.path === '/favicon.ico') return;\n\n  let n = ctx.session.views || 0;\n  ctx.session.views = ++n;\n  ctx.body = n + ' views';\n});\n\napp.listen(3000);\nconsole.log('listening on port 3000');\n```\n\n## API\n\n### Options\n\nThe cookie name is controlled by the `key` option, which defaults\nto \"koa.sess\". All other options are passed to `ctx.cookies.get()` and\n`ctx.cookies.set()` allowing you to control security, domain, path,\nand signing among other settings.\n\n#### Custom `encode/decode` Support\n\nUse `options.encode` and `options.decode` to customize your own encode/decode methods.\n\n### Hooks\n\n- `valid()`: valid session value before use it\n- `beforeSave()`: hook before save session\n\n### External Session Stores\n\nThe session is stored in a cookie by default, but it has some disadvantages:\n\n- Session is stored on client side unencrypted\n- [Browser cookies always have length limits](http://browsercookielimits.squawky.net/)\n\n  You can store the session content in external stores (Redis, MongoDB or other DBs) by passing `options.store` with three methods (these need to be async functions):\n\n- `get(key, maxAge, { rolling, ctx })`: get session object by key\n- `set(key, sess, maxAge, { rolling, changed, ctx })`: set session object for key, with a `maxAge` (in ms)\n- `destroy(key, {ctx})`: destroy session for key\n\n  Once you pass `options.store`, session storage is dependent on your external store -- you can't access the session if your external store is down. **Use external session stores only if necessary, avoid using session as a cache, keep the session lean, and store it in a cookie if possible!**\n\n  The way of generating external session id is controlled by the `options.genid(ctx)`, which defaults to `uuid.v4()`.\n\n  If you want to add prefix for all external session id, you can use `options.prefix`, it will not work if `options.genid(ctx)` present.\n\n  If your session store requires data or utilities from context, `opts.ContextStore` is also supported. `ContextStore` must be a class which claims three instance methods demonstrated above. `new ContextStore(ctx)` will be executed on every request.\n\n### Events\n\n`koa-session` will emit event on `app` when session expired or invalid:\n\n- `session:missed`: can't get session value from external store.\n- `session:invalid`: session value is invalid.\n- `session:expired`: session value is expired.\n\n### Custom External Key\n\nExternal key is used the cookie by default, but you can use `options.externalKey` to customize your own external key methods. `options.externalKey` with two methods:\n\n- `get(ctx)`: get the external key\n- `set(ctx, value)`: set the external key\n\n### Session#isNew\n\nReturns **true** if the session is new.\n\n```js\nif (this.session.isNew) {\n  // user has not logged in\n} else {\n  // user has already logged in\n}\n```\n\n### Session#maxAge\n\nGet cookie's maxAge.\n\n### Session#maxAge=\n\nSet cookie's maxAge.\n\n### Session#externalKey\n\nGet session external key, only exist when external session store present.\n\n### Session#save()\n\nSave this session no matter whether it is populated.\n\n### Session#manuallyCommit()\n\nSession headers are auto committed by default. Use this if `autoCommit` is set to `false`.\n\n### Destroying a session\n\nTo destroy a session simply set it to `null`:\n\n```js\nthis.session = null;\n```\n\n## License\n\n[MIT](LICENSE)\n\n## Contributors\n\n[![Contributors](https://contrib.rocks/image?repo=koajs/session)](https://github.com/koajs/session/graphs/contributors)\n\nMade with [contributors-img](https://contrib.rocks).\n","funding_links":[],"categories":["TypeScript","Middleware","JavaScript","仓库","Node.js, koa"],"sub_categories":["中间件","Utilites"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoajs%2Fsession","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkoajs%2Fsession","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoajs%2Fsession/lists"}