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.
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { env } from '../types/env';

export const verifyToken = (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.header('authorization')?.replace('Bearer ', '');

if (!token) {
return res.status(401).json({ message: 'Missing access token' });
}

const user = jwt.verify(token, env.ACCESS_TOKEN_SECRET);

// req.user = user;
next();
} catch (error) {
console.log(error);
res.status(403).json({ message: 'Invalid access token' });
}
};
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { env } from '../types/env';

export const verifyToken = (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.header('authorization')?.replace('Bearer ', '');

if (!token) {
return res.status(401).json({ message: 'Missing access token' });
}

const user = jwt.verify(token, env.ACCESS_TOKEN_SECRET);

// req.user = user;
next();
} catch (error) {
console.log(error);
res.status(403).json({ message: 'Invalid access token' });
}
};
2 Replies
Ebert
Ebert7mo ago
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:
declare namespace Express {
export interface Request {
user: string | jwt.JwtPayload
}
}
declare namespace Express {
export interface Request {
user: string | jwt.JwtPayload
}
}
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.
Ebert
Ebert7mo ago
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:
req.user = user
req.user = user
You, use:
res.locals.user = user
res.locals.user = user
The typescript will not complain because the res.locals are made to accept any content.