voxpelli / node-connect-pg-simple

A simple, minimal PostgreSQL session store for Express
https://www.npmjs.com/package/connect-pg-simple
MIT License
234 stars 74 forks source link
express express-session node-js postgres postgresql sessionstorage

Connect PG Simple

A simple, minimal PostgreSQL session store for Express/Connect

npm version npm downloads Module type: CJS js-semistandard-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.

Other options

Useful methods

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.