Express js cookies setting properly into browser locally but can not access the value with req.cookies

  Kiến thức lập trình

Here is my protect middleware in expess js application:

const protect = asyncHandler(async (req, res, next) => {
  let token;
  token=req.cookies?.jwt
  if (token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      console.log(decoded)
      req.user = await prisma.user.findFirst({
        where: {
          email: decoded.email,
        },

      });
      next();
    } catch (err) {
      res.status(401);
      throw new Error(`Not Authorized, Invalid Token`);
    }
  } else {
    res.status(401);
    throw new Error(`Not Authorized, No Token`);
  }
});

the token is getting the value undefined though cookies is setting properly into browser after login

Here is generateToken which is generating token after every login.

 const generateToken = (res, email) => {
  console.log('email form generate',email)
  try {
    const token = jwt.sign({ email }, process.env.JWT_SECRET, {
      expiresIn: "30d",
    });
    console.log(token)
    res.cookie("jwt", token, {
      httpOnly: true,
      secure: process.env.NODE_ENV==="Production",
      sameSite: process.env.NODE_ENV==="Production"?"None":"Strict",
      maxAge: 30 * 24 * 60 * 60 * 1000,
    });
  } catch (error) {
    res.status(500);
    throw new Error(`Issue With Assiging JWT`);
  }
};

Here is User Controller where user profile and login user included :

const loginUser = asyncHandler(async (req, res) => {
    const { email, password } = req.body;
    if (!email || !password) throw new Error(`Provide Valid User Details`);
    const validUser = await prisma.user.findFirst({
        where: {
           email:email,
        },

    });
    if (!validUser) throw new Error(`Invalid User Details`);
    const validPassword = await compareHashPassword(password, validUser.password);
    if (validUser && validPassword) {
      generateToken(res, validUser.email);
      const data = {
        email: validUser.email,
        isAdmin: validUser.isAdmin,
      };
      res.status(200).json({
        data,
        message: `Login Successfull`,
      });
    } else {
      res.status(400).send({message:"Invalid User Information"});
      throw new Error(`Invalid User Details`);
    }
  });
 

  const getUserProfile = asyncHandler(async (req, res) => {
    console.log('user',req.user)
   try{ 
    const data = {
      email: req.user.email,
        isAdmin: req.user.isAdmin,
    };
    res.status(200).json({ data });
  }catch(error){
    res.status(401).send({message:"UnAuthorized User"})
  }
  });

here is my user Route :

// Login /api/users/signin
router.route("/signin").post(loginUser);

// Logout /api/users/logout
router.route("/logout").post(logoutUser);

//Get profile
router.get("/profile",protect, getUserProfile);

Why i can not access the cookies value with req.cookies?.jwt though i am using next js as frontend
is there any bug ?
How can i solve the problem?

LEAVE A COMMENT