DEV Community

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.

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";
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 remove @types/express-session
yarn add -D @types/express-session@1.17.0
Enter fullscreen mode Exit fullscreen mode


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)

Editor guide
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

anztrax profile image
andrew ananta

wow that's awesome.. thanks man

d3skdev profile image
jinguangze profile image

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

jinguangze profile image

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