When using req.cookies, it shows [Object: null prototype] {}. Tried cookie-parser, but still not working

64 Views Asked by At

I faced an issue earlier with storing cookies, but now the token is saved as a cookie in the browser. However, when I try to get it using req.cookies, it gives me [Object: null prototype] {}. What might be the problem?

Here are two sets of code: the first one contains routes, and the second one includes middleware between the route and the controller function. In the function where I attempt to retrieve req.cookies, it returns [Object: null prototype] {}

import express from "express";
import { deleteUserAccount, updateUserDetails, userGoogleAuthentication, userLogin, userSignup }     from "../controllers/User.controller.js";
import { userAuthByToken } from "../utils/userAuth.js";

const router=express.Router();


router.post('/signup', userSignup);
router.post('/login', userLogin);
router.post('/google-auth', userGoogleAuthentication);
router.post('/update/:id',userAuthByToken,  updateUserDetails);
router.delete('/delete/:id', deleteUserAccount);

export default router;

import Jwt from "jsonwebtoken";
import UserModel from "../models/User.model.js";
export const userAuthByToken = (req, res, next) => {
    try {

    const token = req.cookies
    // const isAuthenticated = req.headers.authorization==='true' ? true : false;

    console.log("token auth", req);
    if (!token) {
        return response.status(401).json({ error: true, message: 'User is Un-Authorized' });
    }

    Jwt.verify(token, process.env.JWT_SECRET_KEY, (error, user) => {
        
        if (error) return response.status(401).json({ error: true, message: "Forbidden" });
        //User - > userId -> uid
        request.user = user;
        next()
    })

   return isAuthenticated ? next() : response.status(401).json({ error: true, message: "Forbidden" })


} catch (error) {
    next(error)

}

}

0

There are 0 best solutions below