3 [![NPM Version][npm-image]][npm-url]
4 [![NPM Downloads][downloads-image]][downloads-url]
5 [![Build Status][travis-image]][travis-url]
6 [![Test Coverage][coveralls-image]][coveralls-url]
7 [![Gratipay][gratipay-image]][gratipay-url]
12 $ npm install express-session
18 var session = require('express-session')
23 Create a session middleware with the given `options`.
25 **Note** Session data is _not_ saved in the cookie itself, just the session ID.
26 Session data is stored server-side.
28 **Warning** The default server-side session storage, `MemoryStore`, is _purposely_
29 not designed for a production environment. It will leak memory under most
30 conditions, does not scale past a single process, and is meant for debugging and
33 For a list of stores, see [compatible session stores](#compatible-session-stores).
37 `express-session` accepts these properties in the options object.
41 Settings for the session ID cookie. See the "Cookie options" section below for
42 more information on the different values.
44 The default value is `{ path: '/', httpOnly: true, secure: false, maxAge: null }`.
48 Function to call to generate a new session ID. Provide a function that returns
49 a string that will be used as a session ID. The function is given `req` as the
50 first argument if you want to use some value attached to `req` when generating
53 The default value is a function which uses the `uid2` library to generate IDs.
55 **NOTE** be careful to generate unique IDs so your sessions do not conflict.
59 genid: function(req) {
60 return genuuid() // use UUIDs for session IDs
62 secret: 'keyboard cat'
68 The name of the session ID cookie to set in the response (and read from in the
71 The default value is `'connect.sid'`.
73 **Note** if you have multiple apps running on the same host (hostname + port),
74 then you need to separate the session cookies from each other. The simplest
75 method is to simply set different `name`s per app.
79 Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto"
82 The default value is `undefined`.
84 - `true` The "X-Forwarded-Proto" header will be used.
85 - `false` All headers are ignored and the connection is considered secure only
86 if there is a direct TLS/SSL connection.
87 - `undefined` Uses the "trust proxy" setting from express
91 Forces the session to be saved back to the session store, even if the session
92 was never modified during the request. Depending on your store this may be
93 necessary, but it can also create race conditions where a client makes two
94 parallel requests to your server and changes made to the session in one
95 request may get overwritten when the other request ends, even if it made no
96 changes (this behavior also depends on what store you're using).
98 The default value is `true`, but using the default has been deprecated,
99 as the default will change in the future. Please research into this setting
100 and choose what is appropriate to your use-case. Typically, you'll want
103 How do I know if this is necessary for my store? The best way to know is to
104 check with your store if it implements the `touch` method. If it does, then
105 you can safely set `resave: false`. If it does not implement the `touch`
106 method and your store sets an expiration date on stored sessions, then you
107 likely need `resave: true`.
111 Force a cookie to be set on every response. This resets the expiration date.
113 The default value is `false`.
115 ##### saveUninitialized
117 Forces a session that is "uninitialized" to be saved to the store. A session is
118 uninitialized when it is new but not modified. Choosing `false` is useful for
119 implementing login sessions, reducing server storage usage, or complying with
120 laws that require permission before setting a cookie. Choosing `false` will also
121 help with race conditions where a client makes multiple parallel requests
124 The default value is `true`, but using the default has been deprecated, as the
125 default will change in the future. Please research into this setting and
126 choose what is appropriate to your use-case.
128 **Note** if you are using Session in conjunction with PassportJS, Passport
129 will add an empty Passport object to the session for use after a user is
130 authenticated, which will be treated as a modification to the session, causing
137 This is the secret used to sign the session ID cookie. This can be either a string
138 for a single secret, or an array of multiple secrets. If an array of secrets is
139 provided, only the first element will be used to sign the session ID cookie, while
140 all the elements will be considered when verifying the signature in requests.
144 The session store instance, defaults to a new `MemoryStore` instance.
148 Control the result of unsetting `req.session` (through `delete`, setting to `null`,
151 The default value is `'keep'`.
153 - `'destroy'` The session will be destroyed (deleted) when the response ends.
154 - `'keep'` The session in the store will be kept, but modifications made during
155 the request are ignored and not saved.
159 **Note** Since version 1.5.0, the [`cookie-parser` middleware](https://www.npmjs.com/package/cookie-parser)
160 no longer needs to be used for this module to work. This module now directly reads
161 and writes cookies on `req`/`res`. Using `cookie-parser` may result in issues
162 if the `secret` is not the same between this module and `cookie-parser`.
164 Please note that `secure: true` is a **recommended** option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies.
165 If `secure` is set, and you access your site over HTTP, the cookie will not be set. If you have your node.js behind a proxy and are using `secure: true`, you need to set "trust proxy" in express:
169 app.set('trust proxy', 1) // trust first proxy
171 secret: 'keyboard cat',
173 saveUninitialized: true,
174 cookie: { secure: true }
178 For using secure cookies in production, but allowing for testing in development, the following is an example of enabling this setup based on `NODE_ENV` in express:
183 secret: 'keyboard cat',
187 if (app.get('env') === 'production') {
188 app.set('trust proxy', 1) // trust first proxy
189 sess.cookie.secure = true // serve secure cookies
192 app.use(session(sess))
195 By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set
196 so the cookie becomes a browser-session cookie. When the user closes the
197 browser the cookie (and session) will be removed.
201 To store or access session data, simply use the request property `req.session`,
202 which is (generally) serialized as JSON by the store, so nested objects
203 are typically fine. For example below is a user-specific view counter:
206 app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
208 app.use(function(req, res, next) {
209 var sess = req.session
212 res.setHeader('Content-Type', 'text/html')
213 res.write('<p>views: ' + sess.views + '</p>')
214 res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>')
218 res.end('welcome to the session demo. refresh!')
223 #### Session.regenerate()
225 To regenerate the session simply invoke the method, once complete
226 a new SID and `Session` instance will be initialized at `req.session`.
229 req.session.regenerate(function(err) {
230 // will have a new session here
234 #### Session.destroy()
236 Destroys the session, removing `req.session`, will be re-generated next request.
239 req.session.destroy(function(err) {
240 // cannot access session here
244 #### Session.reload()
246 Reloads the session data.
249 req.session.reload(function(err) {
257 req.session.save(function(err) {
264 Updates the `.maxAge` property. Typically this is
265 not necessary to call, as the session middleware does this for you.
267 ### req.session.cookie
269 Each session has a unique cookie object accompany it. This allows
270 you to alter the session cookie per visitor. For example we can
271 set `req.session.cookie.expires` to `false` to enable the cookie
272 to remain for only the duration of the user-agent.
276 Alternatively `req.session.cookie.maxAge` will return the time
277 remaining in milliseconds, which we may also re-assign a new value
278 to adjust the `.expires` property appropriately. The following
279 are essentially equivalent
283 req.session.cookie.expires = new Date(Date.now() + hour)
284 req.session.cookie.maxAge = hour
287 For example when `maxAge` is set to `60000` (one minute), and 30 seconds
288 has elapsed it will return `30000` until the current request has completed,
289 at which time `req.session.touch()` is called to reset `req.session.maxAge`
290 to its original value.
293 req.session.cookie.maxAge // => 30000
296 ## Session Store Implementation
298 Every session store _must_ be an `EventEmitter` and implement the following
301 - `.get(sid, callback)`
302 - `.set(sid, session, callback)`
303 - `.destroy(sid, callback)`
305 Recommended methods include, but are not limited to:
307 - `.touch(sid, session, callback)`
308 - `.length(callback)`
311 For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo.
313 ## Compatible Session Stores
315 The following modules implement a session store that is compatible with this
316 module. Please make a PR to add additional modules :)
318 [![Github Stars][cassandra-store-image] cassandra-store][cassandra-store-url] An Apache Cassandra-based session store.
319 [cassandra-store-url]: https://www.npmjs.com/package/cassandra-store
320 [cassandra-store-image]: https://img.shields.io/github/stars/webcc/cassandra-store.svg?label=%E2%98%85
322 [![Github Stars][connect-mssql-image] connect-mssql][connect-mssql-url] A SQL Server-based session store.
323 [connect-mssql-url]: https://www.npmjs.com/package/connect-mssql
324 [connect-mssql-image]: https://img.shields.io/github/stars/patriksimek/connect-mssql.svg?label=%E2%98%85
326 [![Github Stars][connect-mongo-image] connect-mongo][connect-mongo-url] A MongoDB-based session store.
327 [connect-mongo-url]: https://www.npmjs.com/package/connect-mongo
328 [connect-mongo-image]: https://img.shields.io/github/stars/kcbanner/connect-mongo.svg?label=%E2%98%85
330 [![Github Stars][connect-mongodb-session-image] connect-mongodb-session][connect-mongodb-session-url] Lightweight MongoDB-based session store built and maintained by MongoDB.
331 [connect-mongodb-session-url]: https://www.npmjs.com/package/connect-mongodb-session
332 [connect-mongodb-session-image]: https://img.shields.io/github/stars/mongodb-js/connect-mongodb-session.svg?label=%E2%98%85
334 [![Github Stars][connect-redis-image] connect-redis][connect-redis-url] A Redis-based session store.
335 [connect-redis-url]: https://www.npmjs.com/package/connect-redis
336 [connect-redis-image]: https://img.shields.io/github/stars/tj/connect-redis.svg?label=%E2%98%85
338 [![Github Stars][connect-session-knex-image] connect-session-knex][connect-session-knex-url] A session store using
339 [Knex.js](http://knexjs.org/), which is a SQL query builder for PostgreSQL, MySQL, MariaDB, SQLite3, and Oracle.
340 [connect-session-knex-url]: https://www.npmjs.com/package/connect-session-knex
341 [connect-session-knex-image]: https://img.shields.io/github/stars/llambda/connect-session-knex.svg?label=%E2%98%85
343 [![Github Stars][level-session-store-image] level-session-store][level-session-store-url] A LevelDB-based session store.
344 [level-session-store-url]: https://www.npmjs.com/package/level-session-store
345 [level-session-store-image]: https://img.shields.io/github/stars/scriptollc/level-session-store.svg?label=%E2%98%85
347 [![Github Stars][mssql-session-store-image] mssql-session-store][mssql-session-store-url] A SQL Server-based session store.
348 [mssql-session-store-url]: https://www.npmjs.com/package/mssql-session-store
349 [mssql-session-store-image]: https://img.shields.io/github/stars/jwathen/mssql-session-store.svg?label=%E2%98%85
351 [![Github Stars][session-file-store-image] session-file-store][session-file-store-url] A file system-based session store.
352 [session-file-store-url]: https://www.npmjs.com/package/session-file-store
353 [session-file-store-image]: https://img.shields.io/github/stars/valery-barysok/session-file-store.svg?label=%E2%98%85
355 [![Github Stars][session-rethinkdb-image] session-rethinkdb][session-rethinkdb-url] A [RethinkDB](http://rethinkdb.com/)-based session store.
356 [session-rethinkdb-url]: https://www.npmjs.com/package/session-rethinkdb
357 [session-rethinkdb-image]: https://img.shields.io/github/stars/llambda/session-rethinkdb.svg?label=%E2%98%85
361 A simple example using `express-session` to store page views for a user.
364 var express = require('express')
365 var parseurl = require('parseurl')
366 var session = require('express-session')
371 secret: 'keyboard cat',
373 saveUninitialized: true
376 app.use(function (req, res, next) {
377 var views = req.session.views
380 views = req.session.views = {}
383 // get the url pathname
384 var pathname = parseurl(req).pathname
387 views[pathname] = (views[pathname] || 0) + 1
392 app.get('/foo', function (req, res, next) {
393 res.send('you viewed this page ' + req.session.views['/foo'] + ' times')
396 app.get('/bar', function (req, res, next) {
397 res.send('you viewed this page ' + req.session.views['/bar'] + ' times')
405 [npm-image]: https://img.shields.io/npm/v/express-session.svg
406 [npm-url]: https://npmjs.org/package/express-session
407 [travis-image]: https://img.shields.io/travis/expressjs/session/master.svg
408 [travis-url]: https://travis-ci.org/expressjs/session
409 [coveralls-image]: https://img.shields.io/coveralls/expressjs/session/master.svg
410 [coveralls-url]: https://coveralls.io/r/expressjs/session?branch=master
411 [downloads-image]: https://img.shields.io/npm/dm/express-session.svg
412 [downloads-url]: https://npmjs.org/package/express-session
413 [gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg
414 [gratipay-url]: https://gratipay.com/dougwilson/