Skip to content

Add a cookiePrefix option #112

@rclmenezes

Description

@rclmenezes

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Add an option called expressSessionCompatibilityMode that defaults to false. When enabled, @fastify/session and express-session can be interchangable.

Alternatively, we can add a "cookieSignaturePrefix" option that defaults to "". When set to s:, it will make things compatible with express-session.

Motivation

I'm migrating from an Express monolith to multiple Fastify services. I want them all to share the same sessions and I don't want to use fastify-express unless I have to.

My express-session:

export const expressSession = ExpressSession({
  cookie: {
    maxAge: COOKIE_EXPIRATION_IN_SECONDS * 1000, // in ms
  },
  genid: generateSessionId,
  resave: false,
  rolling: true, 
  saveUninitialized: true,
  secret: SESSION_SECRET,
  store: ...,
});

My fastify-session:

    .register(fastifySession, {
      cookie: {
        maxAge: COOKIE_EXPIRATION_IN_SECONDS * 1000,
      },
      cookieName: "connect.sid",  // Name of the cookie in express-session
      idGenerator: generateSessionId,
      rolling: true,
      secret: SESSION_SECRET,
      saveUninitialized: true,
      store: ...
    })

The only reason this doesn't work? express-session signs cookies with an s: prefix. So the cookie header will look something like s:aa457ab3-ef20-4cee-8cf8-5a915ce82971.nJR5x4qCb5sjfNBGElmb9AirUxkjgeatE1fLm2W1rME

Relevant code here:
https://github.com/expressjs/session/blob/master/index.js#L656

@fastify/session (reasonably) does not do this and breaks inside decryptSession. It clears the cookie.

One work-around is to use hooks around fastifySession which is... rather hacky.

    .addHook("onRequest", async (req, res) => {
      // Transform "connect.sid" to "sessionId"
      req.cookies.sessionId = req.cookies["connect.sid"]?.replace("s:", "");
    })
    .register(fastifySession, {
      cookieName: "sessionId"  // the default
      ...
    })
    .addHook("onResponse", async (req, res) => {
      // Transform "sessionId" back to "connect.sid"
      await res.header(
        "set-cookie",
        res.getHeader("set-cookie")?.replace("sessionId", "connect.sid"),
      );
    })

I would be happy to make this PR myself!

Example

No response

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