Issue
I am facing an issue, my app is getting crashed with JWT Token Expired Error. I have changed the secret key also but still same issue I am facing.
Here is the code :
Mddleware:
const auth = async (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
const isCustomAuth = token?.length < 500;
if (!token)
{return res.status(401).json({ message: "No token provided" });}
let decodedData;
if(token && isCustomAuth){
decodedData= verifyToken(token);
req.userId = decodedData?.id;
}
else{
decodedData = jwt.decode(token);
console.log(decodedData + "decoded token");
req.userId = decodedData?.sub;
}
next();
} catch (error) {
console.log(error);
res.status(403).json({ message: "Token is not valid" });
throw Error();
}
};
Token verification
import jwt from "jsonwebtoken";
const secret = process.env.SECRET;
export const generateToken = (data) => {
try {
return jwt.sign({ email: data.email, id: data._id }, secret , { expiresIn: "24h" });
} catch(e) {
throw new Error(e)
}
}
export const verifyToken = (token) => {
try {
return jwt.verify(token, secret);
} catch(e) {
throw new Error(e)
}
}
The app is getting crashed saying jwt expired error. Please help.
Solution
The issue is likely your catch
statement:
const auth = async (req, res, next) => {
try {
// ...
} catch (error) {
console.log(error);
res.status(403).json({ message: "Token is not valid" });
throw Error(); // <--- Remove this. Don't throw in a middleware, an error response is enough
}
};
By the way, there is another opportunity to improve. The catch below does nothing and is even wrong (you are passing an error instance to another Error), so I suggest you remove the try-catch altogether, or just return some nullish value there.
export const verifyToken = (token) => {
try {
return jwt.verify(token, secret);
} catch(e) {
throw new Error(e) // <---- You are catching only to re-throw another error, not to mention this is a wrong way to create an error.
}
}
This should be
export const verifyToken = (token) => {
return jwt.verify(token, secret);
}
or this, then handle the null value inside your middleware
export const verifyToken = (token) => {
try {
return jwt.verify(token, secret);
} catch(e) {
return null;
}
}
Answered By - Son Nguyen Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.