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
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;
}
}