12

Please help, I am getting this error

src/app/middlewares/authentication.ts:16:17 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

16             req.user = user;

I have created the .d.ts file and also included it in tsconfig file. Still I am not able to run this code

Please find attached screenshots

enter image description here

enter image description here

enter image description here

Dan Bonachea
  • 2,408
  • 5
  • 16
  • 31
Piyush Garg
  • 133
  • 1
  • 2
  • 6

6 Answers6

27
  1. Create a types folder in your src directory
  2. Create a folder within the types folder with the name of the package you intend to extend. (In this case express).
  3. Create an index.d.ts file in that folder
 src/
   - types/
    - express/
     - index.d.ts
  1. add this code to the index file
import express from "express";

declare global {
  namespace Express {
    interface Request {
      user?: Record<string,any>
    }
  }
}
  1. remember to update your tsconfig.json file
{
  "compilerOptions": {
    "typeRoots" : ["./src/types", "./node_modules/@types"]
  }
}

This should work

Solz
  • 296
  • 3
  • 4
7

I was stuck on the same problem earlier. Here is how I solved it.

  1. I created a separate directory called @types in my project for declaration merging to work.
  2. Next I created a file in it called index.d.ts with following content. Please pay attention that we need to declare our own request within global. Also, importing express is important as well.
import * as express from "express"
declare global {
    namespace Express {
        interface Request {
            user? : Record<string,any>
        }
    }
}
  1. I added the following line under compilerOptions in my tsconfig.json.
 "compilerOptions": {
     ...other settings,
     "typeRoots": ["@types", "node_modules/@types"],
     ...other settings
 }

And that's it. It should works with these changes.

2

Another way:

import { NextFunction, Request, Response } from 'express';

interface IDecode {
    address: string,
    role: string,
    iat: number,
    exp: number
  };

 interface RequestWithUserRole extends Request {
    user?: IDecode,
}


 const parseToken = (secret: string) => 
  async (req: RequestWithUserRole, res: Response, next: NextFunction) => {
    try{
      const token  = req.headers?.authorization?.split(' ')[1];
      // console.log(req.headers?.authorization);
      if (!token) {
        return res.status(403).json({message: 'Token not  found'})
      }
      const decodedData = <IDecode> jwt.verify(token, secret);
      req.user = decodedData;
      // console.log(decodedData);
      return next();
    }
    catch(e) {
      return res.status(500).json({e})  
    }
};
Oleg Vovk
  • 21
  • 1
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P May 18 '22 at 15:29
0

A quick walkaround if you are doing a quick prototype or following a tutorial (req as any).user

NB: Do not use this in a real production app, because it would make your code dirty and it's not scalable.

0
  1. These were the variables I want to use in the Request object. In your /src/types/express/index.d.ts you should put::

    export {}
    
    declare global {
      namespace Express {
        export interface Request {
          idUser?: string
          email?: string
          username?: string
          // extra variables you want to use in req object
        }
      }
    
    }
    
  2. In your tsconfig.json:

    {        
        "compilerOptions": {
            // other settings
            "typeRoots": ["./src/types", "./node_modules/@types"]  // it's important to put first your path file otherwise it won't work
            // other settings
        }
    }
    

This should also work for you. Good luck!

0

Just install types for Passport.js:

npm install -D @types/passport
vbg
  • 613
  • 6
  • 10