In my express/nodejs app, I am encountering issues with properties on the request.user object even after implementing Declaration Merging for authentication using passportjs middleware.
To address this, I created a file at /types/index.d.ts in the project root and updated tsconfig.json as follows:
"typeRoots": [
"/types/index.ts", "node_modules/@types"
]
My global declaration merge is structured like this:
import { User } from "../users/user.interface";
declare global {
namespace Express {
export interface Request {
user: User;
}
}
** UPDATE ** I resolved errors related to req.user by modifying the Declaration Merge to Module Augmentation:
import { User } from "../users/user.interface";
declare module "express-serve-static-core" {
interface Request {
user: User;
}
}
However, when accessing the request.session
object, I'm getting this error:
Property 'session' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
Shouldn't the @types/passport types be merging with express's request object to include a session?
https://i.sstatic.net/dhRgz.png
If anyone knows how to resolve these errors and make TypeScript recognize this Declaration Merge properly, I would greatly appreciate the help. I'm still learning TypeScript and have been able to fix most issues so far, but this one remains persistent.