Sessions
Edit this pageSessions allow web applications to maintain state between user requests. Since HTTP is stateless, each request is treated independently. Sessions address this by allowing the server to recognize multiple requests from the same user, which is helpful for tracking authentication and preferences.
How sessions work
A session typically involves:
- Session creation: When tracking is needed (e.g., upon login or first visit), the server creates a session. This involves generating a unique session ID and storing the session data, encrypted and signed, within a cookie.
- Session cookie transmission: The server sends a
Set-Cookie
HTTP header. This instructs the browser to store the session cookie. - Subsequent requests: The browser automatically includes the session cookie in the
Cookie
HTTP header for requests to the server. - Session retrieval and data access: For each request, the server checks for the session cookie, retrieves the session data if a cookie is present, then decrypts and verifies the signature of the session data for the application to access and use this data.
- Session expiration and destruction: Sessions typically expire after a period of time or upon user sign-out and the data is removed.
This is done by setting a
Max-Age
attribute on the cookie or by sending aSet-Cookie
HTTP header with an expired date.
Most of these steps are automatically managed by the session helpers.
Database sessions
For larger applications or when more robust session management is required, SolidStart also supports storing session data in a database. This approach is similar to the cookie-based approach, but with some key differences:
- The session data is stored in the database, associated with the session ID.
- Only the session ID is stored in the cookie, not the session data.
- The session data is retrieved from the database using the session ID, instead of being retrieved directly from the cookie.
- Upon expiration, in addition to the session cookie, the database record containing the session data is also removed.
SolidStart does not automatically handle interactions with a database; you need to implement this yourself.
Session helpers
Vinxi, the underlying server toolkit powering SolidStart, provides helpers to simplify working with sessions. It provides a few key session helpers:
useSession
: Initializes a session or retrieves the existing session and returns a session object.getSession
: Retrieves the current session or initializes a new session.updateSession
: Updates data within the current session.clearSession
: Clears the current session.
These helpers work only in server-side contexts, such as within server functions and API routes. This is because session management requires access to server-side resources as well as the ability to get and set HTTP headers.
For more information, see the Cookies documentation in the Vinxi docs.
Creating a session
The useSession
helper is the primary way to create and manage sessions.
It provides a comprehensive interface for all session operations.
import { useSession } from "vinxi/http";
type SessionData = { theme: "light" | "dark";};
export async function useThemeSession() { "use server"; const session = await useSession<SessionData>({ password: process.env.SESSION_SECRET as string, name: "theme", });
if (!session.data.theme) { await session.update({ theme: "light", }); }
return session;}
In this example, the useThemeSession
server function creates a session that stores a user's theme preference.
useSession
requires a strong password for encrypting and signing the session cookie.
This password must be at least 32 characters long and should be kept highly secure.
It is strongly recommended to store this password in a private environment variable, as shown in the example above, rather than hardcoding it in your source code.
A password can be generated using the following command:
openssl rand -base64 32
useSession
adds a Set-Cookie
HTTP header to the current server response.
By default, the cookie is named h3
, but can be customized with the name
option, as shown in the example above.
Getting the session data
The useSession
helper provides access to the session data from the current request with the data
property.
export async function getThemeSession() { "use server"; const session = await useThemeSession();
return session.data.theme;}
Updating the session data
The useSession
helper provides the update
method to update the session data from the current request.
export async function updateThemeSession(data: SessionData) { "use server"; const session = await useThemeSession(); await session.update(data);}
Clearing the session data
The useSession
helper provides the clear
method to clear the session data from the current request.
export async function clearThemeSession() { "use server"; const session = await useThemeSession(); await session.clear();}