I'm struggling to figure out how to correctly attach my user and session to the request object in my Express backend using TypeScript. My stack includes MongoDB, Prisma, Node, Express, and TypeScript. I've tried creating an interface like this: export interface AuthenticatedRequest extends Request { user: User; session: Session; } but it's not working as expected. My middleware code checks for a session token in the cookies, validates it against the database, and then tries to assign the user and session to the request object. However, I'm getting TypeScript errors saying that the properties 'user' and 'session' do not exist on the Request type. I attempted to define these in a custom types file but the app isn't recognizing it. I've adjusted my tsconfig.json and tried several configurations, but I'm still stuck. Can anyone help?
2 Answers
Make sure to double-check your folder structure; it needs to be set up correctly for TypeScript to recognize the type declarations. The 'src/types' folder should contain the express folder with your index.d.ts file in it. Also, consider adjusting the way you start your server, since different commands can affect how the tsconfig is interpreted. Sometimes subtle differences can lead to confusion in setups like this. Let me know if you still run into issues after that!
It looks like the root of the issue might be in your tsconfig settings. It's crucial to note that when you have a 'types' array defined, TypeScript only loads those specified types. If you have 'types': ['node'], it will ignore your custom types. To resolve this, try removing the 'types' array altogether, or if you want to keep it, add 'express' to it as well. Another key thing is to ensure that your custom type definition file is named correctly; try naming it index.d.ts in a path that looks like src/types/express/index.d.ts. Then, give your TypeScript server a restart to see if that picks it up properly. This should help resolve the type errors you're seeing!
Also, I found that changing my start command to "start": "ts-node --files src/server.ts" worked for me, instead of the previous one I was using with nodemon. Just a thought if you're still having issues!

I had that issue too! After I switched to the new start command I mentioned, everything fell into place!