DEV Community

loading...
Cover image for express-session failing with typescript (@types/express-session)

express-session failing with typescript (@types/express-session)

qoobes profile image Syd Barrett ・1 min read

Typescript can be weird.

TL;DR
The problem stems from req.session being immutable, and can fixed by bumping your @types/express-session version down to 1.17.0, as shown down below, here.

The Problem

This was supposed to be a longer post, but doesn't matter.
A lot of people have been experiencing issues when using express-session with the new version of @types/express-session, since it straight up doesn't work. The documentation is scarce and outdated, and the comments next to the type declarations don't work.

By don't work, I mean the Request.Session (req.session) object is immutable, meaning that, for example, this block of code:

router.get("/", req => {
  req.session.username = "username";
  console.log(req.session);
});
Enter fullscreen mode Exit fullscreen mode

Will throw a typescript error like:

Property 'username' does not exist on type 'Session & Partial<SessionData>'.

Now, it should of course not be throwing this, in fact the reason it's doing so is this line of code:

interface SessionData {
  [key: string]: any;
  cookie: SessionCookieData;
}

Enter fullscreen mode Exit fullscreen mode

being changed to this

interface SessionData {
  cookie: Cookie;
}
Enter fullscreen mode Exit fullscreen mode

As pointed out in this pull request.

** Long story short, it doesn't work. **

The Solution

The solution is of course reverting to an older version of @types/express-session, by running the following commands:

yarn:

yarn remove @types/express-session
yarn add -D @types/express-session@1.17.0
Enter fullscreen mode Exit fullscreen mode

npm:

npm uninstall @types/ty
npm install -D @types/express-session@1.17.0
Enter fullscreen mode Exit fullscreen mode

Have a nice time :P

Discussion (5)

pic
Editor guide
Collapse
maulanasatyaadi profile image
Maulana Satya Adi • Edited

This is not a good solution, the good solution is to merge your SubmitData interface, so you don't need to downgrade the version. Let's check the documentation typescriptlang.org/docs/handbook/d...

Collapse
anztrax profile image
andrew ananta

wow that's awesome.. thanks man

Collapse
d3skdev profile image
Collapse
jinguangze profile image
jinguangze

This is good solution to fix my issue.
I resolved this issue after downgrade from 1.17.3 to 1.17.0
Thanks.

Collapse
jinguangze profile image
jinguangze

But I am not sure why I am getting from 1.17.3
If you know the reason, Can you describe here?
Thanks.