Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TYPESCRIPT - express-session handling

I'm struggling to set-up express-session into my TS project. When I make my basic setup of it (JS way), I create a MW that is called at each API demand, this way I can create or no a new user array into my session.

import {Request, Response, NextFunction} from 'express'

module.exports = (req: Request, res: Response, next: NextFunction) => {
    console.log('session checker : ', req.session)
    if (!req.session){
        req.session.user = []
        console.log('session initialized')
    }
    next();
}

The struggle is on the .user, TS display me this error

Property 'user' does not exist on type 'never'.

Do you have an idea to get over it ?

Thanks in advance,

Paul

like image 500
x2cheese Avatar asked Jun 26 '26 04:06

x2cheese


1 Answers

As per the source code of the typings for express-session, you need to define the properties available in SessionData yourself (somewhere in your codebase):

    /**
     * This interface allows you to declare additional properties on your session
object using [declaration merging]
(https://www.typescriptlang.org/docs/handbook/declaration-merging.html).
     *
     * @example
     * declare module 'express-session' {
     *     interface SessionData {
     *         views: number;
     *     }
     * }
     *
     */
    interface SessionData {
        cookie: Cookie;
    }

I suggest you do that, as you know better which properties the user has:

e.g. (maybe you have different data) in a index.d.ts file in your project:

     declare module 'express-session' {
         interface SessionData {
             user: string;
         }
     }
like image 52
tudor.gergely Avatar answered Jun 28 '26 19:06

tudor.gergely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!