### Install connect-pg-simple and Setup Database Table Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Installs the connect-pg-simple package using npm and sets up the necessary 'session' table in a PostgreSQL database using the provided SQL script. This is a prerequisite for using the session store. ```bash npm install connect-pg-simple psql mydatabase < node_modules/connect-pg-simple/table.sql ``` -------------------------------- ### Install connect-pg-simple using npm Source: https://github.com/voxpelli/node-connect-pg-simple/blob/main/README.md This command installs the connect-pg-simple package using npm. It is the first step to integrate the session store into your Express or Connect application. ```bash npm install connect-pg-simple ``` -------------------------------- ### Full Configuration Options for connect-pg-simple Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Provides a comprehensive example of configuring the `connect-pg-simple` session store with all available options, including connection methods, table configuration, session TTL, pruning settings, error logging, and session cookie parameters. ```javascript const express = require('express'); const session = require('express-session'); const { Pool } = require('pg'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); const pgPool = new Pool({ connectionString: process.env.DATABASE_URL }); const store = new PGStore({ // Connection options (use ONE of these): pool: pgPool, // Recommended: existing pg.Pool instance // pgPromise: db, // pg-promise database instance // conString: 'postgres://...', // Connection string // conObject: { host, port, ... }, // Connection config object // Table configuration: schemaName: undefined, // PostgreSQL schema (default: none/public) tableName: 'session', // Table name (default: 'session') createTableIfMissing: false, // Auto-create table (default: false) // Session TTL: ttl: undefined, // TTL in seconds (default: cookie maxAge or 1 day) disableTouch: false, // Don't update expiry on touch (default: false) // Pruning configuration: pruneSessionInterval: 900, // Prune interval in seconds (default: 900 = 15 min) // Set to false to disable automatic pruning pruneSessionRandomizedInterval: undefined, // Custom randomization function or false // Error handling: errorLog: console.error, // Error logging function }); app.use(session({ store, secret: process.env.SESSION_SECRET, name: 'sessionId', // Cookie name resave: false, // Don't save unchanged sessions saveUninitialized: false, // Don't create empty sessions rolling: true, // Reset expiry on every response cookie: { maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days secure: process.env.NODE_ENV === 'production', httpOnly: true, sameSite: 'lax' } })); app.listen(3000); ``` -------------------------------- ### Advanced Express session setup with connect-pg-simple and pg.Pool (JavaScript) Source: https://github.com/voxpelli/node-connect-pg-simple/blob/main/README.md This advanced JavaScript example shows how to configure Express sessions with connect-pg-simple using a pre-configured pg.Pool. It allows for custom table names and connection pooling. ```javascript 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 })); ``` -------------------------------- ### Basic Express session setup with connect-pg-simple (JavaScript) Source: https://github.com/voxpelli/node-connect-pg-simple/blob/main/README.md This JavaScript code demonstrates a basic setup for Express sessions using connect-pg-simple. It requires the 'express-session' module and configures the session store with default options. ```javascript 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 })); ``` -------------------------------- ### Express Integration with pg-promise Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Integrates connect-pg-simple with applications already using the pg-promise library. This example shows how to initialize pg-promise and pass its database instance to the session store, configuring session pruning. ```javascript const express = require('express'); const session = require('express-session'); const pgp = require('pg-promise')(); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); // Initialize pg-promise connection const db = pgp({ host: 'localhost', port: 5432, database: 'myapp', user: 'dbuser', password: 'secretpassword' }); app.use(session({ store: new PGStore({ pgPromise: db, // Pass pg-promise database instance tableName: 'session', pruneSessionInterval: 60 * 15, // Prune every 15 minutes (in seconds) }), secret: 'your-secret-key', resave: false, saveUninitialized: true, cookie: { maxAge: 24 * 60 * 60 * 1000 } // 1 day })); app.get('/login', (req, res) => { req.session.user = { id: 123, username: 'john' }; res.send('Logged in'); }); app.get('/profile', (req, res) => { if (req.session.user) { res.json(req.session.user); } else { res.status(401).send('Not authenticated'); } }); app.listen(3000); ``` -------------------------------- ### Express Integration with PostgreSQL Connection Pool Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Configures connect-pg-simple to use an existing PostgreSQL connection pool for efficient connection management. This example shows how to create a pool and pass it to the session store, along with custom table names and auto-creation of the table. ```javascript const express = require('express'); const session = require('express-session'); const { Pool } = require('pg'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); // Create a connection pool const pgPool = new Pool({ user: 'dbuser', host: 'localhost', database: 'myapp', password: 'secretpassword', port: 5432, max: 20, // Maximum number of clients in the pool idleTimeoutMillis: 30000, connectionTimeoutMillis: 2000, }); // Handle pool errors pgPool.on('error', (err) => { console.error('Unexpected error on idle client', err); }); app.use(session({ store: new PGStore({ pool: pgPool, tableName: 'user_sessions', // Custom table name createTableIfMissing: true, // Auto-create table if it doesn't exist }), secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days secure: process.env.NODE_ENV === 'production', httpOnly: true } })); app.listen(3000); ``` -------------------------------- ### Configure Custom Schema and Table for Sessions (JavaScript) Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Allows for the specification of custom schema and table names for storing session data in PostgreSQL. This is useful for multi-tenant applications or organizing session data within specific database structures. The example demonstrates using a pre-configured `pg.Pool` and setting `createTableIfMissing` to true. ```javascript const express = require('express'); const session = require('express-session'); const { Pool } = require('pg'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); const pgPool = new Pool({ connectionString: process.env.DATABASE_URL }); app.use(session({ store: new PGStore({ pool: pgPool, schemaName: 'app_schema', // Custom schema name tableName: 'user_sessions', // Custom table name createTableIfMissing: true, // Creates "app_schema"."user_sessions" if missing }), secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 } })); // The store will use: "app_schema"."user_sessions" table app.listen(3000); ``` -------------------------------- ### Graceful Shutdown with connect-pg-simple Session Store Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Illustrates how to implement a graceful shutdown mechanism for a Node.js application using Express.js. It ensures that the HTTP server is closed and the `connect-pg-simple` session store is properly closed before the process exits. ```javascript const express = require('express'); const session = require('express-session'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); const store = new PGStore({ conString: process.env.DATABASE_URL }); app.use(session({ store, secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { maxAge: 24 * 60 * 60 * 1000 } })); const server = app.listen(3000, () => { console.log('Server running on port 3000'); }); // Graceful shutdown handler const gracefulShutdown = async (signal) => { console.log(`${signal} received. Starting graceful shutdown...`); server.close(async () => { console.log('HTTP server closed'); try { // Close the session store (stops pruning timer, closes pool if owned) await store.close(); console.log('Session store closed'); process.exit(0); } catch (err) { console.error('Error closing session store:', err); process.exit(1); } }); }; process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); process.on('SIGINT', () => gracefulShutdown('SIGINT')); ``` -------------------------------- ### Configure Session Connection with Object (JavaScript) Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Sets up session management by configuring the PostgreSQL connection details through a detailed connection object. This method allows for explicit configuration of user, password, host, port, database, and SSL settings. The session is configured with a 24-hour cookie lifespan and set to save uninitialized sessions. ```javascript const express = require('express'); const session = require('express-session'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); app.use(session({ store: new PGStore({ conObject: { user: 'dbuser', password: 'secretpassword', host: 'localhost', port: 5432, database: 'myapp', ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false } }), secret: 'your-secret-key', resave: false, saveUninitialized: true, cookie: { maxAge: 24 * 60 * 60 * 1000 } })); app.listen(3000); ``` -------------------------------- ### Create PostgreSQL session table using psql Source: https://github.com/voxpelli/node-connect-pg-simple/blob/main/README.md This command uses psql to create the 'session' table in your PostgreSQL database from the provided SQL file. This table is necessary for storing session data. ```bash psql mydatabase < node_modules/connect-pg-simple/table.sql ``` -------------------------------- ### Connect using PostgreSQL Connection String (JavaScript) Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Establishes a PostgreSQL connection using a connection string, suitable for cloud databases. It utilizes environment variables for sensitive information like the database URL and session secret. The session cookie is configured for a 30-day lifespan and secured for production environments. ```javascript const express = require('express'); const session = require('express-session'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); app.use(session({ store: new PGStore({ // Connection string format: postgres://user:password@host:port/database conString: process.env.DATABASE_URL || 'postgres://user:pass@localhost:5432/mydb', // For Heroku and similar platforms with SSL // SSL is automatically handled by the pg module }), secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { maxAge: 30 * 24 * 60 * 60 * 1000, secure: process.env.NODE_ENV === 'production' } })); app.listen(process.env.PORT || 3000); ``` -------------------------------- ### Manually Prune Sessions with connect-pg-simple Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Demonstrates how to disable automatic session pruning by setting `pruneSessionInterval` to `false` and then manually trigger session pruning via an Express.js POST route or schedule it using `node-cron`. ```javascript const express = require('express'); const session = require('express-session'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); const store = new PGStore({ conString: process.env.DATABASE_URL, pruneSessionInterval: false, // Disable automatic pruning }); app.use(session({ store, secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { maxAge: 24 * 60 * 60 * 1000 } })); // Manual pruning via API endpoint (protected route) app.post('/admin/prune-sessions', (req, res) => { store.pruneSessions((err) => { if (err) { console.error('Failed to prune sessions:', err); return res.status(500).json({ error: 'Pruning failed' }); } res.json({ message: 'Sessions pruned successfully' }); }); }); // Or schedule pruning with node-cron const cron = require('node-cron'); cron.schedule('0 */6 * * *', () => { // Every 6 hours store.pruneSessions((err) => { if (err) console.error('Scheduled prune failed:', err); else console.log('Scheduled session prune completed'); }); }); app.listen(3000); ``` -------------------------------- ### Configure Session TTL and Touch Behavior (JavaScript) Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Enables fine-grained control over session expiration by configuring the Time-To-Live (TTL) and the 'touch' behavior. The `ttl` option overrides the cookie's `maxAge` for server-side expiration, while `disableTouch` determines if accessing a session resets its expiration. The `rolling` option ensures cookie expiration is reset on each response. ```javascript const express = require('express'); const session = require('express-session'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); app.use(session({ store: new PGStore({ conString: process.env.DATABASE_URL, ttl: 60 * 60 * 24, // 24 hours in seconds (overrides cookie maxAge) disableTouch: false, // Set to true to prevent TTL updates on session access }), secret: 'your-secret-key', resave: false, rolling: true, // Reset cookie expiration on every response saveUninitialized: false, cookie: { maxAge: 24 * 60 * 60 * 1000 // 24 hours in milliseconds } })); // With rolling: true and disableTouch: false (default): // - Every request extends the session expiration // - Active users stay logged in indefinitely // // With disableTouch: true: // - Session expires at original TTL regardless of activity // - Good for strict session timeout requirements app.listen(3000); ``` -------------------------------- ### Configure Automatic Session Pruning (JavaScript) Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Sets up automatic cleanup of expired sessions from the PostgreSQL database. The `pruneSessionInterval` defines how often pruning occurs, with options for randomized intervals to prevent simultaneous pruning by multiple instances. Custom error logging can also be configured. ```javascript const express = require('express'); const session = require('express-session'); const connectPgSimple = require('connect-pg-simple'); const app = express(); const PGStore = connectPgSimple(session); const store = new PGStore({ conString: process.env.DATABASE_URL, // Pruning interval in seconds (default: 900 = 15 minutes) pruneSessionInterval: 60 * 30, // Prune every 30 minutes // By default, intervals are randomized 50-150% to prevent // multiple instances from pruning simultaneously. // Set to false to use exact intervals: pruneSessionRandomizedInterval: false, // Or provide a custom randomization function: // pruneSessionRandomizedInterval: (delay) => delay + Math.random() * 60000, // Custom error logging errorLog: (message, error) => { console.error(`[Session Store] ${message}`, error); } }); app.use(session({ store, secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { maxAge: 24 * 60 * 60 * 1000 } })); app.listen(3000); ``` -------------------------------- ### SQL Schema for Session Table Source: https://context7.com/voxpelli/node-connect-pg-simple/llms.txt Defines the required SQL schema for the 'session' table in PostgreSQL. This table stores session IDs, session data (as JSON), and expiration timestamps, essential for the connect-pg-simple store. ```sql CREATE TABLE "session" ( "sid" varchar NOT NULL COLLATE "default", "sess" json NOT NULL, "expire" timestamp(6) NOT NULL ) WITH (OIDS=FALSE); ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE; CREATE INDEX "IDX_session_expire" ON "session" ("expire"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.