Skip to content

chore: better session.load changeset #13541

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 3, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion .changeset/famous-areas-peel.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,21 @@

Adds support for loading a session by ID

Adds a new `session.load()` method to the experimental session API that allows you to load a session by ID. In normal use a session is loaded automatically from the session cookie. This method allows a session to be loaded manually instead. This is useful for cases where the session ID has been persisted somewhere other than the browser cookie. For example, a session ID might be stored in a user database. This would allow that user's session to be loaded when logging-in on another device or in a different browser. It would also allow a session to be loaded in an API when cookies can't be set, such as when loading across domains.
When using [the experimental sessions API](https://docs.astro.build/en/reference/experimental-flags/sessions/), you don't normally need to worry about managing the session ID and cookies: Astro automatically reads the user's cookies and loads the correct session when needed. However, sometimes you need more control over which session to load. The new `load()` method allows you to manually load a session by ID. This is useful if you are handling the session ID yourself, or if you want to keep track of a session without using cookies. For example, you might want to restore a session from a logged-in user on another device, or work with an API endpoint that doesn't use cookies.

```ts
// src/pages/api/cart.ts
import type { APIRoute } from 'astro';

export const GET: APIRoute = async ({ session, request }) => {
// Load the session from a header instead of cookies
const sessionId = request.headers.get('x-session-id');
await session.load(sessionId);
const cart = await session.get('cart');
return Response.json({ cart });
};
```

If a session with that ID doesn't exist, a new one will be created. This allows you to generate a session ID in the client if needed.

For more information, see the [experimental sessions docs](https://docs.astro.build/en/reference/experimental-flags/sessions/).