5

I am trying to implement an express API that authenticates via a jwt token and I'm using the express-jwt middleware to authenticate access to a method:

import express from 'express'
import jwt from 'express-jwt'

const app = express()

app.get('/protected', jwt({ secret: 'jwtSecret', algorithms: ['HS256'] }), prot)

const prot = (
    req: express.Request,
    res: express.Response,
    _next: express.NextFunction
): void => {
    res.json({
        msg: req.user,
    })
}

app.listen(3000)

But I get this error:

Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.ts(2339)

I've tried attaching req: express.Request & { user: unknown }, but then the function doesn't fit with express anymore.

Any ideas what I can do here. If worse comes to worse, can I just tell TypeScript to shut up somehow, since I know that the field will be there (even though I know that's not the point of TypeScript)

Kavfixnel
  • 151
  • 3
  • 10
  • It would be nice to see an `ExpressJWTRequest` object exported from [`@types/express-jwt`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express-jwt/index.d.ts) but unfortunately there doesn't seem to be anything for that :( – Matthew Herbst Nov 23 '20 at 03:30
  • I realize this is several years later .. but if you check, as of ver. 7.4.2; you don't need the @types; https://github.com/DefinitelyTyped/DefinitelyTyped/blob/b23a36e669fa127d1035e22ca93faab85b98e49f/notNeededPackages.json#L1616-L1619 – Kyle Aug 05 '23 at 17:24

2 Answers2

1

user is not an existing property on req object. You can make your own typings for req object by creating a .d.ts file on your project, for example, create a express.d.ts file and it will contains:

declare namespace Express {
   export interface Request {
       user: SomeType
   }
}

Demo: https://repl.it/repls/OldlaceWhoppingComputationalscience

Try deleting the express.d.ts and the error will appears again.

Owl
  • 6,337
  • 3
  • 16
  • 30
  • If I make a type `declare namespace ExpressJWT { export interface JWTRequest extends express.Request { user: unknown } }` I get `(property) ExpressJWT.JWTRequest.user: unknown Object is of type 'unknown'.ts(2571)` – Kavfixnel Oct 25 '20 at 06:30
  • I've already tried something similar and that did not work either – Kavfixnel Oct 25 '20 at 06:32
  • The name space is supposed to be `Express`, not `ExpressJWT`, have you tried mine? Check my repl.it – Owl Oct 25 '20 at 06:38
0
declare global {
  namespace Express {
    interface Request {
      user?: UserPayload;
    }
  }
}

this is an example of UserPaylaod

  interface UserPayload {
     id: string;
     email: string;
   }
Yilmaz
  • 35,338
  • 10
  • 157
  • 202