Session Management
Learn how BrewHoard manages user sessions, including creation, validation, and security features.
BrewHoard uses secure session-based authentication to manage user access across the application. Sessions are stored server-side and validated on each request.
Session Creation
When a user logs in successfully, a new session is created with a 7-day expiration:
import { createSession } from '$lib/auth/index.js';
// After successful login
const session = await createSession(userId);
// Set session cookie
cookies.set('session', session.id, {
path: '/',
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 7 // 7 days
});Cookie Settings
Session cookies are configured with security best practices:
httpOnly: Prevents JavaScript access to the cookiesecure: Only sent over HTTPS in productionsameSite: 'strict': Prevents CSRF attacksmaxAge: 7 days expiration
Session Validation in hooks.server.js
Session validation occurs in the server hooks for every request:
const handleAuth = async ({ event, resolve }) => {
const sessionId = event.cookies.get('session');
if (sessionId) {
try {
const user = await getSessionUser(sessionId);
event.locals.user = user;
} catch (error) {
event.cookies.delete('session', { path: '/' });
event.locals.user = null;
}
}
return resolve(event);
};The getSessionUser function validates the session against the database:
export async function getSessionUser(sessionId) {
const [session] = await sql`
SELECT s.id, s.expires_at, u.id as user_id, u.username, u.email, u.first_name, u.last_name, u.avatar_url
FROM sessions s
JOIN users u ON s.user_id = u.id
WHERE s.id = ${sessionId}
AND s.expires_at > NOW()
AND u.is_active = true
`;
return session ? {
id: session.user_id,
username: session.username,
email: session.email,
firstName: session.first_name,
lastName: session.last_name,
avatarUrl: session.avatar_url,
} : null;
}Session Refresh
Sessions are automatically refreshed on each valid request by updating the expiration time.
Multi-Device Sessions
Users can be logged in on multiple devices simultaneously. Each device maintains its own session cookie.
Session Listing
Users can view all their active sessions in the account settings.
Logout from All Devices
To logout from all devices, delete all sessions for the user:
await sql`DELETE FROM sessions WHERE user_id = ${userId}`;Next Steps
- API Keys - Learn about API key authentication
- Security Overview - General authentication security practices