I'm currently converting the backend of an ExpressJS application to Typescript. While working on the auth.routes.ts file, I encountered an issue with the middleware (authMiddleware). It seems like there might be a typing error, as the same code in the js extension is functioning properly.
Could someone assist me in resolving this?
Here is the relevant code:
auth.routes.ts
import { Router } from "express"
import authMiddleware from "../middleware/auth.middleware"
import authController from "../controllers/authController"
const router = Router()
router.get("/", authMiddleware, authController.auth)
export default router
auth.middleware.ts
import "dotenv/config"
import { NextFunction, Response } from "express"
import jwt, { JwtPayload, Secret } from "jsonwebtoken"
import { CustomHeaders } from "../models"
const secretKey: Secret = process.env.secretKey as Secret
interface AuthRequest extends Request {
user?: JwtPayload
}
function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
if (req.method === "OPTIONS") {
next()
}
try {
const token = (req.headers as CustomHeaders).authorization?.split(" ")[1]
if (!token) {
return res.status(401).json({ message: "Unauthorized" })
}
const decoded: JwtPayload = jwt.verify(token!, secretKey) as JwtPayload
req.user = decoded
next()
} catch (error) {
return res.status(400).json({ message: "Bad Request" })
}
}
export default authMiddleware
Error description:
The provided information does not match any valid overload. The latest attempt produced the following error. The argument type '(req: AuthRequest, res: Response<any, Record<string, any>>, next: NextFunction) => Response<any, Record<string, any>> | undefined' cannot be assigned to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. The type '(req: AuthRequest, res: Response<any, Record<string, any>>, next: NextFunction) => Response<any, Record<string, any>> | undefined' is not compatible with type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Both parameters 'req' are incompatible. The 'AuthRequest' type is missing properties such as cache, credentials, destination, integrity, and more.ts(2769)
I've attempted seeking assistance from chatGPT but haven't been able to find a working solution yet.