Session Management Demo
This interactive demo shows how StoneJS Framework handles session data. All data is stored server-side and persists across page reloads.
Current Session Information
| Session ID: |
Pfov8mUUq2V9rDAgh_LQqmDYfUZP9C5n |
| Page Views: |
1 |
| First Visit: |
2025-12-26T10:49:15.876Z |
| Last Page View: |
2025-12-26T10:49:15.876Z |
| User Name: |
Not set
|
Interactive Session Tests
1. Set Your Name
Store data in the session:
2. Shopping Cart
Build a simple shopping cart with session storage:
Your cart is empty. Add items above.
How Session Works
Session Flow:
- Client makes first request
- Server creates session and sends session cookie
- Client stores cookie and sends it with subsequent requests
- Server reads cookie, retrieves session data
- Components read/write to
$session object
- Session data is automatically saved after response
Working with Sessions in Code
Reading Session Data
<%
// Read session values
const userId = $session.userId;
const userName = $session.userName;
const cart = $session.cart || [];
// Check if data exists
if ($session.isLoggedIn) {
// User is logged in
}
%>
Writing Session Data
<%
// Set session values
$session.userId = 123;
$session.userName = 'John Doe';
$session.isLoggedIn = true;
// Store complex data
$session.preferences = {
theme: 'dark',
language: 'en'
};
// Arrays
$session.recentPages = ['/home', '/about', '/contact'];
%>
Deleting Session Data
<%
// Delete specific key
delete $session.tempData;
// Clear user data (logout)
delete $session.userId;
delete $session.userName;
delete $session.isLoggedIn;
%>
Session Configuration
In-Memory Sessions (Default)
By default, sessions are stored in memory. This is good for development but sessions will be lost when the server restarts:
const app = new StoneJS({
root: './pages',
session: {
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // true in production with HTTPS
httpOnly: true, // prevents XSS
maxAge: 86400000 // 24 hours in milliseconds
}
}
});
Database Sessions (Persistent) - NEW!
For production applications, use database-backed sessions that persist across server restarts and support horizontal scaling:
const app = new StoneJS({
root: './pages',
session: {
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
maxAge: 86400000
},
// Enable database storage
store: 'database',
database: {
host: process.env.SESSION_DB_HOST || process.env.DB_HOST,
port: parseInt(process.env.SESSION_DB_PORT || process.env.DB_PORT) || 5432,
user: process.env.SESSION_DB_USER || process.env.DB_USER,
password: process.env.SESSION_DB_PASSWORD || process.env.DB_PASSWORD,
database: process.env.SESSION_DB_NAME || process.env.DB_NAME,
tableName: 'session', // Table name
schemaName: 'public', // Schema name
createTableIfMissing: true, // Auto-create table
pruneSessionInterval: 60 // Clean expired sessions every 60s
}
}
});
Quick Setup with .env
Set these environment variables to enable database sessions:
# In .env file
SESSION_STORE=database
SESSION_DB_HOST=localhost
SESSION_DB_PORT=5432
SESSION_DB_USER=postgres
SESSION_DB_PASSWORD=yourpassword
SESSION_DB_NAME=stonejs_sessions
SESSION_TABLE=session
Then run the setup script to create the session table:
npm run setup-sessions
Benefits of Database Sessions
- ✅ Persistence: Sessions survive server restarts
- ✅ Horizontal Scaling: Multiple servers can share sessions
- ✅ Security: Sessions stored securely in database
- ✅ Auto-cleanup: Expired sessions automatically removed
- ✅ Production-ready: Battle-tested PostgreSQL storage
Common Session Use Cases
User Authentication
<%# Login page %>
<%
if ($req.method === 'POST') {
const { username, password } = $req.body;
if (validateCredentials(username, password)) {
$session.userId = user.id;
$session.userName = user.name;
$session.isLoggedIn = true;
$res.redirect('/dashboard');
}
}
%>
Protected Pages (in autohandler)
<%
// Require login for all pages in this directory
if (!$session.isLoggedIn) {
$res.redirect('/login');
return;
}
%>
<!-- Page content for logged-in users -->
<%- await next() %>
Flash Messages
<%# Set flash message %>
<%
$session.flashMessage = 'Item added successfully!';
$res.redirect('/cart');
%>
<%# Display and clear flash message %>
<%
if ($session.flashMessage) {
%>
<div class="alert"><%= $session.flashMessage %></div>
<%
delete $session.flashMessage;
}
%>
Shopping Cart
<%
// Add to cart
if (!$session.cart) {
$session.cart = [];
}
$session.cart.push({
productId: 123,
quantity: 1,
price: 29.99
});
// Get cart total
const total = $session.cart.reduce((sum, item) => {
return sum + (item.price * item.quantity);
}, 0);
%>
Session Security
Security Best Practices:
- Use a strong, random session secret
- Enable
httpOnly cookies to prevent XSS attacks
- Use
secure: true in production (requires HTTPS)
- Set appropriate
maxAge for session cookies
- Regenerate session ID after login
- Never store passwords in session
- Validate session data before use
Clear All Session Data
This will clear all session data and reset your visit counter.
Try It Yourself
- Reload this page several times and watch the page view counter increase
- Set your name and reload - it persists!
- Add items to the cart and navigate to other pages - the cart remains
- Clear the session and start fresh
- Open this page in a private/incognito window - new session!