Session object not modifiable in typescript (while using @types/express-session)
See original GitHub issueI’ve been using express-session in various express applications, but never with typescript. Disclaimer: This might be a bug with @types/express-session, but I figure this is the right community to ask either way, so here’s what’s happening.
The session object is essentially just not modifiable, ie I can’t seem to add properties to it, and, perhaps because of a recent update, all methods of fixing this I’ve found either don’t work or just break the whole thing.
In this example use case:
router.get("/example", (req, res) => {
console.log(req.session); // Works
req.session.username = "mine" // Fails
req.session.destroy(data => console.log(data)); // Works
res.send('something')
});
I get the following error:
Property 'username' does not exist on type 'Session & Partial<SessionData>'
Not sure if this is in any way useful, but these are my session options
const sessionConfig: session.SessionOptions = {
name: "uid",
secret,
store: new RedisStore({
client: redisClient,
disableTTL: true,
disableTouch: true,
}),
cookie: {
maxAge: 1000000000000999,
httpOnly: true,
sameSite: "lax",
secure: __prod__,
},
saveUninitialized: false,
resave: false,
};
I have attempted to create a separate type combining express.Request and the session options, but I can’t really get that to work either, and I’m assuming there’s a bit more elegant way of dealing with this.
Thank your for your time.
Issue Analytics
- State:
- Created 3 years ago
- Comments:9 (1 by maintainers)
Top GitHub Comments
tsconfig.json
’s typeroots declares custom types first, before the node_modules’s.That should be enough, hope this helps everyone who is stuck on Typescript hole 😄
Add this to a file in your project ( ie types.ts etc.)
You can add all of your custom fields in session inside of the
SessionData
interface.