I am new to typescript in nodejs i am have this error
import { Request, Response, NextFunction } from "express";
import * as jwt from "jsonwebtoken";
declare global {
namespace Express {
interface Request {
data?: jwt.JwtPayload;
}
}
}
// Define a middleware function to validate JWT tokens
export const jwtMiddleware = (
req: Request,
res: Response,
next: NextFunction
) => {
// Get the JWT token from the request headers
const token = req.headers.authorization?.split(" ")[1];
if (!token) {
return res.status(401).json({ message: "No token provided" });
}
// Check if JWT_SECRET is defined
if (!process.env.JWT_SECRET) {
return res.status(500).json({ message: "JWT secret is not defined" });
}
// Verify and decode the token
jwt.verify(
token,
process.env.JWT_SECRET,
(err: jwt.VerifyErrors | null, decoded: jwt.JwtPayload | undefined) => {
if (err) {
return res
.status(403)
.json({ message: "Failed to authenticate token" });
}
// Store the decoded token in the request for further use
req.data = decoded;
console.log(req.data);
next();
}
);
};
(err: jwt.VerifyErrors | null, decoded: jwt.JwtPayload | undefined) => {
made nodejs application before without using typescript and never borther me but when using th etypescript this type is here this line show’s type error
No overload matches this call.
The last overload gave the following error.
Type '(err: VerifyErrors | null, decoded: JwtPayload | undefined) => Response<any, Record<string, any>> | undefined' has no properties in common with type 'VerifyOptions'.ts(2769)
index.d.ts(245, 17): The last overload is declared here.
how can i resolve it
i want know how resolve this type error
does it work if you use
(err, decoded) => {
@JaromandaX it does but now the type error goes to req.data which is ` Type ‘string | JwtPayload | undefined’ is not assignable to type ‘JwtPayload | undefined’. Type ‘string’ is not assignable to type ‘JwtPayload’.ts(2322) Codeium: Explain Problem (property) Express.Request.data?: jwt.JwtPayload | undefined`
where are all these
types
defined? couldn’t see any typescript injsonwebtoken
library@JaromandaX do i need define
types
for jsonwebtoken ?Possibly – since
jsonwebtoken
doesn’t seem to have any such definitionsShow 4 more comments