Home > Back-end >  How to fix extended property on express request
How to fix extended property on express request

Time:04-18

I'm building a middleware in javascript where I can get the information of the user by using the famous "req" of the route handler. When i do a console.log(currentUser), I get the expected value but the currentUser is giving a typescript error warning: Property 'currentUser' does not exist on type 'Request<{}, any, any, ParsedQs, Record<string, any>>'.ts(2339)

Below is my piece of code:

middleware

const currentUser = async (req, res, next) => {
  if (!req.cookies?.token) return next();

  try {
    const payload = jwt.verify(req.cookies.token, process.env.JWT_SECRET);

    req.currentUser = payload;
  } catch {}

  next();
};

exports.currentUser = currentUser;

currentUser

const { currentUser } = require("../middleware");

router.get("/users/currentuser", currentUser, (req, res) => {
  const { currentUser } = req;
  console.log(currentUser);
});

exports.currentUser = router;

and this is the result when I do the console.log:

{ id: '625c2298ec690d8db4c6b37d', email: '[email protected]', role: 'user', name: 'Martin', iat: 1650218344, exp: 1650304744 }

Can some one help me out fixing this in javascript because i'm not familiar with typescript.

Thank you in advanced!

CodePudding user response:

for this one you can use Type.

type NewRequest = Request & {
  currentUser: string | JwtPayload,
}

async (req:NewRequest, res:Response, next:NextFunction)

I Hope, this will help you. Thanks)

CodePudding user response:

The Request type of Router contains some fixed properties.

If you want to add your own custom properties to it, either use

req.currentUser = payload;

OR

Create a type for own use like below, and use it for req

export type CustomRequest = ExpressRequest & {
  currentUser?: string | JwtPayload;
};

Hope this helps

  • Related