| 1 | |
| 2 | * react-router v8.3.0
|
| 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 | */
|
| 11 | import { createCookie, isCookie } from "../cookies.js";
|
| 12 | import { createSession, warnOnceAboutSigningSessionCookie } from "../sessions.js";
|
| 13 |
|
| 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 | */
|
| 31 | function 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 | return createSession(cookieHeader && await cookie.parse(cookieHeader, options) || {});
|
| 37 | },
|
| 38 | async commitSession(session, options) {
|
| 39 | let serializedCookie = await cookie.serialize(session.data, options);
|
| 40 | if (serializedCookie.length > 4096) throw new Error("Cookie length will exceed browser maximum. Length: " + serializedCookie.length);
|
| 41 | return serializedCookie;
|
| 42 | },
|
| 43 | async destroySession(_session, options) {
|
| 44 | return cookie.serialize("", {
|
| 45 | ...options,
|
| 46 | maxAge: void 0,
|
| 47 | expires: new Date(0)
|
| 48 | });
|
| 49 | }
|
| 50 | };
|
| 51 | }
|
| 52 |
|
| 53 | export { createCookieSessionStorage };
|