Skip to content

getSession() always persists a new empty session cookie with no opt-out #1523

Description

@MILLERMARRU

Describe the bug

getSession() always creates and persists a brand new session (writes a Set-Cookie) whenever no existing session is found, with no way to opt out of just that side effect.

In src/utils/session.ts:

// New session store in response cookies
if (!session.id) {
  session.id = config.generateId?.() ?? (config.crypto || crypto).randomUUID();
  session.createdAt = Date.now();
  await updateSession(event, config);
}

Any call to getSession(event, config) for a request that doesn't already carry a valid session cookie/header falls into this branch and immediately calls updateSession, which seals and sets the cookie. This happens even when the caller is just checking "is there a session" (e.g. auth middleware peeking at whether a user is logged in) rather than intending to start one, since getSession's name and most other usages in the codebase read as a read-only accessor.

I checked SessionConfig for something to opt out of just this behavior. cookie?: false | (...) does gate the Set-Cookie write inside updateSession (if (config.cookie !== false && ...)), but it's all-or-nothing, setting it disables cookie persistence for every updateSession call, including legitimate ones with real session data, not just the eager empty-session case from getSession. There's no config option scoped to "don't auto-create and persist an empty session just from calling getSession."

Steps to reproduce

import { getSession } from "h3";

app.use(async (event) => {
  // Just checking whether a session exists, not intending to create one
  const session = await getSession(event, { password: "...".repeat(4) });
  console.log(session.data); // {}
});

Any request without an existing session cookie/header will receive a Set-Cookie in the response from this handler, even though nothing was ever written to session.data.

Expected behavior

getSession should be able to read/lazily-initialize a session in memory for the current request without necessarily persisting an empty session to the client, at least optionally, since callers who only read session state shouldn't be forced to also start issuing session cookies for anonymous visitors.

Actual behavior

getSession unconditionally persists a newly created empty session via updateSession whenever no session previously existed, regardless of whether the caller goes on to write any data to it.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions