Hello, I getting annoyed about typescript in my node api. I have written a jwtverify.ts. At first typescript has not accepted the req.user. I found a hint on StackOverflow and brought in a @types folder with a file named index.d.ts and the following code:
import * as express from "express"
declare global {
namespace Express {
interface Request {
user? : Record<string, any>
}
}
}
That solved this issue first, but today the app crashes and throws me that error in my title. When I hover req.user in my verifytoken. Vs-code tells me:
The user object does exist on the Request object type. Instead of manually adding the typedef to a declaration file, I suggest adding the types for Express with:
npm i -D @types/express
This being said, it sounds like you are not checking for the existence of req.user before using it.
As shown in the type def, user is optional on Request. Meaning, it might exist.
So, you need to guard against the cases where it might not exist by doing something like:
if (req.user) {
// Now you can use user
const { user } = req;
...
}
Beyond this, without seeing the code responsible for throwing that error, we cannot help any further.
Hello Sky020, thanks for your help, sadly it only solved the issue in that way, that there are no errors anymore. The jwtVerify not works.
Here is the code:
Log authHeader gives back the correct header. Log (user, req.user) gives back: {
[0] id: ‘6346af949778eba63822fd8b’,
[0] isAdmin: false,
[0] iat: 1665576936,
[0] exp: 1668168936
[0] } undefined
Without typescript I was used to say req.user = user and that has worked.