Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Simple session middleware for Express

License

NotificationsYou must be signed in to change notification settings

expressjs/session

Repository files navigation

NPM VersionNPM DownloadsBuild StatusTest Coverage

Installation

This is aNode.js module available through thenpm registry. Installation is done using thenpm install command:

$ npm install express-session

API

varsession=require('express-session')

session(options)

Create a session middleware with the givenoptions.

Note Session data isnot saved in the cookie itself, just the session ID.Session data is stored server-side.

Note Since version 1.5.0, thecookie-parser middlewareno longer needs to be used for this module to work. This module now directly readsand writes cookies onreq/res. Usingcookie-parser may result in issuesif thesecret is not the same between this module andcookie-parser.

Warning The default server-side session storage,MemoryStore, ispurposelynot designed for a production environment. It will leak memory under mostconditions, does not scale past a single process, and is meant for debugging anddeveloping.

For a list of stores, seecompatible session stores.

Options

express-session accepts these properties in the options object.

cookie

Settings object for the session ID cookie. The default value is{ path: '/', httpOnly: true, secure: false, maxAge: null }.

The following are options that can be set in this object.

cookie.domain

Specifies the value for theDomainSet-Cookie attribute. By default, no domainis set, and most clients will consider the cookie to apply to only the currentdomain.

cookie.expires

Specifies theDate object to be the value for theExpiresSet-Cookie attribute.By default, no expiration is set, and most clients will consider this a"non-persistent cookie" and will delete it on a condition like exiting a web browserapplication.

Note If bothexpires andmaxAge are set in the options, then the last onedefined in the object is what is used.

Note Theexpires option should not be set directly; instead only use themaxAgeoption.

cookie.httpOnly

Specifies theboolean value for theHttpOnlySet-Cookie attribute. When truthy,theHttpOnly attribute is set, otherwise it is not. By default, theHttpOnlyattribute is set.

Note be careful when setting this totrue, as compliant clients will not allowclient-side JavaScript to see the cookie indocument.cookie.

cookie.maxAge

Specifies thenumber (in milliseconds) to use when calculating theExpiresSet-Cookie attribute. This is done by taking the current server time and addingmaxAge milliseconds to the value to calculate anExpires datetime. By default,no maximum age is set.

Note If bothexpires andmaxAge are set in the options, then the last onedefined in the object is what is used.

cookie.partitioned

Specifies theboolean value for thePartitionedSet-Cookieattribute. When truthy, thePartitioned attribute is set, otherwise it is not.By default, thePartitioned attribute is not set.

Note This is an attribute that has not yet been fully standardized, and maychange in the future. This also means many clients may ignore this attribute untilthey understand it.

More information about can be found inthe proposal.

cookie.path

Specifies the value for thePathSet-Cookie. By default, this is set to'/', whichis the root path of the domain.

cookie.priority

Specifies thestring to be the value for thePrioritySet-Cookie attribute.

  • 'low' will set thePriority attribute toLow.
  • 'medium' will set thePriority attribute toMedium, the default priority when not set.
  • 'high' will set thePriority attribute toHigh.

More information about the different priority levels can be found inthe specification.

Note This is an attribute that has not yet been fully standardized, and may change in the future.This also means many clients may ignore this attribute until they understand it.

cookie.sameSite

Specifies theboolean orstring to be the value for theSameSiteSet-Cookie attribute.By default, this isfalse.

  • true will set theSameSite attribute toStrict for strict same site enforcement.
  • false will not set theSameSite attribute.
  • 'lax' will set theSameSite attribute toLax for lax same site enforcement.
  • 'none' will set theSameSite attribute toNone for an explicit cross-site cookie.
  • 'strict' will set theSameSite attribute toStrict for strict same site enforcement.

More information about the different enforcement levels can be found inthe specification.

Note This is an attribute that has not yet been fully standardized, and may change inthe future. This also means many clients may ignore this attribute until they understand it.

Note There is adraft specthat requires that theSecure attribute be set totrue when theSameSite attribute has beenset to'none'. Some web browsers or other clients may be adopting this specification.

cookie.secure

Specifies theboolean value for theSecureSet-Cookie attribute. When truthy,theSecure attribute is set, otherwise it is not. By default, theSecureattribute is not set.

