Express-Session: Get Session with session ID

Viewed 16

I'm fully aware that normally, with express-session, the session is returned with each request and there's no need to try to manage sessions. However, imagine for a moment, you have multiple applications each with different jobs, but you want your authentication to work with all your apps. So the problem there is, a session created on one app will not be magically replicated on all your other apps.

So what do you have to do? Presumably, you would need to query the app which created your sessions and get the session using it's ID. And you would store the session ID on the client via local storage.

I'm unable to find anything that would support this architecture (Micro-Apps instead of Monolithic).

There's some documentation in the readme of express-session which explains their store a bit but not how to use it. As an example, it states you can get the session like this: store.get(sid, callback) However, the only store available is a class called "Store". There's no clear indication in the docs on how to get/use this.

The docs go on to say something about "compatible session stores". Does this mean express session doesn't have it's own store, what are they trying to say in this readme? It's very cryptic and could have been written better...

1 Answers

Here's how I solved it: In your middle-ware do the following (I'm using Typescript):

export const sessionStore = new session.MemoryStore();

...

UserApp.use(session({
    secret: SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    store: sessionStore, // Session store goes here!
    cookie: {
        secure: true,
        httpOnly: false,
        maxAge: ONE_DAY }
}));

We will call this app which contains the middle-ware App A. I have another app, I will call App B. From that app, we will make an http.request to App A. App A will call the following. sessionStore.get(payload.SID, (_err, session) => {/* callback */})

That will return the session from the session store, provided it still exists. We return that session to App B and we can do whatever we want with it. Hope this helps someone, this was annoying for me.

EDIT: Ah and then I saw this...

Warning: the default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is only meant for debugging and developing.

Great.

EDIT 2: I'm using this store instead, pretty simple to swap out. https://www.npmjs.com/package/connect-redis

Related