Installations
npm install koa-session
Score
96.6
Supply Chain
98.6
Quality
82.4
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Developer
koajs
Developer Guide
Module System
Unable to determine the module system for this package.
Min. Node Version
>=8.0.0
Typescript Support
No
Node Version
18.13.0
NPM Version
6.14.17
Statistics
902 Stars
193 Commits
113 Forks
13 Watching
5 Branches
45 Contributors
Updated on 01 Nov 2024
Bundle Size
41.46 kB
Minified
15.28 kB
Minified + Gzipped
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
40,311,553
Last day
0.5%
35,668
Compared to previous day
Last week
3.3%
213,009
Compared to previous week
Last month
4.3%
909,637
Compared to previous month
Last year
-13.9%
10,070,746
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
koa-session
Simple session middleware for Koa. Defaults to cookie-based sessions and supports external stores.
Requires Node 8.0.0 or greater for async/await support
Installation
1$ npm install koa-session
Notice
6.x changed the default cookie key from koa:sess
to koa.sess
to ensure set-cookie
value valid with HTTP spec.see issue. If you want to be compatible with the previous version, you can manually set config.key
to koa:sess
.
Example
View counter example:
1const session = require('koa-session'); 2const Koa = require('koa'); 3const app = new Koa(); 4 5app.keys = ['some secret hurr']; 6 7const CONFIG = { 8 key: 'koa.sess', /** (string) cookie key (default is koa.sess) */ 9 /** (number || 'session') maxAge in ms (default is 1 days) */ 10 /** 'session' will result in a cookie that expires when session/browser is closed */ 11 /** Warning: If a session cookie is stolen, this cookie will never expire */ 12 maxAge: 86400000, 13 autoCommit: true, /** (boolean) automatically commit headers (default true) */ 14 overwrite: true, /** (boolean) can overwrite or not (default true) */ 15 httpOnly: true, /** (boolean) httpOnly or not (default true) */ 16 signed: true, /** (boolean) signed or not (default true) */ 17 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) */ 18 renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/ 19 secure: true, /** (boolean) secure cookie*/ 20 sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */ 21}; 22 23app.use(session(CONFIG, app)); 24// or if you prefer all default config, just use => app.use(session(app)); 25 26app.use(ctx => { 27 // ignore favicon 28 if (ctx.path === '/favicon.ico') return; 29 30 let n = ctx.session.views || 0; 31 ctx.session.views = ++n; 32 ctx.body = n + ' views'; 33}); 34 35app.listen(3000); 36console.log('listening on port 3000');
API
Options
The cookie name is controlled by the key
option, which defaults
to "koa.sess". All other options are passed to ctx.cookies.get()
and
ctx.cookies.set()
allowing you to control security, domain, path,
and signing among other settings.
Custom encode/decode
Support
Use options.encode
and options.decode
to customize your own encode/decode methods.
Hooks
valid()
: valid session value before use itbeforeSave()
: hook before save session
External Session Stores
The session is stored in a cookie by default, but it has some disadvantages:
- Session is stored on client side unencrypted
- Browser cookies always have length limits
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):
get(key, maxAge, { rolling, ctx })
: get session object by keyset(key, sess, maxAge, { rolling, changed, ctx })
: set session object for key, with amaxAge
(in ms)destroy(key, {ctx})
: destroy session for key
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!
The way of generating external session id is controlled by the options.genid(ctx)
, which defaults to uuid.v4()
.
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.
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.
Events
koa-session
will emit event on app
when session expired or invalid:
session:missed
: can't get session value from external store.session:invalid
: session value is invalid.session:expired
: session value is expired.
Custom External Key
External 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:
get(ctx)
: get the external keyset(ctx, value)
: set the external key
Session#isNew
Returns true if the session is new.
1if (this.session.isNew) { 2 // user has not logged in 3} else { 4 // user has already logged in 5}
Session#maxAge
Get cookie's maxAge.
Session#maxAge=
Set cookie's maxAge.
Session#externalKey
Get session external key, only exist when external session store present.
Session#save()
Save this session no matter whether it is populated.
Session#manuallyCommit()
Session headers are auto committed by default. Use this if autoCommit
is set to false
.
Destroying a session
To destroy a session simply set it to null
:
1this.session = null;
License
MIT
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/koajs/.github/SECURITY.md:1
- Info: Found linked content: github.com/koajs/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/koajs/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/koajs/.github/SECURITY.md:1
Reason
Found 10/30 approved changesets -- score normalized to 3
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/koajs/session/nodejs.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/koajs/session/nodejs.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/nodejs.yml:25
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 2 npmCommand dependencies pinned
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/nodejs.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 13 are checked with a SAST tool
Score
4.9
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More