Introduction: Recently, when using express-session middleware, I took some time to translate the document because some parameters were not very clear.
Among the common Settings that are confusing are the Resave and saveUnintialized properties, about which the CNODE community has a more familiar and understandable explanation:
Resave: Resets the session cookie for each request. If your cookie expires in 10 minutes, the session cookie will be reset for another 10 minutes for each request. SaveUninitialized: No matter whether there is a session cookie or not, a session cookie is set for each request. The session cookie is marked connect.sid by default.
The following is the text:
Installation
This is a Node.js module available through NPM Registry. Use the following NPM install command to complete the installation.
$ npm install express-session
Copy the code
API
var session = require('express-session');
Copy the code
sessions(options)
Creates a session middleware with the given options.
Note: Only the session ID is stored in the cookie, the session data itself is not. Session data is stored on the server.
Note: As of version 1.5.0, cookie-Parser middleware is no longer required to run this module. This module now reads and writes cookies directly on req/ RES. Using cookie-parser can cause problems when the secret of this module and cookie-parser does not match.
Warning: The default server session store, MemoryStore, is not specifically designed for production environments. In most cases, it can cause memory leaks and does not extend beyond a single process, which is intended for debugging and development.
For a list of stores, see compatible Session stores
Options
Express-session receives the following parameters in the Options object
cookie
Session ID Setting object of the cookie. Default values are {path: ‘/’, httpOnly: true, Secure: false, maxAge: null}.
The following parameters optionally set the cookie object to be placed.
cookie.domain
Specifies the domain for the set-cookie property. By default, the domain is not set, and most clients treat cookies as if they apply only to the current domain.
cookie.expires
Specifies the Date object in the set-cookie attribute Expires. By default, expires is not set, and most clients will treat this as a “nonpersistent cookie” and delete it in scenarios like exiting the browser application.
Note: If both Expires and maxAge are set in the Options object, the last property defined in the object will be used.
Note: The Expires option should not be set directly; Instead, only the maxAge option should be used.
cookie.httpOnly
Specifies a Boolean value for HttpOnly in the set-cookie attribute. When true, the HttpOnly attribute is set, otherwise not. By default, the HttpOnly attribute is set.
Note: Be careful when setting this value to true, because protocol-compliant clients will not allow JavaScript to view cookies in document.cookie.
cookie.maxAge
Specifies the number (millisecond) value to use when evaluating Expires in the set-cookie attribute. This is done by taking the current server time and adding maxAge milliseconds to it to calculate the Expires date time. MaxAge is not set by default.
Note: If both Expires and maxAge are set in the Options object, the last property defined in the object will be used.
cookie.path
Specify a Path value for the set-cookie property. By default this value is set to ‘/’, which is the root path of the domain.
cookie.sameSite
Specifies a Boolean or string value for SameSite in the set-cookie property. Among them,
true
The SameSite property is set to Strict for Strict same-site enforcement.false
No SameSite attribute.'lax'
The SameSite property is set to Lax for loose same-site enforcement.'strict'
The SameSite property is set to Strict for Strict same-site enforcement.
More information about different enforcement levels can be found in the detailed rules for the tools.ietf.org/html/draft-…
Note: This is a property that has not been fully standardized and may change in the future. This means that many clients may ignore this property until they fully understand it.
cookie.secure
Specifies a Boolean value for Secure in the set-cookie property. When true, the Secure property is set otherwise not set. The Secure property is not set by default.
Note: Be careful when setting this value to true, because protocol-compliant clients will not send cookies back to the server if the browser does not establish HTTPS connections.
Please note that Secure: True is recommended. However, it requires an HTTPS enabled site, which is required for Secure Cookies. If secure is set and you access your site over HTTP, cookies will not be set. If you use Node.js after proxy and set Secure: true, you need to set “trust proxy” in Express:
var app = express()
app.set('trust proxy'.1) // trust first proxy
app.use(session({
secret: 'keyboard cat'.resave: false.saveUninitialized: true.cookie: { secure: true}}))Copy the code
To use secure cookies in a production environment while allowing testing in a development environment, the following is an example of enabling this setting in Express based on NODE_ENV:
var app = express()
var sess = {
secret: 'keyboard cat'.cookie: {}}if (app.get('env') = = ='production') {
app.set('trust proxy'.1) // trust first proxy
sess.cookie.secure = true // serve secure cookies
}
app.use(session(sess))
Copy the code
The cookie.secure option can also be set to the special value “auto” to make this setting automatically match the security of the established connection. Use this setting with care if the site can be used for both HTTP and HTTPS, because cookies are no longer visible to HTTP once their HTTPS properties are set. This is useful when Express’s “Trust Proxy” is properly set up to simplify development and production configurations.
genid
Call the function to generate a new session ID. Provides a function that returns a string and will be used as the session ID. If you want to append some value to req when generating the ID, the function already gives req as the first argument.
The default is a function that uses the UID-safe library to generate the ID.
Note: Be careful to generate unique ids so that your sessions do not conflict.
app.use(session({
genid: function(req) {
return genuuid() // use UUIDs for session IDs
},
secret: 'keyboard cat'
}))
Copy the code
name
Set the cookie name of the session ID in response (and read from request).
The default value is “connect.sid”.
Note: If you have more than one running on the same hostname (just the name, i.e. Localhost or 127.0.0.1; Different protocol (Scheme) and port (port) do not name different host names on the application, then you need to separate session cookies from each other. The easiest way is to set a different name for each application.
proxy
Trust reverse proxies (via the “X-Forwarded-Proto” header) when setting secure cookies.
The default value is undefined.
true
said"X-Forwarded-Proto"
Heads will be used.false
Indicates that all headers are ignored and the connection is considered secure only if there is a direct TLS/SSL connection.undefined
Trust Proxy is used from Express.
resave
Force the session to be saved back to the Session store even if it has never been modified during the request. This may be necessary depending on your storage, But this can also create competitive conditions when A client sends two parallel requests to your server and changes made to the session by one request A may be overwritten by the end of the other request B even though no changes have been made (this behavior depends on the session store you are using).
The default value is true, but it is not recommended to use the default value because it will change in the future. Study this setting and choose the option that suits your use case. In general, you’ll want to choose False.
How do I know if this setting is necessary for my session store? The best way to do this is to check your storage to see if it implements the Touch method. If it does, you can safely set resave to false. If it does not implement the touch method and your store sets the expiration date in the stored sessions, then you may need to set resave: false.
rolling
Enforces a session identifier cookie to be set on each response. Expiration is reset to the initial maxAge, resetting the expiration countdown.
The default value is false.
Note: When this option is set to true but the saveUninitialized option is set to false, cookies are not set in session responses that have not been initialized.
saveUninitialized
Force an uninitialized session to be saved back to the store. A session is uninitialized when it is new but has not been modified. Choosing false is useful for implementing a login session because it reduces the amount of storage on the server and complies with the rule that you need permission before setting cookies. Choosing false also helps the client to make a race condition for a parallel request without a reply.
The default value is true, but it is not recommended to use the default value because it will change in the future. Study this setting and choose the option that suits your use case.
Note: If you are using a Session with PassportJS, PassportJS will add an empty Passport object to the Session for the user after the user authenticates, which will be treated as a modification to the Session, causing the Session to be saved. This has been fixed in PassportJS 0.3.0.
secret
Will set options
This is the secret used to sign the session ID cookie. This can be a single string of secret or an array of secret. If you provide a set of secrets, only the first element will be used to sign the session ID cookie, and all elements will be considered when validating the request signature.
store
Session storage instance, which defaults to a new MemoryStore instance.
unset
Control the result of unsetting req.session (by deleting, setting it to null, etc.).
Default is ‘keep’
'destroy'
Indicates that the session will be destroyed (deleted) when the response ends.'keep'
Indicates that sessions in the store are preserved, but changes made during a request are ignored and not saved.
req.session
Session data is stored or accessed using only the request property req.session, which is (usually) serialized into session by store, so nested objects are generally acceptable. The following example is a user-specific view counter:
// Use the session middleware
app.use(session({ secret: 'keyboard cat'.cookie: { maxAge: 60000 }}))
// Access the session as req.session
app.get('/'.function(req, res, next) {
if (req.session.views) {
req.session.views++
res.setHeader('Content-Type'.'text/html')
res.write('<p>views: ' + req.session.views + '</p>')
res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
req.session.views = 1
res.end('welcome to the session demo. refresh! ')}})Copy the code
Session.regenerate(callback)
To regenerate the session, simply call this method. When this is done, a new SID and Session instance will be initialized in req. Session and callback will be called.
req.session.regenerate(function(err) {
// will have a new session here
})
Copy the code
Session.destroy(callback)
Destroys the Session and unsets the req.session property. When done, the callback is called.
req.session.destroy(function(err) {
// cannot access session here
})
Copy the code
Session.reload(callback)
Reload session data from store and repopulate the req.session object. When done, the callback is called.
req.session.reload(function(err) {
// session updated
})
Copy the code
Session.save(callback)
Save the session back to the store and replace what’s in the store with what’s in memory (although the store might do something else as well – see the Store’s documentation for exactly how it behaves).
This method is automatically called at the end of the HTTP response if session data is changed (although this behavior can be changed by various options in the middleware constructor). Therefore, this method generally does not need to be called manually.
There are situations where calling this method can be useful, such as redirects, long-lived requests, or WebSockets.
req.session.save(function(err) {
// session saved
})
Copy the code
Session.touch(callback)
Update the.maxage property. Normally this method doesn’t need to be called because the Session middleware does it for you.
req.session.id
Each session has a unique ID associated with it. This property is an alias to req.sessionID and cannot be modified. This property has been added to make the session ID accessible from the Session object.
req.session.cookie
Each session is accompanied by a unique cookie. This allows you to change the session cookie for each visitor. For example, we can set up the req. Session. Cookies. Expires to false to make cookies only retained in the duration of the user – agent.
Cookie.maxAge
The req. Session. Cookies. MaxAge will return to the rest of the time in milliseconds, we can also to assign a new value to properly adjust the expires attribute. The following code is equivalent:
var hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour)
req.session.cookie.maxAge = hour
Copy the code
For example, when maxAge is set to 60000 (one minute), thirty seconds later it will return 30000 until the current request is complete, at which point a call to req.session.touch() will reset req.session.maxage to its initial value.
req.session.cookie.maxAge / / = > 30000
Copy the code
req.sessionID
To get the loaded sessionID, the access request property req.sessionID. This is only a read-only value when the session is loaded or created.
Session Store Implementation
Each Session Store must be an EventEmitter and implement specific methods. The following is a list of required, recommended, and optional methods.
- The required methods are the ones the module will always call in the Store.
- The recommended method is the one that the module would call in the Store if available.
- The optional methods are methods that this module will not call at all
See the connect-Redis repository for a sample implementation.
store.all(callback)
optional
This optional method is used to get all sessions in a store as an array. The callback method should be callback(error, sessions).
store.destroy(sid, callback)
necessary
The required method destroys (deletes) the session in the store based on the given session ID. If the session is deleted, the callback function should be called callback(error).
store.clear(callback)
optional
This optional method is used to delete all sessions in the store. The callback function should be called callback(error) after the store is cleared.
store.length(callback)
optional
This optional method is used to get the number of sessions in a store. The callback function should be callback(error, len).
store.get(sid, callback)
necessary
The required method gets the session from the store based on the given session ID. The callback function should be callback(error, session).
The session argument in the session callback should be a session object if it was found, otherwise null or undefined if no session was found (and there is no error). This is a special case when error.code === ‘ENOENT’ appears as callback(NULL, NULL).
store.set(sid, session, callback)
necessary
The required method stores the session based on the given session ID and session object. The callback function should be called callback(error) after the session is stored to the store.
store.touch(sid, session, callback)
recommended
This recommended method “touches” a given session object based on the given session ID and the session object. If the session is “touched”, the callback should be called callback(error).
This method is primarily used by the store to automatically delete idle sessions and to signal to the store that a given session is active, possibly resetting the idle timer.
Compatible Session Stores
The following modules implement a session store compatible with this module. Please make PULL REQUEST to add additional modules 🙂
This section lists only two store implementations, see the original documentation for more
Connect-db2: an IBM DB2-based session store built using the IBM_DB module.
Connect-mongo: a SESSION store based on SQL Server.
Example
A simple example of using express-session to store page access for users:
var express = require('express')
var parseurl = require('parseurl')
var session = require('express-session')
var app = express()
app.use(session({
secret: 'keyboard cat'.resave: false.saveUninitialized: true
}))
app.use(function (req, res, next) {
if(! req.session.views) { req.session.views = {} }// get the url pathname
var pathname = parseurl(req).pathname
// count the views
req.session.views[pathname] = (req.session.views[pathname] || 0) + 1
next()
})
app.get('/foo'.function (req, res, next) {
res.send('you viewed this page ' + req.session.views['/foo'] + ' times')
})
app.get('/bar'.function (req, res, next) {
res.send('you viewed this page ' + req.session.views['/bar'] + ' times')})Copy the code
License
MIT
Keywords
none