Skip to content

Commit 9c5cc18

Browse files
committed
switch directions
1 parent 86563d2 commit 9c5cc18

File tree

8 files changed

+69
-132
lines changed

8 files changed

+69
-132
lines changed

README.md

+45-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,19 @@ The seal stored on the client contains the session data, not your server, making
1010

1111
---
1212

13+
## 📚  Table of Contents
14+
15+
1. [Upgrading](#upgrading-from-v2-to-v3)
16+
1. [Installation](#installation)
17+
1. [Usage](#usage)
18+
1. [Initializing](#initializing)
19+
1. [Secret Rotation](#secret-rotation)
20+
1. [Setting the Session](#setting-the-session)
21+
1. [Accessing the Session](#accessing-the-session)
22+
1. [Destroying the Session](#destroying-the-session)
23+
1. [Refreshing the Session](#refresh-the-session-with-the-same-data-but-renew-the-expiration-date)
24+
1. [Sync sessions between browser and server](#sync-session-between-browser-and-server)
25+
1326
**By default the cookie has an ⏰ expiration time of 7 days**, set via [`expires`] which should be a `number` in `days`.
1427

1528
---
@@ -110,7 +123,9 @@ export const handle = sequence(sessionHandler, ({ resolve, event }) => {
110123
});
111124
```
112125

113-
### ♻️ Secret rotation is supported. It allows you to change the secret used to sign and encrypt sessions while still being able to decrypt sessions that were created with a previous secret.
126+
### Secret rotation
127+
128+
is supported. It allows you to change the secret used to sign and encrypt sessions while still being able to decrypt sessions that were created with a previous secret.
114129

115130
This is useful if you want to:
116131

@@ -223,7 +238,7 @@ export async function del({ locals }) {
223238
}
224239
```
225240

226-
### Refresh the session with the same data but renew the expiration date.
241+
### Refresh the session with the same data but renew the expiration date
227242

228243
> src/routes/refresh.ts
229244
@@ -250,6 +265,34 @@ handleSession({
250265
});
251266
```
252267

268+
### Sync session between browser and server
269+
270+
The `handleSession` function keeps track if the client needs to be synced with the server!
271+
If the header `x-svelte-kit-cookie-session-needs-sync` is set, you know that you have to sync the state.
272+
You can do so by fetching the magic `/__session.json` endpoints, provided by handleSession.
273+
274+
***The enhance function can be extended like so:***
275+
```ts
276+
/// lib/form.ts
277+
export function enhance(){
278+
...
279+
async function handle_submit(e) {
280+
...
281+
if (response.ok) {
282+
if (response.headers.has('x-svelte-kit-cookie-session-needs-sync')) {
283+
const sessionData = await fetch('/__session.json').then((r) => (r.ok ? r.json() : null));
284+
if (sessionData) {
285+
session.set(sessionData);
286+
}
287+
}
288+
...
289+
}
290+
...
291+
}
292+
}
293+
294+
```
295+
253296
### Express/Connect Integration
254297

255298
This library can integrate with express, polka or any other connect compatible middleware layer.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "svelte-kit-cookie-session",
3-
"version": "3.1.0",
3+
"version": "3.1.0-next.6",
44
"description": "⚒️ Encrypted 'stateless' cookie sessions for SvelteKit",
55
"repository": {
66
"type": "git",

src/lib/core.ts

+9
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export async function cookieSession<SessionType = Record<string, any>>(
1414
) {
1515
const config = normalizeConfig(userConfig);
1616

17+
let needsSync = false;
1718
let setCookieString: string | undefined;
1819
const cookieString =
1920
typeof headersOrCookieString === 'string'
@@ -33,6 +34,8 @@ export async function cookieSession<SessionType = Record<string, any>>(
3334
maxAge = new Date(sessionData.expires).getTime() / 1000 - new Date().getTime() / 1000;
3435
}
3536

37+
needsSync = true;
38+
3639
sessionData = {
3740
...sd,
3841
expires: maxAgeToDateOfExpiry(maxAge)
@@ -46,6 +49,8 @@ export async function cookieSession<SessionType = Record<string, any>>(
4649
return false;
4750
}
4851

52+
needsSync = true;
53+
4954
const newMaxAge = daysToMaxage(expiresInDays ? expiresInDays : config.expiresInDays);
5055

5156
sessionData = {
@@ -57,6 +62,7 @@ export async function cookieSession<SessionType = Record<string, any>>(
5762
}
5863

5964
async function destroySession() {
65+
needsSync = true;
6066
sessionData = {};
6167
setCookieString = await makeCookie({}, config, 0, true);
6268
}
@@ -96,6 +102,9 @@ export async function cookieSession<SessionType = Record<string, any>>(
96102

97103
return {
98104
session: {
105+
get needsSync() {
106+
return needsSync;
107+
},
99108
get 'set-cookie'(): string | undefined {
100109
return setCookieString;
101110
},

src/lib/handle.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@ export function handleSession(
88
): Handle {
99
return async function handle({ event, resolve }) {
1010
const { session, cookies } = (await cookieSession(event.request.headers, options)) as any as {
11-
session: { 'set-cookie': string; data: any };
11+
session: { 'set-cookie': string; data: any; needsSync: boolean };
1212
cookies: Record<string, string>;
1313
};
1414

1515
(event.locals as any).session = session;
1616
(event.locals as any).cookies = cookies;
17-
17+
1818
if (event.url.pathname === '/__session.json') {
1919
const getSession = options.getSession ?? (() => session.data);
2020
const sessionData = await getSession(event);
@@ -33,6 +33,10 @@ export function handleSession(
3333
const sessionCookie = session['set-cookie'];
3434
response.headers.append('set-cookie', sessionCookie);
3535

36+
if (session.needsSync) {
37+
response.headers.set('x-svelte-kit-cookie-session-needs-sync', '1');
38+
}
39+
3640
return response;
3741
};
3842
}

src/lib/vite/index.js

-18
This file was deleted.

src/lib/vite/stores.js

-105
This file was deleted.

src/routes/tests/sync-session/index.svelte

+7-2
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,16 @@
33
import { onMount } from 'svelte';
44
55
async function updateSession() {
6-
await fetch('/tests/sync-session', {
6+
const response = await fetch('/tests/sync-session', {
77
method: 'POST',
88
headers: { Accept: 'application/json' }
99
});
10-
await (session as any).sync();
10+
if (response.headers.has('x-svelte-kit-cookie-session-needs-sync')) {
11+
const sessionData = await fetch('/__session.json').then((r) => (r.ok ? r.json() : null));
12+
if (sessionData) {
13+
session.set(sessionData);
14+
}
15+
}
1116
}
1217
1318
onMount(async () => {

vite.config.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import { sveltekit } from '@sveltejs/kit/vite';
2-
import { cookieSession } from "./src/lib/vite/index.js";
32

43
/** @type {import('vite').UserConfig} */
54
const config = {
6-
plugins: [sveltekit(), cookieSession()]
5+
plugins: [sveltekit()]
76
};
87

98
export default config;

0 commit comments

Comments
 (0)