Michel Vorwieger
Michel Vorwieger

Reputation: 722

Typesafe Express Middleware and Routes?

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;
}

Upvotes: 1

Views: 1869

Answers (2)

Michel Vorwieger
Michel Vorwieger

Reputation: 722

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"
]

Upvotes: 4

Rohit Gupta
Rohit Gupta

Reputation: 3231

Have you tried :

const token = req.token as Token;

Upvotes: 0

Related Questions