diff --git a/.changeset/dull-papers-fry.md b/.changeset/dull-papers-fry.md new file mode 100644 index 0000000000..8fec7ddfd5 --- /dev/null +++ b/.changeset/dull-papers-fry.md @@ -0,0 +1,6 @@ +--- +'astro': patch +--- + +Reuses experimental session storage object between requests. This prevents memory leaks and improves performance for drivers that open persistent connections to a database. + diff --git a/packages/astro/src/core/session.ts b/packages/astro/src/core/session.ts index bd07c873a3..89bffd3486 100644 --- a/packages/astro/src/core/session.ts +++ b/packages/astro/src/core/session.ts @@ -76,6 +76,8 @@ export class AstroSession { // preserving in-memory changes and deletions. #partial = true; + static #sharedStorage = new Map(); + constructor( cookies: AstroCookies, { @@ -402,6 +404,14 @@ export class AstroSession { return this.#storage; } + // We reuse the storage object if it has already been created. + // We don't need to worry about the config changing because editing it + // will always restart the process. + if (AstroSession.#sharedStorage.has(this.#config.driver)) { + this.#storage = AstroSession.#sharedStorage.get(this.#config.driver); + return this.#storage!; + } + if (this.#config.driver === 'test') { this.#storage = (this.#config as SessionConfig<'test'>).options.mockStorage; return this.#storage!; @@ -468,6 +478,7 @@ export class AstroSession { this.#storage = createStorage({ driver: driver(this.#config.options), }); + AstroSession.#sharedStorage.set(this.#config.driver, this.#storage); return this.#storage; } catch (err) { throw new AstroError(