📚 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
⚠️ 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
💡 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:
Logout
Destroy the session to log users out:
✅ 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.
✅ 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
Need more help?