UNPKG

1.99 kBJavaScriptView Raw
1/**
2 * react-router v8.5.3
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { createCookie, isCookie } from "../cookies.js";
12import { createSession, warnOnceAboutSigningSessionCookie } from "../sessions.js";
13//#region lib/server-runtime/sessions/cookieStorage.ts
14/**
15* Creates and returns a SessionStorage object that stores all session data
16* directly in the session cookie itself.
17*
18* This has the advantage that no database or other backend services are
19* needed, and can help to simplify some load-balanced scenarios. However, it
20* also has the limitation that serialized session data may not exceed the
21* browser's maximum cookie size. Trade-offs!
22*
23* @public
24* @category Utils
25* @mode framework
26* @mode data
27* @param options Options for creating the cookie-backed session storage.
28* @returns A {@link SessionStorage} object that stores all session data in its
29* cookie.
30*/
31function createCookieSessionStorage({ cookie: cookieArg } = {}) {
32 let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
33 warnOnceAboutSigningSessionCookie(cookie);
34 return {
35 async getSession(cookieHeader, options) {
36 let data = cookieHeader && await cookie.parse(cookieHeader, options);
37 return createSession(typeof data === "object" && data !== null && !Array.isArray(data) ? data : {});
38 },
39 async commitSession(session, options) {
40 let serializedCookie = await cookie.serialize(session.data, options);
41 if (serializedCookie.length > 4096) throw new Error("Cookie length will exceed browser maximum. Length: " + serializedCookie.length);
42 return serializedCookie;
43 },
44 async destroySession(_session, options) {
45 return cookie.serialize("", {
46 ...options,
47 maxAge: void 0,
48 expires: /* @__PURE__ */ new Date(0)
49 });
50 }
51 };
52}
53//#endregion
54export { createCookieSessionStorage };