Skip to content

Commit c381024

Browse files
ascorbicsarah11918
andauthored
chore: better session.load changeset (#13541)
* chore: better session.load changeset * Apply suggestions from code review Co-authored-by: Sarah Rainsberger <[email protected]> --------- Co-authored-by: Sarah Rainsberger <[email protected]>
1 parent 6254d35 commit c381024

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

.changeset/famous-areas-peel.md

+21-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,25 @@
22
'astro': patch
33
---
44

5-
Adds support for loading a session by ID
5+
Adds a new `session.load()` method to the experimental session API that allows you to load a session by ID.
66

7-
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.
7+
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.
8+
9+
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.
10+
11+
```ts
12+
// src/pages/api/cart.ts
13+
import type { APIRoute } from 'astro';
14+
15+
export const GET: APIRoute = async ({ session, request }) => {
16+
// Load the session from a header instead of cookies
17+
const sessionId = request.headers.get('x-session-id');
18+
await session.load(sessionId);
19+
const cart = await session.get('cart');
20+
return Response.json({ cart });
21+
};
22+
```
23+
24+
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.
25+
26+
For more information, see the [experimental sessions docs](https://docs.astro.build/en/reference/experimental-flags/sessions/).

0 commit comments

Comments
 (0)