Note be careful when setting this totrue, as compliant clients will not sendthe cookie back to the server in the future if the browser does not have an HTTPSconnection.

Please note thatsecure: true is arecommended option. However, it requiresan https-enabled website, i.e., HTTPS is necessary for secure cookies. Ifsecureis set, and you access your site over HTTP, the cookie will not be set. If youhave your node.js behind a proxy and are usingsecure: true, you need to set"trust proxy" in express:

varapp=express()app.set('trust proxy',1)// trust first proxyapp.use(session({secret:'keyboard cat',resave:false,saveUninitialized:true,cookie:{secure:true}}))

For using secure cookies in production, but allowing for testing in development,the following is an example of enabling this setup based onNODE_ENV in express:

varapp=express()varsess={secret:'keyboard cat',cookie:{}}if(app.get('env')==='production'){app.set('trust proxy',1)// trust first proxysess.cookie.secure=true// serve secure cookies}app.use(session(sess))

Thecookie.secure option can also be set to the special value'auto' to havethis setting automatically match the determined security of the connection. Becareful when using this setting if the site is available both as HTTP and HTTPS,as once the cookie is set on HTTPS, it will no longer be visible over HTTP. Thisis useful when the Express"trust proxy" setting is properly setup to simplifydevelopment vs production configuration.

genid

Function to call to generate a new session ID. Provide a function that returnsa string that will be used as a session ID. The function is givenreq as thefirst argument if you want to use some value attached toreq when generatingthe ID.

The default value is a function which uses theuid-safe library to generate IDs.

NOTE be careful to generate unique IDs so your sessions do not conflict.

app.use(session({genid:function(req){returngenuuid()// use UUIDs for session IDs},secret:'keyboard cat'}))
name

The name of the session ID cookie to set in the response (and read from in therequest).

The default value is'connect.sid'.

Note if you have multiple apps running on the same hostname (this is justthe name, i.e.localhost or127.0.0.1; different schemes and ports do notname a different hostname), then you need to separate the session cookies fromeach other. The simplest method is to simply set differentnames per app.

proxy

Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto"header).

The default value isundefined.

  • true The "X-Forwarded-Proto" header will be used.
  • false All headers are ignored and the connection is considered secure onlyif there is a direct TLS/SSL connection.
  • undefined Uses the "trust proxy" setting from express
resave

Forces the session to be saved back to the session store, even if the sessionwas never modified during the request. Depending on your store this may benecessary, but it can also create race conditions where a client makes twoparallel requests to your server and changes made to the session in onerequest may get overwritten when the other request ends, even if it made nochanges (this behavior also depends on what store you're using).

The default value istrue, but using the default has been deprecated,as the default will change in the future. Please research into this settingand choose what is appropriate to your use-case. Typically, you'll wantfalse.

How do I know if this is necessary for my store? The best way to know is tocheck with your store if it implements thetouch method. If it does, thenyou can safely setresave: false. If it does not implement thetouchmethod and your store sets an expiration date on stored sessions, then youlikely needresave: true.

rolling

Force the session identifier cookie to be set on every response. The expirationis reset to the originalmaxAge, resetting the expirationcountdown.

The default value isfalse.

With this enabled, the session identifier cookie will expire inmaxAge since the last response was sent instead of inmaxAge since the session was last modified by the server.

This is typically used in conjuction with short, non-session-lengthmaxAge values to provide a quick timeout of the session datawith reduced potential of it occurring during on going server interactions.

Note When this option is set totrue but thesaveUninitialized option isset tofalse, the cookie will not be set on a response with an uninitializedsession. This option only modifies the behavior when an existing session wasloaded for the request.

saveUninitialized

Forces a session that is "uninitialized" to be saved to the store. A session isuninitialized when it is new but not modified. Choosingfalse is useful forimplementing login sessions, reducing server storage usage, or complying withlaws that require permission before setting a cookie. Choosingfalse will alsohelp with race conditions where a client makes multiple parallel requestswithout a session.

The default value istrue, but using the default has been deprecated, as thedefault will change in the future. Please research into this setting andchoose what is appropriate to your use-case.

Note if you are using Session in conjunction with PassportJS, Passportwill add an empty Passport object to the session for use after a user isauthenticated, which will be treated as a modification to the session, causingit to be saved.This has been fixed in PassportJS 0.3.0

secret

Required option

This is the secret used to sign the session ID cookie. The secret can be any typeof value that is supported by Node.jscrypto.createHmac (like a string or aBuffer). This can be either a single secret, or an array of multiple secrets. Ifan array of secrets is provided, only the first element will be used to sign thesession ID cookie, while all the elements will be considered when verifying thesignature in requests. The secret itself should be not easily parsed by a human andwould best be a random set of characters. A best practice may include:

  • The use of environment variables to store the secret, ensuring the secret itselfdoes not exist in your repository.
  • Periodic updates of the secret, while ensuring the previous secret is in thearray.

Using a secret that cannot be guessed will reduce the ability to hijack a session toonly guessing the session ID (as determined by thegenid option).

Changing the secret value will invalidate all existing sessions. In order to rotatethe secret without invalidating sessions, provide an array of secrets, with the newsecret as first element of the array, and including previous secrets as the laterelements.

Note HMAC-256 is used to sign the session ID. For this reason, the secret shouldcontain at least 32 bytes of entropy.

store

The session store instance, defaults to a newMemoryStore instance.

unset

Control the result of unsettingreq.session (throughdelete, setting tonull,etc.).

The default value is'keep'.

  • 'destroy' The session will be destroyed (deleted) when the response ends.
  • 'keep' The session in the store will be kept, but modifications made duringthe request are ignored and not saved.

req.session

To store or access session data, simply use the request propertyreq.session,which is (generally) serialized as JSON by the store, so nested objectsare typically fine. For example below is a user-specific view counter:

// Use the session middlewareapp.use(session({secret:'keyboard cat',cookie:{maxAge:60000}}))// Access the session as req.sessionapp.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=1res.end('welcome to the session demo. refresh!')}})

Session.regenerate(callback)

To regenerate the session simply invoke the method. Once complete,a new SID andSession instance will be initialized atreq.sessionand thecallback will be invoked.

req.session.regenerate(function(err){// will have a new session here})

Session.destroy(callback)

Destroys the session and will unset thereq.session property.Once complete, thecallback will be invoked.

req.session.destroy(function(err){// cannot access session here})

Session.reload(callback)

Reloads the session data from the store and re-populates thereq.session object. Once complete, thecallback will be invoked.

req.session.reload(function(err){// session updated})

Session.save(callback)

Save the session back to the store, replacing the contents on the store with thecontents in memory (though a store may do something else--consult the store'sdocumentation for exact behavior).

This method is automatically called at the end of the HTTP response if thesession data has been altered (though this behavior can be altered with variousoptions in the middleware constructor). Because of this, typically this methoddoes not need to be called.

There are some cases where it is useful to call this method, for example,redirects, long-lived requests or in WebSockets.

req.session.save(function(err){// session saved})

Session.touch()

Updates the.maxAge property. Typically this isnot necessary to call, as the session middleware does this for you.

req.session.id

Each session has a unique ID associated with it. This property is analias ofreq.sessionID and cannot be modified.It has been added to make the session ID accessible from thesessionobject.

req.session.cookie

Each session has a unique cookie object accompany it. This allowsyou to alter the session cookie per visitor. For example we cansetreq.session.cookie.expires tofalse to enable the cookieto remain for only the duration of the user-agent.

Cookie.maxAge

Alternativelyreq.session.cookie.maxAge will return the timeremaining in milliseconds, which we may also re-assign a new valueto adjust the.expires property appropriately. The followingare essentially equivalent

varhour=3600000req.session.cookie.expires=newDate(Date.now()+hour)req.session.cookie.maxAge=hour

For example whenmaxAge is set to60000 (one minute), and 30 secondshas elapsed it will return30000 until the current request has completed,at which timereq.session.touch() is called to resetreq.session.cookie.maxAge to its original value.

req.session.cookie.maxAge// => 30000

Cookie.originalMaxAge

Thereq.session.cookie.originalMaxAge property returns the originalmaxAge (time-to-live), in milliseconds, of the session cookie.

req.sessionID

To get the ID of the loaded session, access the request propertyreq.sessionID. This is simply a read-only value set when a sessionis loaded/created.

Session Store Implementation

Every session storemust be anEventEmitter and implement specificmethods. The following methods are the list ofrequired,recommended,andoptional.

  • Required methods are ones that this module will always call on the store.
  • Recommended methods are ones that this module will call on the store ifavailable.
  • Optional methods are ones this module does not call at all, but helpspresent uniform stores to users.

For an example implementation view theconnect-redis repo.

store.all(callback)

Optional

This optional method is used to get all sessions in the store as an array. Thecallback should be called ascallback(error, sessions).

store.destroy(sid, callback)

Required

This required method is used to destroy/delete a session from the store givena session ID (sid). Thecallback should be called ascallback(error) oncethe session is destroyed.

store.clear(callback)

Optional

This optional method is used to delete all sessions from the store. Thecallback should be called ascallback(error) once the store is cleared.

store.length(callback)

Optional

This optional method is used to get the count of all sessions in the store.Thecallback should be called ascallback(error, len).

store.get(sid, callback)

Required

This required method is used to get a session from the store given a sessionID (sid). Thecallback should be called ascallback(error, session).

Thesession argument should be a session if found, otherwisenull orundefined if the session was not found (and there was no error). A specialcase is made whenerror.code === 'ENOENT' to act likecallback(null, null).

store.set(sid, session, callback)

Required

This required method is used to upsert a session into the store given asession ID (sid) and session (session) object. The callback should becalled ascallback(error) once the session has been set in the store.

store.touch(sid, session, callback)

Recommended

This recommended method is used to "touch" a given session given asession ID (sid) and session (session) object. Thecallback should becalled ascallback(error) once the session has been touched.

This is primarily used when the store will automatically delete idle sessionsand this method is used to signal to the store the given session is active,potentially resetting the idle timer.

Compatible Session Stores

The following modules implement a session store that is compatible with thismodule. Please make a PR to add additional modules :)

★ aerospike-session-store A session store usingAerospike.

★ better-sqlite3-session-store A session store based onbetter-sqlite3.

★ cassandra-store An Apache Cassandra-based session store.

★ cluster-store A wrapper for using in-process / embeddedstores - such as SQLite (via knex), leveldb, files, or memory - with node cluster (desirable for Raspberry Pi 2and other multi-core embedded devices).

★ connect-arango An ArangoDB-based session store.

★ connect-azuretables AnAzure Table Storage-based session store.

★ connect-cloudant-store AnIBM Cloudant-based session store.

★ connect-cosmosdb An AzureCosmos DB-based session store.

★ connect-couchbase Acouchbase-based session store.

★ connect-datacache AnIBM Bluemix Data Cache-based session store.

★ @google-cloud/connect-datastore AGoogle Cloud Datastore-based session store.

★ connect-db2 An IBM DB2-based session store built usingibm_db module.

★ connect-dynamodb A DynamoDB-based session store.

★ @google-cloud/connect-firestore AGoogle Cloud Firestore-based session store.

★ connect-hazelcast Hazelcast session store for Connect and Express.

★ connect-loki A Loki.js-based session store.

★ connect-lowdb A lowdb-based session store.

★ connect-memcached A memcached-based session store.

★ connect-memjs A memcached-based session store usingmemjs as the memcached client.

★ connect-ml A MarkLogic Server-based session store.

★ connect-monetdb A MonetDB-based session store.

★ connect-mongo A MongoDB-based session store.

★ connect-mongodb-session Lightweight MongoDB-based session store built and maintained by MongoDB.

★ connect-mssql-v2 A Microsoft SQL Server-based session store based onconnect-mssql.

★ connect-neo4j ANeo4j-based session store.

★ connect-ottoman Acouchbase ottoman-based session store.

★ connect-pg-simple A PostgreSQL-based session store.

★ connect-redis A Redis-based session store.

★ connect-session-firebase A session store based on theFirebase Realtime Database

★ connect-session-knex A session store usingKnex.js, which is a SQL query builder for PostgreSQL, MySQL, MariaDB, SQLite3, and Oracle.

★ connect-session-sequelize A session store usingSequelize.js, which is a Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL.

★ connect-sqlite3 ASQLite3 session store modeled after the TJ'sconnect-redis store.

★ connect-typeorm ATypeORM-based session store.

★ couchdb-expression ACouchDB-based session store.

★ dynamodb-store A DynamoDB-based session store.

★ dynamodb-store-v3 Implementation of a session store using DynamoDB backed by theAWS SDK for JavaScript v3.

★ express-etcd Anetcd based session store.

★ express-mysql-session A session store using nativeMySQL via thenode-mysql module.

★ express-nedb-session A NeDB-based session store.

★ express-oracle-session A session store using nativeoracle via thenode-oracledb module.

★ express-session-cache-managerA store that implementscache-manager, which supportsavariety of storage types.

★ express-session-etcd3 Anetcd3 based session store.

★ express-session-level ALevelDB based session store.

★ express-session-rsdb Session store based on Rocket-Store: A very simple, super fast and yet powerfull, flat file database.

★ express-sessions A session store supporting both MongoDB and Redis.

★ firestore-store AFirestore-based session store.

★ fortune-session AFortune.jsbased session store. Supports all backends supported by Fortune (MongoDB, Redis, Postgres, NeDB).

★ hazelcast-store A Hazelcast-based session store built on theHazelcast Node Client.

★ level-session-store A LevelDB-based session store.

★ lowdb-session-store Alowdb-based session store.

★ medea-session-store A Medea-based session store.

★ memorystore A memory session store made for production.

★ mssql-session-store A SQL Server-based session store.

★ nedb-session-store An alternate NeDB-based (either in-memory or file-persisted) session store.

★ @quixo3/prisma-session-store A session store for thePrisma Framework.

★ restsession Store sessions utilizing a RESTful API

★ sequelstore-connect A session store usingSequelize.js.

★ session-file-store A file system-based session store.

★ session-pouchdb-store Session store for PouchDB / CouchDB. Accepts embedded, custom, or remote PouchDB instance and realtime synchronization.

★ @cyclic.sh/session-store A DynamoDB-based session store forCyclic.sh apps.

★ @databunker/session-store ADatabunker-based encrypted session store.

★ sessionstore A session store that works with various databases.

★ tch-nedb-session A file system session store based on NeDB.

Examples

View counter

A simple example usingexpress-session to store page views for a user.

varexpress=require('express')varparseurl=require('parseurl')varsession=require('express-session')varapp=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 pathnamevarpathname=parseurl(req).pathname// count the viewsreq.session.views[pathname]=(req.session.views[pathname]||0)+1next()})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')})app.listen(3000)

User login

A simple example usingexpress-session to keep a user log in session.

varescapeHtml=require('escape-html')varexpress=require('express')varsession=require('express-session')varapp=express()app.use(session({secret:'keyboard cat',resave:false,saveUninitialized:true}))// middleware to test if authenticatedfunctionisAuthenticated(req,res,next){if(req.session.user)next()elsenext('route')}app.get('/',isAuthenticated,function(req,res){// this is only called when there is an authentication user due to isAuthenticatedres.send('hello, '+escapeHtml(req.session.user)+'!'+' <a href="/logout">Logout</a>')})app.get('/',function(req,res){res.send('<form action="/login" method="post">'+'Username: <input name="user"><br>'+'Password: <input name="pass" type="password"><br>'+'<input type="submit" text="Login"></form>')})app.post('/login',express.urlencoded({extended:false}),function(req,res){// login logic to validate req.body.user and req.body.pass// would be implemented here. for this example any combo works// regenerate the session, which is good practice to help// guard against forms of session fixationreq.session.regenerate(function(err){if(err)next(err)// store user information in session, typically a user idreq.session.user=req.body.user// save the session before redirection to ensure page// load does not happen before session is savedreq.session.save(function(err){if(err)returnnext(err)res.redirect('/')})})})app.get('/logout',function(req,res,next){// logout logic// clear the user from the session object and save.// this will ensure that re-using the old session id// does not have a logged in userreq.session.user=nullreq.session.save(function(err){if(err)next(err)// regenerate the session, which is good practice to help// guard against forms of session fixationreq.session.regenerate(function(err){if(err)next(err)res.redirect('/')})})})app.listen(3000)

Debugging

This module uses thedebug moduleinternally to log information about session operations.

To see all the internal logs, set theDEBUG environment variable toexpress-session when launching your app (npm start, in this example):

$ DEBUG=express-session npm start

On Windows, use the corresponding command;

>set DEBUG=express-session& npm start

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp