Typescript ExpressJS middleware for jwt auth
hey guys! I am new to ts. I am trying to create a expressJS middleware for verifying jwt token. And after successful verification i want to attach the user object i get from payload which is typed
string | jwt.JwtPayload
in request object. but typescript is complaining. I dont want to just make it work i want to do it the correct way. help me out or Guide me to relavant resources.
2 Replies
Hello, you could create a type definition file to include the user property on the express Request.
Example:
Create an
express.d.ts
file in your project, this file could be located in a types
folder or anywhere you want to inside src, with this content:
Doing this everywhere that you call the express request
you will be able to use request.user
.
The bad side of this is if you try to access request.user
in a route that does not have the verifyToken
middleware you will get an runtime error, because the middleware is the one who saves the user value on the request.There is another way to do this that is recommended by the express using the
res.locals
.
Link to docs: https://expressjs.com/en/api.html#res.locals
Basically, instead of using:
You, use:
The typescript will not complain because the res.locals
are made to accept any content.