skip to Main Content

I am trying to add a property to the Request object of express

First create a middleware to validate the session and the token brings the companyId

import { verifyToken } from '../utils/jwt/jwt';

declare module 'express-serve-static-core' {
  interface Request {
    companyId: string;
  }
}

export const validateSession = (
  req: Request,
  res: Response,
  next: NextFunction
): void => {
  try {
    const jwtByUser = req.headers.authorization ?? null;
    const jwt = jwtByUser?.split(' ').pop();
    console.log(jwtByUser);
    console.log(jwt);

    const session = verifyToken(`${jwt}`);

    if (!session) {
      res.status(400).send('Invalid Token Session');
    }
    // Add userId and companyId to the request object
    // req.user.id = session.user.id;
    req.companyId = session.companyId;
    // req.user.role = session.user.role;
    // req.user.email = session.user.email;
    next();
  } catch (error) {
    res.status(400).send('Invalid Session');
  }
};

Note: I have to put the same thing that I put on the index.d.ts if not I have an error req.companyId doesn’t exist

Then create a file inside src/types index.d.ts

import 'express-serve-static-core';

declare module 'express-serve-static-core' {
  export interface Request {
    companyId: string;
  }
}

then inside my user.routes.ts file I add the middleware and finally in my controller I should be able to use this property.

this is my route
router.get('/', validateSession, usersController.getAllUsers);

this is my controller user.controller:

getAllUsers = async (req: Request, res: Response): Promise<void> => {
    const companyId = req.companyId;
    console.log(companyId);
    const filteredUser = await this.usersService.getAllUsers();

    handleResult(res, filteredUser, 200);
  };

I have seen several posts where they ask to modify the tsconfig.json file I have tried thousands of things but none of them work for me I keep getting the same error.

The error occurs when I start the server with npm run dev.

this is the error:
Error importing module: Error: ⨯ Unable to compile TypeScript: src/app/users/infrastructure/controller/user.controller.ts(60,27): error TS2339: Property 'companyId' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

this is my folder structure:
x

2

Answers


  1. Chosen as BEST ANSWER

    I could solve it.

    I am using ts-node so I'd to add the flag --files to npm run dev script.

    I expend 7 hours or so just to discover that.


  2. I have verified that:

    1. Your solution works fine if you copy
    declare module 'express-serve-static-core' {
      export interface Request {
        companyId: string;
      }
    }
    

    into the file where you are using it (eg. your controller)

    1. Or: adding an index.d.ts file like:
    
    export * from'express-serve-static-core' 
    
    declare module 'express-serve-static-core' {
        interface Request {
          companyId: string;
        }
      }
    

    Also appears to work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search