包详细信息

connect-pg-simple

voxpelli1.3mMIT10.0.0

A simple, minimal PostgreSQL session store for Connect/Express

自述文件

Connect PG Simple

A simple, minimal PostgreSQL session store for Express/Connect

npm version npm downloads Module type: CJS neostandard javascript style Follow @voxpelli@mastodon.social

Installation

npm install connect-pg-simple

Once npm installed the module, you need to create the "session" table in your database.

For that you can use the table.sql file provided with the module:

psql mydatabase < node_modules/connect-pg-simple/table.sql

Or simply play the file via a GUI, like the pgAdminIII queries tool.

Or instruct this module to create it itself, by setting the createTableIfMissing option.

Note that connect-pg-simple requires PostgreSQL version 9.5 or above.

Usage

Examples are based on Express 4.

Simple example:

const session = require('express-session');

app.use(session({
  store: new (require('connect-pg-simple')(session))({
    // Insert connect-pg-simple options here
  }),
  secret: process.env.FOO_COOKIE_SECRET,
  resave: false,
  cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
  // Insert express-session options here
}));

Advanced example showing some custom options:

const pg = require('pg');
const expressSession = require('express-session');
const pgSession = require('connect-pg-simple')(expressSession);

const pgPool = new pg.Pool({
    // Insert pool options here
});

app.use(expressSession({
  store: new pgSession({
    pool : pgPool,                // Connection pool
    tableName : 'user_sessions'   // Use another table-name than the default "session" one
    // Insert connect-pg-simple options here
  }),
  secret: process.env.FOO_COOKIE_SECRET,
  resave: false,
  cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
  // Insert express-session options here
}));

Advanced options

Connection options

Listed in the order they will be picked up. If multiple are defined, then the first in the lists that is defined will be used, the rest ignored.

  • pool - The recommended one – Connection pool object (compatible with pg.Pool) for the underlying database module.
  • pgPromise - Database object from pg-promise to be used for DB communications.
  • conObject - If you don't specify a pool object, use this option or conString to specify a PostgreSQL Pool connection object and this module will create a new pool for you.
  • conString - If you don't specify a pool object, use this option or conObject to specify a PostgreSQL connection string like postgres://user:password@host:5432/database and this module will create a new pool for you. If there's a connection string in the DATABASE_URL environment variable (as it is by default on eg. Heroku) then this module will fallback to that if no other connection method has been specified.

