I am working on API in nodejs/expressjs, Right now I am working with "JWT TOKEN" for this I created function for "generate jwt token", now i want to verify that token but I am getting the following errors
JsonWebTokenError: jwt malformed
Here is my current code
const secretKey = 'mySecretKey';
const logins = async (req, res) => {
const user = { id: 123, phoneNumber:'123XXXXXXXX' };
// Create a JWT token with the user payload and the secret key
const token = jwt.sign(user, secretKey);
// Return the token to the client
res.json({ token });
}
function verifyToken(req, res, next) {
const token = req.body.token;
if (token) {
const decode = jwt.verify(token, "secret");
res.json({
login: true,
data: decode,
});
} else {
// Return response with error
res.json({
login: false,
data: "error",
});
}
}
I have a few questions regarding this
1) How can we create a common function for all other APIs ( if the token does not match then display an error)
2) How can we verify the token?