Search code examples
node.jstypescriptexpressexpress-session

Express Sessions 1.17.1+ ( req.session.myUserId )


I noticed changes in express-session 1.17.1+ so I can't just put custom property (like req.session.userId) into req.session. It causes a type check error. I tried to extend SessionData, Object.defineProperty and many other options but for some reason, it doesn't work. Please help!

I wrote a simple code to reproduce problem clearly here


Solution

  • Maybe this will work for you, I share it with you to save time.

    modify file tsconfig.json and add

    "typeRoots": [
        "@types",
        "./node_modules/@types"
    ]
    

    create file with following content: @types/express/index.d.ts

    import "express-session";
    
    // what we are all looking to solve xD
    // req.session.propertyX
    declare module "express-session" {
        interface SessionData {
            propertyX: number;
        }
    }
    
    // additional properties on other objects
    // req.propertyY
    declare global {
        namespace Express {
            interface Request {
                propertyY: number;
            }
        }
    }
    
    

    hope it works for you, and saves time.