auth0 / express-jwt

connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeScript types should not extend Express' Request type.

samwightt opened this issue · comments

Description

The TypeScript type definitions have something like this:

declare global
   declare Express {
      interface User {}

      interface Request {
        user?: User
      }
  }
}

When users try to make a type like this:

import type { Request } from 'express';

type CustomUserType {
  name: string;
  example: string
}

type OtherCustomUserType {
  otherName: string;
  foo: bar;
}

export type CustomRequest = Request & { user?: CustomUserType }
export type OtherCustomRequest = Request & { user?: OtherCustomRequest }

// in another file

router.get('/', (req: CustomRequest, res: Response) // This raises an error in strict mode
// because `CustomRequest` is not assignable to the new `Request` type.

Users can extend the User type in the Express namespace, but this is not type safe. Users might have multiple User types that they need to use, and users might try to access the user field before the authentication middleware is run. Due to TypeScript's declaration merging, it is not possible to remove the user field from the Request object unless the express-jwt types are removed.

Any update on this? Trying to get around this but these types are making it impossible to.

I think the PR for this would have to happen in DefinitelyTyped - I see there was a bit of conversation about this over there DefinitelyTyped/DefinitelyTyped#51314 (comment) but yes I agree the current types are causing me issues as well.

Fixed in v7. You don't need to install @types/express-jwt and you can use the exported type which extend request as follows:

https://github.com/auth0/express-jwt#typescript

import { expressjwt, ExpressJwtRequest } from "express-jwt";

app.get(
  "/protected",
  expressjwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }),
  function (req: ExpressJwtRequest, res: express.Response) {
    if (!req.auth.admin) return res.sendStatus(401);
    res.sendStatus(200);
  }
);