Files
Tomas Dvorak 898a3c303f update
2026-02-24 10:33:59 +01:00

17 lines
6.7 KiB
JSON

{
"id": "339e4671ffa5672f11d7e10c",
"source": "solid:signals",
"type": "github-document",
"title": "session",
"content": "---\ntitle: Sessions\nuse_cases: \u003e-\n user sessions, authentication state, preferences storage, stateful\n interactions, login persistence\ntags:\n - sessions\n - cookies\n - authentication\n - state\n - storage\n - persistence\nversion: '1.0'\ndescription: \u003e-\n Manage user sessions with encrypted cookies in SolidStart. Maintain\n authentication state and user preferences between requests.\n---\n\nSessions allow web applications to maintain state between user requests.\nSince HTTP is stateless, each request is treated independently.\nSessions address this by allowing the server to recognize multiple requests from the same user, which is helpful for tracking authentication and preferences.\n\n## How sessions work\n\nA session typically involves:\n\n1. **Session creation**: When tracking is needed (e.g., upon login or first visit), the server creates a session.\n This involves generating a unique **session ID** and storing the session data, _encrypted and signed_, within a cookie.\n2. **Session cookie transmission**: The server sends a `Set-Cookie` HTTP header.\n This instructs the browser to store the session cookie.\n3. **Subsequent requests**: The browser automatically includes the session cookie in the `Cookie` HTTP header for requests to the server.\n4. **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.\n5. **Session expiration and destruction**: Sessions typically expire after a period of time or upon user sign-out and the data is removed.\n This is done by setting a `Max-Age` attribute on the cookie or by sending a `Set-Cookie` HTTP header with an expired date.\n\nMost of these steps are automatically managed by the [session helpers](#session-helpers).\n\n### Database sessions\n\nFor larger applications or when more advanced session management is needed, session data can be stored in a database.\nThis approach is similar to the cookie-based approach, but with some key differences:\n\n- The session data is stored in the database, associated with the session ID.\n- Only the session ID is stored in the cookie, not the session data.\n- The session data is retrieved from the database using the session ID, instead of being retrieved directly from the cookie.\n- Upon expiration, in addition to the session cookie, the database record containing the session data is also removed.\n\nSolidStart does not automatically handle interactions with a database; you need to implement this yourself.\n\n## Session helpers\n\n[Vinxi](https://vinxi.vercel.app), the underlying server toolkit powering SolidStart, provides helpers to simplify working with sessions.\nIt provides a few key session helpers:\n\n- [`useSession`](https://vinxi.vercel.app/api/server/session.html#usesession): Initializes a session or retrieves the existing session and returns a session object.\n- [`getSession`](https://vinxi.vercel.app/api/server/session.html#getsession): Retrieves the current session or initializes a new session.\n- [`updateSession`](https://vinxi.vercel.app/api/server/session.html#updatesession): Updates data within the current session.\n- [`clearSession`](https://vinxi.vercel.app/api/server/session.html#clearsession): Clears the current session.\n\nThese helpers work _only_ in server-side contexts, such as within server functions and API routes.\nThis is because session management requires access to server-side resources as well as the ability to get and set HTTP headers.\n\nFor more information, see the [Cookies documentation in the Vinxi docs](https://vinxi.vercel.app/api/server/session.html).\n\n## Creating a session\n\nThe `useSession` helper is the primary way to create and manage sessions.\nIt provides a comprehensive interface for all session operations.\n\n```ts title=\"src/lib/session.ts\"\nimport { useSession } from \"vinxi/http\";\n\ntype SessionData = {\n\ttheme: \"light\" | \"dark\";\n};\n\nexport async function useThemeSession() {\n\t\"use server\";\n\tconst session = await useSession\u003cSessionData\u003e({\n\t\tpassword: process.env.SESSION_SECRET as string,\n\t\tname: \"theme\",\n\t});\n\n\tif (!session.data.theme) {\n\t\tawait session.update({\n\t\t\ttheme: \"light\",\n\t\t});\n\t}\n\n\treturn session;\n}\n```\n\nIn this example, the `useThemeSession` server function creates a session that stores a user's theme preference.\n\n`useSession` requires a strong password for encrypting and signing the session cookie.\nThis password must be at least 32 characters long and should be kept highly secure.\nIt is strongly recommended to store this password in a [private environment variable](/configuration/environment-variables#private-environment-variables), as shown in the example above, rather than hardcoding it in your source code.\n\nA password can be generated using the following command:\n\n```sh frame=\"none\"\nopenssl rand -base64 32\n```\n\n`useSession` adds a `Set-Cookie` HTTP header to the current server response.\nBy default, the cookie is named `h3`, but can be customized with the `name` option, as shown in the example above.\n\n## Getting the session data\n\nThe `useSession` helper provides access to the session data from the current request with the `data` property.\n\n```ts title=\"src/lib/session.ts\"\nexport async function getThemeSession() {\n\t\"use server\";\n\tconst session = await useThemeSession();\n\n\treturn session.data.theme;\n}\n```\n\n## Updating the session data\n\nThe `useSession` helper provides the `update` method to update the session data from the current request.\n\n```ts title=\"src/lib/session.ts\"\nexport async function updateThemeSession(data: SessionData) {\n\t\"use server\";\n\tconst session = await useThemeSession();\n\tawait session.update(data);\n}\n```\n\n## Clearing the session data\n\nThe `useSession` helper provides the `clear` method to clear the session data from the current request.\n\n```ts title=\"src/lib/session.ts\"\nexport async function clearThemeSession() {\n\t\"use server\";\n\tconst session = await useThemeSession();\n\tawait session.clear();\n}\n```",
"url": "https://github.com/solidjs/solid-docs/blob/HEAD/src/routes/solid-start/advanced/session.mdx",
"metadata": {
"path": "src/routes/solid-start/advanced/session.mdx",
"repo": "solidjs/solid-docs",
"repo_url": "https://github.com/solidjs/solid-docs.git",
"size": 6023,
"source_type": "github"
},
"hash": "ed6e600c4ee3c93cc4d4e07fc8673de3f02d180fc6b1fb236016f3699e437c22",
"timestamp": "2026-02-23T11:43:00.193685079+01:00"
}