I'm having trouble extending Express' Request object to access req.user, and I'm encountering an overload error. I've attempted a couple of solutions, but none of them seem to work for me.
EDIT: I am currently using Passport.js and JWT
Extend Express Request object using Typescript
Unable to extend Express Request in TypeScript
I've tried two different methods to extend Express' Request object:
- Using interface extend. This method sort of works, but I receive an overload error preventing me from compiling with 'tsc':
// index.d.ts file
import { IUser } from "../models/user";
import { Request } from "express";
export interface IUserRequest extends Request {
user: IUser; // or any other type
}
- Creating a global namespace. This approach doesn't work as I'm unable to access the req.user property. I've attempted importing { Request } from "express", but it doesn't seem to work for this option due to the 'Request is declared but never used' error:
//index.d.ts file
import { IUser } from "../models/user";
// import { Request } from "express"
export {};
declare global {
namespace Express {
interface Request {
user?: IUser;
}
}
}
This is the post controller that attempts to access req.user:
export const admin_code_post = [
body("admin_code", "Wrong code buddy")
.trim()
.escape()
.custom((value: string) => {
if (value !== process.env.SECRET_CODE) {
throw new Error("Admin code is incorrect");
}
return true;
}),
(req: IUserRequest, res: Response, next: NextFunction) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.render("admin_code", {
title: "Enter Code",
errors: errors.array(),
user: req.user,
});
return;
}
User.findOneAndUpdate(
{ username: req.user?.username }, // issue here if I create a global namespace
{ admin: true },
(err: Error, user: IUser) => {
if (err) return next(err);
res.render("index", {
title: "Welcome",
user,
});
}
);
},
];
Unable to find req.user when using global namespace method
This is my tsconfig.json :
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./src",
"typeRoots": [
"./node_modules/@types",
"./types"
],
"sourceMap": true,
"outDir": "dist",
"noEmitOnError": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true
},
"include": ["./src/**/*"],
"exclude": ["node_modules"],
"ts-node": {
"files": true
},
"files": [
"./src/types/index.d.ts"
]
}
What am I doing wrong? Any suggestions would be greatly appreciated.