1

im currently working on a express application that uses typescript. Im currently working on a Authentication Middleware and was wondering if you can make the Middlewares typesafe in a way:

authenticateJwt = (
  req: RequestWithToken,
  res: Response,
  next: () => void
) => {
// Append the decoded req.token to the req header so we can use it internally
const token = req.token;

// @ts-ignore
this.verifyJwt(token)
  .then((decoded: Token) => {
    req.token = decoded;
    next();
  })
  .catch(() => res.status(401).send('Unauthorized'));
};

now in my routes.ts:

router.get(
  '/me',
  // @ts-ignore
  jwtService.authenticateJwt,
  userController.getProfileFromUser
);

I have to write // @ts-ignore because it says that '(req: RequestWithToken, res: Response, next: () => void) => void is not of type RequestHandlerParams

definition of RequestWithToken:

export interface RequestWithToken extends Request {
  token: Token;
}
export interface Token {
  username: string;
}
Michel Vorwieger
  • 692
  • 5
  • 14

2 Answers2

4

create a custom.d.ts and overwrite the Request Interface of express and express-serve-static-core

declare module 'express' {
  interface Request {
    token: Token;
  }
}

declare module 'express-serve-static-core' {
    interface Request {
        token: Token;
    }
}

this way both the RequestHandlerParams(useually your controller) and RequestHandler(useually your Middleware) are getting your new Request Interface.

then add it to the files section of your tsconfig.json:

"files": [
    "src/custom.d.ts"
]
Michel Vorwieger
  • 692
  • 5
  • 14
0

Have you tried :

const token = req.token as Token;
Rohit Gupta
  • 2,571
  • 3
  • 16
  • 25
  • If I use `req: Request` and what you have wrote then it says that `req.token` doesnt exist on type `Request` – Michel Vorwieger Jan 15 '19 at 09:42
  • @MichelVorwieger I forgot, you also need to retype your Request interface as in https://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript – Rohit Gupta Jan 15 '19 at 09:48
  • it now works in my middleware but the express Router still complains that `(req: Request, res: Response, next: () => void) => void` is not of type RequestHandlerParams – Michel Vorwieger Jan 15 '19 at 10:26
  • I fixed it by also overwritting the `Request` object from `express-serve-static-core` – Michel Vorwieger Jan 15 '19 at 10:47
  • 1
    @MichelVorwieger, I'm glad that you resolved it. I would still request you to answer your own question for this thread and not just leave a comment on my answer. This will help other fellows as well. – Rohit Gupta Jan 15 '19 at 10:53