Install express-session via npm
masterInstall the express-session module using the npm registry to add session support to your Express applications.
$ npm install express-sessionrepository·master·Indexed 27 days ago
https://github.com/expressjs/sessionSimple session middleware for Express applications (version 1.19.0) that provides session support by storing user data server-side and using a session ID in a cookie. It includes a default MemoryStore for development and supports various third-party persistent stores for production, such as Redis, MongoDB, and PostgreSQL. The middleware allows for session lifecycle management via req.session methods like regenerate, destroy, reload, and save.
Install the express-session module using the npm registry to add session support to your Express applications.
$ npm install express-sessionTo create a custom session store for express-session, your implementation must be an EventEmitter and implement several specific methods. Methods are categorized as Required, Recommended, or Optional.
The session(options) constructor accepts several configuration properties:
secret: Required. A string or Buffer used to sign the session ID cookie. Use an array of secrets to allow for rotation (new secret as first element).genid: Function to generate a new session ID. Receives req as an argument.name: The name of the session ID cookie (default: 'connect.sid').proxy: Boolean or undefined. If true, uses X-Forwarded-Proto header. If undefined, uses Express trust proxy setting.resave: Forces session to be saved back to store even if unmodified. Typically set to false if the store implements .touch().rolling: Boolean. If true, resets the cookie expiration on every response.saveUninitialized: Forces uninitialized sessions to be saved. Set to false to reduce storage or comply with privacy laws.store: The session store instance (defaults to MemoryStore).unset: Controls result of unsetting req.session. Options: 'keep' (default) or 'destroy' (deletes session from store).The cookie option is a settings object for the session ID cookie. You can provide a static object or a callback function that receives req and returns a cookie settings object.
Available cookie options:
cookie.domain: The Domain attribute.cookie.expires: The Expires attribute (use maxAge instead).cookie.httpOnly: Boolean for HttpOnly attribute (default is true).cookie.maxAge: Number in milliseconds for the cookie lifetime.cookie.partitioned: Boolean for the Partitioned attribute.cookie.path: The Path attribute (default '/').cookie.priority: 'low', 'medium', or 'high'.cookie.sameSite: 'true' (Strict), false (not set), 'lax', 'none', 'strict', or 'auto'.cookie.secure: Boolean for Secure attribute. If using a proxy, set Express trust proxy and use proxy: true or cookie.secure: 'auto'.app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: function(req) {
var match = req.url.match(/^/([^/]+)/);
return {
path: match ? '/' + match[1] : '/',
httpOnly: true,
secure: req.secure || false,
maxAge: 60000
}
}
}))express-session uses the debug module. You can view internal logs by setting the DEBUG environment variable to express-session.Once the middleware is installed, you can access the session object via req.session. Data is typically serialized as JSON, allowing for nested objects.
Example usage:
app.get('/', function(req, res) {
if (req.session.views) {
req.session.views++
res.send('views: ' + req.session.views);
} else {
req.session.views = 1;
res.send('welcome!');
}
});// 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!')
}
})You can access session metadata through the following properties:
req.sessionID: A read-only property containing the loaded session ID.req.session.id: An alias for req.sessionID.req.session.cookie: The session's unique cookie object.req.session.cookie.maxAge: The remaining time in milliseconds until expiration. Can be reassigned to adjust expiration.req.session.cookie.originalMaxAge: The original time-to-live (TTL) in milliseconds.Example: Adjusting cookie expiration
var hour = 3600000;
req.session.cookie.expires = new Date(Date.now() + hour);
// OR
req.session.cookie.maxAge = hour;Create a session middleware using session(options). Note that session data is stored server-side, and only the session ID is stored in the cookie. Since version 1.5.0, cookie-parser is no longer required as the module reads and writes cookies directly on req/res.
Warning: The default MemoryStore is intended for development/debugging only. It is not designed for production as it leaks memory and does not scale.
The req.session object provides several methods to manage the session lifecycle:
req.session.regenerate(callback): Generates a new SID and initializes a new session instance.req.session.destroy(callback): Destroys the session and unsets req.session.req.session.reload(callback): Reloads session data from the store into req.session.req.session.save(callback): Manually saves the session back to the store. Useful for redirects or WebSockets.req.session.touch(): Updates the .maxAge property.// Regenerate
req.session.regenerate(function(err) {
// new session here
})
// Destroy
req.session.destroy(function(err) {
// cannot access session here
})
// Reload
req.session.reload(function(err) {
// session updated
})
// Save
req.session.save(function(err) {
// session saved
})You can configure the session cookie using the cookie option in the session() middleware. This can be a static object or a function that receives the req object, allowing for dynamic configuration (e.g., setting secure: true only if the request is HTTPS).
Special Values:
secure: 'auto': Automatically sets the secure flag based on whether the connection is secure.sameSite: 'auto': Automatically sets sameSite to 'none' if secure, otherwise 'lax'.The express-session middleware is compatible with a wide variety of third-party session stores. Instead of using the default in-memory store (which is not designed for production), you can use these modules to persist session data in databases like Redis, MongoDB, PostgreSQL, or cloud-based services.
Commonly used stores include:
connect-redisconnect-mongo or connect-mongodb-sessionconnect-pg-simpleconnect-session-knex, connect-session-sequelize, connect-typeorm, or @quixo3/prisma-session-storebetter-sqlite3-session-store or connect-sqlite3connect-redis, connect-dynamodb, @google-cloud/connect-firestore, or connect-azuretablesRefer to the specific documentation for the store you choose to handle its unique configuration requirements.
The following methods are optional and are not called by express-session itself, but are useful for managing the store directly:
store.all(callback): Returns all sessions in the store as an array. Callback: callback(error, sessions).store.clear(callback): Deletes all sessions from the store. Callback: callback(error).store.length(callback): Returns the count of all sessions in the store. Callback: callback(error, len).