Reputation: 3
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
Upvotes: 0
Views: 527
Reputation: 124
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.
Upvotes: 1
Reputation: 13
I ran into this exact same problem.
There is a lot of discussion about this issue on the pull request. https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46576
In summary, in your express-session.d.ts
file, you need to import the package and declare the module like below, so that declaration merging takes effect.
import 'express-session';
declare module 'express-session' {
interface SessionData {
userId: number;
}
}
You then want to specify your typeRoots
in your tsconfig.json
file so the compiler picks up your custom declaration files.
Based on your repo, it looks like your typeRoots
should be:
"typeRoots": ["./src/@types", "./node_modules/@types"]
Upvotes: 0
Reputation: 126
I also faced the same issue. Then realized that behavior is changed in the latest release(https://github.com/DefinitelyTyped/DefinitelyTyped/commit/d1259ee31e6b17c31a5a86e27a0d12f3ec7c5a19#diff-0d13c95494fa97febecd0fbc1fb1b8f6e17bbcaedb8c88d10a0b655046e1c97b). Define the required fields as below to make it work.
declare module 'express-session' {
interface SessionData {
userId: string;
}
}
Upvotes: 0