📚 StoneJS Developer Guide

Complete reference for building modern web applications with the StoneJS Framework

🔐 Session Management

Session Configuration

StoneJS provides flexible session management supporting both in-memory (development) and database-backed (production) sessions.

Configuration Options

Environment Variable Description Example
SESSION_SECRET Secret key for signing session cookies (required) your-secret-key-here
SESSION_STORE Session storage type: omit for in-memory, set to database for persistent storage database
SESSION_DB_HOST Session database host (optional, defaults to main DB) localhost
SESSION_DB_PORT Session database port (optional) 5432
SESSION_DB_USER Session database username (optional) session_user
SESSION_DB_PASSWORD Session database password (optional) secure_password
SESSION_DB_NAME Session database name (optional) sessions

Example .env Configuration

# Basic configuration (in-memory sessions) SESSION_SECRET=your-secret-key-change-in-production # Production configuration (database sessions) SESSION_SECRET=your-secret-key-change-in-production SESSION_STORE=database

⚠️ Security: Always use a strong, random SESSION_SECRET in production. Generate one with: openssl rand -base64 32

Using Sessions

The $session object is available in all components, allowing you to store user-specific data across requests.

Session Operations

Operation Syntax Example
Read Access property directly const userId = $session.userId;
Write Assign to property $session.userId = 123;
Delete Use delete keyword delete $session.userId;
Session ID Read id property const id = $session.id;

Example: Shopping Cart

<%%js> // Read session data (with default value) const cart = $session.cart || []; // Add item to cart $session.cart = [...cart, { id: productId, name: 'Product Name', price: 29.99, quantity: 1 }]; // Get user info const isLoggedIn = $session.userId != null; const username = $session.username || 'Guest';

💡 Storage: Session data is automatically serialized/deserialized. You can store strings, numbers, objects, and arrays.

Authentication Example

A common pattern for user authentication using sessions:

<%%js> // Login page handler if ($req.method === 'POST') { const { username, password } = $req.body; // Query user from database const users = await $db.query( 'SELECT * FROM users WHERE username = $1', [username] ); if (users.length > 0 && verifyPassword(password, users[0].password_hash)) { // Authentication successful - store in session $session.userId = users[0].id; $session.username = users[0].username; $session.isAuthenticated = true; $session.loginTime = new Date().toISOString(); // Redirect to dashboard $res.redirect('/dashboard'); return; } else { // Authentication failed $context.set('error', 'Invalid username or password'); } }

Logout

Destroy the session to log users out:

<%%js> // Logout handler $req.session.destroy((err) => { if (err) { console.error('Session destroy error:', err); } $res.redirect('/'); });

✅ Security Tip: Always destroy sessions on logout rather than just clearing properties. This prevents session fixation attacks.

Session Availability

The $session object is automatically injected into all components by StoneJS middleware:

Component Type Access Method Example
Pages (.html) $session global $session.userId
Includes $session global $session.cart
Autohandlers $session global $session.isAuthenticated
Dhandlers context.session context.session.userId

Database Session Store

For production deployments, use database-backed sessions to persist across server restarts and support load balancing.

Setup Steps

1. Configure environment: Set SESSION_STORE=database in your .env file.

2. Run setup script: Creates the stonejs_sessions table with automatic cleanup.

# Run once to create session table node scripts/setup-session-store.js

✅ Automatic Cleanup: Expired sessions are automatically removed from the database, preventing table bloat.

Best Practices

  • Use database sessions for production (survives server restarts)
  • Store minimal data in sessions (IDs, not full objects)
  • Set strong SESSION_SECRET in production
  • Implement session timeout for sensitive applications
  • Clear sessions on logout

Caching → Session Demo

Need more help?

View All Demos Getting Started GitHub Repository