You are probably getting undefined because you signed the jwt with the secret process.env.Acess_Token but you are trying to verify it with process.env.JWT_Secret. Please correct that and check if it works.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
always get udefined in req.cookies.toke
require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors")
const cookie = require("cookie-parser");
const jwt = require("jsonwebtoken");
app.use(cors());
app.use(cookie());
const createToken = function(res,user){
try{
const token = jwt.sign({user},process.env.ACESS_TOKEN);
console.log(token);
return res.cookie('token', token, {
secure: false, // set to true if your using https
httpOnly: true,
});
}catch(e){
return console
.log(e)
}
}
const verifyToken = async (req, res, next) => {
const token = req.cookies.token || '';
console.log(token);
try {
if (!token) {
return res.status(401).json('You need to Login')
}
const decrypt = await jwt.verify(token, process.env.JWT_SECRET,(err,data)=>{
if(err)res.send("Token is undefined")
});
req.user = {
id: decrypt.id,
firstname: decrypt.firstname,
};
next();
} catch (err) {
return res.status(500).json(err.toString());
}
};
app.get("/",verifyToken,async(req,res)=>{
res.send("Token")
});
app.post("/post",(req,res)=>{
user = {
Name : "vibhor",
Age : "27"
}
createToken(res,user);
});
app.listen(6000,()=>{
console.log("Server has started")
})
You are probably getting undefined because you signed the jwt with the secret process.env.Acess_Token but you are trying to verify it with process.env.JWT_Secret. Please correct that and check if it works.