Gathering detailed insights and metrics for cookie-session
Gathering detailed insights and metrics for cookie-session
Gathering detailed insights and metrics for cookie-session
Gathering detailed insights and metrics for cookie-session
npm install cookie-session
Module System
Unable to determine the module system for this package.
Min. Node Version
Typescript Support
Node Version
NPM Version
1,126 Stars
421 Commits
208 Forks
21 Watching
3 Branches
38 Contributors
Updated on 27 Oct 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-2.7%
38,319
Compared to previous day
Last week
6.4%
218,944
Compared to previous week
Last month
14%
864,678
Compared to previous month
Last year
-12.6%
9,946,340
Compared to previous year
Simple cookie-based session middleware.
A user session can be stored in two main ways with cookies: on the server or on the client. This module stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.
The following points can help you choose which to use:
cookie-session
does not require any database / resources on the server side,
though the total session data cannot exceed the browser's max cookie size.cookie-session
can simplify certain load-balanced scenarios.cookie-session
can be used to store a "light" session and include an identifier
to look up a database-backed secondary store to reduce database lookups.NOTE This module does not encrypt the session contents in the cookie, only provides
signing to prevent tampering. The client will be able to read the session data by
examining the cookie's value. Secret data should not be set in req.session
without
encrypting it, or use a server-side session instead.
NOTE This module does not prevent session replay, as the expiration set is that
of the cookie only; if that is a concern of your application, you can store an expiration
date in req.session
object and validate it on the sever, and implement any other logic
to extend the session as your application needs.
This is a Node.js module available through the
npm registry. Installation is done using the
npm install
command:
1$ npm install cookie-session
1var cookieSession = require('cookie-session') 2var express = require('express') 3 4var app = express() 5 6app.use(cookieSession({ 7 name: 'session', 8 keys: [/* secret keys */], 9 10 // Cookie Options 11 maxAge: 24 * 60 * 60 * 1000 // 24 hours 12}))
Create a new cookie session middleware with the provided options. This middleware
will attach the property session
to req
, which provides an object representing
the loaded session. This session is either a new session if no valid session was
provided in the request, or a loaded session from the request.
The middleware will automatically add a Set-Cookie
header to the response if the
contents of req.session
were altered. Note that no Set-Cookie
header will be
in the response (and thus no session created for a specific user) unless there are
contents in the session, so be sure to add something to req.session
as soon as
you have identifying information to store for the session.
Cookie session accepts these properties in the options object.
The name of the cookie to set, defaults to session
.
The list of keys to use to sign & verify cookie values, or a configured
Keygrip
instance. Set cookies are always
signed with keys[0]
, while the other keys are valid for verification, allowing
for key rotation. If a Keygrip
instance is provided, it can be used to
change signature parameters like the algorithm of the signature.
A string which will be used as single key if keys
is not provided.
Other options are passed to cookies.get()
and cookies.set()
allowing you
to control security, domain, path, and signing among other settings.
The options can also contain any of the following (for the full list, see cookies module documentation:
maxAge
: a number representing the milliseconds from Date.now()
for expiryexpires
: a Date
object indicating the cookie's expiration date (expires at the end of session by default).path
: a string indicating the path of the cookie (/
by default).domain
: a string indicating the domain of the cookie (no default).partitioned
: a boolean indicating whether to partition the cookie in Chrome for the CHIPS Update (false
by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created.priority
: a string indicating the cookie priority. This can be set to 'low'
, 'medium'
, or 'high'
.sameSite
: a boolean or string indicating whether the cookie is a "same site" cookie (false
by default). This can be set to 'strict'
, 'lax'
, 'none'
, or true
(which maps to 'strict'
).secure
: a boolean indicating whether the cookie is only to be sent over HTTPS (false
by default for HTTP, true
by default for HTTPS). If this is set to true
and Node.js is not directly over a TLS connection, be sure to read how to setup Express behind proxies or the cookie may not ever set correctly.httpOnly
: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (true
by default).signed
: a boolean indicating whether the cookie is to be signed (true
by default).overwrite
: a boolean indicating whether to overwrite previously set cookies of the same name (true
by default).Represents the session for the given request.
Is true
if the session has been changed during the request.
Is true
if the session is new.
Determine if the session has been populated with data or is empty.
Represents the session options for the current request. These options are a shallow clone of what was provided at middleware construction and can be altered to change cookie setting behavior on a per-request basis.
To destroy a session simply set it to null
:
1req.session = null
Since the entire contents of the session is kept in a client-side cookie, the
session is "saved" by writing a cookie out in a Set-Cookie
response header.
This is done automatically if there has been a change made to the session when
the Node.js response headers are being written to the client and the session
was not destroyed.
1var cookieSession = require('cookie-session') 2var express = require('express') 3 4var app = express() 5 6app.set('trust proxy', 1) // trust first proxy 7 8app.use(cookieSession({ 9 name: 'session', 10 keys: ['key1', 'key2'] 11})) 12 13app.get('/', function (req, res, next) { 14 // Update views 15 req.session.views = (req.session.views || 0) + 1 16 17 // Write response 18 res.end(req.session.views + ' views') 19}) 20 21app.listen(3000)
1var cookieSession = require('cookie-session') 2var express = require('express') 3 4var app = express() 5 6app.set('trust proxy', 1) // trust first proxy 7 8app.use(cookieSession({ 9 name: 'session', 10 keys: ['key1', 'key2'] 11})) 12 13// This allows you to set req.session.maxAge to let certain sessions 14// have a different value than the default. 15app.use(function (req, res, next) { 16 req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge 17 next() 18}) 19 20// ... your logic here ...
This module does not send a Set-Cookie
header if the contents of the session
have not changed. This means that to extend the expiration of a session in the
user's browser (in response to user activity, for example) some kind of
modification to the session needs be made.
1var cookieSession = require('cookie-session') 2var express = require('express') 3 4var app = express() 5 6app.use(cookieSession({ 7 name: 'session', 8 keys: ['key1', 'key2'] 9})) 10 11// Update a value in the cookie so that the set-cookie will be sent. 12// Only changes every minute so that it's not sent with every request. 13app.use(function (req, res, next) { 14 req.session.nowInMinutes = Math.floor(Date.now() / 60e3) 15 next() 16}) 17 18// ... your logic here ...
This example shows creating a custom Keygrip
instance as the keys
option
to provide keys and additional signature configuration.
1var cookieSession = require('cookie-session') 2var express = require('express') 3var Keygrip = require('keygrip') 4 5var app = express() 6 7app.use(cookieSession({ 8 name: 'session', 9 keys: new Keygrip(['key1', 'key2'], 'SHA384', 'base64') 10})) 11 12// ... your logic here ...
Because the entire session object is encoded and stored in a cookie, it is possible to exceed the maximum cookie size limits on different browsers. The RFC6265 specification recommends that a browser SHOULD allow
At least 4096 bytes per cookie (as measured by the sum of the length of the cookie's name, value, and attributes)
In practice this limit differs slightly across browsers. See a list of browser limits here. As a rule of thumb don't exceed 4093 bytes per domain.
If your session object is large enough to exceed a browser limit when encoded, in most cases the browser will refuse to store the cookie. This will cause the following requests from the browser to either a) not have any session information or b) use old session information that was small enough to not exceed the cookie limit.
If you find your session object is hitting these limits, it is best to consider if data in your session should be loaded from a database on the server instead of transmitted to/from the browser with every request. Or move to an alternative session strategy
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
2 out of 2 merged PRs checked by a CI test -- score normalized to 10
Reason
6 different organizations found -- score normalized to 10
Details
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
no vulnerabilities detected
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
found 28 unreviewed changesets out of 30 -- score normalized to 0
Reason
no update tool detected
Details
Reason
project is not fuzzed
Details
Reason
0 commit(s) out of 30 and 0 issue activity out of 30 found in the last 90 days -- score normalized to 0
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
security policy file not detected
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Score
Last Scanned on 2024-11-25T21:23:27Z
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