Search code examples
typescriptexpress-session

Cannot modify session object express-session


I know there are tons of topics about this but i spent the past 2 hours searching and nothing helped.

Hello, i am having a very hard time trying to extend the session object for express-session in typescript.

I have the following files

src/types/express/index.d.ts

import account_document from "../account/account-document"
import xcsrftoken from "../data-types/x-csrf-token"

declare global {
    namespace Express {
        interface Request {
            authenticated_user: account_document
        }
        interface SessionData {
            xcsrftoken: xcsrftoken
        }
    }
}

src/types/express-session/index.d.ts

import xcsrftoken from "../data-types/x-csrf-token";

declare module "express-session" {
    interface SessionData {
        xcsrftoken: xcsrftoken
    }
}

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2017",
        "module": "commonjs",
        "strict": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "typeRoots": ["./src/types/express", "./src/types/express-session", "./node_modules/@types"]
    },
    "exclude": ["node_modules"]
}

However the script below returns Property 'xcsrftoken' does not exist on type 'Session & Partial<SessionData>'.

if (!req.session.xcsrftoken) {
    req.session.xcsrftoken = {};
}

How can i resolve this?


Solution

  • I solved the issue. You basically have to create a main folder, a folder for each package and an index.d.ts file for each package folder. You then want to put your code to extend packages types in the index.d.ts files.

    For example:

    types
        /libs
            /express
                /index.d.ts
            /express-session
                /index.d.ts
    

    and then add the libs folder to the typeRoots like this

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