Other options

  • ttl - the time to live for the session in the database – specified in seconds. Defaults to the cookie maxAge if the cookie has a maxAge defined and otherwise defaults to one day.
  • createTableIfMissing - if set to true then creates the table in the case where the table does not already exist. Defaults to false.
  • disableTouch – boolean value that if set to true disables the updating of TTL in the database when using touch. Defaults to false.
  • schemaName - if your session table is in another Postgres schema than the default (it normally isn't), then you can specify that here.
  • tableName - if your session table is named something else than session, then you can specify that here.
  • pruneSessionInterval - sets the delay in seconds at which expired sessions are pruned from the database. Default is 900 seconds (15 minutes). If set to false no automatic pruning will happen. By default every delay is randomized between 50% and 150% of set value, resulting in an average delay equal to the set value, but spread out to even the load on the database. Automatic pruning will happen pruneSessionInterval seconds after the last pruning (includes manual prunes).
  • pruneSessionRandomizedInterval – if set to false, then the exact value of pruneSessionInterval will be used in all delays. No randomization will happen. If multiple instances all start at once, disabling randomization can mean that multiple instances are all triggering pruning at once, causing unnecessary load on the database. Can also be set to a method, taking a numeric delay parameter and returning a modified one, thus allowing a custom delay algorithm if wanted.
  • errorLog – the method used to log errors in those cases where an error can't be returned to a callback. Defaults to console.error(), but can be useful to override if one eg. uses Bunyan for logging.

Useful methods

  • close() – if this module used its own database module to connect to Postgres, then this will shut that connection down to allow a graceful shutdown. Returns a Promise that will resolve when the database has shut down.
  • pruneSessions([callback(err)]) – will prune old sessions. Only really needed to be called if pruneSessionInterval has been set to false – which can be useful if one wants improved control of the pruning.

For enterprise

Available as part of the Tidelift Subscription.

The maintainers of connect-pg-simple and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. Learn more.

更新日志

Changelog

10.0.0 (2024-09-13)

⚠ BREAKING CHANGES

  • require node.js >=18

🩹 Fixes

  • add name to main function (c98e2ec)
  • deps: use latest version of pg (81b5630)
  • require node.js >=18 (d51b6ca)

🧹 Chores

  • deps: update knip (f78ef50)
  • deps: update validate-conventional-commit (84f525a)
  • deps: update dependency dotenv to ^16.4.5 (#308) (f97bd51)
  • deps: update dependency express to ^4.21.0 (#310) (01c9a55)
  • deps: update dependency express-session to ^1.18.0 (#309) (eef0e31)
  • deps: update dependency pg-promise to ^11.9.1 (#312) (a553301)
  • deps: update dev dependencies (d4488dc)
  • deps: update dev dependencies (21e41c4)
  • deps: update linting dependencies (817f082)
  • deps: update linting dependencies (a4e9e46)
  • deps: update type dependencies (97e581f)
  • deps: update typescript setup (7c86411)
  • deps: use neostandard linting (354f6b3)
  • fix @types/superagent type regression (649888c)

9.0.1 (2023-11-01)

Bug Fixes

  • 18: Move @types/pg to dev dependencies (ea4a9c1)

9.0.0 (2023-06-07)

  • Breaking change: Require Node version >=16.0.0
  • Notable: Start automatic pruning lazily. Wait for first use of the session manager before scheduling the pruning. #285
  • Change: Log whole error object instead of only message. Thanks @safareli! #225
  • ...and internal updates to dev dependencies etc

8.0.0 (2022-11-12)

  • Breaking change: Require Node version ^14.18.0 || >=16.0.0
  • Notable: Mark most private methods and properties as actually private using the Private class feature (having the name begin with a #) This can be breaking if you relied on those properties or methods
  • Internal: Update included version of pg
  • Internal: Use node: to import built in modules
  • ...and a lot of updates to dev dependencies, GitHub Action workflows etc

7.0.0 (2021-09-06)

  • Breaking change: Now requires at least Node.js 12.x
  • Internal: Updated some developer dependencies and test targets
  • As well as all changes in 7.0.0-0

7.0.0-0 (2021-01-18)

  • Possibly breaking change: Align session expiration logic with connect-redis which in turned aligned with connect-mongo. Fixes #54.
  • Minor breaking change: The .close() method is now async and returns a Promise that will be resolved when this session store is fully shut down. Fixes #183.
  • Minor breaking change: Now requires Node version ^10.17.0 || >=11.14.0
  • Feature: New option: disableTouch. Disables updating of TTL in database on touch. Fixes #55.
  • Feature: New option: createTableIfMissing. When set, the session table will be automatically created if missing. Fixes #158 and #173. Thanks @aadeshmisra!
  • Tweak: Slightly tweaked the pg-promise integration. Fixes #153.
  • Tweak: Introduced a new internal _asyncQuery() function in a move to modernize internal code on top of Promise / async / await.

6.2.1 (2020-08-19)

  • Fix: Regression, query errors wasn't properly forwarded. Fixes #180 and #179. Thanks @alxndrsn! (5c324ac)
  • Test: Added test for above regression (fd36978)
  • Change: Improved types + error return values (f73ea0d 68a2242)
  • Change: Updated SECURITY.md to delegate security reports to Tidelift, and thus ensure quicker responses (7683d40 59c7fbc)

6.2.0 (2020-08-06)

  • Important fix: Bump pg to 8.2.1 to support node 14+
  • Change: Change default prine interval to 15 mins
  • Test: Add Node 14 to GitHub CI
  • Test: Added more types and type linting

6.1.0 (2019-12-29)

  • Feature: Prune intervals are now by default randomized between 50% and 150% of the set prune value, making the average prune interval be the same as before, but makes database load more even by making it unlikely for eg. many instances to all prune at once.
  • Feature: New option pruneSessionRandomizedInterval enables deactivation + customization of the new random prune interval feature.
  • Change: Default prune interval is now 5 minutes, rather than 1 minute. No need to clean extremely often. Will probably make even longer eventually, but a more drastic change could be kind of a breaking change. Please comment in #162 with feedback on future default.
  • Performance: The database schema definition now specifies an index on the expire column. You have to add this yourself if you have already set up this module. The change is purely for enhancing performance and can be skipped if no performance issues have been experiences. It is recommended to apply it though.

6.0.1 (2019-08-21)

  • Very minor security fix: schemaName and tableName wasn't escaped. If any of the two contained a string with a double quote in it, then that would enable an SQL injection. This was previously a feature of tableName, before the introduction of a separate schemaName, as that allowed a schema to be defined as part of tableName. Defining schema name through tableName is still supported after this fix, but is now deprecated.
  • Fix: Errors wasn't propagated properly. Fixed in #150. Thanks @bobnil!

6.0.0 (2019-07-28)

  • Breaking change: Now requires at least Node.js 10.x, this as Node.js 8.x only have a short time left in its LTS
  • Breaking change: This project now uses INSERT ... ON CONFLICT, more popularly known as UPSERT. This is only supported on PostgreSQL version 9.5 and above.
  • Listen on pool errors. Fixes #29

5.0.0 (2018-06-06)

  • Breaking change: Now requires at least Node.js 8.x (this as Node.js 6.x only have a short time left in its LTS and I rather don't bump the major version more often than I have to)
  • Breaking change: Now expects pg 7.x to be used
  • Fix: Connection string is now handled by pg instead of by this module. Should improve support for things like ssl.

4.2.1 (2017-08-20)

  • Fix: The pruning timer will no longer keep Node alive, it's been given the unref() treatment

4.2.0 (2017-05-20)

  • Feature: New option pgPromise enables the library to re-use an existing connection from pg-promise. This is a mutually-exclusive alternative to specifying pool, conObject, or conString (only one of these can be provided).

4.1.0 (2017-05-19)

  • Feature: New option conObject enables connection details to be set through an object
  • Improvement: Hardening of conString parsing + some added tests of it

4.0.0 (2017-05-19)

  • Breaking change + improved support: When the pg module is provided to this module, then a pool from the new 6.x version of that module is now required rather than providing the module itself

3.1.2

  • Bug fix: Previous timestamp fix failed critically, fixing it again. Thanks @G3z and @eemeli

3.1.1

  • Bug fix: The internal query helper was treating params() wrong when called with two argument. Thanks for reporting @colideum!
  • Bug fix: If the database and the node instances had different clocks, then things wouldn't work that well due to mixed timestamp sources. Now node handles all timestamps. Thanks for reporting @sverkoye!

3.1.0

  • Feature: Support the store.touch() method to allow for extending the life time of a session without changing the data of it. This enables setting the resave option to false, which is recommended to avoid a session extender save overwriting another save that adds new data to the session. More info in the express-session readme.
  • Fix: Relax the engine requirements – accept newer versions of Node.js/iojs as well

3.0.2

  • Fix: Added support for sails by supporting sending the full Express 3 object into the plugin

3.0.1

  • Fix: If the pg instance used is created by this module, then this module should also close it on close()

3.0.0

  • Improvement: Rather than randomly cleaning up expired sessions that will now happen at the options.pruneSessionInterval defined interval.
  • Breaking change: Clients now need to close the session store to gracefully shut down their app as the pruning of sessions can't know when the rest of the app has stopped running and thus can't know when to stop pruning sessions if it itsn't told so explicitly through thew new close() method – or by deactivating the automatic pruning by settinging options.pruneSessionInterval to false. If automatic pruning is disabled the client needs to call pruneSessions() manually or otherwise ensure that old sessions are pruned.

2.3.0

  • Fix regression: No longer default to public schema, as added in 2.2.0, but rather default to the pre-2.2.0 behavior of no defined schema. This to ensure backwards compatibility with the 2.x branch, per semantic versioning best practise.

2.2.1

  • Hotfix: Update require('pg') to match package.json, thanks for reporting @dmitriiabramov

2.2.0

  • New: Now possibly to set another schema than the default
  • Change: Now using the pg dependency again rather than pg.js as the latter will be discontinued as pg now fills its role

2.1.1

  • Fix bug with creating new sessions that was caused by 2.1.0

2.1.0

  • Enable the table name to be configured through new tableName option

2.0.0

  • Backwards incompatible change: Support for Express 4 means that Express 3 apps (and similar for Connect apps) should send express.session to the module rather than just express.
  • Dependency change: The database module is now pg.js rather than pg – same library, but without compilation of any native bindings and thus less delay when eg. installing the application from scratch.

1.0.2

  • Support for PostgreSQL versions older than 9.2

1.0.1

  • Fix for sometimes not expiring sessions correctly

1.0.0